diff --git "a/assets/worker-CL_jKwe6.js" "b/assets/worker-CL_jKwe6.js" new file mode 100644--- /dev/null +++ "b/assets/worker-CL_jKwe6.js" @@ -0,0 +1,2805 @@ +var Df=Object.defineProperty;var Lf=(dr,Jr,no)=>Jr in dr?Df(dr,Jr,{enumerable:!0,configurable:!0,writable:!0,value:no}):dr[Jr]=no;var _e=(dr,Jr,no)=>Lf(dr,typeof Jr!="symbol"?Jr+"":Jr,no);(function(){"use strict";var dr={},Jr={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Le,$,r)=>{Le.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb":(Le,$,r)=>{Le.exports=r.p+"ort.bundle.min.mjs"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Le,$,r)=>{r.r($),r.d($,{Environment:()=>st,Interpreter:()=>ut,Template:()=>mt,parse:()=>ye,tokenize:()=>y});var f=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),F=Object.freeze({set:f.Set,for:f.For,in:f.In,is:f.Is,if:f.If,else:f.Else,endif:f.EndIf,elif:f.ElseIf,endfor:f.EndFor,and:f.And,or:f.Or,not:f.Not,"not in":f.NotIn,macro:f.Macro,endmacro:f.EndMacro,true:f.BooleanLiteral,false:f.BooleanLiteral,none:f.NullLiteral,True:f.BooleanLiteral,False:f.BooleanLiteral,None:f.NullLiteral}),N=class{constructor(L,ie){this.value=L,this.type=ie}};function Y(L){return/\w/.test(L)}function R(L){return/[0-9]/.test(L)}var g=[["{%",f.OpenStatement],["%}",f.CloseStatement],["{{",f.OpenExpression],["}}",f.CloseExpression],["(",f.OpenParen],[")",f.CloseParen],["{",f.OpenCurlyBracket],["}",f.CloseCurlyBracket],["[",f.OpenSquareBracket],["]",f.CloseSquareBracket],[",",f.Comma],[".",f.Dot],[":",f.Colon],["|",f.Pipe],["<=",f.ComparisonBinaryOperator],[">=",f.ComparisonBinaryOperator],["==",f.ComparisonBinaryOperator],["!=",f.ComparisonBinaryOperator],["<",f.ComparisonBinaryOperator],[">",f.ComparisonBinaryOperator],["+",f.AdditiveBinaryOperator],["-",f.AdditiveBinaryOperator],["*",f.MultiplicativeBinaryOperator],["/",f.MultiplicativeBinaryOperator],["%",f.MultiplicativeBinaryOperator],["=",f.Equals]],v=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function M(L,ie={}){return L.endsWith(` +`)&&(L=L.slice(0,-1)),L=L.replace(/{#.*?#}/gs,"{##}"),ie.lstrip_blocks&&(L=L.replace(/^[ \t]*({[#%])/gm,"$1")),ie.trim_blocks&&(L=L.replace(/([#%]})\n/g,"$1")),L.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function y(L,ie={}){var qe,at,ct;const G=[],he=M(L,ie);let ke=0;const Re=vt=>{let kt="";for(;vt(he[ke]);){if(he[ke]==="\\"){if(++ke,ke>=he.length)throw new SyntaxError("Unexpected end of input");const $t=he[ke++],os=v.get($t);if(os===void 0)throw new SyntaxError(`Unexpected escaped character: ${$t}`);kt+=os;continue}if(kt+=he[ke++],ke>=he.length)throw new SyntaxError("Unexpected end of input")}return kt};e:for(;ke0){G.push(new N($t,f.Text));continue}}Re($t=>/\s/.test($t));const kt=he[ke];if(kt==="-"||kt==="+"){const $t=(at=G.at(-1))==null?void 0:at.type;if($t===f.Text||$t===void 0)throw new SyntaxError(`Unexpected character: ${kt}`);switch($t){case f.Identifier:case f.NumericLiteral:case f.BooleanLiteral:case f.NullLiteral:case f.StringLiteral:case f.CloseParen:case f.CloseSquareBracket:break;default:{++ke;const os=Re(R);G.push(new N(`${kt}${os}`,os.length>0?f.NumericLiteral:f.UnaryOperator));continue}}}for(const[$t,os]of g)if(he.slice(ke,ke+$t.length)===$t){G.push(new N($t,os)),ke+=$t.length;continue e}if(kt==="'"||kt==='"'){++ke;const $t=Re(os=>os!==kt);G.push(new N($t,f.StringLiteral)),++ke;continue}if(R(kt)){const $t=Re(R);G.push(new N($t,f.NumericLiteral));continue}if(Y(kt)){const $t=Re(Y),os=Object.hasOwn(F,$t)?F[$t]:f.Identifier;os===f.In&&((ct=G.at(-1))==null?void 0:ct.type)===f.Not?(G.pop(),G.push(new N("not in",f.NotIn))):G.push(new N($t,os));continue}throw new SyntaxError(`Unexpected character: ${kt}`)}return G}var b=class{constructor(){_e(this,"type","Statement")}},I=class extends b{constructor(ie){super();_e(this,"type","Program");this.body=ie}},H=class extends b{constructor(ie,G,he){super();_e(this,"type","If");this.test=ie,this.body=G,this.alternate=he}},se=class extends b{constructor(ie,G,he,ke){super();_e(this,"type","For");this.loopvar=ie,this.iterable=G,this.body=he,this.defaultBlock=ke}},ne=class extends b{constructor(ie,G){super();_e(this,"type","Set");this.assignee=ie,this.value=G}},W=class extends b{constructor(ie,G,he){super();_e(this,"type","Macro");this.name=ie,this.args=G,this.body=he}},U=class extends b{constructor(){super(...arguments);_e(this,"type","Expression")}},q=class extends U{constructor(ie,G,he){super();_e(this,"type","MemberExpression");this.object=ie,this.property=G,this.computed=he}},A=class extends U{constructor(ie,G){super();_e(this,"type","CallExpression");this.callee=ie,this.args=G}},S=class extends U{constructor(ie){super();_e(this,"type","Identifier");this.value=ie}},w=class extends U{constructor(ie){super();_e(this,"type","Literal");this.value=ie}},T=class extends w{constructor(){super(...arguments);_e(this,"type","NumericLiteral")}},O=class extends w{constructor(){super(...arguments);_e(this,"type","StringLiteral")}},ae=class extends w{constructor(){super(...arguments);_e(this,"type","BooleanLiteral")}},oe=class extends w{constructor(){super(...arguments);_e(this,"type","NullLiteral")}},Te=class extends w{constructor(){super(...arguments);_e(this,"type","ArrayLiteral")}},we=class extends w{constructor(){super(...arguments);_e(this,"type","TupleLiteral")}},re=class extends w{constructor(){super(...arguments);_e(this,"type","ObjectLiteral")}},xe=class extends U{constructor(ie,G,he){super();_e(this,"type","BinaryExpression");this.operator=ie,this.left=G,this.right=he}},ce=class extends U{constructor(ie,G){super();_e(this,"type","FilterExpression");this.operand=ie,this.filter=G}},Se=class extends U{constructor(ie,G){super();_e(this,"type","SelectExpression");this.iterable=ie,this.test=G}},Ie=class extends U{constructor(ie,G,he){super();_e(this,"type","TestExpression");this.operand=ie,this.negate=G,this.test=he}},Ee=class extends U{constructor(ie,G){super();_e(this,"type","UnaryExpression");this.operator=ie,this.argument=G}},tt=class extends U{constructor(ie=void 0,G=void 0,he=void 0){super();_e(this,"type","SliceExpression");this.start=ie,this.stop=G,this.step=he}},Ge=class extends U{constructor(ie,G){super();_e(this,"type","KeywordArgumentExpression");this.key=ie,this.value=G}};function ye(L){const ie=new I([]);let G=0;function he(ot,Tt){const Ft=L[G++];if(!Ft||Ft.type!==ot)throw new Error(`Parser Error: ${Tt}. ${Ft.type} !== ${ot}.`);return Ft}function ke(){switch(L[G].type){case f.Text:return at();case f.OpenStatement:return ct();case f.OpenExpression:return vt();default:throw new SyntaxError(`Unexpected token type: ${L[G].type}`)}}function Re(...ot){return G+ot.length<=L.length&&ot.some((Tt,Ft)=>Tt!==L[G+Ft].type)}function qe(...ot){return G+ot.length<=L.length&&ot.every((Tt,Ft)=>Tt===L[G+Ft].type)}function at(){return new O(he(f.Text,"Expected text token").value)}function ct(){he(f.OpenStatement,"Expected opening statement token");let ot;switch(L[G].type){case f.Set:++G,ot=kt(),he(f.CloseStatement,"Expected closing statement token");break;case f.If:++G,ot=$t(),he(f.OpenStatement,"Expected {% token"),he(f.EndIf,"Expected endif token"),he(f.CloseStatement,"Expected %} token");break;case f.Macro:++G,ot=os(),he(f.OpenStatement,"Expected {% token"),he(f.EndMacro,"Expected endmacro token"),he(f.CloseStatement,"Expected %} token");break;case f.For:++G,ot=ks(),he(f.OpenStatement,"Expected {% token"),he(f.EndFor,"Expected endfor token"),he(f.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${L[G].type}`)}return ot}function vt(){he(f.OpenExpression,"Expected opening expression token");const ot=Ls();return he(f.CloseExpression,"Expected closing expression token"),ot}function kt(){const ot=Ls();if(qe(f.Equals)){++G;const Tt=kt();return new ne(ot,Tt)}return ot}function $t(){var Vs,Ur,Ir,bs,ar,Os,xr,ss;const ot=Ls();he(f.CloseStatement,"Expected closing statement token");const Tt=[],Ft=[];for(;!(((Vs=L[G])==null?void 0:Vs.type)===f.OpenStatement&&(((Ur=L[G+1])==null?void 0:Ur.type)===f.ElseIf||((Ir=L[G+1])==null?void 0:Ir.type)===f.Else||((bs=L[G+1])==null?void 0:bs.type)===f.EndIf));)Tt.push(ke());if(((ar=L[G])==null?void 0:ar.type)===f.OpenStatement&&((Os=L[G+1])==null?void 0:Os.type)!==f.EndIf)if(++G,qe(f.ElseIf))he(f.ElseIf,"Expected elseif token"),Ft.push($t());else for(he(f.Else,"Expected else token"),he(f.CloseStatement,"Expected closing statement token");!(((xr=L[G])==null?void 0:xr.type)===f.OpenStatement&&((ss=L[G+1])==null?void 0:ss.type)===f.EndIf);)Ft.push(ke());return new H(ot,Tt,Ft)}function os(){const ot=ir();if(ot.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Tt=$r();he(f.CloseStatement,"Expected closing statement token");const Ft=[];for(;Re(f.OpenStatement,f.EndMacro);)Ft.push(ke());return new W(ot,Tt,Ft)}function Ms(ot=!1){const Tt=ot?ir:Ls,Ft=[Tt()],Vs=qe(f.Comma);for(;Vs&&(++G,Ft.push(Tt()),!!qe(f.Comma)););return Vs?new we(Ft):Ft[0]}function ks(){const ot=Ms(!0);if(!(ot instanceof S||ot instanceof we))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ot.type} instead`);he(f.In,"Expected `in` keyword following loop variable");const Tt=Ls();he(f.CloseStatement,"Expected closing statement token");const Ft=[];for(;Re(f.OpenStatement,f.EndFor)&&Re(f.OpenStatement,f.Else);)Ft.push(ke());const Vs=[];if(qe(f.OpenStatement,f.Else))for(++G,++G,he(f.CloseStatement,"Expected closing statement token");Re(f.OpenStatement,f.EndFor);)Vs.push(ke());return new se(ot,Tt,Ft,Vs)}function Ls(){return sr()}function sr(){const ot=kr();if(qe(f.If)){++G;const Tt=kr();if(qe(f.Else)){++G;const Ft=kr();return new H(Tt,[ot],[Ft])}else return new Se(ot,Tt)}return ot}function kr(){let ot=Zr();for(;qe(f.Or);){const Tt=L[G];++G;const Ft=Zr();ot=new xe(Tt,ot,Ft)}return ot}function Zr(){let ot=Us();for(;qe(f.And);){const Tt=L[G];++G;const Ft=Us();ot=new xe(Tt,ot,Ft)}return ot}function Us(){let ot;for(;qe(f.Not);){const Tt=L[G];++G;const Ft=Us();ot=new Ee(Tt,Ft)}return ot??Tr()}function Tr(){let ot=Nt();for(;qe(f.ComparisonBinaryOperator)||qe(f.In)||qe(f.NotIn);){const Tt=L[G];++G;const Ft=Nt();ot=new xe(Tt,ot,Ft)}return ot}function Nt(){let ot=Ar();for(;qe(f.AdditiveBinaryOperator);){const Tt=L[G];++G;const Ft=Ar();ot=new xe(Tt,ot,Ft)}return ot}function en(){const ot=Rr(ir());return qe(f.OpenParen)?Sr(ot):ot}function Sr(ot){let Tt=new A(ot,$r());return Tt=Rr(Tt),qe(f.OpenParen)&&(Tt=Sr(Tt)),Tt}function $r(){he(f.OpenParen,"Expected opening parenthesis for arguments list");const ot=tn();return he(f.CloseParen,"Expected closing parenthesis for arguments list"),ot}function tn(){const ot=[];for(;!qe(f.CloseParen);){let Tt=Ls();if(qe(f.Equals)){if(++G,!(Tt instanceof S))throw new SyntaxError("Expected identifier for keyword argument");const Ft=Ls();Tt=new Ge(Tt,Ft)}ot.push(Tt),qe(f.Comma)&&++G}return ot}function cr(){const ot=[];let Tt=!1;for(;!qe(f.CloseSquareBracket);)qe(f.Colon)?(ot.push(void 0),++G,Tt=!0):(ot.push(Ls()),qe(f.Colon)&&(++G,Tt=!0));if(ot.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Tt){if(ot.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new tt(...ot)}return ot[0]}function Rr(ot){for(;qe(f.Dot)||qe(f.OpenSquareBracket);){const Tt=L[G];++G;let Ft;const Vs=Tt.type!==f.Dot;if(Vs)Ft=cr(),he(f.CloseSquareBracket,"Expected closing square bracket");else if(Ft=ir(),Ft.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ot=new q(ot,Ft,Vs)}return ot}function Ar(){let ot=Nr();for(;qe(f.MultiplicativeBinaryOperator);){const Tt=L[G];++G;const Ft=Nr();ot=new xe(Tt,ot,Ft)}return ot}function Nr(){let ot=jr();for(;qe(f.Is);){++G;const Tt=qe(f.Not);Tt&&++G;let Ft=ir();if(Ft instanceof ae?Ft=new S(Ft.value.toString()):Ft instanceof oe&&(Ft=new S("none")),!(Ft instanceof S))throw new SyntaxError("Expected identifier for the test");ot=new Ie(ot,Tt,Ft)}return ot}function jr(){let ot=en();for(;qe(f.Pipe);){++G;let Tt=ir();if(!(Tt instanceof S))throw new SyntaxError("Expected identifier for the filter");qe(f.OpenParen)&&(Tt=Sr(Tt)),ot=new ce(ot,Tt)}return ot}function ir(){const ot=L[G];switch(ot.type){case f.NumericLiteral:return++G,new T(Number(ot.value));case f.StringLiteral:return++G,new O(ot.value);case f.BooleanLiteral:return++G,new ae(ot.value.toLowerCase()==="true");case f.NullLiteral:return++G,new oe(null);case f.Identifier:return++G,new S(ot.value);case f.OpenParen:{++G;const Tt=Ms();if(L[G].type!==f.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${L[G].type} instead`);return++G,Tt}case f.OpenSquareBracket:{++G;const Tt=[];for(;!qe(f.CloseSquareBracket);)Tt.push(Ls()),qe(f.Comma)&&++G;return++G,new Te(Tt)}case f.OpenCurlyBracket:{++G;const Tt=new Map;for(;!qe(f.CloseCurlyBracket);){const Ft=Ls();he(f.Colon,"Expected colon between key and value in object literal");const Vs=Ls();Tt.set(Ft,Vs),qe(f.Comma)&&++G}return++G,new re(Tt)}default:throw new SyntaxError(`Unexpected token: ${ot.type}`)}}for(;G=0?(ie=(ie??(ie=0))<0?Math.max(L.length+ie,0):Math.min(ie,L.length),G=(G??(G=L.length))<0?Math.max(L.length+G,0):Math.min(G,L.length)):(ie=(ie??(ie=L.length-1))<0?Math.max(L.length+ie,-1):Math.min(ie,L.length-1),G=(G??(G=-1))<-1?Math.max(L.length+G,-1):Math.min(G,L.length-1));const Re=[];for(let qe=ie;ke*qeie.toUpperCase())}var Be=class{constructor(L=void 0){_e(this,"type","RuntimeValue");_e(this,"value");_e(this,"builtins",new Map);this.value=L}__bool__(){return new Ke(!!this.value)}},Je=class extends Be{constructor(){super(...arguments);_e(this,"type","NumericValue")}},te=class extends Be{constructor(){super(...arguments);_e(this,"type","StringValue");_e(this,"builtins",new Map([["upper",new We(()=>new te(this.value.toUpperCase()))],["lower",new We(()=>new te(this.value.toLowerCase()))],["strip",new We(()=>new te(this.value.trim()))],["title",new We(()=>new te(Ce(this.value)))],["length",new Je(this.value.length)],["rstrip",new We(()=>new te(this.value.trimEnd()))],["lstrip",new We(()=>new te(this.value.trimStart()))],["split",new We(ie=>{const G=ie[0]??new Ne;if(!(G instanceof te||G instanceof Ne))throw new Error("sep argument must be a string or null");const he=ie[1]??new Je(-1);if(!(he instanceof Je))throw new Error("maxsplit argument must be a number");let ke=[];if(G instanceof Ne){const Re=this.value.trimStart();for(const{0:qe,index:at}of Re.matchAll(/\S+/g)){if(he.value!==-1&&ke.length>=he.value&&at!==void 0){ke.push(qe+Re.slice(at+qe.length));break}ke.push(qe)}}else{if(G.value==="")throw new Error("empty separator");ke=this.value.split(G.value),he.value!==-1&&ke.length>he.value&&ke.push(ke.splice(he.value).join(G.value))}return new be(ke.map(Re=>new te(Re)))})]]))}},Ke=class extends Be{constructor(){super(...arguments);_e(this,"type","BooleanValue")}},Ue=class extends Be{constructor(){super(...arguments);_e(this,"type","ObjectValue");_e(this,"builtins",new Map([["get",new We(([ie,G])=>{if(!(ie instanceof te))throw new Error(`Object key must be a string: got ${ie.type}`);return this.value.get(ie.value)??G??new Ne})],["items",new We(()=>new be(Array.from(this.value.entries()).map(([ie,G])=>new be([new te(ie),G]))))]]))}__bool__(){return new Ke(this.value.size>0)}},le=class extends Ue{constructor(){super(...arguments);_e(this,"type","KeywordArgumentsValue")}},be=class extends Be{constructor(){super(...arguments);_e(this,"type","ArrayValue");_e(this,"builtins",new Map([["length",new Je(this.value.length)]]))}__bool__(){return new Ke(this.value.length>0)}},Ve=class extends be{constructor(){super(...arguments);_e(this,"type","TupleValue")}},We=class extends Be{constructor(){super(...arguments);_e(this,"type","FunctionValue")}},Ne=class extends Be{constructor(){super(...arguments);_e(this,"type","NullValue")}},je=class extends Be{constructor(){super(...arguments);_e(this,"type","UndefinedValue")}},st=class{constructor(L){_e(this,"variables",new Map([["namespace",new We(L=>{if(L.length===0)return new Ue(new Map);if(L.length!==1||!(L[0]instanceof Ue))throw new Error("`namespace` expects either zero arguments or a single object argument");return L[0]})]]));_e(this,"tests",new Map([["boolean",L=>L.type==="BooleanValue"],["callable",L=>L instanceof We],["odd",L=>{if(L.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${L.type}`);return L.value%2!==0}],["even",L=>{if(L.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${L.type}`);return L.value%2===0}],["false",L=>L.type==="BooleanValue"&&!L.value],["true",L=>L.type==="BooleanValue"&&L.value],["none",L=>L.type==="NullValue"],["string",L=>L.type==="StringValue"],["number",L=>L.type==="NumericValue"],["integer",L=>L.type==="NumericValue"&&Number.isInteger(L.value)],["iterable",L=>L.type==="ArrayValue"||L.type==="StringValue"],["mapping",L=>L.type==="ObjectValue"],["lower",L=>{const ie=L.value;return L.type==="StringValue"&&ie===ie.toLowerCase()}],["upper",L=>{const ie=L.value;return L.type==="StringValue"&&ie===ie.toUpperCase()}],["none",L=>L.type==="NullValue"],["defined",L=>L.type!=="UndefinedValue"],["undefined",L=>L.type==="UndefinedValue"],["equalto",(L,ie)=>L.value===ie.value],["eq",(L,ie)=>L.value===ie.value]]));this.parent=L}set(L,ie){return this.declareVariable(L,pt(ie))}declareVariable(L,ie){if(this.variables.has(L))throw new SyntaxError(`Variable already declared: ${L}`);return this.variables.set(L,ie),ie}setVariable(L,ie){return this.variables.set(L,ie),ie}resolve(L){if(this.variables.has(L))return this;if(this.parent)return this.parent.resolve(L);throw new Error(`Unknown variable: ${L}`)}lookupVariable(L){try{return this.resolve(L).variables.get(L)??new je}catch{return new je}}},ut=class{constructor(L){_e(this,"global");this.global=L??new st}run(L){return this.evaluate(L,this.global)}evaluateBinaryExpression(L,ie){const G=this.evaluate(L.left,ie);switch(L.operator.value){case"and":return G.__bool__().value?this.evaluate(L.right,ie):G;case"or":return G.__bool__().value?G:this.evaluate(L.right,ie)}const he=this.evaluate(L.right,ie);switch(L.operator.value){case"==":return new Ke(G.value==he.value);case"!=":return new Ke(G.value!=he.value)}if(G instanceof je||he instanceof je)throw new Error("Cannot perform operation on undefined values");if(G instanceof Ne||he instanceof Ne)throw new Error("Cannot perform operation on null values");if(G instanceof Je&&he instanceof Je)switch(L.operator.value){case"+":return new Je(G.value+he.value);case"-":return new Je(G.value-he.value);case"*":return new Je(G.value*he.value);case"/":return new Je(G.value/he.value);case"%":return new Je(G.value%he.value);case"<":return new Ke(G.value":return new Ke(G.value>he.value);case">=":return new Ke(G.value>=he.value);case"<=":return new Ke(G.value<=he.value)}else if(G instanceof be&&he instanceof be)switch(L.operator.value){case"+":return new be(G.value.concat(he.value))}else if(he instanceof be){const ke=he.value.find(Re=>Re.value===G.value)!==void 0;switch(L.operator.value){case"in":return new Ke(ke);case"not in":return new Ke(!ke)}}if(G instanceof te||he instanceof te)switch(L.operator.value){case"+":return new te(G.value.toString()+he.value.toString())}if(G instanceof te&&he instanceof te)switch(L.operator.value){case"in":return new Ke(he.value.includes(G.value));case"not in":return new Ke(!he.value.includes(G.value))}if(G instanceof te&&he instanceof Ue)switch(L.operator.value){case"in":return new Ke(he.value.has(G.value));case"not in":return new Ke(!he.value.has(G.value))}throw new SyntaxError(`Unknown operator "${L.operator.value}" between ${G.type} and ${he.type}`)}evaluateArguments(L,ie){const G=[],he=new Map;for(const ke of L)if(ke.type==="KeywordArgumentExpression"){const Re=ke;he.set(Re.key.value,this.evaluate(Re.value,ie))}else{if(he.size>0)throw new Error("Positional arguments must come before keyword arguments");G.push(this.evaluate(ke,ie))}return[G,he]}evaluateFilterExpression(L,ie){const G=this.evaluate(L.operand,ie);if(L.filter.type==="Identifier"){const he=L.filter;if(he.value==="tojson")return new te(lt(G));if(G instanceof be)switch(he.value){case"list":return G;case"first":return G.value[0];case"last":return G.value[G.value.length-1];case"length":return new Je(G.value.length);case"reverse":return new be(G.value.reverse());case"sort":return new be(G.value.sort((ke,Re)=>{if(ke.type!==Re.type)throw new Error(`Cannot compare different types: ${ke.type} and ${Re.type}`);switch(ke.type){case"NumericValue":return ke.value-Re.value;case"StringValue":return ke.value.localeCompare(Re.value);default:throw new Error(`Cannot compare type: ${ke.type}`)}}));case"join":return new te(G.value.map(ke=>ke.value).join(""));default:throw new Error(`Unknown ArrayValue filter: ${he.value}`)}else if(G instanceof te)switch(he.value){case"length":return new Je(G.value.length);case"upper":return new te(G.value.toUpperCase());case"lower":return new te(G.value.toLowerCase());case"title":return new te(Ce(G.value));case"capitalize":return new te(G.value.charAt(0).toUpperCase()+G.value.slice(1));case"trim":return new te(G.value.trim());case"indent":return new te(G.value.split(` +`).map((ke,Re)=>Re===0||ke.length===0?ke:" "+ke).join(` +`));case"join":case"string":return G;default:throw new Error(`Unknown StringValue filter: ${he.value}`)}else if(G instanceof Je)switch(he.value){case"abs":return new Je(Math.abs(G.value));default:throw new Error(`Unknown NumericValue filter: ${he.value}`)}else if(G instanceof Ue)switch(he.value){case"items":return new be(Array.from(G.value.entries()).map(([ke,Re])=>new be([new te(ke),Re])));case"length":return new Je(G.value.size);default:throw new Error(`Unknown ObjectValue filter: ${he.value}`)}throw new Error(`Cannot apply filter "${he.value}" to type: ${G.type}`)}else if(L.filter.type==="CallExpression"){const he=L.filter;if(he.callee.type!=="Identifier")throw new Error(`Unknown filter: ${he.callee.type}`);const ke=he.callee.value;if(ke==="tojson"){const[,Re]=this.evaluateArguments(he.args,ie),qe=Re.get("indent")??new Ne;if(!(qe instanceof Je||qe instanceof Ne))throw new Error("If set, indent must be a number");return new te(lt(G,qe.value))}else if(ke==="join"){let Re;if(G instanceof te)Re=Array.from(G.value);else if(G instanceof be)Re=G.value.map(vt=>vt.value);else throw new Error(`Cannot apply filter "${ke}" to type: ${G.type}`);const[qe,at]=this.evaluateArguments(he.args,ie),ct=qe.at(0)??at.get("separator")??new te("");if(!(ct instanceof te))throw new Error("separator must be a string");return new te(Re.join(ct.value))}if(G instanceof be){switch(ke){case"selectattr":case"rejectattr":{const Re=ke==="selectattr";if(G.value.some($t=>!($t instanceof Ue)))throw new Error(`\`${ke}\` can only be applied to array of objects`);if(he.args.some($t=>$t.type!=="StringLiteral"))throw new Error(`arguments of \`${ke}\` must be strings`);const[qe,at,ct]=he.args.map($t=>this.evaluate($t,ie));let vt;if(at){const $t=ie.tests.get(at.value);if(!$t)throw new Error(`Unknown test: ${at.value}`);vt=$t}else vt=(...$t)=>$t[0].__bool__().value;const kt=G.value.filter($t=>{const os=$t.value.get(qe.value),Ms=os?vt(os,ct):!1;return Re?Ms:!Ms});return new be(kt)}case"map":{const[,Re]=this.evaluateArguments(he.args,ie);if(Re.has("attribute")){const qe=Re.get("attribute");if(!(qe instanceof te))throw new Error("attribute must be a string");const at=Re.get("default"),ct=G.value.map(vt=>{if(!(vt instanceof Ue))throw new Error("items in map must be an object");return vt.value.get(qe.value)??at??new je});return new be(ct)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${ke}`)}else if(G instanceof te){switch(ke){case"indent":{const[Re,qe]=this.evaluateArguments(he.args,ie),at=Re.at(0)??qe.get("width")??new Je(4);if(!(at instanceof Je))throw new Error("width must be a number");const ct=Re.at(1)??qe.get("first")??new Ke(!1),vt=Re.at(2)??qe.get("blank")??new Ke(!1),kt=G.value.split(` +`),$t=" ".repeat(at.value),os=kt.map((Ms,ks)=>!ct.value&&ks===0||!vt.value&&Ms.length===0?Ms:$t+Ms);return new te(os.join(` +`))}}throw new Error(`Unknown StringValue filter: ${ke}`)}else throw new Error(`Cannot apply filter "${ke}" to type: ${G.type}`)}throw new Error(`Unknown filter: ${L.filter.type}`)}evaluateTestExpression(L,ie){const G=this.evaluate(L.operand,ie),he=ie.tests.get(L.test.value);if(!he)throw new Error(`Unknown test: ${L.test.value}`);const ke=he(G);return new Ke(L.negate?!ke:ke)}evaluateUnaryExpression(L,ie){const G=this.evaluate(L.argument,ie);switch(L.operator.value){case"not":return new Ke(!G.value);default:throw new SyntaxError(`Unknown operator: ${L.operator.value}`)}}evalProgram(L,ie){return this.evaluateBlock(L.body,ie)}evaluateBlock(L,ie){let G="";for(const he of L){const ke=this.evaluate(he,ie);ke.type!=="NullValue"&&ke.type!=="UndefinedValue"&&(G+=ke.value)}return new te(G)}evaluateIdentifier(L,ie){return ie.lookupVariable(L.value)}evaluateCallExpression(L,ie){const[G,he]=this.evaluateArguments(L.args,ie);he.size>0&&G.push(new le(he));const ke=this.evaluate(L.callee,ie);if(ke.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${ke.type}`);return ke.value(G,ie)}evaluateSliceExpression(L,ie,G){if(!(L instanceof be||L instanceof te))throw new Error("Slice object must be an array or string");const he=this.evaluate(ie.start,G),ke=this.evaluate(ie.stop,G),Re=this.evaluate(ie.step,G);if(!(he instanceof Je||he instanceof je))throw new Error("Slice start must be numeric or undefined");if(!(ke instanceof Je||ke instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(Re instanceof Je||Re instanceof je))throw new Error("Slice step must be numeric or undefined");return L instanceof be?new be(de(L.value,he.value,ke.value,Re.value)):new te(de(Array.from(L.value),he.value,ke.value,Re.value).join(""))}evaluateMemberExpression(L,ie){const G=this.evaluate(L.object,ie);let he;if(L.computed){if(L.property.type==="SliceExpression")return this.evaluateSliceExpression(G,L.property,ie);he=this.evaluate(L.property,ie)}else he=new te(L.property.value);let ke;if(G instanceof Ue){if(!(he instanceof te))throw new Error(`Cannot access property with non-string: got ${he.type}`);ke=G.value.get(he.value)??G.builtins.get(he.value)}else if(G instanceof be||G instanceof te)if(he instanceof Je)ke=G.value.at(he.value),G instanceof te&&(ke=new te(G.value.at(he.value)));else if(he instanceof te)ke=G.builtins.get(he.value);else throw new Error(`Cannot access property with non-string/non-number: got ${he.type}`);else{if(!(he instanceof te))throw new Error(`Cannot access property with non-string: got ${he.type}`);ke=G.builtins.get(he.value)}return ke instanceof Be?ke:new je}evaluateSet(L,ie){const G=this.evaluate(L.value,ie);if(L.assignee.type==="Identifier"){const he=L.assignee.value;ie.setVariable(he,G)}else if(L.assignee.type==="MemberExpression"){const he=L.assignee,ke=this.evaluate(he.object,ie);if(!(ke instanceof Ue))throw new Error("Cannot assign to member of non-object");if(he.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");ke.value.set(he.property.value,G)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(L.assignee)}`);return new Ne}evaluateIf(L,ie){const G=this.evaluate(L.test,ie);return this.evaluateBlock(G.__bool__().value?L.body:L.alternate,ie)}evaluateFor(L,ie){const G=new st(ie);let he,ke;if(L.iterable.type==="SelectExpression"){const vt=L.iterable;ke=this.evaluate(vt.iterable,G),he=vt.test}else ke=this.evaluate(L.iterable,G);if(!(ke instanceof be))throw new Error(`Expected iterable type in for loop: got ${ke.type}`);const Re=[],qe=[];for(let vt=0;vtMs.setVariable(L.loopvar.value,$t);else if(L.loopvar.type==="TupleLiteral"){const Ms=L.loopvar;if($t.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${$t.type}`);const ks=$t;if(Ms.value.length!==ks.value.length)throw new Error(`Too ${Ms.value.length>ks.value.length?"few":"many"} items to unpack`);os=Ls=>{for(let sr=0;sr0?Re[vt-1]:new je],["nextitem",vt{var qe;const ke=new st(he);G=G.slice();let Re;((qe=G.at(-1))==null?void 0:qe.type)==="KeywordArgumentsValue"&&(Re=G.pop());for(let at=0;atthis.evaluate(G,ie)));case"TupleLiteral":return new Ve(L.value.map(G=>this.evaluate(G,ie)));case"ObjectLiteral":{const G=new Map;for(const[he,ke]of L.value){const Re=this.evaluate(he,ie);if(!(Re instanceof te))throw new Error(`Object keys must be strings: got ${Re.type}`);G.set(Re.value,this.evaluate(ke,ie))}return new Ue(G)}case"Identifier":return this.evaluateIdentifier(L,ie);case"CallExpression":return this.evaluateCallExpression(L,ie);case"MemberExpression":return this.evaluateMemberExpression(L,ie);case"UnaryExpression":return this.evaluateUnaryExpression(L,ie);case"BinaryExpression":return this.evaluateBinaryExpression(L,ie);case"FilterExpression":return this.evaluateFilterExpression(L,ie);case"TestExpression":return this.evaluateTestExpression(L,ie);default:throw new SyntaxError(`Unknown node type: ${L.type}`)}}};function pt(L){switch(typeof L){case"number":return new Je(L);case"string":return new te(L);case"boolean":return new Ke(L);case"undefined":return new je;case"object":return L===null?new Ne:Array.isArray(L)?new be(L.map(pt)):new Ue(new Map(Object.entries(L).map(([ie,G])=>[ie,pt(G)])));case"function":return new We((ie,G)=>{const he=L(...ie.map(ke=>ke.value))??null;return pt(he)});default:throw new Error(`Cannot convert to runtime value: ${L}`)}}function lt(L,ie,G){const he=G??0;switch(L.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(L.value);case"ArrayValue":case"ObjectValue":{const ke=ie?" ".repeat(ie):"",Re=` +`+ke.repeat(he),qe=Re+ke;if(L.type==="ArrayValue"){const at=L.value.map(ct=>lt(ct,ie,he+1));return ie?`[${qe}${at.join(`,${qe}`)}${Re}]`:`[${at.join(", ")}]`}else{const at=Array.from(L.value.entries()).map(([ct,vt])=>{const kt=`"${ct}": ${lt(vt,ie,he+1)}`;return ie?`${qe}${kt}`:kt});return ie?`{${at.join(",")}${Re}}`:`{${at.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${L.type}`)}}var mt=class{constructor(L){_e(this,"parsed");const ie=y(L,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ye(ie)}render(L){const ie=new st;if(ie.set("false",!1),ie.set("true",!0),ie.set("raise_exception",ke=>{throw new Error(ke)}),ie.set("range",J),L)for(const[ke,Re]of Object.entries(L))ie.set(ke,Re);return new ut(ie).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Le,$,r)=>{r.r($),r.d($,{registerBackend:()=>N,resolveBackendAndExecutionProviders:()=>R});const f=new Map,F=[],N=(g,v,M)=>{if(v&&typeof v.init=="function"&&typeof v.createInferenceSessionHandler=="function"){const y=f.get(g);if(y===void 0)f.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 b=F.indexOf(g);b!==-1&&F.splice(b,1);for(let I=0;I{const v=f.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}}},R=async g=>{const v=g.executionProviders||[],M=v.map(ne=>typeof ne=="string"?ne:ne.name),y=M.length===0?F:M;let b;const I=[],H=new Set;for(const ne of y){const W=await Y(ne);typeof W=="string"?I.push({name:ne,err:W}):(b||(b=W),b===W&&H.add(ne))}if(!b)throw new Error(`no available backend found. ERR: ${I.map(ne=>`[${ne.name}] ${ne.err}`).join(", ")}`);for(const{name:ne,err:W}of I)M.includes(ne)&&console.warn(`removing requested execution provider "${ne}" from session options because it is not available: ${W}`);const se=v.filter(ne=>H.has(typeof ne=="string"?ne:ne.name));return[b,new Proxy(g,{get:(ne,W)=>W==="executionProviders"?se:Reflect.get(ne,W)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Le,$,r)=>{r.r($),r.d($,{registerBackend:()=>f.registerBackend});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Le,$,r)=>{r.r($),r.d($,{env:()=>N});var f=r("./node_modules/onnxruntime-common/dist/esm/version.js");let F="warning";const N={wasm:{},webgl:{},webgpu:{},versions:{common:f.version},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);F=Y}},get logLevel(){return F}};Object.defineProperty(N,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Le,$,r)=>{r.r($),r.d($,{env:()=>F});var f=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const F=f.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Le,$,r)=>{r.r($),r.d($,{InferenceSession:()=>N.InferenceSession,TRACE:()=>R.TRACE,TRACE_FUNC_BEGIN:()=>R.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>R.TRACE_FUNC_END,Tensor:()=>Y.Tensor,TrainingSession:()=>g.TrainingSession,env:()=>F.env,registerBackend:()=>f.registerBackend});var f=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),F=r("./node_modules/onnxruntime-common/dist/esm/env.js"),N=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Y=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),r("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var R=r("./node_modules/onnxruntime-common/dist/esm/trace.js");r("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),r("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var g=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Le,$,r)=>{r.r($),r.d($,{InferenceSession:()=>Y});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),F=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),N=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class Y{constructor(g){this.handler=g}async run(g,v,M){(0,N.TRACE_FUNC_BEGIN)();const y={};let b={};if(typeof g!="object"||g===null||g instanceof F.Tensor||Array.isArray(g))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let I=!0;if(typeof v=="object"){if(v===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(v instanceof F.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.");I=!1;for(const ne of v){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);y[ne]=null}if(typeof M=="object"&&M!==null)b=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const W=Object.getOwnPropertyNames(v);for(const U of this.outputNames)if(W.indexOf(U)!==-1){const q=v[U];(q===null||q instanceof F.Tensor)&&(ne=!0,I=!1,y[U]=q)}if(ne){if(typeof M=="object"&&M!==null)b=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else b=v}}else if(typeof v<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of this.inputNames)if(typeof g[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(I)for(const ne of this.outputNames)y[ne]=null;const H=await this.handler.run(g,y,b),se={};for(const ne in H)if(Object.hasOwnProperty.call(H,ne)){const W=H[ne];W instanceof F.Tensor?se[ne]=W:se[ne]=new F.Tensor(W.type,W.data,W.dims)}return(0,N.TRACE_FUNC_END)(),se}async release(){return this.handler.dispose()}static async create(g,v,M,y){(0,N.TRACE_FUNC_BEGIN)();let b,I={};if(typeof g=="string"){if(b=g,typeof v=="object"&&v!==null)I=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof Uint8Array){if(b=g,typeof v=="object"&&v!==null)I=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 W=g;let U=0,q=g.byteLength;if(typeof v=="object"&&v!==null)I=v;else if(typeof v=="number"){if(U=v,!Number.isSafeInteger(U))throw new RangeError("'byteOffset' must be an integer.");if(U<0||U>=W.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${W.byteLength}).`);if(q=g.byteLength-U,typeof M=="number"){if(q=M,!Number.isSafeInteger(q))throw new RangeError("'byteLength' must be an integer.");if(q<=0||U+q>W.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${W.byteLength-U}].`);if(typeof y=="object"&&y!==null)I=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.");b=new Uint8Array(W,U,q)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[H,se]=await(0,f.resolveBackendAndExecutionProviders)(I),ne=await H.createInferenceSessionHandler(b,se);return(0,N.TRACE_FUNC_END)(),new Y(ne)}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":(Le,$,r)=>{r.r($),r.d($,{InferenceSession:()=>F});var f=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const F=f.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Le,$,r)=>{r.r($)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Le,$,r)=>{r.r($)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Le,$,r)=>{r.r($),r.d($,{tensorToDataURL:()=>f,tensorToImageData:()=>F});const f=(N,Y)=>{const R=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);R.width=N.dims[3],R.height=N.dims[2];const g=R.getContext("2d");if(g!=null){let v,M;(Y==null?void 0:Y.tensorLayout)!==void 0&&Y.tensorLayout==="NHWC"?(v=N.dims[2],M=N.dims[3]):(v=N.dims[3],M=N.dims[2]);const y=(Y==null?void 0:Y.format)!==void 0?Y.format:"RGB",b=Y==null?void 0:Y.norm;let I,H;b===void 0||b.mean===void 0?I=[255,255,255,255]:typeof b.mean=="number"?I=[b.mean,b.mean,b.mean,b.mean]:(I=[b.mean[0],b.mean[1],b.mean[2],0],b.mean[3]!==void 0&&(I[3]=b.mean[3])),b===void 0||b.bias===void 0?H=[0,0,0,0]:typeof b.bias=="number"?H=[b.bias,b.bias,b.bias,b.bias]:(H=[b.bias[0],b.bias[1],b.bias[2],0],b.bias[3]!==void 0&&(H[3]=b.bias[3]));const se=M*v;let ne=0,W=se,U=se*2,q=-1;y==="RGBA"?(ne=0,W=se,U=se*2,q=se*3):y==="RGB"?(ne=0,W=se,U=se*2):y==="RBG"&&(ne=0,U=se,W=se*2);for(let A=0;A{const R=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let g;if(R!=null){let v,M,y;(Y==null?void 0:Y.tensorLayout)!==void 0&&Y.tensorLayout==="NHWC"?(v=N.dims[2],M=N.dims[1],y=N.dims[3]):(v=N.dims[3],M=N.dims[2],y=N.dims[1]);const b=Y!==void 0&&Y.format!==void 0?Y.format:"RGB",I=Y==null?void 0:Y.norm;let H,se;I===void 0||I.mean===void 0?H=[255,255,255,255]:typeof I.mean=="number"?H=[I.mean,I.mean,I.mean,I.mean]:(H=[I.mean[0],I.mean[1],I.mean[2],255],I.mean[3]!==void 0&&(H[3]=I.mean[3])),I===void 0||I.bias===void 0?se=[0,0,0,0]:typeof I.bias=="number"?se=[I.bias,I.bias,I.bias,I.bias]:(se=[I.bias[0],I.bias[1],I.bias[2],0],I.bias[3]!==void 0&&(se[3]=I.bias[3]));const ne=M*v;if(Y!==void 0&&(Y.format!==void 0&&y===4&&Y.format!=="RGBA"||y===3&&Y.format!=="RGB"&&Y.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const W=4;let U=0,q=1,A=2,S=3,w=0,T=ne,O=ne*2,ae=-1;b==="RGBA"?(w=0,T=ne,O=ne*2,ae=ne*3):b==="RGB"?(w=0,T=ne,O=ne*2):b==="RBG"&&(w=0,O=ne,T=ne*2),g=R.createImageData(v,M);for(let oe=0;oe{r.r($)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Le,$,r)=>{r.r($),r.d($,{bufferToTensor:()=>F,tensorFromGpuBuffer:()=>R,tensorFromImage:()=>N,tensorFromMLTensor:()=>g,tensorFromPinnedBuffer:()=>v,tensorFromTexture:()=>Y});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const F=(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:b,width:I}=y,H=y.norm??{mean:255,bias:0};let se,ne;typeof H.mean=="number"?se=[H.mean,H.mean,H.mean,H.mean]:se=[H.mean[0],H.mean[1],H.mean[2],H.mean[3]??255],typeof H.bias=="number"?ne=[H.bias,H.bias,H.bias,H.bias]:ne=[H.bias[0],H.bias[1],H.bias[2],H.bias[3]??0];const W=y.format!==void 0?y.format:"RGBA",U=y.tensorFormat!==void 0&&y.tensorFormat!==void 0?y.tensorFormat:"RGB",q=b*I,A=U==="RGBA"?new Float32Array(q*4):new Float32Array(q*3);let S=4,w=0,T=1,O=2,ae=3,oe=0,Te=q,we=q*2,re=-1;W==="RGB"&&(S=3,w=0,T=1,O=2,ae=-1),U==="RGBA"?re=q*3:U==="RBG"?(oe=0,we=q,Te=q*2):U==="BGR"&&(we=0,Te=q,oe=q*2);for(let ce=0;ce{const b=typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement,I=typeof ImageData<"u"&&M instanceof ImageData,H=typeof ImageBitmap<"u"&&M instanceof ImageBitmap,se=typeof M=="string";let ne,W=y??{};const U=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},q=A=>typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||A instanceof OffscreenCanvas?A.getContext("2d"):null;if(b){const A=U();A.width=M.width,A.height=M.height;const S=q(A);if(S!=null){let w=M.height,T=M.width;if(y!==void 0&&y.resizedHeight!==void 0&&y.resizedWidth!==void 0&&(w=y.resizedHeight,T=y.resizedWidth),y!==void 0){if(W=y,y.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");W.tensorFormat="RGBA",W.height=w,W.width=T}else W.tensorFormat="RGBA",W.height=w,W.width=T;S.drawImage(M,0,0),ne=S.getImageData(0,0,T,w).data}else throw new Error("Can not access image data")}else if(I){let A,S;if(y!==void 0&&y.resizedWidth!==void 0&&y.resizedHeight!==void 0?(A=y.resizedHeight,S=y.resizedWidth):(A=M.height,S=M.width),y!==void 0&&(W=y),W.format="RGBA",W.height=A,W.width=S,y!==void 0){const w=U();w.width=S,w.height=A;const T=q(w);if(T!=null)T.putImageData(M,0,0),ne=T.getImageData(0,0,S,A).data;else throw new Error("Can not access image data")}else ne=M.data}else if(H){if(y===void 0)throw new Error("Please provide image config with format for Imagebitmap");const A=U();A.width=M.width,A.height=M.height;const S=q(A);if(S!=null){const w=M.height,T=M.width;return S.drawImage(M,0,0,T,w),ne=S.getImageData(0,0,T,w).data,W.height=w,W.width=T,F(ne,W)}else throw new Error("Can not access image data")}else{if(se)return new Promise((A,S)=>{const w=U(),T=q(w);if(!M||!T)return S();const O=new Image;O.crossOrigin="Anonymous",O.src=M,O.onload=()=>{w.width=O.width,w.height=O.height,T.drawImage(O,0,0,w.width,w.height);const ae=T.getImageData(0,0,w.width,w.height);W.height=w.height,W.width=w.width,A(F(ae.data,W))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ne!==void 0)return F(ne,W);throw new Error("Input data provided is not supported - aborted tensor creation")},Y=(M,y)=>{const{width:b,height:I,download:H,dispose:se}=y,ne=[1,I,b,4];return new f.Tensor({location:"texture",type:"float32",texture:M,dims:ne,download:H,dispose:se})},R=(M,y)=>{const{dataType:b,dims:I,download:H,dispose:se}=y;return new f.Tensor({location:"gpu-buffer",type:b??"float32",gpuBuffer:M,dims:I,download:H,dispose:se})},g=(M,y)=>{const{dataType:b,dims:I,download:H,dispose:se}=y;return new f.Tensor({location:"ml-tensor",type:b??"float32",mlTensor:M,dims:I,download:H,dispose:se})},v=(M,y,b)=>new f.Tensor({location:"cpu-pinned",type:M,data:y,dims:b??[y.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Le,$,r)=>{r.r($)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Le,$,r)=>{r.r($),r.d($,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>F,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>f,checkTypedArray:()=>Y});const f=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),F=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let N=!1;const Y=()=>{if(!N){N=!0;const R=typeof BigInt64Array<"u"&&BigInt64Array.from,g=typeof BigUint64Array<"u"&&BigUint64Array.from,v=typeof Float16Array<"u"&&Float16Array.from;R&&(f.set("int64",BigInt64Array),F.set(BigInt64Array,"int64")),g&&(f.set("uint64",BigUint64Array),F.set(BigUint64Array,"uint64")),v?(f.set("float16",Float16Array),F.set(Float16Array,"float16")):f.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Le,$,r)=>{r.r($),r.d($,{Tensor:()=>R});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),F=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),N=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Y=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class R{constructor(v,M,y){(0,N.checkTypedArray)();let b,I;if(typeof v=="object"&&"location"in v)switch(this.dataLocation=v.location,b=v.type,I=v.dims,v.location){case"cpu-pinned":{const se=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(!se)throw new TypeError(`unsupported type "${b}" to create tensor from pinned buffer`);if(!(v.data instanceof se))throw new TypeError(`buffer should be of type ${se.name}`);this.cpuData=v.data;break}case"texture":{if(b!=="float32")throw new TypeError(`unsupported type "${b}" to create tensor from texture`);this.gpuTextureData=v.texture,this.downloader=v.download,this.disposer=v.dispose;break}case"gpu-buffer":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint8"&&b!=="bool"&&b!=="uint4"&&b!=="int4")throw new TypeError(`unsupported type "${b}" to create tensor from gpu buffer`);this.gpuBufferData=v.gpuBuffer,this.downloader=v.download,this.disposer=v.dispose;break}case"ml-tensor":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint64"&&b!=="int8"&&b!=="uint8"&&b!=="bool")throw new TypeError(`unsupported type "${b}" to create tensor from MLTensor`);this.mlTensorData=v.mlTensor,this.downloader=v.download,this.disposer=v.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let se,ne;if(typeof v=="string")if(b=v,ne=y,v==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");se=M}else{const W=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(W===void 0)throw new TypeError(`Unsupported tensor type: ${v}.`);if(Array.isArray(M)){if(v==="float16"&&W===Uint16Array||v==="uint4"||v==="int4")throw new TypeError(`Creating a ${v} tensor from number array is not supported. Please use ${W.name} as data.`);v==="uint64"||v==="int64"?se=W.from(M,BigInt):se=W.from(M)}else if(M instanceof W)se=M;else if(M instanceof Uint8ClampedArray)if(v==="uint8")se=Uint8Array.from(M);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${b} tensor's data must be type of ${W}`)}else if(ne=M,Array.isArray(v)){if(v.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const W=typeof v[0];if(W==="string")b="string",se=v;else if(W==="boolean")b="bool",se=Uint8Array.from(v);else throw new TypeError(`Invalid element type of data array: ${W}.`)}else if(v instanceof Uint8ClampedArray)b="uint8",se=Uint8Array.from(v);else{const W=N.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(v.constructor);if(W===void 0)throw new TypeError(`Unsupported type for tensor data: ${v.constructor}.`);b=W,se=v}if(ne===void 0)ne=[se.length];else if(!Array.isArray(ne))throw new TypeError("A tensor's dims must be a number array");I=ne,this.cpuData=se,this.dataLocation="cpu"}const H=(0,Y.calculateSize)(I);if(this.cpuData&&H!==this.cpuData.length&&!((b==="uint4"||b==="int4")&&Math.ceil(H/2)===this.cpuData.length))throw new Error(`Tensor's size(${H}) does not match data length(${this.cpuData.length}).`);this.type=b,this.dims=I,this.size=H}static async fromImage(v,M){return(0,F.tensorFromImage)(v,M)}static fromTexture(v,M){return(0,F.tensorFromTexture)(v,M)}static fromGpuBuffer(v,M){return(0,F.tensorFromGpuBuffer)(v,M)}static fromMLTensor(v,M){return(0,F.tensorFromMLTensor)(v,M)}static fromPinnedBuffer(v,M,y){return(0,F.tensorFromPinnedBuffer)(v,M,y)}toDataURL(v){return(0,f.tensorToDataURL)(this,v)}toImageData(v){return(0,f.tensorToImageData)(this,v)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(v){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const 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,Y.tensorReshape)(this,v)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Le,$,r)=>{r.r($),r.d($,{calculateSize:()=>F,tensorReshape:()=>N});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const F=Y=>{let R=1;for(let g=0;g{switch(Y.location){case"cpu":return new f.Tensor(Y.type,Y.data,R);case"cpu-pinned":return new f.Tensor({location:"cpu-pinned",data:Y.data,type:Y.type,dims:R});case"texture":return new f.Tensor({location:"texture",texture:Y.texture,type:Y.type,dims:R});case"gpu-buffer":return new f.Tensor({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:R});case"ml-tensor":return new f.Tensor({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:R});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Le,$,r)=>{r.r($),r.d($,{Tensor:()=>F});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const F=f.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Le,$,r)=>{r.r($),r.d($,{TRACE:()=>F,TRACE_FUNC_BEGIN:()=>Y,TRACE_FUNC_END:()=>R});var f=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const F=(g,v)=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||console.timeStamp(`${g}::ORT::${v}`)},N=(g,v)=>{var b;const M=((b=new Error().stack)==null?void 0:b.split(/\r\n|\r|\n/g))||[];let y=!1;for(let I=0;I{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||N("BEGIN",g)},R=g=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||N("END",g)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Le,$,r)=>{r.r($),r.d($,{TrainingSession:()=>Y});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),F=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const N="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Y{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||"",b=v||{},[I,H]=await(0,f.resolveBackendAndExecutionProviders)(b);if(I.createTrainingSessionHandler){const se=await I.createTrainingSessionHandler(g.checkpointState,g.trainModel,M,y,H);return new Y(se,!!g.optimizerModel,!!g.evalModel)}else throw new Error(N)}typeNarrowingForRunStep(g,v,M,y,b){const I={};let H={};if(typeof M!="object"||M===null||M instanceof F.Tensor||Array.isArray(M))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let se=!0;if(typeof y=="object"){if(y===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(y instanceof F.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.");se=!1;for(const ne of y){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(v.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);I[ne]=null}if(typeof b=="object"&&b!==null)H=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const W=Object.getOwnPropertyNames(y);for(const U of v)if(W.indexOf(U)!==-1){const q=y[U];(q===null||q instanceof F.Tensor)&&(ne=!0,se=!1,I[U]=q)}if(ne){if(typeof b=="object"&&b!==null)H=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else H=y}}else if(typeof y<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of g)if(typeof M[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(se)for(const ne of v)I[ne]=null;return[I,H]}convertHandlerReturnTypeToMapOfTensors(g){const v={};for(const M in g)if(Object.hasOwnProperty.call(g,M)){const y=g[M];y instanceof F.Tensor?v[M]=y:v[M]=new F.Tensor(y.type,y.data,y.dims)}return v}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(g,v,M){const[y,b]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,g,v,M),I=await this.handler.runTrainStep(g,y,b);return this.convertHandlerReturnTypeToMapOfTensors(I)}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,b]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,g,v,M),I=await this.handler.runEvalStep(g,y,b);return this.convertHandlerReturnTypeToMapOfTensors(I)}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":(Le,$,r)=>{r.r($),r.d($,{TrainingSession:()=>F});var f=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const F=f.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Le,$,r)=>{r.r($),r.d($,{version:()=>f});const f="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96":(Le,$,r)=>{r.r($),r.d($,{InferenceSession:()=>lt,TRACE:()=>Ve,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>je,Tensor:()=>le,default:()=>__,env:()=>O,registerBackend:()=>H});/*! + * ONNX Runtime Web v1.21.0-dev.20250206-d981b153d3 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var f=Object.defineProperty,F=Object.getOwnPropertyDescriptor,N=Object.getOwnPropertyNames,Y=Object.prototype.hasOwnProperty,R=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),g=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{for(var s in t)f(e,s,{get:t[s],enumerable:!0})},M=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of N(t))!Y.call(e,o)&&o!==s&&f(e,o,{get:()=>t[o],enumerable:!(n=F(t,o))||n.enumerable});return e},y=e=>M(f({},"__esModule",{value:!0}),e),b,I,H,se,ne,W=g(()=>{b=new Map,I=[],H=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=b.get(e);if(n===void 0)b.set(e,{backend:t,priority:s});else{if(n.priority>s)return;if(n.priority===s&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let o=I.indexOf(e);o!==-1&&I.splice(o,1);for(let a=0;a{let t=b.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return s||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ne=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?I:s,o,a=[],i=new Set;for(let p of n){let h=await se(p);typeof h=="string"?a.push({name:p,err:h}):(o||(o=h),o===h&&i.add(p))}if(!o)throw new Error(`no available backend found. ERR: ${a.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of a)s.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let u=t.filter(p=>i.has(typeof p=="string"?p:p.name));return[o,new Proxy(e,{get:(p,h)=>h==="executionProviders"?u:Reflect.get(p,h)})]}}),U=g(()=>{W()}),q,A=g(()=>{q="1.21.0-dev.20250206-d981b153d3"}),S,w,T=g(()=>{A(),S="warning",w={wasm:{},webgl:{},webgpu:{},versions:{common:q},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);S=e}},get logLevel(){return S}},Object.defineProperty(w,"logLevel",{enumerable:!0})}),O,ae=g(()=>{T(),O=w}),oe,Te,we=g(()=>{oe=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let o,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[3]):(o=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,p,h;u===void 0||u.mean===void 0?p=[255,255,255,255]:typeof u.mean=="number"?p=[u.mean,u.mean,u.mean,u.mean]:(p=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(p[3]=u.mean[3])),u===void 0||u.bias===void 0?h=[0,0,0,0]:typeof u.bias=="number"?h=[u.bias,u.bias,u.bias,u.bias]:(h=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(h[3]=u.bias[3]));let C=a*o,k=0,d=C,z=C*2,B=-1;i==="RGBA"?(k=0,d=C,z=C*2,B=C*3):i==="RGB"?(k=0,d=C,z=C*2):i==="RBG"&&(k=0,z=C,d=C*2);for(let V=0;V{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let o,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[1],i=e.dims[3]):(o=e.dims[3],a=e.dims[2],i=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,C;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?C=[0,0,0,0]:typeof p.bias=="number"?C=[p.bias,p.bias,p.bias,p.bias]:(C=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(C[3]=p.bias[3]));let k=a*o;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,z=0,B=1,V=2,Z=3,ee=0,X=k,me=k*2,pe=-1;u==="RGBA"?(ee=0,X=k,me=k*2,pe=k*3):u==="RGB"?(ee=0,X=k,me=k*2):u==="RBG"&&(ee=0,me=k,X=k*2),n=s.createImageData(o,a);for(let Me=0;Me{Ue(),re=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:n}=t,o=t.norm??{mean:255,bias:0},a,i;typeof o.mean=="number"?a=[o.mean,o.mean,o.mean,o.mean]:a=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=s*n,C=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),k=4,d=0,z=1,B=2,V=3,Z=0,ee=h,X=h*2,me=-1;u==="RGB"&&(k=3,d=0,z=1,B=2,V=-1),p==="RGBA"?me=h*3:p==="RBG"?(Z=0,X=h,ee=h*2):p==="BGR"&&(X=0,ee=h,Z=h*2);for(let pe=0;pe{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,u=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=C=>typeof HTMLCanvasElement<"u"&&C instanceof HTMLCanvasElement||C instanceof OffscreenCanvas?C.getContext("2d"):null;if(s){let C=p();C.width=e.width,C.height=e.height;let k=h(C);if(k!=null){let d=e.height,z=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,z=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=d,u.width=z}else u.tensorFormat="RGBA",u.height=d,u.width=z;k.drawImage(e,0,0),i=k.getImageData(0,0,z,d).data}else throw new Error("Can not access image data")}else if(n){let C,k;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(C=t.resizedHeight,k=t.resizedWidth):(C=e.height,k=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=C,u.width=k,t!==void 0){let d=p();d.width=k,d.height=C;let z=h(d);if(z!=null)z.putImageData(e,0,0),i=z.getImageData(0,0,k,C).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let C=p();C.width=e.width,C.height=e.height;let k=h(C);if(k!=null){let d=e.height,z=e.width;return k.drawImage(e,0,0,z,d),i=k.getImageData(0,0,z,d).data,u.height=d,u.width=z,re(i,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((C,k)=>{let d=p(),z=h(d);if(!e||!z)return k();let B=new Image;B.crossOrigin="Anonymous",B.src=e,B.onload=()=>{d.width=B.width,d.height=B.height,z.drawImage(B,0,0,d.width,d.height);let V=z.getImageData(0,0,d.width,d.height);u.height=d.height,u.width=d.width,C(re(V.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return re(i,u);throw new Error("Input data provided is not supported - aborted tensor creation")},ce=(e,t)=>{let{width:s,height:n,download:o,dispose:a}=t,i=[1,n,s,4];return new Ke({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:a})},Se=(e,t)=>{let{dataType:s,dims:n,download:o,dispose:a}=t;return new Ke({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:o,dispose:a})},Ie=(e,t)=>{let{dataType:s,dims:n,download:o,dispose:a}=t;return new Ke({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:o,dispose:a})},Ee=(e,t,s)=>new Ke({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Ge,ye,J,de,Ce=g(()=>{Ge=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ye=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),J=!1,de=()=>{if(!J){J=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(Ge.set("int64",BigInt64Array),ye.set(BigInt64Array,"int64")),t&&(Ge.set("uint64",BigUint64Array),ye.set(BigUint64Array,"uint64")),s?(Ge.set("float16",Float16Array),ye.set(Float16Array,"float16")):Ge.set("float16",Uint16Array)}}}),Be,Je,te=g(()=>{Ue(),Be=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Ke(e.type,e.data,t);case"cpu-pinned":return new Ke({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ke({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ke({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ke({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ke,Ue=g(()=>{we(),tt(),Ce(),te(),Ke=class{constructor(e,t,s){de();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Ge.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,u;if(typeof e=="string")if(n=e,u=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let p=Ge.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?i=p.from(t,BigInt):i=p.from(t)}else if(t instanceof p)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${p}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof e[0];if(p==="string")n="string",i=e;else if(p==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let p=ye.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,i=e}if(u===void 0)u=[i.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");o=u,this.cpuData=i,this.dataLocation="cpu"}let a=Be(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,t){return xe(e,t)}static fromTexture(e,t){return ce(e,t)}static fromGpuBuffer(e,t){return Se(e,t)}static fromMLTensor(e,t){return Ie(e,t)}static fromPinnedBuffer(e,t,s){return Ee(e,t,s)}toDataURL(e){return oe(this,e)}toImageData(e){return Te(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 Je(this,e)}}}),le,be=g(()=>{Ue(),le=Ke}),Ve,We,Ne,je,st=g(()=>{T(),Ve=(e,t)=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||console.timeStamp(`${e}::ORT::${t}`)},We=(e,t)=>{var o;let s=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||We("BEGIN",e)},je=e=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||We("END",e)}}),ut,pt=g(()=>{W(),be(),st(),ut=class t_{constructor(t){this.handler=t}async run(t,s,n){Ne();let o={},a={};if(typeof t!="object"||t===null||t instanceof le||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof le)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);o[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,C=Object.getOwnPropertyNames(s);for(let k of this.outputNames)if(C.indexOf(k)!==-1){let d=s[k];(d===null||d instanceof le)&&(h=!0,i=!1,o[k]=d)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(i)for(let h of this.outputNames)o[h]=null;let u=await this.handler.run(t,o,a),p={};for(let h in u)if(Object.hasOwnProperty.call(u,h)){let C=u[h];C instanceof le?p[h]=C:p[h]=new le(C.type,C.data,C.dims)}return je(),p}async release(){return this.handler.dispose()}static async create(t,s,n,o){Ne();let a,i={};if(typeof t=="string"){if(a=t,typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let C=t,k=0,d=t.byteLength;if(typeof s=="object"&&s!==null)i=s;else if(typeof s=="number"){if(k=s,!Number.isSafeInteger(k))throw new RangeError("'byteOffset' must be an integer.");if(k<0||k>=C.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${C.byteLength}).`);if(d=t.byteLength-k,typeof n=="number"){if(d=n,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||k+d>C.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${C.byteLength-k}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(C,k,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,p]=await ne(i),h=await u.createInferenceSessionHandler(a,p);return je(),new t_(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),lt,mt=g(()=>{pt(),lt=ut}),L=g(()=>{}),ie=g(()=>{}),G=g(()=>{}),he=g(()=>{}),ke={};v(ke,{InferenceSession:()=>lt,TRACE:()=>Ve,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>je,Tensor:()=>le,env:()=>O,registerBackend:()=>H});var Re=g(()=>{U(),ae(),mt(),be(),L(),ie(),st(),G(),he()}),qe=g(()=>{}),at={};v(at,{default:()=>kt});var ct,vt,kt,$t=g(()=>{var e;vh(),ar(),jr(),ct="ort-wasm-proxy-worker",vt=((e=globalThis.self)==null?void 0:e.name)===ct,vt&&(self.onmessage=t=>{let{type:s,in:n}=t.data;try{switch(s){case"init-wasm":Ir(n.wasm).then(()=>{Yn(n).then(()=>{postMessage({type:s})},o=>{postMessage({type:s,err:o})})},o=>{postMessage({type:s,err:o})});break;case"init-ep":{let{epName:o,env:a}=n;zo(a,o).then(()=>{postMessage({type:s})},i=>{postMessage({type:s,err:i})});break}case"copy-from":{let{buffer:o}=n,a=kn(o);postMessage({type:s,out:a});break}case"create":{let{model:o,options:a}=n;Ac(o,a).then(i=>{postMessage({type:s,out:i})},i=>{postMessage({type:s,err:i})});break}case"release":Ic(n),postMessage({type:s});break;case"run":{let{sessionId:o,inputIndices:a,inputs:i,outputIndices:u,options:p}=n;Yr(o,a,i,u,new Array(u.length).fill(null),p).then(h=>{h.some(C=>C[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:h},qp([...i,...h]))},h=>{postMessage({type:s,err:h})});break}case"end-profiling":mr(n),postMessage({type:s});break;default:}}catch(o){postMessage({type:s,err:o})}}),kt=vt?null:t=>new Worker(t??Us,{type:"module",name:ct})}),os={};v(os,{default:()=>Ls});var Ms,ks,Ls,sr=g(()=>{var e;ks=(Ms=self.location.href,async function(t={}){function s(){return wt.buffer!=Ut.buffer&&Cs(),Ut}function n(){return wt.buffer!=Ut.buffer&&Cs(),Qt}function o(){return wt.buffer!=Ut.buffer&&Cs(),gs}function a(){return wt.buffer!=Ut.buffer&&Cs(),it}function i(){return wt.buffer!=Ut.buffer&&Cs(),Et}function u(){return wt.buffer!=Ut.buffer&&Cs(),hs}function p(){return wt.buffer!=Ut.buffer&&Cs(),Ns}function h(){return wt.buffer!=Ut.buffer&&Cs(),mn}var C,k,d=Object.assign({},t),z=new Promise((l,m)=>{C=l,k=m}),B=typeof window=="object",V=typeof importScripts=="function",Z=V&&self.name=="em-pthread";d.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(d.Fb||(d.Fb=new Map)).set(l,m)},d.unmountExternalData=()=>{delete d.Fb};var ee=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let X=()=>{let l=(E,D,K)=>(...ge)=>{let Ye=gn,nt=D==null?void 0:D();ge=E(...ge);let yt=D==null?void 0:D();return nt!==yt&&(E=yt,K(nt),D=K=null),gn!=Ye?new Promise((Ct,Vt)=>{mh={resolve:Ct,reject:Vt}}):ge},m=E=>async(...D)=>{var K;try{if(d.Gb)throw Error("Session already started");let ge=d.Gb={hc:D[0],errors:[]},Ye=await E(...D);if(d.Gb!==ge)throw Error("Session mismatch");(K=d.Hb)==null||K.flush();let nt=ge.errors;if(0Ct),0d._OrtCreateSession,E=>d._OrtCreateSession=E),d._OrtRun=m(l(d._OrtRun,()=>d._OrtRun,E=>d._OrtRun=E)),d._OrtRunWithBinding=m(l(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,E=>d._OrtRunWithBinding=E)),d._OrtBindInput=l(d._OrtBindInput,()=>d._OrtBindInput,E=>d._OrtBindInput=E),X=void 0};d.jsepInit=(l,m)=>{if(X==null||X(),l==="webgpu"){[d.Hb,d.Vb,d.Zb,d.Ob,d.Yb,d.kb,d.$b,d.cc,d.Wb,d.Xb,d.ac]=m;let E=d.Hb;d.jsepRegisterBuffer=(D,K,ge,Ye)=>E.registerBuffer(D,K,ge,Ye),d.jsepGetBuffer=D=>E.getBuffer(D),d.jsepCreateDownloader=(D,K,ge)=>E.createDownloader(D,K,ge),d.jsepOnCreateSession=D=>{E.onCreateSession(D)},d.jsepOnReleaseSession=D=>{E.onReleaseSession(D)},d.jsepOnRunStart=D=>E.onRunStart(D),d.dc=(D,K)=>{E.upload(D,K)}}else if(l==="webnn"){[d.Hb,d.bc,d.Pb,d.jsepEnsureTensor,d.ec,d.jsepDownloadTensor]=m,d.jsepReleaseTensorId=d.Pb;let E=d.Hb;d.jsepOnRunStart=D=>E.onRunStart(D),d.jsepRegisterMLContext=(D,K)=>{E.registerMLContext(D,K)},d.jsepOnReleaseSession=D=>{E.onReleaseSession(D)},d.jsepCreateMLTensorDownloader=(D,K)=>E.createMLTensorDownloader(D,K),d.jsepRegisterMLTensor=(D,K,ge)=>E.registerMLTensor(D,K,ge),d.jsepCreateMLContext=D=>E.createMLContext(D),d.jsepRegisterMLConstant=(D,K,ge,Ye,nt)=>E.registerMLConstant(D,K,ge,Ye,nt,d.Fb)}};var me,pe,Me=Object.assign({},d),Ae=(l,m)=>{throw m},De="";(B||V)&&(V?De=self.location.href:typeof document<"u"&&document.currentScript&&(De=document.currentScript.src),Ms&&(De=Ms),De=De.startsWith("blob:")?"":De.substr(0,De.replace(/[?#].*/,"").lastIndexOf("/")+1),V&&(pe=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),me=(l,m,E)=>{var D=new XMLHttpRequest;D.open("GET",l,!0),D.responseType="arraybuffer",D.onload=()=>{D.status==200||D.status==0&&D.response?m(D.response):E()},D.onerror=E,D.send(null)});var et,dt=console.log.bind(console),Pt=console.error.bind(console),qt=dt,Bt=Pt;if(Object.assign(d,Me),Me=null,Z){let l=function(m){try{var E=m.data,D=E.cmd;if(D==="load"){let K=[];self.onmessage=ge=>K.push(ge),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ge of K)l(ge);self.onmessage=l};for(let ge of E.handlers)d[ge]&&!d[ge].proxy||(d[ge]=(...Ye)=>{postMessage({Nb:"callHandler",pc:ge,args:Ye})},ge=="print"&&(qt=d[ge]),ge=="printErr"&&(Bt=d[ge]));wt=E.wasmMemory,Cs(),It(E.wasmModule)}else if(D==="run"){wh(E.pthread_ptr,0,0,1,0,0),ph(E.pthread_ptr),w_(),Kh(),ts||(Vm(),ts=!0);try{y_(E.start_routine,E.arg)}catch(K){if(K!="unwind")throw K}}else D==="cancel"?Ra()&&jp(-1):E.target!=="setimmediate"&&(D==="checkMailbox"?ts&&Ap():D&&(Bt(`worker: received unknown command ${D}`),Bt(E)))}catch(K){throw Wm(),K}};var It,ts=!1;Bt=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:Ra()})},d.instantiateWasm=(m,E)=>new Promise(D=>{It=K=>{K=new WebAssembly.Instance(K,jh()),E(K),D()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}d.wasmBinary&&(et=d.wasmBinary);var wt,Ht,ps,Ut,Qt,gs,it,Et,hs,Ns,qs,Lr,mn,zr=!1;function Cs(){var l=wt.buffer;d.HEAP8=Ut=new Int8Array(l),d.HEAP16=gs=new Int16Array(l),d.HEAPU8=Qt=new Uint8Array(l),d.HEAPU16=it=new Uint16Array(l),d.HEAP32=Et=new Int32Array(l),d.HEAPU32=hs=new Uint32Array(l),d.HEAPF32=Ns=new Float32Array(l),d.HEAPF64=mn=new Float64Array(l),d.HEAP64=qs=new BigInt64Array(l),d.HEAPU64=Lr=new BigUint64Array(l)}if(!Z){if(!((wt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof ee))throw Bt("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");Cs()}var Js=[],Sn=[],Zp=[],No=0,Lc=null;function Lh(){if(--No==0&&Lc){var l=Lc;Lc=null,l()}}function Zn(l){throw Bt(l="Aborted("+l+")"),zr=!0,ps=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),k(l),l}var eh,zh=l=>l.startsWith("data:application/octet-stream;base64,"),Bh=l=>l.startsWith("file://");function Rh(l){if(l==eh&&et)return new Uint8Array(et);if(pe)return pe(l);throw"both async and sync fetching of the wasm failed"}function Nh(l,m,E){return function(D){if(!et&&(B||V)){if(typeof fetch=="function"&&!Bh(D))return fetch(D,{credentials:"same-origin"}).then(K=>{if(!K.ok)throw`failed to load wasm binary file at '${D}'`;return K.arrayBuffer()}).catch(()=>Rh(D));if(me)return new Promise((K,ge)=>{me(D,Ye=>K(new Uint8Array(Ye)),ge)})}return Promise.resolve().then(()=>Rh(D))}(l).then(D=>WebAssembly.instantiate(D,m)).then(E,D=>{Bt(`failed to asynchronously prepare wasm: ${D}`),Zn(D)})}function jh(){return{a:{O:g_,Aa:f_,b:b_,aa:Xh,B:Zh,qa:em,Y:sm,_:rm,ra:nm,oa:om,ha:im,na:am,L:lm,Z:um,W:dm,pa:cm,X:pm,va:v_,F:T_,Q:x_,P:E_,E:k_,u:S_,q:$_,G:A_,A:B_,R:R_,ua:N_,ka:j_,U:U_,ba:V_,H:W_,ja:ph,ta:G_,t:K_,Ba:H_,x:X_,o:Y_,m:Z_,c:dh,n:ef,k:rf,w:nf,p:of,f:af,s:lf,l:uf,e:df,j:cf,i:pf,g:hf,d:mf,ea:_f,fa:ff,ga:gf,ca:Em,da:Cm,T:wf,h:yf,D:Mf,I:bf,M:vf,y:Tf,sa:xf,V:Pf,v:Sm,z:Ef,N:Cf,S:kf,za:Sf,ya:$f,la:Im,ma:Om,$:oh,C:Fm,K:Dm,ia:Lm,J:zm,a:wt,xa:nh,wa:Nm,r:Of}}}var th={916868:(l,m,E,D,K)=>{if(d===void 0||!d.Fb)return 1;if((l=Qs(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=d.Fb.get(l)))return 2;if(m=Number(m>>>0),E=Number(E>>>0),D=Number(D>>>0),m+E>l.byteLength)return 3;try{let ge=l.subarray(m,m+E);switch(K){case 0:n().set(ge,D>>>0);break;case 1:d.dc(D,ge);break;default:return 4}return 0}catch{return 4}},917583:(l,m,E)=>{d.ec(l,n().subarray(m>>>0,m+E>>>0))},917646:()=>d.bc(),917687:l=>{d.Pb(l)},917723:()=>{d.Wb()},917754:()=>{d.Xb()},917783:()=>{d.ac()},917808:l=>d.Vb(l),917841:l=>d.Zb(l),917873:(l,m,E)=>{d.Ob(Number(l),Number(m),Number(E),!0)},917936:(l,m,E)=>{d.Ob(Number(l),Number(m),Number(E))},917993:()=>typeof wasmOffsetConverter<"u",918050:l=>{d.kb("Abs",l,void 0)},918101:l=>{d.kb("Neg",l,void 0)},918152:l=>{d.kb("Floor",l,void 0)},918205:l=>{d.kb("Ceil",l,void 0)},918257:l=>{d.kb("Reciprocal",l,void 0)},918315:l=>{d.kb("Sqrt",l,void 0)},918367:l=>{d.kb("Exp",l,void 0)},918418:l=>{d.kb("Erf",l,void 0)},918469:l=>{d.kb("Sigmoid",l,void 0)},918524:(l,m,E)=>{d.kb("HardSigmoid",l,{alpha:m,beta:E})},918603:l=>{d.kb("Log",l,void 0)},918654:l=>{d.kb("Sin",l,void 0)},918705:l=>{d.kb("Cos",l,void 0)},918756:l=>{d.kb("Tan",l,void 0)},918807:l=>{d.kb("Asin",l,void 0)},918859:l=>{d.kb("Acos",l,void 0)},918911:l=>{d.kb("Atan",l,void 0)},918963:l=>{d.kb("Sinh",l,void 0)},919015:l=>{d.kb("Cosh",l,void 0)},919067:l=>{d.kb("Asinh",l,void 0)},919120:l=>{d.kb("Acosh",l,void 0)},919173:l=>{d.kb("Atanh",l,void 0)},919226:l=>{d.kb("Tanh",l,void 0)},919278:l=>{d.kb("Not",l,void 0)},919329:(l,m,E)=>{d.kb("Clip",l,{min:m,max:E})},919398:l=>{d.kb("Clip",l,void 0)},919450:(l,m)=>{d.kb("Elu",l,{alpha:m})},919508:l=>{d.kb("Gelu",l,void 0)},919560:l=>{d.kb("Relu",l,void 0)},919612:(l,m)=>{d.kb("LeakyRelu",l,{alpha:m})},919676:(l,m)=>{d.kb("ThresholdedRelu",l,{alpha:m})},919746:(l,m)=>{d.kb("Cast",l,{to:m})},919804:l=>{d.kb("Add",l,void 0)},919855:l=>{d.kb("Sub",l,void 0)},919906:l=>{d.kb("Mul",l,void 0)},919957:l=>{d.kb("Div",l,void 0)},920008:l=>{d.kb("Pow",l,void 0)},920059:l=>{d.kb("Equal",l,void 0)},920112:l=>{d.kb("Greater",l,void 0)},920167:l=>{d.kb("GreaterOrEqual",l,void 0)},920229:l=>{d.kb("Less",l,void 0)},920281:l=>{d.kb("LessOrEqual",l,void 0)},920340:(l,m,E,D,K)=>{d.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},920515:(l,m,E,D,K)=>{d.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},920689:(l,m,E,D,K)=>{d.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},920863:(l,m,E,D,K)=>{d.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},921038:(l,m,E,D,K)=>{d.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},921212:(l,m,E,D,K)=>{d.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},921385:(l,m,E,D,K)=>{d.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},921558:(l,m,E,D,K)=>{d.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},921735:(l,m,E,D,K)=>{d.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},921915:(l,m,E,D,K)=>{d.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},922095:l=>{d.kb("Where",l,void 0)},922148:(l,m,E)=>{d.kb("Transpose",l,{perm:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[]})},922272:(l,m,E,D)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Qs(E),format:D?"NHWC":"NCHW"})},922405:(l,m,E,D)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Qs(E),format:D?"NHWC":"NCHW"})},922538:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He,ls)=>{d.kb("ConvTranspose",l,{format:yt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:D,kernelShape:[K],pads:[ge,Ye],strides:[nt],wIsConst:()=>!!s()[Ct>>>0],outputPadding:Vt?Array.from(i().subarray(Number(Vt)>>>0,Number(ms)>>>0)):[],outputShape:vs?Array.from(i().subarray(Number(vs)>>>0,Number(He)>>>0)):[],activation:Qs(ls)})},922971:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:D,kernelShape:Array.from(i().subarray(Number(K)>>>0,2+(Number(K)>>>0)>>>0)),pads:Array.from(i().subarray(Number(ge)>>>0,4+(Number(ge)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Ye)>>>0,2+(Number(Ye)>>>0)>>>0)),wIsConst:()=>!!s()[yt>>>0],outputPadding:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],outputShape:ms?Array.from(i().subarray(Number(ms)>>>0,Number(vs)>>>0)):[],activation:Qs(He)})},923632:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He,ls)=>{d.kb("ConvTranspose",l,{format:yt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:D,kernelShape:[K],pads:[ge,Ye],strides:[nt],wIsConst:()=>!!s()[Ct>>>0],outputPadding:Vt?Array.from(i().subarray(Number(Vt)>>>0,Number(ms)>>>0)):[],outputShape:vs?Array.from(i().subarray(Number(vs)>>>0,Number(He)>>>0)):[],activation:Qs(ls)})},924065:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:D,kernelShape:Array.from(i().subarray(Number(K)>>>0,2+(Number(K)>>>0)>>>0)),pads:Array.from(i().subarray(Number(ge)>>>0,4+(Number(ge)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Ye)>>>0,2+(Number(Ye)>>>0)>>>0)),wIsConst:()=>!!s()[yt>>>0],outputPadding:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],outputShape:ms?Array.from(i().subarray(Number(ms)>>>0,Number(vs)>>>0)):[],activation:Qs(He)})},924726:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},924817:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:K,dilations:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Ye)>>>0)):[],kernel_shape:nt?Array.from(i().subarray(Number(nt)>>>0,Number(yt)>>>0)):[],pads:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],strides:ms?Array.from(i().subarray(Number(ms)>>>0,Number(vs)>>>0)):[]})},925296:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},925387:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:K,dilations:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Ye)>>>0)):[],kernel_shape:nt?Array.from(i().subarray(Number(nt)>>>0,Number(yt)>>>0)):[],pads:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],strides:ms?Array.from(i().subarray(Number(ms)>>>0,Number(vs)>>>0)):[]})},925866:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},925953:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:K,dilations:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Ye)>>>0)):[],kernel_shape:nt?Array.from(i().subarray(Number(nt)>>>0,Number(yt)>>>0)):[],pads:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],strides:ms?Array.from(i().subarray(Number(ms)>>>0,Number(vs)>>>0)):[]})},926428:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},926515:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:K,dilations:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Ye)>>>0)):[],kernel_shape:nt?Array.from(i().subarray(Number(nt)>>>0,Number(yt)>>>0)):[],pads:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],strides:ms?Array.from(i().subarray(Number(ms)>>>0,Number(vs)>>>0)):[]})},926990:(l,m,E,D,K)=>{d.kb("Gemm",l,{alpha:m,beta:E,transA:D,transB:K})},927094:l=>{d.kb("MatMul",l,void 0)},927148:(l,m,E,D)=>{d.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!E,axis:D})},927256:(l,m,E,D)=>{d.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!E,axis:D})},927364:(l,m)=>{d.kb("Softmax",l,{axis:m})},927427:(l,m)=>{d.kb("Concat",l,{axis:m})},927487:(l,m,E,D,K)=>{d.kb("Split",l,{axis:m,numOutputs:E,splitSizes:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},927643:l=>{d.kb("Expand",l,void 0)},927697:(l,m)=>{d.kb("Gather",l,{axis:Number(m)})},927768:(l,m)=>{d.kb("GatherElements",l,{axis:Number(m)})},927847:(l,m)=>{d.kb("GatherND",l,{batch_dims:Number(m)})},927926:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt)=>{d.kb("Resize",l,{antialias:m,axes:E?Array.from(i().subarray(Number(E)>>>0,Number(D)>>>0)):[],coordinateTransformMode:Qs(K),cubicCoeffA:ge,excludeOutside:Ye,extrapolationValue:nt,keepAspectRatioPolicy:Qs(yt),mode:Qs(Ct),nearestMode:Qs(Vt)})},928288:(l,m,E,D,K,ge,Ye)=>{d.kb("Slice",l,{starts:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[],ends:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[],axes:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Ye)>>>0)):[]})},928552:l=>{d.kb("Tile",l,void 0)},928604:(l,m,E)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},928718:(l,m,E)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},928832:l=>{d.kb("Range",l,void 0)},928885:(l,m)=>{d.kb("Einsum",l,{equation:Qs(m)})},928966:(l,m,E,D,K)=>{d.kb("Pad",l,{mode:m,value:E,pads:D?Array.from(i().subarray(Number(D)>>>0,Number(K)>>>0)):[]})},929109:(l,m,E,D,K,ge)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!K,trainingMode:!!D,format:ge?"NHWC":"NCHW"})},929278:(l,m,E,D,K,ge)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!K,trainingMode:!!D,format:ge?"NHWC":"NCHW"})},929447:(l,m,E)=>{d.kb("CumSum",l,{exclusive:Number(m),reverse:Number(E)})},929544:(l,m,E)=>{d.kb("DequantizeLinear",l,{axis:m,blockSize:E})},929634:(l,m,E,D,K)=>{d.kb("GridSample",l,{align_corners:m,mode:Qs(E),padding_mode:Qs(D),format:K?"NHWC":"NCHW"})},929804:(l,m,E,D,K)=>{d.kb("GridSample",l,{align_corners:m,mode:Qs(E),padding_mode:Qs(D),format:K?"NHWC":"NCHW"})},929974:(l,m,E,D,K,ge,Ye,nt,yt)=>{d.kb("Attention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:D,scale:K,doRotary:ge,qkvHiddenSizes:Ye?Array.from(i().subarray(Number(nt)>>>0,Number(nt)+Ye>>>0)):[],pastPresentShareBuffer:!!yt})},930246:l=>{d.kb("BiasAdd",l,void 0)},930301:l=>{d.kb("BiasSplitGelu",l,void 0)},930362:l=>{d.kb("FastGelu",l,void 0)},930418:(l,m,E,D,K,ge,Ye,nt,yt,Ct,Vt,ms,vs,He,ls,js)=>{d.kb("Conv",l,{format:ms?"NHWC":"NCHW",auto_pad:m,dilations:E?Array.from(i().subarray(Number(E)>>>0,Number(D)>>>0)):[],group:K,kernel_shape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Ye)>>>0)):[],pads:nt?Array.from(i().subarray(Number(nt)>>>0,Number(yt)>>>0)):[],strides:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],w_is_const:()=>!!s()[Number(vs)>>>0],activation:Qs(He),activation_params:ls?Array.from(p().subarray(Number(ls)>>>0,Number(js)>>>0)):[]})},931002:l=>{d.kb("Gelu",l,void 0)},931054:(l,m,E,D,K,ge,Ye,nt,yt)=>{d.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:E,scale:D,softcap:K,doRotary:ge,rotaryInterleaved:Ye,smoothSoftmax:nt,localWindowSize:yt})},931271:(l,m,E,D)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!D})},931382:(l,m,E,D)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!D})},931493:(l,m,E,D,K,ge)=>{d.kb("MatMulNBits",l,{k:m,n:E,accuracyLevel:D,bits:K,blockSize:ge})},931620:(l,m,E,D,K,ge)=>{d.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:D,scale:K,doRotary:ge})},931779:(l,m)=>{d.kb("QuickGelu",l,{alpha:m})},931843:(l,m,E,D,K)=>{d.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:E,rotaryEmbeddingDim:D,scale:K})},931982:(l,m,E)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},932084:(l,m,E)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},932186:(l,m,E,D)=>{d.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:E,blockSize:D})},932307:l=>{d.$b(l)},932341:(l,m)=>d.cc(Number(l),Number(m),d.Gb.hc,d.Gb.errors)};function f_(l,m,E){return bm(async()=>{await d.Yb(Number(l),Number(m),Number(E))})}function g_(){return typeof wasmOffsetConverter<"u"}function sh(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var rh=l=>{l.terminate(),l.onmessage=()=>{}},Uh=l=>{eo.length==0&&(qh(),Hh(eo[0]));var m=eo.pop();if(!m)return 6;Uo.push(m),_n[l.Bb]=m,m.Bb=l.Bb;var E={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(E,l.nc),0},jo=0,Rs=(l,m,...E)=>{for(var D=2*E.length,K=bh(),ge=Mh(8*D),Ye=ge>>>3,nt=0;nt>>0]=yt)}return l=Gm(l,0,D,ge,m),Up(K),l};function nh(l){if(Z)return Rs(0,1,l);if(ps=l,!(0{if(ps=l,Z)throw Vh(l),"unwind";nh(l)},eo=[],Uo=[],Wh=[],_n={},Gh=l=>{var m=l.Bb;delete _n[m],eo.push(l),Uo.splice(Uo.indexOf(l),1),l.Bb=0,yh(m)};function Kh(){Wh.forEach(l=>l())}var Hh=l=>new Promise(m=>{l.onmessage=K=>{var ge=(K=K.data).cmd;if(K.targetThread&&K.targetThread!=Ra()){var Ye=_n[K.targetThread];Ye?Ye.postMessage(K,K.transferList):Bt(`Internal error! Worker sent a message "${ge}" to target pthread ${K.targetThread}, but that thread no longer exists!`)}else ge==="checkMailbox"?Ap():ge==="spawnThread"?Uh(K):ge==="cleanupThread"?Gh(_n[K.thread]):ge==="killThread"?(K=K.thread,ge=_n[K],delete _n[K],rh(ge),yh(K),Uo.splice(Uo.indexOf(ge),1),ge.Bb=0):ge==="cancelThread"?_n[K.thread].postMessage({cmd:"cancel"}):ge==="loaded"?(l.loaded=!0,m(l)):ge==="alert"?alert(`Thread ${K.threadId}: ${K.text}`):K.target==="setimmediate"?l.postMessage(K):ge==="callHandler"?d[K.handler](...K.args):ge&&Bt(`worker sent an unknown command ${ge}`)},l.onerror=K=>{throw Bt(`worker sent an error! ${K.filename}:${K.lineno}: ${K.message}`),K};var E,D=[];for(E of[])d.hasOwnProperty(E)&&D.push(E);l.postMessage({cmd:"load",handlers:D,wasmMemory:wt,wasmModule:Ht})});function qh(){var l=new Worker(self.location.href.startsWith("file:")?new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b):new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});eo.push(l)}var $p=l=>{for(;0{var l=Ra(),m=u()[l+52>>>2>>>0];l=u()[l+56>>>2>>>0],Hm(m,m-l),Up(m)},y_=(l,m)=>{jo=0,l=qm(l,m),0>>=0);throw m>>>=0,E>>>=0,u()[D.Kb+16>>>2>>>0]=0,u()[D.Kb+4>>>2>>>0]=m,u()[D.Kb+8>>>2>>>0]=E,l}function Qh(l,m,E,D){return Z?Rs(2,1,l,m,E,D):Xh(l,m,E,D)}function Xh(l,m,E,D){if(l>>>=0,m>>>=0,E>>>=0,D>>>=0,ee===void 0)return Bt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var K=[];return Z&&K.length===0?Qh(l,m,E,D):(l={ic:E,Bb:l,Rb:D,nc:K},Z?(l.Nb="spawnThread",postMessage(l,K),0):Uh(l))}var Yh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Jh=(l,m,E)=>{var D=(m>>>=0)+E;for(E=m;l[E]&&!(E>=D);)++E;if(16(K=(240&K)==224?(15&K)<<12|ge<<6|Ye:(7&K)<<18|ge<<12|Ye<<6|63&l[m++])?D+=String.fromCharCode(K):(K-=65536,D+=String.fromCharCode(55296|K>>10,56320|1023&K))}}else D+=String.fromCharCode(K)}return D},Qs=(l,m)=>(l>>>=0)?Jh(n(),l,m):"";function Zh(l,m,E){return Z?Rs(3,1,l,m,E):0}function em(l,m){if(Z)return Rs(4,1,l,m)}var ih=l=>{for(var m=0,E=0;E=D?m++:2047>=D?m+=2:55296<=D&&57343>=D?(m+=4,++E):m+=3}return m},tm=(l,m,E,D)=>{if(!(0>>=0;D=E+D-1;for(var ge=0;ge=Ye&&(Ye=65536+((1023&Ye)<<10)|1023&l.charCodeAt(++ge)),127>=Ye){if(E>=D)break;m[E++>>>0]=Ye}else{if(2047>=Ye){if(E+1>=D)break;m[E++>>>0]=192|Ye>>6}else{if(65535>=Ye){if(E+2>=D)break;m[E++>>>0]=224|Ye>>12}else{if(E+3>=D)break;m[E++>>>0]=240|Ye>>18,m[E++>>>0]=128|Ye>>12&63}m[E++>>>0]=128|Ye>>6&63}m[E++>>>0]=128|63&Ye}}return m[E>>>0]=0,E-K},za=(l,m,E)=>tm(l,n(),m,E);function sm(l,m){if(Z)return Rs(5,1,l,m)}function rm(l,m,E){if(Z)return Rs(6,1,l,m,E)}function nm(l,m,E){return Z?Rs(7,1,l,m,E):0}function om(l,m){if(Z)return Rs(8,1,l,m)}function im(l,m,E){if(Z)return Rs(9,1,l,m,E)}function am(l,m,E,D){if(Z)return Rs(10,1,l,m,E,D)}function lm(l,m,E,D){if(Z)return Rs(11,1,l,m,E,D)}function um(l,m,E,D){if(Z)return Rs(12,1,l,m,E,D)}function dm(l){if(Z)return Rs(13,1,l)}function cm(l,m){if(Z)return Rs(14,1,l,m)}function pm(l,m,E){if(Z)return Rs(15,1,l,m,E)}var hm,to,v_=()=>{Zn("")},fn=l=>{for(var m="";n()[l>>>0];)m+=hm[n()[l++>>>0]];return m},ah={},lh={};function $n(l,m,E={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(D,K,ge={}){var Ye=K.name;if(!D)throw new to(`type "${Ye}" must have a positive integer typeid pointer`);if(lh.hasOwnProperty(D)){if(ge.Tb)return;throw new to(`Cannot register type '${Ye}' twice`)}lh[D]=K,ah.hasOwnProperty(D)&&(K=ah[D],delete ah[D],K.forEach(nt=>nt()))}(l,m,E)}var mm=(l,m,E)=>{switch(m){case 1:return E?D=>s()[D>>>0]:D=>n()[D>>>0];case 2:return E?D=>o()[D>>>1>>>0]:D=>a()[D>>>1>>>0];case 4:return E?D=>i()[D>>>2>>>0]:D=>u()[D>>>2>>>0];case 8:return E?D=>qs[D>>>3]:D=>Lr[D>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function T_(l,m,E){E>>>=0,$n(l>>>=0,{name:m=fn(m>>>0),fromWireType:D=>D,toWireType:function(D,K){if(typeof K!="bigint"&&typeof K!="number")throw K=K===null?"null":(D=typeof K)=="object"||D==="array"||D==="function"?K.toString():""+K,new TypeError(`Cannot convert "${K}" to ${this.name}`);return typeof K=="number"&&(K=BigInt(K)),K},argPackAdvance:so,readValueFromPointer:mm(m,E,m.indexOf("u")==-1),Eb:null})}var so=8;function x_(l,m,E,D){$n(l>>>=0,{name:m=fn(m>>>0),fromWireType:function(K){return!!K},toWireType:function(K,ge){return ge?E:D},argPackAdvance:so,readValueFromPointer:function(K){return this.fromWireType(n()[K>>>0])},Eb:null})}var uh=[],An=[];function dh(l){9<(l>>>=0)&&--An[l+1]==0&&(An[l]=void 0,uh.push(l))}var Cr=l=>{if(!l)throw new to("Cannot use deleted val. handle = "+l);return An[l]},Br=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=uh.pop()||An.length;return An[m]=l,An[m+1]=1,m}};function ch(l){return this.fromWireType(u()[l>>>2>>>0])}var P_={name:"emscripten::val",fromWireType:l=>{var m=Cr(l);return dh(l),m},toWireType:(l,m)=>Br(m),argPackAdvance:so,readValueFromPointer:ch,Eb:null};function E_(l){return $n(l>>>0,P_)}var C_=(l,m)=>{switch(m){case 4:return function(E){return this.fromWireType(p()[E>>>2>>>0])};case 8:return function(E){return this.fromWireType(h()[E>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function k_(l,m,E){E>>>=0,$n(l>>>=0,{name:m=fn(m>>>0),fromWireType:D=>D,toWireType:(D,K)=>K,argPackAdvance:so,readValueFromPointer:C_(m,E),Eb:null})}function S_(l,m,E,D,K){if(l>>>=0,E>>>=0,m=fn(m>>>0),K===-1&&(K=4294967295),K=nt=>nt,D===0){var ge=32-8*E;K=nt=>nt<>>ge}var Ye=m.includes("unsigned")?function(nt,yt){return yt>>>0}:function(nt,yt){return yt};$n(l,{name:m,fromWireType:K,toWireType:Ye,argPackAdvance:so,readValueFromPointer:mm(m,E,D!==0),Eb:null})}function $_(l,m,E){function D(ge){var Ye=u()[ge>>>2>>>0];return ge=u()[ge+4>>>2>>>0],new K(s().buffer,ge,Ye)}var K=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];$n(l>>>=0,{name:E=fn(E>>>0),fromWireType:D,argPackAdvance:so,readValueFromPointer:D},{Tb:!0})}function A_(l,m){l>>>=0;var E=(m=fn(m>>>0))==="std::string";$n(l,{name:m,fromWireType:function(D){var K=u()[D>>>2>>>0],ge=D+4;if(E)for(var Ye=ge,nt=0;nt<=K;++nt){var yt=ge+nt;if(nt==K||n()[yt>>>0]==0){if(Ye=Qs(Ye,yt-Ye),Ct===void 0)var Ct=Ye;else Ct+="\0",Ct+=Ye;Ye=yt+1}}else{for(Ct=Array(K),nt=0;nt>>0]);Ct=Ct.join("")}return wn(D),Ct},toWireType:function(D,K){K instanceof ArrayBuffer&&(K=new Uint8Array(K));var ge=typeof K=="string";if(!(ge||K instanceof Uint8Array||K instanceof Uint8ClampedArray||K instanceof Int8Array))throw new to("Cannot pass non-string to std::string");var Ye=E&&ge?ih(K):K.length,nt=Np(4+Ye+1),yt=nt+4;if(u()[nt>>>2>>>0]=Ye,E&&ge)za(K,yt,Ye+1);else if(ge)for(ge=0;ge>>0]=Ct}else for(ge=0;ge>>0]=K[ge];return D!==null&&D.push(wn,nt),nt},argPackAdvance:so,readValueFromPointer:ch,Eb(D){wn(D)}})}var _m=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,I_=(l,m)=>{for(var E=l>>1,D=E+m/2;!(E>=D)&&a()[E>>>0];)++E;if(32<(E<<=1)-l&&_m)return _m.decode(n().slice(l,E));for(E="",D=0;!(D>=m/2);++D){var K=o()[l+2*D>>>1>>>0];if(K==0)break;E+=String.fromCharCode(K)}return E},O_=(l,m,E)=>{if(E??(E=2147483647),2>E)return 0;var D=m;E=(E-=2)<2*l.length?E/2:l.length;for(var K=0;K>>1>>>0]=ge,m+=2}return o()[m>>>1>>>0]=0,m-D},F_=l=>2*l.length,D_=(l,m)=>{for(var E=0,D="";!(E>=m/4);){var K=i()[l+4*E>>>2>>>0];if(K==0)break;++E,65536<=K?(K-=65536,D+=String.fromCharCode(55296|K>>10,56320|1023&K)):D+=String.fromCharCode(K)}return D},L_=(l,m,E)=>{if(m>>>=0,E??(E=2147483647),4>E)return 0;var D=m;E=D+E-4;for(var K=0;K=ge&&(ge=65536+((1023&ge)<<10)|1023&l.charCodeAt(++K)),i()[m>>>2>>>0]=ge,(m+=4)+4>E)break}return i()[m>>>2>>>0]=0,m-D},z_=l=>{for(var m=0,E=0;E=D&&++E,m+=4}return m};function B_(l,m,E){if(l>>>=0,m>>>=0,E=fn(E>>>=0),m===2)var D=I_,K=O_,ge=F_,Ye=nt=>a()[nt>>>1>>>0];else m===4&&(D=D_,K=L_,ge=z_,Ye=nt=>u()[nt>>>2>>>0]);$n(l,{name:E,fromWireType:nt=>{for(var yt,Ct=u()[nt>>>2>>>0],Vt=nt+4,ms=0;ms<=Ct;++ms){var vs=nt+4+ms*m;ms!=Ct&&Ye(vs)!=0||(Vt=D(Vt,vs-Vt),yt===void 0?yt=Vt:(yt+="\0",yt+=Vt),Vt=vs+m)}return wn(nt),yt},toWireType:(nt,yt)=>{if(typeof yt!="string")throw new to(`Cannot pass non-string to C++ string type ${E}`);var Ct=ge(yt),Vt=Np(4+Ct+m);return u()[Vt>>>2>>>0]=Ct/m,K(yt,Vt+4,Ct+m),nt!==null&&nt.push(wn,Vt),Vt},argPackAdvance:so,readValueFromPointer:ch,Eb(nt){wn(nt)}})}function R_(l,m){$n(l>>>=0,{Ub:!0,name:m=fn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var N_=()=>1;function j_(l){wh(l>>>0,!V,1,!B,131072,!1),Kh()}var fm=l=>{if(!zr)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(i(),l>>>2,l).value.then(Ap),l+=128,Atomics.store(i(),l>>>2,1))}var Ap=()=>{var l=Ra();l&&(ph(l),fm(Km))};function U_(l,m){(l>>>=0)==m>>>0?setTimeout(Ap):Z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=_n[l])&&l.postMessage({cmd:"checkMailbox"})}var hh=[];function V_(l,m,E,D,K){for(m>>>=0,D/=2,hh.length=D,E=K>>>0>>>3,K=0;K>>0];return(m?th[m]:Ff[l])(...hh)}function W_(l){l>>>=0,Z?postMessage({cmd:"cleanupThread",thread:l}):Gh(_n[l])}function G_(l){}var Ip=(l,m)=>{var E=lh[l];if(E===void 0)throw l=Um(l),E=fn(l),wn(l),new to(`${m} has unknown type ${E}`);return E},gm=(l,m,E)=>{var D=[];return l=l.toWireType(D,E),D.length&&(u()[m>>>2>>>0]=Br(D)),l};function K_(l,m,E){return m>>>=0,E>>>=0,l=Cr(l>>>0),m=Ip(m,"emval::as"),gm(m,E,l)}function H_(l,m){return m>>>=0,l=Cr(l>>>0),(m=Ip(m,"emval::as")).toWireType(null,l)}var Op=l=>{try{l()}catch(m){Zn(m)}},ro=0,gn=null,wm=0,Fp=[],ym={},Mm={},q_=0,mh=null,Q_=[];function bm(l){return function(m){if(!zr){if(ro===0){var E=!1,D=!1;m((K=0)=>{if(!zr&&(wm=K,E=!0,D)){ro=2,Op(()=>Ym(gn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),K=!1;try{var ge=function(){var yt=i()[gn+8>>>2>>>0];return yt=jt[Mm[yt]],--jo,yt()}()}catch(yt){ge=yt,K=!0}var Ye=!1;if(!gn){var nt=mh;nt&&(mh=null,(K?nt.reject:nt.resolve)(ge),Ye=!0)}if(K&&!Ye)throw ge}}),D=!0,E||(ro=1,gn=function(){var K=Np(65548),ge=K+12;u()[K>>>2>>>0]=ge,u()[K+4>>>2>>>0]=ge+65536,ge=Fp[0];var Ye=ym[ge];return Ye===void 0&&(Ye=q_++,ym[ge]=Ye,Mm[Ye]=ge),ge=Ye,i()[K+8>>>2>>>0]=ge,K}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Op(()=>Qm(gn)))}else ro===2?(ro=0,Op(Jm),wn(gn),gn=null,Q_.forEach(fm)):Zn(`invalid state: ${ro}`);return wm}}(m=>{l().then(m)})}function X_(l){return l>>>=0,bm(()=>(l=Cr(l)).then(Br))}var Dp=[];function Y_(l,m,E,D){return E>>>=0,D>>>=0,(l=Dp[l>>>0])(null,m=Cr(m>>>0),E,D)}var J_={},Lp=l=>{var m=J_[l];return m===void 0?fn(l):m};function Z_(l,m,E,D,K){return E>>>=0,D>>>=0,K>>>=0,(l=Dp[l>>>0])(m=Cr(m>>>0),m[E=Lp(E)],D,K)}var vm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function ef(l){return(l>>>=0)==0?Br(vm()):(l=Lp(l),Br(vm()[l]))}var tf=l=>{var m=Dp.length;return Dp.push(l),m},sf=(l,m)=>{for(var E=Array(l),D=0;D>>2>>>0],"parameter "+D);return E},Tm=(l,m)=>Object.defineProperty(m,"name",{value:l});function rf(l,m,E){var D=(m=sf(l,m>>>0)).shift();l--;var K=`return function (obj, func, destructorsRef, args) { +`,ge=0,Ye=[];E===0&&Ye.push("obj");for(var nt=["retType"],yt=[D],Ct=0;CtVt.name).join(", ")}) => ${D.name}>`,tf(Tm(E,l))}function nf(l){return l=Lp(l>>>0),Br(d[l])}function of(l,m){return m>>>=0,l=Cr(l>>>0),m=Cr(m),Br(l[m])}function af(l){9<(l>>>=0)&&(An[l+1]+=1)}function lf(){return Br([])}function uf(l){l=Cr(l>>>0);for(var m=Array(l.length),E=0;E>>0))}function cf(){return Br({})}function pf(l){for(var m=Cr(l>>>=0);m.length;){var E=m.pop();m.pop()(E)}dh(l)}function hf(l,m,E){m>>>=0,E>>>=0,l=Cr(l>>>0),m=Cr(m),E=Cr(E),l[m]=E}function mf(l,m){return m>>>=0,l=(l=Ip(l>>>0,"_emval_take_value")).readValueFromPointer(m),Br(l)}function _f(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getUTCSeconds(),i()[m+4>>>2>>>0]=l.getUTCMinutes(),i()[m+8>>>2>>>0]=l.getUTCHours(),i()[m+12>>>2>>>0]=l.getUTCDate(),i()[m+16>>>2>>>0]=l.getUTCMonth(),i()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,i()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[m+28>>>2>>>0]=l}var Ba=l=>l%4==0&&(l%100!=0||l%400==0),xm=[0,31,60,91,121,152,182,213,244,274,305,335],Pm=[0,31,59,90,120,151,181,212,243,273,304,334];function ff(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getSeconds(),i()[m+4>>>2>>>0]=l.getMinutes(),i()[m+8>>>2>>>0]=l.getHours(),i()[m+12>>>2>>>0]=l.getDate(),i()[m+16>>>2>>>0]=l.getMonth(),i()[m+20>>>2>>>0]=l.getFullYear()-1900,i()[m+24>>>2>>>0]=l.getDay();var E=(Ba(l.getFullYear())?xm:Pm)[l.getMonth()]+l.getDate()-1|0;i()[m+28>>>2>>>0]=E,i()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),E=new Date(l.getFullYear(),6,1).getTimezoneOffset();var D=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(E!=D&&l.getTimezoneOffset()==Math.min(D,E)),i()[m+32>>>2>>>0]=l}function gf(l){l>>>=0;var m=new Date(i()[l+20>>>2>>>0]+1900,i()[l+16>>>2>>>0],i()[l+12>>>2>>>0],i()[l+8>>>2>>>0],i()[l+4>>>2>>>0],i()[l>>>2>>>0],0),E=i()[l+32>>>2>>>0],D=m.getTimezoneOffset(),K=new Date(m.getFullYear(),6,1).getTimezoneOffset(),ge=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Ye=Math.min(ge,K);return 0>E?i()[l+32>>>2>>>0]=+(K!=ge&&Ye==D):0>>2>>>0]=m.getDay(),E=(Ba(m.getFullYear())?xm:Pm)[m.getMonth()]+m.getDate()-1|0,i()[l+28>>>2>>>0]=E,i()[l>>>2>>>0]=m.getSeconds(),i()[l+4>>>2>>>0]=m.getMinutes(),i()[l+8>>>2>>>0]=m.getHours(),i()[l+12>>>2>>>0]=m.getDate(),i()[l+16>>>2>>>0]=m.getMonth(),i()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function Em(l,m,E,D,K,ge,Ye){return Z?Rs(16,1,l,m,E,D,K,ge,Ye):-52}function Cm(l,m,E,D,K,ge){if(Z)return Rs(17,1,l,m,E,D,K,ge)}function wf(l,m,E,D){l>>>=0,m>>>=0,E>>>=0,D>>>=0;var K=new Date().getFullYear(),ge=new Date(K,0,1),Ye=new Date(K,6,1);K=ge.getTimezoneOffset();var nt=Ye.getTimezoneOffset(),yt=Math.max(K,nt);u()[l>>>2>>>0]=60*yt,i()[m>>>2>>>0]=+(K!=nt),ge=(l=Ct=>Ct.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ge),Ye=l(Ye),nt{_h.length=0;for(var E;E=n()[l++>>>0];){var D=E!=105;m+=(D&=E!=112)&&m%8?4:0,_h.push(E==112?u()[m>>>2>>>0]:E==106?qs[m>>>3]:E==105?i()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=D?8:4}return _h};function yf(l,m,E){return l>>>=0,m=km(m>>>0,E>>>0),th[l](...m)}function Mf(l,m,E){return l>>>=0,m=km(m>>>0,E>>>0),th[l](...m)}var bf=()=>{},vf=()=>Date.now();function Tf(l,m){return Bt(Qs(l>>>0,m>>>0))}var Sm,xf=()=>{throw jo+=1,"unwind"};function Pf(){return 4294901760}Sm=()=>performance.timeOrigin+performance.now();var Ef=()=>navigator.hardwareConcurrency;function Cf(){return Zn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function kf(l){l>>>=0;var m=n().length;if(l<=m||4294901760=E;E*=2){var D=m*(1+.2/E);D=Math.min(D,l+100663296);var K=Math;D=Math.max(l,D);e:{K=(K.min.call(K,4294901760,D+(65536-D%65536)%65536)-wt.buffer.byteLength+65535)/65536;try{wt.grow(K),Cs();var ge=1;break e}catch{}ge=void 0}if(ge)return!0}return!1}var zp=()=>(Zn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),zc={},$m=l=>{l.forEach(m=>{zp()})};function Sf(){var l=Error().stack.toString().split(` +`);return l[0]=="Error"&&l.shift(),$m(l),zc.Qb=zp(),zc.fc=l,zc.Qb}function $f(l,m,E){if(l>>>=0,m>>>=0,zc.Qb==l)var D=zc.fc;else(D=Error().stack.toString().split(` +`))[0]=="Error"&&D.shift(),$m(D);for(var K=3;D[K]&&zp()!=l;)++K;for(l=0;l>>2>>>0]=zp();return l}var fh,gh={},Am=()=>{if(!fh){var l,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(l in gh)gh[l]===void 0?delete m[l]:m[l]=gh[l];var E=[];for(l in m)E.push(`${l}=${m[l]}`);fh=E}return fh};function Im(l,m){if(Z)return Rs(18,1,l,m);l>>>=0,m>>>=0;var E=0;return Am().forEach((D,K)=>{var ge=m+E;for(K=u()[l+4*K>>>2>>>0]=ge,ge=0;ge>>0]=D.charCodeAt(ge);s()[K>>>0]=0,E+=D.length+1}),0}function Om(l,m){if(Z)return Rs(19,1,l,m);l>>>=0,m>>>=0;var E=Am();u()[l>>>2>>>0]=E.length;var D=0;return E.forEach(K=>D+=K.length+1),u()[m>>>2>>>0]=D,0}function Fm(l){return Z?Rs(20,1,l):52}function Dm(l,m,E,D){return Z?Rs(21,1,l,m,E,D):52}function Lm(l,m,E,D){return Z?Rs(22,1,l,m,E,D):70}var Af=[null,[],[]];function zm(l,m,E,D){if(Z)return Rs(23,1,l,m,E,D);m>>>=0,E>>>=0,D>>>=0;for(var K=0,ge=0;ge>>2>>>0],nt=u()[m+4>>>2>>>0];m+=8;for(var yt=0;yt>>0],Vt=Af[l];Ct===0||Ct===10?((l===1?qt:Bt)(Jh(Vt,0)),Vt.length=0):Vt.push(Ct)}K+=nt}return u()[D>>>2>>>0]=K,0}var Bm=[31,29,31,30,31,30,31,31,30,31,30,31],Rm=[31,28,31,30,31,30,31,31,30,31,30,31],If=(l,m)=>{s().set(l,m>>>0)};function Nm(l,m,E,D){function K(He,ls,js){for(He=typeof He=="number"?He.toString():He||"";He.lengthe_?-1:0Vo-He.getDate())){He.setDate(He.getDate()+ls);break}ls-=Vo-He.getDate()+1,He.setDate(1),11>js?He.setMonth(js+1):(He.setMonth(0),He.setFullYear(He.getFullYear()+1))}return js=new Date(He.getFullYear()+1,0,4),ls=nt(new Date(He.getFullYear(),0,4)),js=nt(js),0>=Ye(ls,He)?0>=Ye(js,He)?He.getFullYear()+1:He.getFullYear():He.getFullYear()-1}l>>>=0,m>>>=0,E>>>=0,D>>>=0;var Ct=u()[D+40>>>2>>>0];for(var Vt in D={lc:i()[D>>>2>>>0],kc:i()[D+4>>>2>>>0],Ib:i()[D+8>>>2>>>0],Mb:i()[D+12>>>2>>>0],Jb:i()[D+16>>>2>>>0],Db:i()[D+20>>>2>>>0],vb:i()[D+24>>>2>>>0],Cb:i()[D+28>>>2>>>0],sc:i()[D+32>>>2>>>0],jc:i()[D+36>>>2>>>0],mc:Ct?Qs(Ct):""},E=Qs(E),Ct={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})E=E.replace(new RegExp(Vt,"g"),Ct[Vt]);var ms="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),vs="January February March April May June July August September October November December".split(" ");for(Vt in Ct={"%a":He=>ms[He.vb].substring(0,3),"%A":He=>ms[He.vb],"%b":He=>vs[He.Jb].substring(0,3),"%B":He=>vs[He.Jb],"%C":He=>ge((He.Db+1900)/100|0,2),"%d":He=>ge(He.Mb,2),"%e":He=>K(He.Mb,2," "),"%g":He=>yt(He).toString().substring(2),"%G":yt,"%H":He=>ge(He.Ib,2),"%I":He=>((He=He.Ib)==0?He=12:12{for(var ls=0,js=0;js<=He.Jb-1;ls+=(Ba(He.Db+1900)?Bm:Rm)[js++]);return ge(He.Mb+ls,3)},"%m":He=>ge(He.Jb+1,2),"%M":He=>ge(He.kc,2),"%n":()=>` +`,"%p":He=>0<=He.Ib&&12>He.Ib?"AM":"PM","%S":He=>ge(He.lc,2),"%t":()=>" ","%u":He=>He.vb||7,"%U":He=>ge(Math.floor((He.Cb+7-He.vb)/7),2),"%V":He=>{var ls=Math.floor((He.Cb+7-(He.vb+6)%7)/7);if(2>=(He.vb+371-He.Cb-2)%7&&ls++,ls)ls==53&&((js=(He.vb+371-He.Cb)%7)==4||js==3&&Ba(He.Db)||(ls=1));else{ls=52;var js=(He.vb+7-He.Cb-1)%7;(js==4||js==5&&Ba(He.Db%400-1))&&ls++}return ge(ls,2)},"%w":He=>He.vb,"%W":He=>ge(Math.floor((He.Cb+7-(He.vb+6)%7)/7),2),"%y":He=>(He.Db+1900).toString().substring(2),"%Y":He=>He.Db+1900,"%z":He=>{var ls=0<=(He=He.jc);return He=Math.abs(He)/60,(ls?"+":"-")+("0000"+(He/60*100+He%60)).slice(-4)},"%Z":He=>He.mc,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0"),Ct)E.includes(Vt)&&(E=E.replace(new RegExp(Vt,"g"),Ct[Vt](D)));return Vt=function(He){var ls=Array(ih(He)+1);return tm(He,ls,0,ls.length),ls}(E=E.replace(/\0\0/g,"%")),Vt.length>m?0:(If(Vt,l),Vt.length-1)}function Of(l,m,E,D){return Nm(l>>>0,m>>>0,E>>>0,D>>>0)}Z||function(){for(var l=d.numThreads-1;l--;)qh();Js.unshift(()=>{No++,function(m){Z?m():Promise.all(eo.map(Hh)).then(m)}(()=>Lh())})}();for(var jm=Array(256),Bp=0;256>Bp;++Bp)jm[Bp]=String.fromCharCode(Bp);hm=jm,to=d.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},d.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},An.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>An.length/2-5-uh.length;var Ff=[nh,Vh,Qh,Zh,em,sm,rm,nm,om,im,am,lm,um,dm,cm,pm,Em,Cm,Im,Om,Fm,Dm,Lm,zm],jt=function(){function l(E,D){return jt=E.exports,jt=function(){var K=jt,ge={};for(let[Ye,nt]of Object.entries(K))ge[Ye]=typeof nt=="function"?(...yt)=>{Fp.push(Ye);try{return nt(...yt)}finally{zr||(Fp.pop(),gn&&ro===1&&Fp.length===0&&(ro=0,jo+=1,Op(Xm),typeof Fibers<"u"&&Fibers.tc()))}}:nt;return ge}(),jt=function(){var K=jt,ge=nt=>yt=>nt(yt)>>>0,Ye=nt=>()=>nt()>>>0;return(K=Object.assign({},K)).Da=ge(K.Da),K.gb=Ye(K.gb),K.ib=ge(K.ib),K.emscripten_main_runtime_thread_id=Ye(K.emscripten_main_runtime_thread_id),K.tb=ge(K.tb),K.ub=Ye(K.ub),K}(),Wh.push(jt.jb),Sn.unshift(jt.Ca),Ht=D,Lh(),jt}var m=jh();if(No++,d.instantiateWasm)try{return d.instantiateWasm(m,l)}catch(E){Bt(`Module.instantiateWasm callback failed with error: ${E}`),k(E)}return eh||(eh=d.locateFile?zh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":d.locateFile?d.locateFile("ort-wasm-simd-threaded.jsep.wasm",De):De+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(E,D){var K=eh;return et||typeof WebAssembly.instantiateStreaming!="function"||zh(K)||Bh(K)||typeof fetch!="function"?Nh(K,E,D):fetch(K,{credentials:"same-origin"}).then(ge=>WebAssembly.instantiateStreaming(ge,E).then(D,function(Ye){return Bt(`wasm streaming compile failed: ${Ye}`),Bt("falling back to ArrayBuffer instantiation"),Nh(K,E,D)}))}(m,function(E){l(E.instance,E.module)}).catch(k),{}}(),Um=l=>(Um=jt.Da)(l),Vm=()=>(Vm=jt.Ea)();d._OrtInit=(l,m)=>(d._OrtInit=jt.Fa)(l,m),d._OrtGetLastError=(l,m)=>(d._OrtGetLastError=jt.Ga)(l,m),d._OrtCreateSessionOptions=(l,m,E,D,K,ge,Ye,nt,yt,Ct)=>(d._OrtCreateSessionOptions=jt.Ha)(l,m,E,D,K,ge,Ye,nt,yt,Ct),d._OrtAppendExecutionProvider=(l,m)=>(d._OrtAppendExecutionProvider=jt.Ia)(l,m),d._OrtAddFreeDimensionOverride=(l,m,E)=>(d._OrtAddFreeDimensionOverride=jt.Ja)(l,m,E),d._OrtAddSessionConfigEntry=(l,m,E)=>(d._OrtAddSessionConfigEntry=jt.Ka)(l,m,E),d._OrtReleaseSessionOptions=l=>(d._OrtReleaseSessionOptions=jt.La)(l),d._OrtCreateSession=(l,m,E)=>(d._OrtCreateSession=jt.Ma)(l,m,E),d._OrtReleaseSession=l=>(d._OrtReleaseSession=jt.Na)(l),d._OrtGetInputOutputCount=(l,m,E)=>(d._OrtGetInputOutputCount=jt.Oa)(l,m,E),d._OrtGetInputName=(l,m)=>(d._OrtGetInputName=jt.Pa)(l,m),d._OrtGetOutputName=(l,m)=>(d._OrtGetOutputName=jt.Qa)(l,m),d._OrtFree=l=>(d._OrtFree=jt.Ra)(l),d._OrtCreateTensor=(l,m,E,D,K,ge)=>(d._OrtCreateTensor=jt.Sa)(l,m,E,D,K,ge),d._OrtGetTensorData=(l,m,E,D,K)=>(d._OrtGetTensorData=jt.Ta)(l,m,E,D,K),d._OrtReleaseTensor=l=>(d._OrtReleaseTensor=jt.Ua)(l),d._OrtCreateRunOptions=(l,m,E,D)=>(d._OrtCreateRunOptions=jt.Va)(l,m,E,D),d._OrtAddRunConfigEntry=(l,m,E)=>(d._OrtAddRunConfigEntry=jt.Wa)(l,m,E),d._OrtReleaseRunOptions=l=>(d._OrtReleaseRunOptions=jt.Xa)(l),d._OrtCreateBinding=l=>(d._OrtCreateBinding=jt.Ya)(l),d._OrtBindInput=(l,m,E)=>(d._OrtBindInput=jt.Za)(l,m,E),d._OrtBindOutput=(l,m,E,D)=>(d._OrtBindOutput=jt._a)(l,m,E,D),d._OrtClearBoundOutputs=l=>(d._OrtClearBoundOutputs=jt.$a)(l),d._OrtReleaseBinding=l=>(d._OrtReleaseBinding=jt.ab)(l),d._OrtRunWithBinding=(l,m,E,D,K)=>(d._OrtRunWithBinding=jt.bb)(l,m,E,D,K),d._OrtRun=(l,m,E,D,K,ge,Ye,nt)=>(d._OrtRun=jt.cb)(l,m,E,D,K,ge,Ye,nt),d._OrtEndProfiling=l=>(d._OrtEndProfiling=jt.db)(l),d._JsepOutput=(l,m,E)=>(d._JsepOutput=jt.eb)(l,m,E),d._JsepGetNodeName=l=>(d._JsepGetNodeName=jt.fb)(l);var Rp,Ra=()=>(Ra=jt.gb)(),wn=d._free=l=>(wn=d._free=jt.hb)(l),Np=d._malloc=l=>(Np=d._malloc=jt.ib)(l),wh=(l,m,E,D,K,ge)=>(wh=jt.lb)(l,m,E,D,K,ge),Wm=()=>(Wm=jt.mb)(),Gm=(l,m,E,D,K)=>(Gm=jt.nb)(l,m,E,D,K),yh=l=>(yh=jt.ob)(l),jp=l=>(jp=jt.pb)(l),Km=()=>(Km=jt.qb)(),Hm=(l,m)=>(Hm=jt.rb)(l,m),Up=l=>(Up=jt.sb)(l),Mh=l=>(Mh=jt.tb)(l),bh=()=>(bh=jt.ub)(),qm=d.dynCall_ii=(l,m)=>(qm=d.dynCall_ii=jt.wb)(l,m),Qm=l=>(Qm=jt.xb)(l),Xm=()=>(Xm=jt.yb)(),Ym=l=>(Ym=jt.zb)(l),Jm=()=>(Jm=jt.Ab)();function Zm(){0bh(),d.stackRestore=l=>Up(l),d.stackAlloc=l=>Mh(l),d.setValue=function(l,m,E="i8"){switch(E.endsWith("*")&&(E="*"),E){case"i1":case"i8":s()[l>>>0]=m;break;case"i16":o()[l>>>1>>>0]=m;break;case"i32":i()[l>>>2>>>0]=m;break;case"i64":qs[l>>>3]=BigInt(m);break;case"float":p()[l>>>2>>>0]=m;break;case"double":h()[l>>>3>>>0]=m;break;case"*":u()[l>>>2>>>0]=m;break;default:Zn(`invalid type for setValue: ${E}`)}},d.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return s()[l>>>0];case"i16":return o()[l>>>1>>>0];case"i32":return i()[l>>>2>>>0];case"i64":return qs[l>>>3];case"float":return p()[l>>>2>>>0];case"double":return h()[l>>>3>>>0];case"*":return u()[l>>>2>>>0];default:Zn(`invalid type for getValue: ${m}`)}},d.UTF8ToString=Qs,d.stringToUTF8=za,d.lengthBytesUTF8=ih,Lc=function l(){Rp||Zm(),Rp||(Lc=l)},Zm(),d.PTR_SIZE=4,z}),Ls=ks,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&ks()}),kr,Zr,Us,Tr,Nt,en,Sr,$r,tn,cr,Rr,Ar,Nr,jr=g(()=>{qe(),kr=typeof location>"u"?void 0:location.origin,Zr=()=>{var e;return(e=self.location.href)!=null&&e.startsWith("file:")?new URL(new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b).href,kr).href:self.location.href},Us=Zr(),Tr=()=>{if(Us&&!Us.startsWith("blob:"))return Us.substring(0,Us.lastIndexOf("/")+1)},Nt=(e,t)=>{try{let s=t??Us;return(s?new URL(e,s):new URL(e)).origin===kr}catch{return!1}},en=(e,t)=>{let s=t??Us;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},Sr=(e,t)=>`${t??"./"}${e}`,$r=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},tn=async e=>(await import(e)).default,cr=($t(),y(at)).default,Rr=async()=>{if(!Us)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nt(Us))return[void 0,cr()];let e=await $r(Us);return[e,cr(e)]},Ar=(sr(),y(os)).default,Nr=async(e,t,s)=>{if(!e&&!t&&Ar&&Us&&Nt(Us))return[void 0,Ar];{let n="ort-wasm-simd-threaded.jsep.mjs",o=e??en(n,t),a=s&&o&&!Nt(o,t),i=a?await $r(o):o??Sr(n,t);return[a?i:void 0,await tn(i)]}}}),ir,ot,Tt,Ft,Vs,Ur,Ir,bs,ar=g(()=>{jr(),ot=!1,Tt=!1,Ft=!1,Vs=()=>{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}},Ur=()=>{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}},Ir=async e=>{if(ot)return Promise.resolve();if(Tt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ft)throw new Error("previous call to 'initializeWebAssembly()' failed.");Tt=!0;let t=e.initTimeout,s=e.numThreads;if(!Ur())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Vs();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=s=1);let o=e.wasmPaths,a=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,u=(i==null?void 0:i.href)??i,p=o==null?void 0:o.wasm,h=(p==null?void 0:p.href)??p,C=e.wasmBinary,[k,d]=await Nr(u,a,s>1),z=!1,B=[];if(t>0&&B.push(new Promise(V=>{setTimeout(()=>{z=!0,V()},t)})),B.push(new Promise((V,Z)=>{let ee={numThreads:s};if(C)ee.wasmBinary=C;else if(h||a)ee.locateFile=X=>h??a+X;else if(u&&u.indexOf("blob:")!==0)ee.locateFile=X=>new URL(X,u).href;else if(k){let X=Tr();X&&(ee.locateFile=me=>X+me)}d(ee).then(X=>{Tt=!1,ot=!0,ir=X,V(),k&&URL.revokeObjectURL(k)},X=>{Tt=!1,Ft=!0,Z(X)})})),await Promise.race(B),z)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},bs=()=>{if(ot&&ir)return ir;throw new Error("WebAssembly is not initialized yet.")}}),Os,xr,ss,yn=g(()=>{ar(),Os=(e,t)=>{let s=bs(),n=s.lengthBytesUTF8(e)+1,o=s._malloc(n);return s.stringToUTF8(e,o,n),t.push(o),o},xr=(e,t,s,n)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([o,a])=>{let i=t?t+o:o;if(typeof a=="object")xr(a,i+".",s,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},ss=e=>{let t=bs(),s=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let a=Number(t.getValue(o,n===4?"i32":"i64")),i=t.getValue(o+n,"*"),u=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(s)}}}),Vr,oo=g(()=>{ar(),yn(),Vr=e=>{let t=bs(),s=0,n=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(o.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Os(e.tag,n)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,a),s===0&&ss("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&xr(e.extra,"",new WeakSet,(i,u)=>{let p=Os(i,n),h=Os(u,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&ss(`Can't set a run config entry: ${i} - ${u}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(i=>t._free(i)),a}}}),In,On,Fn,Wr,Dn,io=g(()=>{ar(),yn(),In=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}`)}},On=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Fn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},Wr=(e,t,s)=>{for(let n of t){let o=typeof n=="string"?n:n.name;switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let u=Os("deviceType",s),p=Os(i,s);bs()._OrtAddSessionConfigEntry(e,u,p)!==0&&ss(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(o="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let u=Os("preferredLayout",s),p=Os(i.preferredLayout,s);bs()._OrtAddSessionConfigEntry(e,u,p)!==0&&ss(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let a=Os(o,s);bs()._OrtAppendExecutionProvider(e,a)!==0&&ss(`Can't append execution provider: ${o}.`)}},Dn=e=>{let t=bs(),s=0,n=[],o=e||{};Fn(o);try{let a=In(o.graphOptimizationLevel??"all"),i=On(o.executionMode??"sequential"),u=typeof o.logId=="string"?Os(o.logId,n):0,p=o.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=o.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let C=typeof o.optimizedModelFilePath=="string"?Os(o.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(a,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,u,p,h,C),s===0&&ss("Can't create session options."),o.executionProviders&&Wr(s,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let k=Os("enableGraphCapture",n),d=Os(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,k,d)!==0&&ss(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[k,d]of Object.entries(o.freeDimensionOverrides)){if(typeof k!="string")throw new Error(`free dimension override name must be a string: ${k}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let z=Os(k,n);t._OrtAddFreeDimensionOverride(s,z,d)!==0&&ss(`Can't set a free dimension override: ${k} - ${d}.`)}return o.extra!==void 0&&xr(o.extra,"",new WeakSet,(k,d)=>{let z=Os(k,n),B=Os(d,n);t._OrtAddSessionConfigEntry(s,z,B)!==0&&ss(`Can't set a session config entry: ${k} - ${d}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&ss("Can't release session options."),n.forEach(i=>t._free(i)),a}}}),Gr,_r,lr,Mn,sn,bn,vn,Tn,Lt=g(()=>{Gr=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}`)}},_r=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}`)}},lr=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((o,a)=>o*a,1);return s>0?Math.ceil(n*s):void 0},Mn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},sn=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}`)}},bn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",vn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Tn=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}`)}}}),xn,Ln=g(()=>{qe(),xn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let p=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw u}let i=0;for(;;){let{done:u,value:p}=await o.read();if(u)break;let h=p.byteLength;new Uint8Array(a,i,h).set(p),i+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),zn,Bn,Kr,Rn,Pn,Nn,is,Pe=g(()=>{Lt(),zn=["V","I","W","E","F"],Bn=(e,t)=>{console.log(`[${zn[e]},${new Date().toISOString()}]${t}`)},Pn=(e,t)=>{Kr=e,Rn=t},Nn=(e,t)=>{let s=sn(e),n=sn(Kr);s>=n&&Bn(s,typeof t=="function"?t():t)},is=(...e)=>{Rn&&Nn(...e)}}),P,Q=g(()=>{Lt(),P=(e,t)=>new(Mn(t))(e)}),ue=g(()=>{}),ve,$e,Xe,ht,gt,_t,xt,Kt,_s,us=g(()=>{Pe(),ue(),ve=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]]),$e=[],Xe=e=>Math.ceil(Number(e)/16)*16,ht=e=>{for(let t=0;t<$e.length;t++){let s=$e[t];if(e<=s)return s}return Math.ceil(e/16)*16},gt=1,_t=()=>gt++,xt=async(e,t,s,n)=>{let o=Xe(s),a=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,o),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(u,0,s)),p}else return new Uint8Array(u.slice(0,s))}finally{a.destroy()}},Kt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of ve)$e.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,o=t.byteLength,a=Xe(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=u.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,o)),u.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(u,0,i.gpuData.buffer,0,a),this.backend.device.queue.submit([h.finish()]),u.destroy(),is("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=Xe(s.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(s.gpuData.buffer,0,n.gpuData.buffer,0,o)}registerExternalBuffer(e,t,s){let n;if(s){if(n=s[0],e===s[1])return is("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else n=_t();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),is("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),is("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=ht(e),n,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||a){let u=(o?this.freeBuffers:this.freeUniformBuffers).get(s);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:s,usage:t}):n=this.backend.device.createBuffer({size:s,usage:t})}else n=this.backend.device.createBuffer({size:s,usage:t});let i={id:_t(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),is("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return is("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await xt(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=ve.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(is("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},_s=(...e)=>new Kt(...e)}),Fs,zt,rs=g(()=>{Fs=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}},zt=e=>new Fs(e)}),rr,Ws,ze,Zs,Or,Ss,Xs,Ot=g(()=>{rr=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Ws=class{static calcShape(e,t,s=!1){let n=e.length,o=t.length;if(n===0)return t;if(o===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(s){if(n<2||o<2)return;let u=rr.calcMatMulShape([e[n-2],e[n-1]],[t[o-2],t[o-1]]);if(u===void 0)return;[i[a-2],i[a-1]]=u}for(let u=s?3:1;u<=a;u++){let p=n-u<0?1:e[n-u],h=o-u<0?1:t[o-u];if(p!==h&&p>1&&h>1)return;let C=Math.max(p,h);if(p&&h)i[a-u]=Math.max(p,h);else{if(C>1)return;i[a-u]=0}}return i}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let o=1;o<=s;o++)if(e[s-o]!==1&&e[s-o]!==t[n-o])return!1;return!0}},ze=class Vp{static size(t){return Vp.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let n=t.length;if(n===0)return[];let o=new Array(n),a=n-1;for(;a>=0;){if(t[a]%s===0){o[a]=t[a]/s;break}if(s%t[a]!==0)throw new Error("cannot convert shape");o[a]=1,s/=t[a],a--}for(a--;a>=0;a--)o[a]=t[a];return o}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Vp.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Vp.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,n){let o=1;for(let a=s;a=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(n=>this.normalizeAxis(n,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(n=>t[n]):t.slice().reverse()}static padShape(t,s){let n=t.length;return t.map((o,a)=>o+s[a]+s[a+n])}static areEqual(t,s){return t.length!==s.length?!1:t.every((n,o)=>n===s[o])}},Zs=class Bc{static adjustPoolAttributes(t,s,n,o,a,i){if(!t&&n.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(s[u+2]):n[u]=s[u+2];for(let u=0;u=n[u]||i[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,n,o,a,i,u){if(u){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{Lt(),Ot(),or=64,fr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},fs=(e,t=1)=>{let s=fr(e,t);return typeof s=="string"?s:s[0]},$s=(e,t=1)=>{let s=fr(e,t);return typeof s=="string"?s:s[1]},Mt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:ze.computeStrides(s)})}),t},Xt=e=>e%4===0?4:e%2===0?2:1,zs=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,As=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,Gs=(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,s,n)=>e.startsWith("uniforms.")&&s>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:s>1?`${e}[${t}]`:e,rn=(e,t,s,n,o)=>{let a=typeof s=="number",i=a?s:s.length,u=[...new Array(i).keys()],p=i<2?"u32":i<=4?`vec${i}`:`array`,h=fr(t,o),C=typeof h=="string"?h:h[1],k=typeof h=="string"?h:h[0],d={indices:p,value:C,storage:k,tensor:t},z=it=>typeof it=="string"?it:`${it}u`,B={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},V=a?"uniforms.":"",Z=`${V}${e}_shape`,ee=`${V}${e}_strides`,X="";for(let it=0;it ${d.indices} { + var indices: ${d.indices}; + var current = offset; + ${X} + return indices; + }`,pe=it=>(B.offsetToIndices=!0,i<2?it:`o2i_${e}(${it})`),Me=[];if(i>=2)for(let it=i-1;it>=0;it--)Me.push(`${St(ee,it,i)} * (indices[${it}])`);let Ae=i<2?"":` + fn i2o_${e}(indices: ${d.indices}) -> u32 { + return ${Me.join("+")}; + }`,De=it=>(B.indicesToOffset=!0,i<2?it:`i2o_${e}(${it})`),et=(...it)=>i===0?"0u":`${d.indices}(${it.map(z).join(",")})`,dt=(it,Et)=>i<2?`${it}`:`${St(it,Et,i)}`,Pt=(it,Et,hs)=>i<2?`${it}=${hs};`:`${St(it,Et,i)}=${hs};`,qt={},Bt=(it,Et)=>{B.broadcastedIndicesToOffset=!0;let hs=`${Et.name}broadcastedIndicesTo${e}Offset`;if(hs in qt)return`${hs}(${it})`;let Ns=[];for(let qs=i-1;qs>=0;qs--){let Lr=Et.indicesGet("outputIndices",qs+Et.rank-i);Ns.push(`${dt(ee,qs)} * (${Lr} % ${dt(Z,qs)})`)}return qt[hs]=`fn ${hs}(outputIndices: ${Et.type.indices}) -> u32 { + return ${Ns.length>0?Ns.join("+"):"0u"}; + }`,`${hs}(${it})`},It=(it,Et)=>(()=>{if(d.storage===d.value)return`${e}[${it}]=${Et};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${it}]=vec2(u32(${Et}), select(0u, 0xFFFFFFFFu, ${Et} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${it}]=vec2(u32(${Et}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${it}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Et}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),ts=it=>(()=>{if(d.storage===d.value)return`${e}[${it}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${it}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${it}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${it}] & 0xFFu), bool(${e}[${it}] & 0xFF00u), bool(${e}[${it}] & 0xFF0000u), bool(${e}[${it}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),wt=i<2?"":` + fn get_${e}ByIndices(indices: ${d.indices}) -> ${C} { + return ${ts(`i2o_${e}(indices)`)}; + }`,Ht=i<2?"":(()=>{let it=u.map(hs=>`d${hs}: u32`).join(", "),Et=u.map(hs=>`d${hs}`).join(", ");return` + fn get_${e}(${it}) -> ${C} { + return get_${e}ByIndices(${et(Et)}); + }`})(),ps=(...it)=>{if(it.length!==i)throw new Error(`indices length must be ${i}`);let Et=it.map(z).join(",");return i===0?ts("0u"):i===1?ts(Et[0]):(B.get=!0,B.getByIndices=!0,B.indicesToOffset=!0,`get_${e}(${Et})`)},Ut=it=>i<2?ts(it):(B.getByIndices=!0,B.indicesToOffset=!0,`get_${e}ByIndices(${it})`),Qt=i<2?"":` + fn set_${e}ByIndices(indices: ${d.indices}, value: ${C}) { + ${It(`i2o_${e}(indices)`,"value")} + }`,gs=i<2?"":(()=>{let it=u.map(hs=>`d${hs}: u32`).join(", "),Et=u.map(hs=>`d${hs}`).join(", ");return` + fn set_${e}(${it}, value: ${C}) { + set_${e}ByIndices(${et(Et)}, value); + }`})();return{impl:()=>{let it=[],Et=!1;return B.offsetToIndices&&(it.push(me),Et=!0),B.indicesToOffset&&(it.push(Ae),Et=!0),B.broadcastedIndicesToOffset&&(Object.values(qt).forEach(hs=>it.push(hs)),Et=!0),B.set&&(it.push(gs),Et=!0),B.setByIndices&&(it.push(Qt),Et=!0),B.get&&(it.push(Ht),Et=!0),B.getByIndices&&(it.push(wt),Et=!0),!a&&Et&&it.unshift(`const ${Z} = ${d.indices}(${s.join(",")});`,`const ${ee} = ${d.indices}(${ze.computeStrides(s).join(",")});`),it.join(` +`)},type:d,offsetToIndices:pe,indicesToOffset:De,broadcastedIndicesToOffset:Bt,indices:et,indicesGet:dt,indicesSet:Pt,set:(...it)=>{if(it.length!==i+1)throw new Error(`indices length must be ${i}`);let Et=it[i];if(typeof Et!="string")throw new Error("value must be string");let hs=it.slice(0,i).map(z).join(",");return i===0?It("0u",Et):i===1?It(hs[0],Et):(B.set=!0,B.setByIndices=!0,B.indicesToOffset=!0,`set_${e}(${hs}, ${Et})`)},setByOffset:It,setByIndices:(it,Et)=>i<2?It(it,Et):(B.setByIndices=!0,B.indicesToOffset=!0,`set_${e}ByIndices(${it}, ${Et});`),get:ps,getByOffset:ts,getByIndices:Ut,usage:n,name:e,strides:ee,shape:Z,rank:i}},Qe=(e,t,s,n=1)=>rn(e,t,s,"input",n),At=(e,t,s,n=1)=>rn(e,t,s,"output",n),Na=(e,t,s)=>rn(e,t,s,"atomicOutput",1),Go=(e,t,s,n=1)=>rn(e,t,s,"internal",n),ja=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=or){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=o?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${n}) + fn main(${a}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let s=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,s=1){return this.uniforms.push({name:e,type:t,length:s}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:s,length:n}of this.uniforms)if(n&&n>4)s==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let o=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${o}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Ua=(e,t)=>new ja(e,t)}),Va,Ko,Ho,Wa,Ga,qo,pr,Ka,Qo,Hr=g(()=>{Lt(),Ot(),rs(),Jt(),Va=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},Ko=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Ho=(e,t)=>ze.sortBasedOnPerm(e,Ko(e.length,t)),Wa=(e,t,s,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`;for(let a=0;a{let s=[],n=[];for(let o=0;o{let s=0;for(let n=0;n{let s=e.dataType,n=e.dims.length,o=Ko(n,t),a=Ho(e.dims,o),i=e.dims,u=a,p=n<2||qo(o,e.dims),h;if(p)return h=B=>{let V=Qe("input",s,i,4),Z=At("output",s,u,4);return` + ${B.registerUniform("output_size","u32").declareVariables(V,Z)} + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let B=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(B/64/4)},programUniforms:[{type:12,data:Math.ceil(B/4)}]}},getShaderSource:h};let{newShape:C,newPerm:k}=Ga(e.dims,o),d=ze.areEqual(k,[2,3,1]),z=ze.areEqual(k,[3,1,2]);if(C.length===2||d||z){i=d?[C[0],C[1]*C[2]]:z?[C[0]*C[1],C[2]]:C,u=[i[1],i[0]];let B=16;return h=V=>{let Z=Qe("a",s,i.length),ee=At("output",s,u.length);return` + ${V.registerUniform("output_size","u32").declareVariables(Z,ee)} + var tile : array, ${B}>; + ${V.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] = ${Z.getByIndices(`${Z.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]) { + ${ee.setByIndices(`${ee.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let V=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/B),y:Math.ceil(u[0]/B)},programUniforms:[{type:12,data:V},...Mt(i,u)]}},getShaderSource:h}}return h=B=>{let V=Qe("a",s,i.length),Z=At("output",s,u.length);return` + ${B.registerUniform("output_size","u32").declareVariables(V,Z)} + + ${Wa(o,n,V,Z)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${Z.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${Z.setByOffset("global_idx",V.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let B=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...Mt(i,u)]}},getShaderSource:h}},Ka=(e,t)=>{Va(e.inputs,t.perm),e.compute(pr(e.inputs[0],t.perm))},Qo=e=>zt({perm:e.perm})}),ao,Ha,qa,Qa,Xa,Ya,Ja,Za,Xo,el,hr,nn,tl,Rc,sl,Nc,rl,Yo,nl,ol,il,jc=g(()=>{Lt(),Ot(),Jt(),co(),Hr(),ao={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"},Ha={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"},qa={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Qa={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Xa=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let a=0;ae[a]);return[s,o]},Ja=(e,t)=>{let s=e.length+t.length,n=[],o=0;for(let a=0;a{for(let s=0;s{let s=[];if(!Za(e,t)){for(let n=0;ns.push(n))}return s},el=(e,t,s,n,o,a,i)=>{let u=s[0].dims,p=ze.size(a),h=ze.size(i),C=Qe("_A",s[0].dataType,u),k=At("output",o,a),d=64;p===1&&(d=256);let z=` + var aBestValues : array; + `,B=V=>` + ${V.registerUniform("reduceSize","u32").declareVariables(C,k)} + ${z} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${V.mainStart(d)} + + let outputIndex = global_idx / ${d}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${qa[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${d}) { + let candidate = f32(${C.getByOffset("offset + k")}); + bestValue = ${ao[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${d}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 = ${Ha[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${k.setByOffset("outputIndex",`${n==="mean"?`${k.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${k.type.storage}(${Qa[n]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${t};${d}`,inputDependencies:["type"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},hr=(e,t,s,n)=>{let o=e.inputs.length===1?s:Jo(e.inputs,s),a=o.axes;a.length===0&&!o.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((z,B)=>B));let i=ze.normalizeAxes(a,e.inputs[0].dims.length),u=i,p=e.inputs[0],h=Xo(u,e.inputs[0].dims.length);h.length>0&&(p=e.compute(pr(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],u=Xa(u.length,p.dims.length));let[C,k]=Ya(p.dims,u),d=C;o.keepDims&&(d=Ja(C,i)),e.compute(el(t,o.cacheKey,[p],n,e.inputs[0].dataType,d,k),{inputs:[p]})},nn=(e,t)=>{hr(e,"ReduceMeanShared",t,"mean")},tl=(e,t)=>{hr(e,"ReduceL1Shared",t,"l1")},Rc=(e,t)=>{hr(e,"ReduceL2Shared",t,"l2")},sl=(e,t)=>{hr(e,"ReduceLogSumExpShared",t,"logSumExp")},Nc=(e,t)=>{hr(e,"ReduceMaxShared",t,"max")},rl=(e,t)=>{hr(e,"ReduceMinShared",t,"min")},Yo=(e,t)=>{hr(e,"ReduceProdShared",t,"prod")},nl=(e,t)=>{hr(e,"ReduceSumShared",t,"sum")},ol=(e,t)=>{hr(e,"ReduceSumSquareShared",t,"sumSquare")},il=(e,t)=>{hr(e,"ReduceLogSumShared",t,"logSum")}}),gr,lo,uo,Jo,wr,Zo,al,ll,ei,ul,dl,ti,cl,pl,si,yr,hl,ri,ml,_l,ni,fl,gl,oi,wl,yl,co=g(()=>{Lt(),Ot(),rs(),Jt(),jc(),gr=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.")},lo=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],uo=(e,t,s,n,o,a,i=!1,u=!1)=>{let p=[],h=s[0].dims,C=h.length,k=ze.normalizeAxes(o,C),d=!u&&k.length===0;h.forEach((V,Z)=>{d||k.indexOf(Z)>=0?i&&p.push(1):p.push(V)});let z=p.length,B=ze.size(p);return{name:e,shaderCache:t,getShaderSource:V=>{let Z=[],ee=Qe("_A",s[0].dataType,C),X=At("output",a,z),me=n(ee,X,k),pe=me[2];for(let Me=0,Ae=0;Me=0?(i&&Ae++,pe=`for(var j${Me}: u32 = 0; j${Me} < ${h[Me]}; j${Me}++) { + ${me[2].includes("last_index")?`let last_index = j${Me};`:""} + ${ee.indicesSet("input_indices",Me,`j${Me}`)} + ${pe} + }`):(Z.push(`${ee.indicesSet("input_indices",Me,X.indicesGet("output_indices",Ae))};`),Ae++);return` + + ${V.registerUniform("output_size","u32").declareVariables(ee,X)} + + ${V.mainStart()} + ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${ee.type.indices}; + let output_indices = ${X.offsetToIndices("global_idx")}; + + ${Z.join(` +`)} + ${me[0]} // init ops for reduce max/min + ${me[1]} + ${pe} + ${me[3]} + ${me.length===4?X.setByOffset("global_idx","value"):me.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...Mt(h,p)]})}},Jo=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),zt({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},wr=(e,t,s,n)=>{let o=e.inputs,a=o.length===1?s:Jo(o,s);e.compute(uo(t,{hint:a.cacheKey,inputDependencies:["rank"]},[o[0]],a.noopWithEmptyAxes&&a.axes.length===0?lo:n,a.axes,o[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Zo=(e,t)=>{gr(e.inputs),wr(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},al=(e,t)=>{gr(e.inputs),wr(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},ll=(e,t)=>{gr(e.inputs),wr(e,"ReduceL2",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},ei=(e,t)=>{gr(e.inputs),wr(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},ul=(e,t)=>{gr(e.inputs),wr(e,"ReduceMax",t,(s,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(s.indicesSet("input_indices",i,0));return[`${a.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},dl=(e,t)=>{gr(e.inputs),wr(e,"ReduceMean",t,(s,n,o)=>{let a=1;for(let i=0;i=0||o.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},ti=(e,t)=>{gr(e.inputs),wr(e,"ReduceMin",t,(s,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},cl=(e,t)=>{gr(e.inputs),wr(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},pl=(e,t)=>{gr(e.inputs),wr(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},si=(e,t)=>{gr(e.inputs),wr(e,"ReduceSumSquare",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},yr=(e,t,s)=>{if(t.length===0)return s;let n=1,o=1;for(let a=0;a1024},hl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?dl(e,t):nn(e,t)},ri=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?al(e,t):tl(e,t)},ml=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ll(e,t):Rc(e,t)},_l=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ei(e,t):sl(e,t)},ni=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ul(e,t):Nc(e,t)},fl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ti(e,t):rl(e,t)},gl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?cl(e,t):Yo(e,t)},oi=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?pl(e,t):nl(e,t)},wl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?si(e,t):ol(e,t)},yl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Zo(e,t):il(e,t)}}),ii,Ml,ai,li,Uc=g(()=>{Lt(),rs(),co(),ii=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)=>{ii(e.inputs);let s=(n,o,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(uo("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},ai=(e,t)=>{ii(e.inputs);let s=(n,o,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(uo("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},li=e=>zt(e)}),ui,po,bl,di,vl,jn,ci,Tl,pi=g(()=>{Lt(),Ot(),ue(),Jt(),ui=(e,t)=>{let s=e[0],n=e[1],o=e[2],a=e[3],i=e[4],u=e[5];if(i&&u)throw new Error("Attention cannot have both past and attention_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=s.dims[0],h=s.dims[1],C=s.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==C)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let k=o.dims[0]/3,d=k,z=d;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let me of t.qkvHiddenSizes)if(me%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");k=t.qkvHiddenSizes[0],d=t.qkvHiddenSizes[1],z=t.qkvHiddenSizes[2]}let B=h;if(k!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==k+d+z)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let V=0;if(i){if(d!==z)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==d/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(V=i.dims[3])}let Z=B+V,ee=-1,X=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==p||u.dims[1]!==t.numHeads||u.dims[2]!==h||u.dims[3]!==Z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:V,kvSequenceLength:B,totalSequenceLength:Z,maxSequenceLength:ee,inputHiddenSize:C,hiddenSize:k,vHiddenSize:z,headSize:Math.floor(k/t.numHeads),vHeadSize:Math.floor(z/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},po=(e,t,s)=>t&&e?` + let total_sequence_length_input = u32(${t.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${s?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,bl=(e,t,s,n,o,a,i,u)=>{let p=Xt(i?1:a),h=64,C=a/p;C{let X=At("x",e.dataType,e.dims,p),me=[X],pe=i?Qe("seq_lens",i.dataType,i.dims):void 0;pe&&me.push(pe);let Me=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;Me&&me.push(Me);let Ae=$s(e.dataType),De=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${ee.registerUniforms(De).declareVariables(...me)} + ${ee.mainStart([h,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${po(pe,Me,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${B}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${B}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(p){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${p}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${h}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${B}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${B}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(p){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${p}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${h}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${X.type.value}(${Ae}(1.0) / ${Ae}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${B}(x[offset + i]); + x[offset + i] = ${X.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${X.type.value}(${Ae}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${z};${p}`,inputDependencies:V},getShaderSource:Z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/h),y:o,z:t*s},programUniforms:d})}},di=(e,t,s,n,o,a,i,u,p)=>{let h=i+a.kvSequenceLength,C=[a.batchSize,a.numHeads,a.sequenceLength,h],k=e>1&&n,d=a.kvNumHeads?a.kvNumHeads:a.numHeads,z=k?[a.batchSize,d,h,a.headSize]:void 0,B=a.nReps?a.nReps:1,V=a.scale===0?1/Math.sqrt(a.headSize):a.scale,Z=Xt(a.headSize),ee=a.headSize/Z,X=12,me={x:Math.ceil(h/X),y:Math.ceil(a.sequenceLength/X),z:a.batchSize*a.numHeads},pe=[{type:12,data:a.sequenceLength},{type:12,data:ee},{type:12,data:h},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:V},{type:12,data:i},{type:12,data:a.kvSequenceLength},{type:12,data:B}],Me=k&&n&&ze.size(n.dims)>0,Ae=["type","type"];Me&&Ae.push("type"),o&&Ae.push("type"),u&&Ae.push("type"),p&&Ae.push("type");let De=[{dims:C,dataType:t.dataType,gpuDataType:0}];k&&De.push({dims:z,dataType:t.dataType,gpuDataType:0});let et=dt=>{let Pt=Qe("q",t.dataType,t.dims,Z),qt=Qe("key",s.dataType,s.dims,Z),Bt=[Pt,qt];if(Me){let Qt=Qe("past_key",n.dataType,n.dims,Z);Bt.push(Qt)}o&&Bt.push(Qe("attention_bias",o.dataType,o.dims));let It=u?Qe("seq_lens",u.dataType,u.dims):void 0;It&&Bt.push(It);let ts=p?Qe("total_sequence_length_input",p.dataType,p.dims):void 0;ts&&Bt.push(ts);let wt=At("output",t.dataType,C),Ht=[wt];k&&Ht.push(At("present_key",t.dataType,z,Z));let ps=$s(1,Z),Ut=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${X}u; + + var tileQ: array<${Pt.type.storage}, ${X*X}>; + var tileK: array<${Pt.type.storage}, ${X*X}>; + ${dt.registerUniforms(Ut).declareVariables(...Bt,...Ht)} + ${dt.mainStart([X,X,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${B===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${B===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${po(It,ts,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${Me&&k?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${k?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${ps}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${Me&&k?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${k?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${ps}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(Z){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${Z}`)}})()}; + output[outputIdx] = ${wt.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${Z};${o!==void 0};${n!==void 0};${e}`,inputDependencies:Ae},getRunData:()=>({outputs:De,dispatchGroup:me,programUniforms:pe}),getShaderSource:et}},vl=(e,t,s,n,o,a,i=void 0,u=void 0)=>{let p=a+o.kvSequenceLength,h=o.nReps?o.nReps:1,C=o.vHiddenSize*h,k=e>1&&n,d=o.kvNumHeads?o.kvNumHeads:o.numHeads,z=k?[o.batchSize,d,p,o.headSize]:void 0,B=[o.batchSize,o.sequenceLength,C],V=12,Z={x:Math.ceil(o.vHeadSize/V),y:Math.ceil(o.sequenceLength/V),z:o.batchSize*o.numHeads},ee=[{type:12,data:o.sequenceLength},{type:12,data:p},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:C},{type:12,data:a},{type:12,data:o.kvSequenceLength},{type:12,data:h}],X=k&&n&&ze.size(n.dims)>0,me=["type","type"];X&&me.push("type"),i&&me.push("type"),u&&me.push("type");let pe=[{dims:B,dataType:t.dataType,gpuDataType:0}];k&&pe.push({dims:z,dataType:t.dataType,gpuDataType:0});let Me=Ae=>{let De=Qe("probs",t.dataType,t.dims),et=Qe("v",s.dataType,s.dims),dt=[De,et];X&&dt.push(Qe("past_value",n.dataType,n.dims));let Pt=i?Qe("seq_lens",i.dataType,i.dims):void 0;i&&dt.push(Pt);let qt=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&dt.push(qt);let Bt=[At("output",t.dataType,B)];k&&Bt.push(At("present_value",t.dataType,z));let It=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${V}u; + var tileQ: array<${De.type.value}, ${V*V}>; + var tileV: array<${De.type.value}, ${V*V}>; + ${Ae.registerUniforms(It).declareVariables(...dt,...Bt)} + ${Ae.mainStart([V,V,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${h===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${po(Pt,qt,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${X&&k?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${k?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${De.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${X&&k?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${k?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:me},getRunData:()=>({outputs:pe,dispatchGroup:Z,programUniforms:ee}),getShaderSource:Me}},jn=(e,t,s,n,o,a,i,u,p,h,C=void 0,k=void 0)=>{let d=Math.min(e.outputCount,1+(i?1:0)+(u?1:0)),z=d>1?h.pastSequenceLength:0,B=z+h.kvSequenceLength,V=p&&ze.size(p.dims)>0?p:void 0,Z=[t,s];d>1&&i&&ze.size(i.dims)>0&&Z.push(i),V&&Z.push(V),C&&Z.push(C),k&&Z.push(k);let ee=e.compute(di(d,t,s,i,V,h,z,C,k),{inputs:Z,outputs:d>1?[-1,1]:[-1]})[0];e.compute(bl(ee,h.batchSize,h.numHeads,z,h.sequenceLength,B,C,k),{inputs:C&&k?[ee,C,k]:[ee],outputs:[]});let X=[ee,n];d>1&&u&&ze.size(u.dims)>0&&X.push(u),C&&X.push(C),k&&X.push(k),e.compute(vl(d,ee,n,u,h,z,C,k),{inputs:X,outputs:d>1?[0,2]:[0]})},ci=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,a=t.headSize,i=12,u={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:o},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],C=k=>{let d=At("output_q",p[0].dataType,s),z=At("output_k",p[0].dataType,s),B=At("output_v",p[0].dataType,s),V=Qe("input",p[0].dataType,p[0].dims),Z=Qe("weight",p[1].dataType,p[1].dims),ee=Qe("bias",p[2].dataType,p[2].dims),X=V.type.storage,me=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${i}u; + var tileInput: array<${X}, ${i*i}>; + var tileWeightQ: array<${X}, ${i*i}>; + var tileWeightK: array<${X}, ${i*i}>; + var tileWeightV: array<${X}, ${i*i}>; + ${k.registerUniforms(me).declareVariables(V,Z,ee,d,z,B)} + ${k.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${X}(0); + var valueK = ${X}(0); + var valueV = ${X}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:h}),getShaderSource:C},{inputs:p,outputs:[-1,-1,-1]})},Tl=(e,t)=>{let s=ui(e.inputs,t),[n,o,a]=ci(e,s);return jn(e,n,o,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),hi,xl,Pl,mi,Vc=g(()=>{Re(),Lt(),Ot(),rs(),Jt(),hi=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,o,a)=>{let i=o.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);o.forEach((u,p)=>{if(u!==n[p])throw new Error(`${a}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);s(e[1].dims,n,"Invalid input scale"),s(e[2].dims,n,"Invalid input B"),s(e[3].dims,n,"Invalid input mean"),s(e[4].dims,n,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},xl=(e,t)=>{let{epsilon:s,spatial:n,format:o}=t,a=e[0].dims,i=n?Xt(a[a.length-1]):1,u=o==="NHWC"&&a.length>1?i:1,p=ze.size(a)/i,h=n,C=h?a.length:a,k=Qe("x",e[0].dataType,e[0].dims,i),d=Qe("scale",e[1].dataType,e[1].dims,u),z=Qe("bias",e[2].dataType,e[2].dims,u),B=Qe("inputMean",e[3].dataType,e[3].dims,u),V=Qe("inputVar",e[4].dataType,e[4].dims,u),Z=At("y",e[0].dataType,C,i),ee=()=>{let me="";if(n)me=`let cOffset = ${a.length===1?"0u":o==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")me=` + ${Z.indicesSet("outputIndices","0","0")} + let cOffset = ${Z.indicesToOffset("outputIndices")};`;else{me=`var cIndices = ${d.type.indices}(0); + cIndices[0] = outputIndices[${a.length-1}];`;for(let pe=1;pe` + const epsilon = ${s}; + ${me.registerUniform("outputSize","u32").declareVariables(k,d,z,B,V,Z)} + ${me.mainStart()} + ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${Z.offsetToIndices(`global_idx * ${i}`)}; + ${ee()} + let scale = ${d.getByOffset("cOffset")}; + let bias = ${z.getByOffset("cOffset")}; + let inputMean = ${B.getByOffset("cOffset")}; + let inputVar = ${V.getByOffset("cOffset")}; + let x = ${k.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${Z.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:X,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...Mt(a)]:[{type:12,data:p}]})}},Pl=e=>zt(e),mi=(e,t)=>{let{inputs:s,outputCount:n}=e,o=Pl({...t,outputCount:n});if(O.webgpu.validateInputContent&&hi(s,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(xl(s,o))}}),El,_i,Cl,Wc=g(()=>{Ot(),Jt(),El=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")},_i=e=>{let t=e[0].dims,s=e[0].dims[2],n=ze.size(t)/4,o=e[0].dataType,a=Qe("input",o,t,4),i=Qe("bias",o,[s],4),u=Qe("residual",o,t,4),p=At("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` + const channels = ${s}u / 4; + ${h.declareVariables(a,i,u,p)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${a.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx","value")} + }`}},Cl=e=>{El(e.inputs),e.compute(_i(e.inputs))}}),fi,ds,kl,gi,Sl,$l,wi,Al,Il,yi,Ol,Fl,Mi,Dl,Ll,bi,Un,zl,ho,Bl,vi,Rl,Nl,Ti,jl,Ul,xi,Vl,Wl,Pi,Gl,Kl,Ei,Hl,ql,mo,Ql,Ci,_o,Xl,Yl,Jl,Zl,ki,eu,Si=g(()=>{Lt(),Ot(),rs(),Jt(),fi=(e,t,s,n,o,a,i)=>{let u=Math.ceil(t/4),p="";typeof o=="string"?p=`${o}(a)`:p=o("a");let h=Qe("inputData",s,[u],4),C=At("outputData",n,[u],4),k=[{name:"vec_size",type:"u32"}];return i&&k.push(...i),` + ${e.registerUniforms(k).declareVariables(h,C)} + + ${a??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${h.getByOffset("global_idx")}; + ${C.setByOffset("global_idx",p)} + }`},ds=(e,t,s,n,o,a=e.dataType,i,u)=>{let p=[{type:12,data:Math.ceil(ze.size(e.dims)/4)}];return i&&p.push(...i),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:h=>fi(h,ze.size(e.dims),e.dataType,a,s,n,u),getRunData:h=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(ze.size(h[0].dims)/64/4)},programUniforms:p})}},kl=e=>{e.compute(ds(e.inputs[0],"Abs","abs"))},gi=e=>{e.compute(ds(e.inputs[0],"Acos","acos"))},Sl=e=>{e.compute(ds(e.inputs[0],"Acosh","acosh"))},$l=e=>{e.compute(ds(e.inputs[0],"Asin","asin"))},wi=e=>{e.compute(ds(e.inputs[0],"Asinh","asinh"))},Al=e=>{e.compute(ds(e.inputs[0],"Atan","atan"))},Il=e=>{e.compute(ds(e.inputs[0],"Atanh","atanh"))},yi=e=>zt(e),Ol=(e,t)=>{let s;switch(t.to){case 10:s="vec4";break;case 1:s="vec4";break;case 12:s="vec4";break;case 6:s="vec4";break;case 9:s="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ds(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},Fl=e=>{let t,s,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,s=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,s=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return zt({min:t,max:s})},Mi=(e,t)=>{let s=t||Fl(e.inputs),n=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},Dl=e=>{e.compute(ds(e.inputs[0],"Ceil","ceil"))},Ll=e=>{e.compute(ds(e.inputs[0],"Cos","cos"))},bi=e=>{e.compute(ds(e.inputs[0],"Cosh","cosh"))},Un=e=>zt(e),zl=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${s}(${t.alpha}); + + fn elu_f32(a: ${s}) -> ${s} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},ho=(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=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,ho(t)))},vi=e=>{e.compute(ds(e.inputs[0],"Exp","exp"))},Rl=e=>{e.compute(ds(e.inputs[0],"Floor","floor"))},Nl=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,ho(t)))},Ti=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${t.alpha});`,t.cacheKey))},jl=e=>{e.compute(ds(e.inputs[0],"Not",t=>`!${t}`))},Ul=e=>{e.compute(ds(e.inputs[0],"Neg",t=>`-${t}`))},xi=e=>{e.compute(ds(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Vl=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},Wl=e=>{e.compute(ds(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Pi=e=>zt(e),Gl=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"HardSigmoid",n=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${n} + vec4<${s}>(${t.beta})))`,void 0,t.cacheKey))},Kl=e=>{e.compute(ds(e.inputs[0],"Sin","sin"))},Ei=e=>{e.compute(ds(e.inputs[0],"Sinh","sinh"))},Hl=e=>{e.compute(ds(e.inputs[0],"Sqrt","sqrt"))},ql=e=>{e.compute(ds(e.inputs[0],"Tan","tan"))},mo=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ql=e=>{e.compute(ds(e.inputs[0],"Tanh",mo))},Ci=(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 ${mo("v")}; +} +`,_o=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Xl=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"FastGelu",_o,Ci(t),void 0,e.inputs[0].dataType))},Yl=(e,t)=>{let s=$s(e.inputs[0].dataType);return e.compute(ds(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${s}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`,t.cacheKey)),0},Jl=e=>{e.compute(ds(e.inputs[0],"Log","log"))},Zl=(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; +} +`,ki=e=>`quick_gelu_impl(${e})`,eu=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"QuickGelu",ki,Zl(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),tu,su,$i,Gc=g(()=>{Ot(),Jt(),Si(),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")},su=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=Qe("input",e[0].dataType,e[0].dims,4),n=Qe("bias",e[0].dataType,[e[0].dims[2]],4),o=At("output",e[0].dataType,t,4),a=ze.size(t)/4,i=fs(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${u.declareVariables(s,n,o)} + + ${ho(i)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},$i=e=>{tu(e.inputs),e.compute(su(e.inputs))}}),ru,nu,Mr,Ai,ou,iu,au,lu,Ii,uu,du,Oi,cu,Kc=g(()=>{Lt(),Ot(),Jt(),ru=(e,t,s,n,o,a,i,u,p,h,C,k)=>{let d,z;typeof u=="string"?d=z=(X,me)=>`${u}((${X}),(${me}))`:typeof u=="function"?d=z=u:(d=u.scalar,z=u.vector);let B=At("outputData",C,n.length,4),V=Qe("aData",p,t.length,4),Z=Qe("bData",h,s.length,4),ee;if(o)if(a){let X=ze.size(t)===1,me=ze.size(s)===1,pe=t.length>0&&t[t.length-1]%4===0,Me=s.length>0&&s[s.length-1]%4===0;X||me?ee=B.setByOffset("global_idx",z(X?`${V.type.value}(${V.getByOffset("0")}.x)`:V.getByOffset("global_idx"),me?`${Z.type.value}(${Z.getByOffset("0")}.x)`:Z.getByOffset("global_idx"))):ee=` + let outputIndices = ${B.offsetToIndices("global_idx * 4u")}; + let offsetA = ${V.broadcastedIndicesToOffset("outputIndices",B)}; + let offsetB = ${Z.broadcastedIndicesToOffset("outputIndices",B)}; + ${B.setByOffset("global_idx",z(i||pe?V.getByOffset("offsetA / 4u"):`${V.type.value}(${V.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||Me?Z.getByOffset("offsetB / 4u"):`${Z.type.value}(${Z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else ee=B.setByOffset("global_idx",z(V.getByOffset("global_idx"),Z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let X=(me,pe,Me="")=>{let Ae=`aData[indexA${pe}][componentA${pe}]`,De=`bData[indexB${pe}][componentB${pe}]`;return` + let outputIndices${pe} = ${B.offsetToIndices(`global_idx * 4u + ${pe}u`)}; + let offsetA${pe} = ${V.broadcastedIndicesToOffset(`outputIndices${pe}`,B)}; + let offsetB${pe} = ${Z.broadcastedIndicesToOffset(`outputIndices${pe}`,B)}; + let indexA${pe} = offsetA${pe} / 4u; + let indexB${pe} = offsetB${pe} / 4u; + let componentA${pe} = offsetA${pe} % 4u; + let componentB${pe} = offsetB${pe} % 4u; + ${me}[${pe}] = ${Me}(${d(Ae,De)}); + `};C===9?ee=` + var data = vec4(0); + ${X("data",0,"u32")} + ${X("data",1,"u32")} + ${X("data",2,"u32")} + ${X("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:ee=` + ${X("outputData[global_idx]",0)} + ${X("outputData[global_idx]",1)} + ${X("outputData[global_idx]",2)} + ${X("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(V,Z,B)} + + ${k??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${ee} + }`},nu=(e,t,s,n,o,a,i=s.dataType)=>{let u=s.dims.map(V=>Number(V)??1),p=n.dims.map(V=>Number(V)??1),h=!ze.areEqual(u,p),C=u,k=ze.size(u),d=!1,z=!1,B=[h];if(h){let V=Ws.calcShape(u,p,!1);if(!V)throw new Error("Can't perform binary op on the given tensors");C=V.slice(),k=ze.size(C);let Z=ze.size(u)===1,ee=ze.size(p)===1,X=u.length>0&&u[u.length-1]%4===0,me=p.length>0&&p[p.length-1]%4===0;B.push(Z),B.push(ee),B.push(X),B.push(me);let pe=1;for(let Me=1;MeV.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:V=>ru(V,u,p,C,d,h,z,o,s.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:C,dataType:i}],dispatchGroup:{x:Math.ceil(k/64/4)},programUniforms:[{type:12,data:Math.ceil(ze.size(C)/4)},...Mt(u,p,C)]})}},Mr=(e,t,s,n,o,a)=>{e.compute(nu(t,o??"",e.inputs[0],e.inputs[1],s,n,a))},Ai=e=>{Mr(e,"Add",(t,s)=>`${t}+${s}`)},ou=e=>{Mr(e,"Div",(t,s)=>`${t}/${s}`)},iu=e=>{Mr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},au=e=>{Mr(e,"Mul",(t,s)=>`${t}*${s}`)},lu=e=>{let t=Qe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Mr(e,"Pow",{scalar:(s,n)=>`pow_custom(${s},${n})`,vector:(s,n)=>`pow_vector_custom(${s},${n})`},` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},Ii=e=>{Mr(e,"Sub",(t,s)=>`${t}-${s}`)},uu=e=>{Mr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},du=e=>{Mr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},Oi=e=>{Mr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},cu=e=>{Mr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),Fi,pu,hu,Di,mu,_u,fu=g(()=>{Lt(),Ot(),rs(),Jt(),Fi=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],o=n.dataType,a=n.dims.length;e.forEach((i,u)=>{if(u!==s){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},pu=(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; + }`,hu=(e,t)=>{let s=e.length,n=[];for(let o=0;o{let o=ze.size(s),a=new Array(e.length),i=new Array(e.length),u=0,p=[],h=[],C=[{type:12,data:o}];for(let V=0;V`uniforms.sizeInConcatAxis${V}`).join(","),B=V=>` + + ${(()=>{V.registerUniform("outputSize","u32");for(let Z=0;Z(${z}); + ${d} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${hu(i,k)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:C}),getShaderSource:B}},mu=(e,t)=>{let s=e.inputs,n=s[0].dims,o=ze.normalizeAxis(t.axis,n.length);Fi(s,o);let a=n.slice();a[o]=s.reduce((u,p)=>u+(p.dims.length>o?p.dims[o]:0),0);let i=s.filter(u=>ze.size(u.dims)>0);e.compute(Di(i,o,a,s[0].dataType),{inputs:i})},_u=e=>zt({axis:e.axis})}),on,an,Fr,Li,ln=g(()=>{Lt(),Ot(),on=(e,t,s="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},an=(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})},Fr=(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"})},Li=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[s,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:s,beta:n}}else if(t==="Clip"){let[s,n]=(e==null?void 0:e.activation_params)||[Ss,Xs];return{activation:t,clipMax:n,clipMin:s}}else if(t==="LeakyRelu"){let[s]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:s}}return{activation:t}}}),Ks,zi,Bi=g(()=>{Ks=(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.`)}},zi=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),Ri,Hc=g(()=>{Ri=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)); +} +`}),Vn,Ni,fo=g(()=>{Lt(),Ot(),Jt(),ln(),Vn=(e,t,s,n,o)=>{let a=n-s;return` + ${Array.from({length:s}).map((i,u)=>` + if (${St(t.shape,u,t.rank)} != 1) { + ${t.indicesSet(e,u,St(o,u+a,n))} + } else { + ${t.indicesSet(e,u,0)} + }`).join("")} +`},Ni=(e,t,s,n,o=!1,a)=>{let i=e[0].dims,u=e[1].dims,p=i[i.length-2],h=u[u.length-1],C=i[i.length-1],k=Xt(h),d=Xt(C),z=Xt(p),B=ze.size(s)/k/z,V=e.length>2,Z=n?n.slice(0,-2):s.slice(0,-2),ee=[ze.size(Z),p,h],X=[{type:12,data:B},{type:12,data:p},{type:12,data:h},{type:12,data:C}];an(t,X),X.push(...Mt(Z,i,u)),V&&X.push(...Mt(e[2].dims)),X.push(...Mt(ee));let me=pe=>{let Me=Go("batch_dims",e[0].dataType,Z.length),Ae=Qe("a",e[0].dataType,i.length,d),De=Qe("b",e[1].dataType,u.length,k),et=At("output",e[0].dataType,ee.length,k),dt=fs(et.type.tensor),Pt=on(t,et.type.value,dt),qt=[Ae,De],Bt="";if(V){let wt=o?k:1;qt.push(Qe("bias",e[2].dataType,e[2].dims.length,wt)),Bt=`${o?`value += bias[col / ${wt}];`:`value += ${et.type.value}(bias[row + i]);`}`}let It=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Fr(t,It);let ts=()=>{let wt=`var a_data: ${Ae.type.value};`;for(let Ht=0;Ht; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { + ${ts()} + } + for (var i = 0u; i < ${z}u; i++) { + var value = values[i]; + ${Bt} + ${Pt} + let cur_indices = ${et.type.indices}(batch, row + i, col); + let offset = ${et.indicesToOffset("cur_indices")}; + ${et.setByOffset(`offset / ${k}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${k};${d};${z};${o}`,inputDependencies:V?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:X}),getShaderSource:me}}}),gu,wu,ji,go,yu,Ui,Vi,wo,Wi=g(()=>{Lt(),Ot(),Jt(),ln(),fo(),Bi(),gu=(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":""}); + `,wu=(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];"} + }`,ji=(e,t,s="f32",n,o=!1,a=32,i=!1,u=32)=>{let p=t[1]*e[1],h=t[0]*e[0],C=o?p:a,k=o?a:p,d=C/t[0],z=a/t[1];if(!((o&&d===4&&e[1]===4||!o&&(d===3||d===4))&&C%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${d} must be 3 or 4. + tileAWidth ${C} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${C/d}>, ${k}>; +var mm_Bsub: array, ${h/e[0]}>, ${a}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${d}; +const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${p}; + + let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${z}; + 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; + ${gu(o,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${z}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${wu(o,d)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},go=(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":""}); + `,yu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ui=(e,t,s="f32",n,o=!1,a=32,i=!1,u=32,p=!1)=>{let h=e[1]*t[1],C=e[0]*t[0],k=o?h:a,d=o?a:h;if(!(d%t[1]===0&&k%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${k} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let z=d/t[1],B=k/t[0],V=a/t[1],Z=p?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${h}; + let globalColStart = i32(workgroupId.x) * ${C}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { + ${go(o,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${C}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${h}; + +let tileRowA = i32(localId.y) * ${z}; +let tileColA = i32(localId.x) * ${B}; +let tileRowB = i32(localId.y) * ${V}; +// 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 < ${z}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${B}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${go(o,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${V}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${yu(o)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${d}>; + var mm_Bsub : array, ${a}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; + + var acc : array, rowPerThread>; + ${Z} + } +`},Vi=(e,t,s,n,o=!1)=>{let[a,i,u,p]=n,h=fs(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Ks(e,h)} { + var value = ${Ks(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${Vn("aIndices",i,i.rank-2,a.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Ks(e,h)} { + var value = ${Ks(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${u.type.indices}; + ${Vn("bIndices",u,u.rank-2,a.rank,"batchIndices")} + ${u.indicesSet("bIndices",u.rank-2,"u32(row)")} + ${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")} + value = ${u.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ks(e,h)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${o?"bias[colIn]":`${Ks(e,h)}(bias[row])`};`:""} + ${s} + ${p.setByIndices("vec3(coords)","value")} + } + } + `},wo=(e,t,s,n,o=!1,a)=>{let i=e[0].dims,u=e[1].dims,p=i.slice(0,-2),h=u.slice(0,-2),C=n?n.slice(0,-2):s.slice(0,-2),k=ze.size(C),d=i[i.length-2],z=i[i.length-1],B=u[u.length-1],V=z%4===0&&B%4===0,Z=d<=8?[4,1,1]:[4,4,1],ee=[8,8,1],X=[Math.ceil(B/ee[0]/Z[0]),Math.ceil(d/ee[1]/Z[1]),Math.ceil(k/ee[2]/Z[2])],me=V?4:1,pe=[...p,d,z/me],Me=pe.length,Ae=[...h,z,B/me],De=Ae.length,et=[k,d,B/me],dt=[{type:6,data:d},{type:6,data:B},{type:6,data:z}];an(t,dt),dt.push(...Mt(C,pe,Ae));let Pt=["rank","rank"],qt=e.length>2;qt&&(dt.push(...Mt(e[2].dims)),Pt.push("rank")),dt.push(...Mt(et));let Bt=It=>{let ts=C.length,wt=Go("batchDims",e[0].dataType,ts,1),Ht=fs(e[0].dataType),ps=Qe("a",e[0].dataType,Me,me),Ut=Qe("b",e[1].dataType,De,me),Qt=At("result",e[0].dataType,et.length,me),gs=[ps,Ut];if(qt){let qs=o?me:1;gs.push(Qe("bias",e[2].dataType,e[2].dims.length,qs))}let it=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Fr(t,it);let Et=fs(Qt.type.tensor),hs=on(t,Qt.type.value,Et),Ns=Vi(me,qt,hs,[wt,ps,Ut,Qt],o);return` + ${It.registerUniforms(it).registerInternalVariables(wt).declareVariables(...gs,Qt)} + ${Ns} + ${V?ji(Z,ee,Ht,wt):Ui(Z,ee,Ht,wt)} + `};return{name:"MatMul",shaderCache:{hint:`${Z};${t.activation};${V};${o}`,inputDependencies:Pt},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:X[0],y:X[1],z:X[2]},programUniforms:dt}),getShaderSource:Bt}}}),Gi,Mu,qc=g(()=>{Lt(),Pe(),Jt(),ln(),Bi(),Hc(),Wi(),Gi=(e,t,s,n,o=!1,a,i=4,u=4,p=4,h="f32")=>{let C=dt=>{switch(dt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${dt} is not supported.`)}},k=dt=>{switch(dt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${dt} is not supported.`)}},d=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,z=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,B=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",V=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Z=e?"row":"col",ee=e?"col":"row",X=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${Z} / outWidth; + let outCol = ${Z} % outWidth; + + let WRow = ${ee} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${ee} / 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 = ${ee} % inChannels; + var resData = ${Ks(i,h)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${B} && xCol >= 0 && xCol < ${V}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${C(i)} + } + return resData;`,me=e?t&&n?` + let col = colIn * ${i}; + ${X}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${X} + } + return ${Ks(i,h)}(0.0);`:n&&s?` + let col = colIn * ${i}; + ${X}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${X} + } + return ${Ks(i,h)}(0.0);`,pe=e?n&&s?k(u):` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${k(u)} + } + return ${Ks(u,h)}(0.0);`:` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${k(u)} + } + return ${Ks(u,h)}(0.0);`,Me=Ks(p,h),Ae=Ks(e?i:u,h),De=Ks(e?u:i,h),et=on(a,Me,h);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ae} { + ${e?me:pe} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${De} { + ${e?pe:me} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Me}) { + let col = colIn * ${p}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${z} + ${zi(o)} + ${et} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Mu=(e,t,s,n,o,a,i,u,p)=>{let h=t.format==="NHWC",C=h?e[0].dims[3]:e[0].dims[1],k=s[0],d=h?s[2]:s[3],z=h?s[1]:s[2],B=h?s[3]:s[1],V=h&&(C%4===0||C%3===0)&&B%4===0,Z=h?B:d*z,ee=h?d*z:B,X=[8,8,1],me=n<=8?[4,1,1]:[4,4,1],pe=[Math.ceil(Z/X[0]/me[0]),Math.ceil(ee/X[1]/me[1]),Math.ceil(k/X[2]/me[2])];is("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${pe}`);let Me=V?h&&C%4!==0?3:4:1,Ae=X[1]*me[1],De=X[0]*me[0],et=Math.max(X[0]*Me,X[1]),dt=n%Ae===0,Pt=o%De===0,qt=a%et===0,Bt=V?[Me,4,4]:[1,1,1],It=[{type:6,data:n},{type:6,data:o},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];an(t,It),It.push(...Mt(e[0].dims,e[1].dims));let ts=["rank","rank"];i&&(It.push(...Mt(e[2].dims)),ts.push("rank")),It.push(...Mt(s));let wt=Ht=>{let ps=[{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}];Fr(t,ps);let Ut=V?4:1,Qt=fs(e[0].dataType),gs=` + fn setOutputAtIndex(flatIndex : i32, value : ${V?`vec4<${Qt}>`:Qt}) { + result[flatIndex] = ${V?`vec4<${Qt}>`:Qt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${V?`vec4<${Qt}>`:Qt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${V?"/ 4":""}, value); + }`,it=Qe("x",e[0].dataType,e[0].dims.length,Me===3?1:Me),Et=Qe("w",e[1].dataType,e[1].dims.length,Ut),hs=[it,Et],Ns=At("result",e[0].dataType,s.length,Ut);if(i){let qs=Qe("bias",e[2].dataType,e[2].dims.length,Ut);hs.push(qs),gs+=` + fn getBiasByOutputCoords(coords : vec4) -> ${V?`vec4<${Qt}>`:Qt} { + return bias[coords.${h?"w":"y"}${V?"/ 4":""}]; + }`}return` + ${Ri("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 }; + ${Ht.registerUniforms(ps).declareVariables(...hs,Ns)} + ${gs} + ${Gi(h,dt,Pt,qt,i,t,Bt[0],Bt[1],Bt[2],Qt)} + ${V?ji(me,X,Qt,void 0,!h,et):Ui(me,X,Qt,void 0,!h,et,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Me};${V};${dt};${Pt};${qt};${Ae};${De};${et}`,inputDependencies:ts},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:pe[0],y:pe[1],z:pe[2]},programUniforms:It}),getShaderSource:wt}}}),Ki,Hi,Wn,qi,Qi,bu,Xi,vu,Qc=g(()=>{Lt(),Pe(),Ot(),Jt(),ln(),Bi(),Ki=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,Wn=(e,t)=>t<=1?e:e+(e-1)*(t-1),qi=(e,t,s,n=1)=>{let o=Wn(t,n);return Math.floor((e[0]*(s-1)-s+o)/2)},Qi=(e,t,s,n,o)=>{o==null&&(o=qi(e,t[0],n[0]));let a=[0,0,0,s];for(let i=0;i<3;i++)e[i]+2*o>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*o)/n[i]+1));return a},bu=(e,t,s,n,o,a,i,u,p,h)=>{let C,k,d,z;if(e==="VALID"&&(e=0),typeof e=="number"){C={top:e,bottom:e,left:e,right:e,front:e,back:e};let B=Qi([t,s,n,1],[u,p,h],1,[o,a,i],e);k=B[0],d=B[1],z=B[2]}else if(Array.isArray(e)){if(!e.every((V,Z,ee)=>V===ee[0]))throw Error(`Unsupported padding parameter: ${e}`);C={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let B=Qi([t,s,n,1],[u,p,h],1,[o,a,i],e[0]);k=B[0],d=B[1],z=B[2]}else if(e==="SAME_UPPER"){k=Math.ceil(t/o),d=Math.ceil(s/a),z=Math.ceil(n/i);let B=(k-1)*o+u-t,V=(d-1)*a+p-s,Z=(z-1)*i+h-n,ee=Math.floor(B/2),X=B-ee,me=Math.floor(V/2),pe=V-me,Me=Math.floor(Z/2),Ae=Z-Me;C={top:me,bottom:pe,left:Me,right:Ae,front:ee,back:X}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:C,outDepth:k,outHeight:d,outWidth:z}},Xi=(e,t,s,n,o,a=!1,i="channelsLast")=>{let u,p,h,C,k;if(i==="channelsLast")[u,p,h,C,k]=e;else if(i==="channelsFirst")[u,k,p,h,C]=e;else throw new Error(`Unknown dataFormat ${i}`);let[d,,z,B,V]=t,[Z,ee,X]=Hi(s),[me,pe,Me]=Hi(n),Ae=Wn(z,me),De=Wn(B,pe),et=Wn(V,Me),{padInfo:dt,outDepth:Pt,outHeight:qt,outWidth:Bt}=bu(o,p,h,C,Z,ee,X,Ae,De,et),It=a?d*k:d,ts=[0,0,0,0,0];return i==="channelsFirst"?ts=[u,It,Pt,qt,Bt]:i==="channelsLast"&&(ts=[u,Pt,qt,Bt,It]),{batchSize:u,dataFormat:i,inDepth:p,inHeight:h,inWidth:C,inChannels:k,outDepth:Pt,outHeight:qt,outWidth:Bt,outChannels:It,padInfo:dt,strideDepth:Z,strideHeight:ee,strideWidth:X,filterDepth:z,filterHeight:B,filterWidth:V,effectiveFilterDepth:Ae,effectiveFilterHeight:De,effectiveFilterWidth:et,dilationDepth:me,dilationHeight:pe,dilationWidth:Me,inShape:e,outShape:ts,filterShape:t}},vu=(e,t,s,n,o,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],p={x:s.map((Z,ee)=>ee)},h=[Math.ceil(Ki(p.x.map(Z=>s[Z]))/u[0]),1,1];is("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let C=1,k=ze.size(s),d=[{type:12,data:k},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];an(t,d),d.push(...Mt(e[0].dims,e[1].dims));let z=["rank","rank"],B=e.length===3;B&&(d.push(...Mt(e[2].dims)),z.push("rank")),d.push(...Mt(s));let V=Z=>{let ee=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Fr(t,ee);let X=1,me=fs(e[0].dataType),pe=Qe("x",e[0].dataType,e[0].dims.length,C),Me=Qe("W",e[1].dataType,e[1].dims.length,X),Ae=[pe,Me],De=At("result",e[0].dataType,s.length,X),et="";if(B){let qt=Qe("bias",e[2].dataType,e[2].dims.length,X);Ae.push(qt),et+=` + fn getBiasByOutputCoords(coords : array) -> ${me} { + return bias[${i?St("coords",4,5):St("coords",1,5)}]; + }`}let dt=Ks(C,me),Pt=on(t,dt,me);return` + ${et} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${pe.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Me.getByIndices("aIndices")}; + } + ${Z.registerUniforms(ee).declareVariables(...Ae,De)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${De.offsetToIndices("global_idx")}; + let batch = ${St("coords",0,pe.rank)}; + let d2 = ${i?St("coords",pe.rank-1,pe.rank):St("coords",1,pe.rank)}; + let xFRCCorner = vec3(${i?St("coords",1,pe.rank):St("coords",2,pe.rank)}, + ${i?St("coords",2,pe.rank):St("coords",3,pe.rank)}, + ${i?St("coords",3,pe.rank):St("coords",4,pe.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?St("uniforms.x_shape",1,pe.rank):St("uniforms.x_shape",2,pe.rank)}; + let xShapeZ = ${i?St("uniforms.x_shape",2,pe.rank):St("uniforms.x_shape",3,pe.rank)}; + let xShapeW = ${i?St("uniforms.x_shape",3,pe.rank):St("uniforms.x_shape",4,pe.rank)}; + let xShapeU = ${i?St("uniforms.x_shape",4,pe.rank):St("uniforms.x_shape",1,pe.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${B?"value = value + getBiasByOutputCoords(coords)":""}; + ${Pt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${C};${B}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:d}),getShaderSource:V}}}),Tu,xu,Yi=g(()=>{Lt(),Ot(),Jt(),ln(),Tu=(e,t,s,n)=>{let o=e.length>2,a=o?"value += b[output_channel];":"",i=e[0].dims,u=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],C=h/t.group,k=p&&C>=4?Xt(h):1,d=ze.size(s)/k,z=[{type:12,data:d},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:C}];an(t,z),z.push(...Mt(i,[u[0],u[1],u[2],u[3]/k]));let B=o?["rank","rank","rank"]:["rank","rank"];z.push(...Mt([s[0],s[1],s[2],s[3]/k]));let V=Z=>{let ee=At("output",e[0].dataType,s.length,k),X=fs(ee.type.tensor),me=on(t,ee.type.value,X),pe=Qe("x",e[0].dataType,i.length),Me=Qe("w",e[1].dataType,u.length,k),Ae=[pe,Me];o&&Ae.push(Qe("b",e[2].dataType,e[2].dims,k));let De=[{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"}];Fr(t,De);let et=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 = ${pe.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${Me.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${pe.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${Me.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${Z.registerUniforms(De).declareVariables(...Ae,ee)} + + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${ee.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 * ${k} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; + + var value: ${ee.type.value} = ${ee.type.value}(0); + ${et} + ${a} + ${me} + ${ee.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${k}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:z}),getShaderSource:V}},xu=(e,t,s,n)=>{let o=e.length>2,a=Xt(s[3]),i=Xt(s[2]),u=ze.size(s)/a/i,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],C=[s[0],s[1],s[2],s[3]/a],k=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];an(t,k),k.push(...Mt(p,h,C));let d=(i-1)*t.strides[1]+h[1],z=B=>{let V=At("output",e[0].dataType,C.length,a),Z=fs(V.type.tensor),ee=on(t,V.type.value,Z),X=Qe("x",e[0].dataType,p.length,a),me=Qe("w",e[1].dataType,h.length,a),pe=[X,me];o&&pe.push(Qe("b",e[2].dataType,e[2].dims,a));let Me=o?"value += b[output_channel];":"",Ae=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Fr(t,Ae),` + ${B.registerUniforms(Ae).declareVariables(...pe,V)} + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${X.type.value}, ${d}>; + var values: array<${V.type.value}, ${i}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${d}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${X.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${X.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { + let w_val = ${me.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${Me} + ${ee} + ${V.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${d};${h[0]};${h[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:k}),getShaderSource:z}}}),Pu,yo,Eu,Mo,Ji,bo,Cu,ku,vo,Xc=g(()=>{Ot(),qc(),Qc(),Wi(),Yi(),ln(),fo(),Hr(),Pu=(e,t,s,n,o,a)=>{let i=e[0],u=e.slice(a?1:2,a?3:4),p=u.length,h=t[0],C=t.slice(2).map((d,z)=>d+(d-1)*(s[z]-1)),k=u.map((d,z)=>d+n[z]+n[z+p]).map((d,z)=>Math.floor((d-C[z]+o[z])/o[z]));return k.splice(0,0,i),k.splice(a?3:1,0,h),k},yo=[2,3,1,0],Eu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Mo=(e,t)=>{let s=e.kernelShape.slice();s.length{let t=Li(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,a=e.group,i=e.kernel_shape,u=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:o,group:a,kernelShape:i,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},bo=(e,t,s,n)=>{let o=s.format==="NHWC",a=Pu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,o);if(s.group!==1){let Ae=[t[0]];if(o){let De=e.kernelCustomData.wT??e.compute(pr(t[1],yo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=De),Ae.push(De)}else Ae.push(t[1]);t.length===3&&Ae.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(xu(Ae,s,a,n),{inputs:Ae}):e.compute(Tu(Ae,s,a,n),{inputs:Ae});return}let i=t.length===3,u=t[0].dims[o?1:2],p=t[0].dims[o?2:3],h=t[0].dims[o?3:1],C=t[1].dims[2],k=t[1].dims[3],d=a[o?1:2],z=a[o?2:3],B=a[o?3:1],V=o&&C===u&&k===p&&s.pads[0]===0&&s.pads[1]===0;if(V||C===1&&k===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let Ae=a[0],De,et,dt,Pt=[];if(o){let It=e.kernelCustomData.wT??e.compute(pr(t[1],yo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=It),V){let ts=u*p*h;De=t[0].reshape([1,Ae,ts]),et=It.reshape([1,ts,B]),dt=[1,Ae,B]}else De=t[0].reshape([Ae,u*p,h]),et=It.reshape([1,h,B]),dt=[Ae,d*z,B];Pt.push(De),Pt.push(et)}else De=t[0].reshape([Ae,h,u*p]),et=t[1].reshape([1,B,h]),dt=[Ae,B,d*z],Pt.push(et),Pt.push(De);i&&Pt.push(t[2]);let qt=dt[2],Bt=Pt[0].dims[Pt[0].dims.length-1];qt<8&&Bt<8?e.compute(Ni(Pt,s,a,dt,o,n),{inputs:Pt}):e.compute(wo(Pt,s,a,dt,o,n),{inputs:Pt});return}let Z=!0,ee=e.kernelCustomData.wT??e.compute(pr(t[1],yo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ee);let X=[t[0],ee];i&&X.push(t[2]);let me=o?d*z:B,pe=o?B:d*z,Me=C*k*h;e.compute(Mu(X,s,a,me,pe,Me,i,Z,n),{inputs:X})},Cu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),u=[1].concat(t.kernelShape),p=Mo({...t,pads:o,strides:a,dilations:i,kernelShape:u},n);bo(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},ku=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",o=Mo(s,t),a=s.autoPad==="NOTSET"?s.pads:s.autoPad,i=Xi(t[0].dims,t[1].dims,s.strides,s.dilations,a,!1,n);e.compute(vu(t,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},vo=(e,t)=>{if(Eu(e.inputs,t),e.inputs[0].dims.length===3)Cu(e,t);else if(e.inputs[0].dims.length===5)ku(e,e.inputs,t);else{let s=Mo(t,e.inputs);bo(e,e.inputs,s)}}}),Su,Yc=g(()=>{Lt(),Pe(),Ot(),Jt(),Su=(e,t,s)=>{let n=e.length>2,o=t.outputShape,a=t.format==="NHWC",i=t.group,u=e[1].dims,p=u[2]/i,h=u[3],C=a?Xt(p):1,k=a?Xt(h):1,d=a?h===1?C:k:1,z=ze.size(o)/k,B=[Math.ceil(z/64),1,1];is("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${B}`);let V=["rank","rank"],Z=[t.strides[0],t.strides[1]],ee=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],X=[t.dilations[0],t.dilations[1]],me=[ee[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),ee[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],pe=[me[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),me[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Me=[{type:12,data:z},{type:12,data:Z},{type:12,data:ee},{type:12,data:X},{type:12,data:me},{type:6,data:pe},{type:12,data:p},{type:12,data:h},...Mt(e[0].dims,e[1].dims)];n&&(Me.push(...Mt(e[2].dims)),V.push("rank")),Me.push(...Mt(o));let Ae=De=>{let et=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:Z.length},{name:"filter_dims",type:"u32",length:ee.length},{name:"dilations",type:"u32",length:ee.length},{name:"effective_filter_dims",type:"u32",length:me.length},{name:"pads",type:"i32",length:pe.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],dt=fs(e[0].dataType),Pt=a?1:2,qt=a?2:3,Bt=a?3:1,It=Qe("W",e[1].dataType,e[1].dims.length,d),ts=Qe("Dy",e[0].dataType,e[0].dims.length,C),wt=[ts,It];n&&wt.push(Qe("bias",e[2].dataType,[o[Bt]].length,k));let Ht=At("result",e[0].dataType,o.length,k),ps=()=>{let Qt="";if(C===1)Qt+=` + let w_offset = ${It.indicesToOffset(`${It.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${It.getByOffset(`w_offset / ${d}`)}; + dotProd = dotProd + xValue * wValue;`;else if(h===1)Qt+=` + let wValue = ${It.getByOffset(`${It.indicesToOffset(`${It.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${d}`)}; + dotProd = dotProd + dot(xValue, wValue);`;else for(let gs=0;gs(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 = ${Ht.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${dt}(dyRCorner) + ${dt}(wR)) / ${dt}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${dt}(uniforms.Dy_shape[${Pt}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${dt}(dyCCorner) + ${dt}(wC)) / ${dt}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${dt}(uniforms.Dy_shape[${qt}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + ${C}) { + let xValue = ${a?ts.getByOffset(`${ts.indicesToOffset(`${ts.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${C}`):ts.get("batch","inputChannel","idyR","idyC")}; + ${ps()} + inputChannel = inputChannel + ${C}; + } + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${n?` + bias[d1 / ${k}]`:""}; + ${Ht.setByOffset("global_idx","value")}; + `;return` + ${De.registerUniforms(et).declareVariables(...wt,Ht)} + ${De.mainStart()} + ${De.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${Ut}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${C}${d}${k}${h===1}`,inputDependencies:V},getRunData:()=>({dispatchGroup:{x:B[0],y:B[1],z:B[2]},outputs:[{dims:s?s(o):o,dataType:e[0].dataType}],programUniforms:Me}),getShaderSource:Ae}}}),$u,Zi,Au,ea,ta,Iu,sa,ra,Ou,Jc=g(()=>{Yc(),ln(),Hr(),$u=(e,t,s,n,o,a)=>(e-1)*t+s+(n-1)*o+1-a,Zi=(e,t,s,n,o)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(s[n]=a,s[o]=e-a):t==="SAME_LOWER"&&(s[n]=e-a,s[o]=a)},Au=(e,t,s,n,o,a,i,u,p,h)=>{let C=e.length-2,k=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((k,d)=>k*d,1)===0){s.length=0;for(let k=2;kk+d,0)===0){let k=t[0].dims.length-2;p=new Array(k).fill(1)}let h=e.strides.slice();if(h.reduce((k,d)=>k+d,0)===0){let k=t[0].dims.length-2;h=new Array(k).fill(1)}Au(u,s,p,e.autoPad,e.group,o,h,n,i,a);let C=Object.assign({},e);return Object.assign(C,{kernelShape:s,pads:o,outputPadding:i,outputShape:a,dilations:p,strides:h}),C},ta=e=>{let t=Li(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,a=e.group,i=e.kernelShape,u=e.pads,p=e.strides,h=e.wIsConst(),C=e.outputPadding,k=e.outputShape;return{autoPad:n,format:s,dilations:o,group:a,kernelShape:i,outputPadding:C,outputShape:k,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Iu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,u)=>i+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,u)=>i+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,u)=>i+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,u)=>i+u,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")},sa=(e,t,s,n)=>{let o=e.kernelCustomData.wT??e.compute(pr(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let a=[t[0],o];t.length===3&&a.push(t[2]),e.compute(Su(a,s,n),{inputs:a})},ra=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],i=[1].concat(i),a=[1].concat(a),o=[1].concat(o);let p=t.outputPadding;p=[0].concat(p);let h=ea({...t,pads:u,strides:i,dilations:a,kernelShape:o,outputPadding:p},n);sa(e,n,h,C=>s?[C[0],C[2],C[3]]:[C[0],C[1],C[3]])},Ou=(e,t)=>{if(Iu(e.inputs,t),e.inputs[0].dims.length===3)ra(e,t);else{let s=ea(t,e.inputs);sa(e,e.inputs,s)}}}),na,Fu,Du,Zc=g(()=>{Lt(),Ot(),rs(),Jt(),na=(e,t,s,n)=>{let o=ze.size(t),a=t.length,i=Qe("input",e,a),u=At("output",e,a),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=ze.normalizeAxis(p,a),C=k=>{let d=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,z=St("uniforms.input_shape","uniforms.axis",a),B=n.reverse?d+(n.exclusive?" + 1":""):"0",V=n.reverse?z:d+(n.exclusive?"":" + 1");return` + ${k.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,u)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${B}; + let last : i32 = ${V}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:h},...Mt(t,t)]}),getShaderSource:C}},Fu=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(na(n,s,o,t),{inputs:[0]})},Du=e=>{let t=e.exclusive===1,s=e.reverse===1;return zt({exclusive:t,reverse:s})}}),Lu,oa,zu,Bu,Ru,ep=g(()=>{Lt(),Ot(),rs(),Jt(),Lu=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.")},oa=(e,t,s,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let a=0;a{let s,n,o,a,i,u,p=t.format==="NHWC",h=t.blocksize,C=t.mode==="DCR";p?([s,n,o,a]=e.dims,i=C?[s,n,o,h,h,a/h**2]:[s,n,o,a/h**2,h,h],u=C?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,o,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=C?[s,h,h,a/h**2,n,o]:[s,a/h**2,h,h,n,o],u=C?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let k=e.reshape(i),d=k.dims.length,z=e.dataType,B=Qe("a",z,d),V=At("output",z,d),Z=ee=>` + ${ee.registerUniform("output_size","u32").declareVariables(B,V)} + + ${oa(u,d,B,V)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${V.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${V.setByOffset("global_idx",B.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:ee=>{let X=p?[s,n*h,o*h,a/h**2]:[s,a/h**2,n*h,o*h],me=ze.size(X),pe=k.dims,Me=ze.sortBasedOnPerm(pe,u);return{outputs:[{dims:X,dataType:ee[0].dataType}],dispatchGroup:{x:Math.ceil(me/64)},programUniforms:[{type:12,data:me},...Mt(pe,Me)]}},getShaderSource:Z}},Bu=(e,t)=>{Lu(e.inputs),e.compute(zu(e.inputs[0],t))},Ru=e=>zt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),To,Gn,xo,Nu,ju,ia,Uu,aa,qr,Vu,Wu,tp=g(()=>{Lt(),Ot(),rs(),Jt(),To="[a-zA-Z]|\\.\\.\\.",Gn="("+To+")+",xo="^"+Gn+"$",Nu="("+Gn+",)*"+Gn,ju="^"+Nu+"$",ia=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},Uu=class{constructor(e,t){var o;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,n]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(ju)))throw new Error("Invalid LHS term");if(s.split(",").forEach((a,i)=>{let u=e[i].dims.slice();if(!a.match(RegExp(xo)))throw new Error("Invalid LHS term");let p=this.processTerm(a,!0,u,i);this.lhs.push(p)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Gn)))throw new Error("Invalid RHS");(o=n.match(RegExp(To,"g")))==null||o.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,s){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let o=s.length,a=!1,i=[],u=0;if(!e.match(RegExp(xo))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(To,"g")),h=new ia(n);return p==null||p.forEach((C,k)=>{if(C==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let d=o-p.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(i=s.slice(u,u+d),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let z=0;ze+"_max",qr=(e,t,s,n)=>{let o=e.map(h=>h.length).map((h,C)=>Qe(`input${C}`,t,h)),a=ze.size(n),i=At("output",t,n.length),u=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let C=[],k="var prod = 1.0;",d="var sum = 0.0;",z="sum += prod;",B=[],V=[],Z=[],ee=[],X=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((pe,Me)=>{var Ae;if(s.rhs.symbolToIndices.has(Me)){let De=(Ae=s.rhs.symbolToIndices.get(Me))==null?void 0:Ae[0];De!==void 0&&s.lhs.forEach((et,dt)=>{if(pe.inputIndices.includes(dt)){let Pt=et.symbolToIndices.get(Me);if(Pt===void 0)throw new Error("Invalid symbol error");Pt.forEach(qt=>{C.push(`${o[dt].indicesSet(`input${dt}Indices`,qt,i.indicesGet("outputIndices",De))}`)})}})}else s.lhs.forEach((De,et)=>{if(pe.inputIndices.includes(et)){let dt=De.symbolToIndices.get(Me);if(dt===void 0)throw new Error("Invalid symbol error");dt.forEach(Pt=>{B.push(`${o[et].indicesSet(`input${et}Indices`,Pt,`${Me}`)}`)}),ee.push(`prod *= ${o[et].getByIndices(`input${et}Indices`)};`)}}),V.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${aa(Me)}; ${Me}++) {`),Z.push("}")});let me=X?[...C,`let sum = ${o.map((pe,Me)=>pe.getByIndices(`input${Me}Indices`)).join(" * ")};`]:[...C,d,...V,...B,k,...ee,z,...Z];return` + ${h.registerUniforms(u.map(pe=>({name:`${aa(pe)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((pe,Me)=>`var input${Me}Indices: ${o[Me].type.indices};`).join(` +`)} + ${me.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=u.filter(k=>s.symbolToInfo.has(k)).map(k=>{var d;return{type:12,data:((d=s.symbolToInfo.get(k))==null?void 0:d.dimValue)||0}});h.push({type:12,data:a});let C=e.map((k,d)=>[...Mt(k)]).reduce((k,d)=>k.concat(d),h);return C.push(...Mt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:C}},getShaderSource:p}},Vu=(e,t)=>{let s=new Uu(e.inputs,t.equation),n=s.outputDims,o=e.inputs.map((a,i)=>a.dims);e.compute(qr(o,e.inputs[0].dataType,s,n))},Wu=e=>{let t=e.equation.replace(/\s+/g,"");return zt({equation:t})}}),Gu,Po,Ku,Hu,qu,sp=g(()=>{Lt(),Ot(),Jt(),Gu=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=s.length{let s=e.length-t.length,n=[];for(let o=0;oe.length>t.length?Po(e,t):Po(t,e),Hu=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=Ku(t,s),o=e[0].dataType,a=o===9||ze.size(t)===1,i=o===9||t.length>0&&t[t.length-1]%4===0?4:1,u=a||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(ze.size(n)/u),h=k=>{let d=Qe("input",o,t.length,i),z=At("output",o,n.length,u),B;if(o===9){let V=(Z,ee,X="")=>` + let outputIndices${ee} = ${z.offsetToIndices(`outputOffset + ${ee}u`)}; + let offset${ee} = ${d.broadcastedIndicesToOffset(`outputIndices${ee}`,z)}; + let index${ee} = offset${ee} / 4u; + let component${ee} = offset${ee} % 4u; + ${Z}[${ee}] = ${X}(${d.getByOffset(`index${ee}`)}[component${ee}]); + `;B=` + let outputOffset = global_idx * ${u}; + var data = vec4(0); + ${V("data",0,"u32")} + ${V("data",1,"u32")} + ${V("data",2,"u32")} + ${V("data",3,"u32")} + ${z.setByOffset("global_idx","data")} + }`}else B=` + let outputIndices = ${z.offsetToIndices(`global_idx * ${u}`)}; + let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",z)}; + let data = ${z.type.value}(${d.getByOffset(`inputOffset / ${i}`)}); + ${z.setByOffset("global_idx","data")} + }`;return` + ${k.registerUniform("vec_size","u32").declareVariables(d,z)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${B}`},C=[{type:12,data:p},...Mt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${i}${u}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:C})}},qu=e=>{Gu(e.inputs),e.compute(Hu(e.inputs),{inputs:[0]})}}),Eo,Qu,rp=g(()=>{Lt(),Ot(),Jt(),Si(),Eo=e=>{let t=e[0].dataType,s=ze.size(e[0].dims),n=ze.size(e[1].dims),o=n%4===0,a=i=>{let u=Qe("x",t,[1],4),p=Qe("bias",t,[1],4),h=At("y",t,[1],4),C=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],k=z=>` + let bias${z}_offset: u32 = (global_idx * 4 + ${z}) % uniforms.bias_size; + let bias${z} = ${p.getByOffset(`bias${z}_offset / 4`)}[bias${z}_offset % 4];`,d=o?` + let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${k(0)}${k(1)}${k(2)}${k(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(C).declareVariables(u,p,h)} + + ${Ci($s(t))} + + ${i.mainStart(or)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${d} + let x_in = x + bias; + ${h.setByOffset("global_idx",_o("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(s/or/4)}})}},Qu=e=>{e.inputs.length<2||ze.size(e.inputs[1].dims)===0?Xl(e):e.compute(Eo(e.inputs))}}),Xu,Kn,Yu,Ju,np=g(()=>{Lt(),Ot(),rs(),Jt(),Xu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Kn=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s.length,a=ze.normalizeAxis(t.axis,o),i=s.slice(0);i.splice(a,1,...n);let u=s[a],p=e[0].dataType===9?4:1,h=Math.ceil(ze.size(i)/p),C=[{type:12,data:h},{type:6,data:u},{type:12,data:a},...Mt(e[0].dims,e[1].dims,i)],k=d=>{let z=Qe("data",e[0].dataType,e[0].dims.length,p),B=Qe("inputIndices",e[1].dataType,e[1].dims.length),V=At("output",e[0].dataType,i.length,p),Z=X=>{let me=n.length,pe=`var indicesIndices${X} = ${B.type.indices}(0);`;for(let Me=0;Me1?`indicesIndices${X}[${Me}]`:`indicesIndices${X}`} = ${i.length>1?`outputIndices${X}[uniforms.axis + ${Me}]`:`outputIndices${X}`};`;pe+=` + var idx${X} = ${B.getByIndices(`indicesIndices${X}`)}; + if (idx${X} < 0) { + idx${X} = idx${X} + uniforms.axisDimLimit; + } + var dataIndices${X} : ${z.type.indices}; + `;for(let Me=0,Ae=0;Me1?`dataIndices${X}[${Me}]`:`dataIndices${X}`} = u32(idx${X});`,Ae+=me):(pe+=`${o>1?`dataIndices${X}[${Me}]`:`dataIndices${X}`} = ${i.length>1?`outputIndices${X}[${Ae}]`:`outputIndices${X}`};`,Ae++);return pe},ee;if(e[0].dataType===9){let X=(me,pe,Me="")=>` + let outputIndices${pe} = ${V.offsetToIndices(`outputOffset + ${pe}u`)}; + ${Z(pe)}; + let offset${pe} = ${z.indicesToOffset(`dataIndices${pe}`)}; + let index${pe} = offset${pe} / 4u; + let component${pe} = offset${pe} % 4u; + ${me}[${pe}] = ${Me}(${z.getByOffset(`index${pe}`)}[component${pe}]); + `;ee=` + let outputOffset = global_idx * ${p}; + var value = vec4(0); + ${X("value",0,"u32")} + ${X("value",1,"u32")} + ${X("value",2,"u32")} + ${X("value",3,"u32")} + ${V.setByOffset("global_idx","value")} + `}else ee=` + let outputIndices = ${V.offsetToIndices("global_idx")}; + ${Z("")}; + let value = ${z.getByIndices("dataIndices")}; + ${V.setByOffset("global_idx","value")}; + `;return` + ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(z,B,V)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${ee} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:C}),getShaderSource:k}},Yu=e=>zt({axis:e.axis}),Ju=(e,t)=>{let s=e.inputs;Xu(s),e.compute(Kn(e.inputs,t))}}),Zu,Co,ed,op=g(()=>{Lt(),Ot(),Jt(),Zu=(e,t,s,n,o,a,i,u,p)=>{let h=[{type:12,data:a},{type:12,data:n},{type:12,data:o},{type:12,data:s},{type:12,data:i},{type:12,data:u},{type:12,data:p}],C=[a];h.push(...Mt(t.dims,C));let k=d=>{let z=Qe("indices_data",t.dataType,t.dims.length),B=At("input_slice_offsets_data",12,1,1),V=[z,B],Z=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${d.registerUniforms(Z).declareVariables(...V)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${s.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:C,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:k},{inputs:[t],outputs:[-1]})[0]},Co=(e,t)=>{let s=e.inputs,n=s[0].dims,o=s[0].dataType,a=s[1].dims,i=a[a.length-1],u=ze.sizeToDimension(a,a.length-1),p=ze.sizeFromDimension(n,t.batchDims+i),h=ze.sizeToDimension(n,t.batchDims),C=ze.sizeFromDimension(n,t.batchDims),k=u/h,d=new Array(i),z=p;for(let pe=0;pen.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let Z=a.slice(0,-1).concat(n.slice(V)),ee=ze.size(Z),X=[{type:12,data:ee},{type:12,data:p},...Mt(s[0].dims,B.dims,Z)],me=pe=>{let Me=Qe("data",s[0].dataType,s[0].dims.length),Ae=Qe("slice_offsets",12,B.dims.length),De=At("output",s[0].dataType,Z.length);return` + ${pe.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Me,Ae,De)} + ${pe.mainStart()} + ${pe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:Z,dataType:o}],dispatchGroup:{x:Math.ceil(ee/64)},programUniforms:X}),getShaderSource:me},{inputs:[s[0],B]})},ed=e=>({batchDims:e.batch_dims,cacheKey:""})}),td,ip,sd,rd,ap=g(()=>{Lt(),Ot(),rs(),Jt(),td=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=ze.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],a=e[2],i=e.length===4?e[3]:void 0;if(a.dims.length!==o.dims.length||!o.dims.map((u,p)=>p===s?Math.ceil(u/n)===a.dims[p]:u===a.dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==a.dims.length||!i.dims.map((u,p)=>u===a.dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},ip=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s.length,a=ze.normalizeAxis(t.gatherAxis,o),i=ze.normalizeAxis(t.quantizeAxis,o),u=s.slice(0);u.splice(a,1,...n);let p=ze.size(u),h=e[2].dataType,C=e[0].dataType===22,k=[{type:12,data:p},{type:12,data:i},{type:12,data:a},{type:12,data:t.blockSize},...Mt(...e.map((z,B)=>z.dims),u)],d=z=>{let B=Qe("data",e[0].dataType,e[0].dims.length),V=Qe("inputIndices",e[1].dataType,e[1].dims.length),Z=Qe("scales",e[2].dataType,e[2].dims.length),ee=e.length>3?Qe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,X=At("output",h,u.length),me=[B,V,Z];ee&&me.push(ee);let pe=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${z.registerUniforms(pe).declareVariables(...me,X)} + ${z.mainStart()} + let output_indices = ${X.offsetToIndices("global_idx")}; + var indices_indices = ${V.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${X.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${V.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${X.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${B.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${X.indicesGet("output_indices","i")}; + ${B.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${V.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${s[a]}; + } + ${B.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { + let index = ${X.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${B.indicesSet("data_indices","i","index")}; + } + let data_offset = ${B.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${B.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${C?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${Z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${Z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${Z.getByIndices("scale_indices")}; + ${ee?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${ee.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${ee.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${C?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${$s(h)}(quantized_data - zero_point) * scale; + ${X.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((z,B)=>B!==1).map(z=>z.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(z,B)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k}),getShaderSource:d}},sd=(e,t)=>{let s=e.inputs;td(s,t),e.compute(ip(e.inputs,t))},rd=e=>zt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),En,nd,od,id,lp=g(()=>{Lt(),Ot(),rs(),Jt(),En=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.`)},nd=(e,t)=>{let s=e[0].dims,n=e[0].dataType,o=s.length,a=e[1].dims,i=e[1].dataType,u=ze.normalizeAxis(t.axis,o),p=s[u],h=a.slice(0),C=ze.size(h),k=Qe("input",n,o),d=Qe("indicesInput",i,a.length),z=At("output",n,h.length),B=[{type:12,data:C},{type:6,data:p},{type:12,data:u}];return B.push(...Mt(s,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:B}),getShaderSource:V=>` + ${V.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(k,d,z)} + ${V.mainStart()} + ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${z.offsetToIndices("global_idx")}; + + var idx = ${d.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${k.type.indices}(outputIndices); + ${k.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${k.getByIndices("inputIndices")}; + + ${z.setByOffset("global_idx","value")}; + }`}},od=e=>zt({axis:e.axis}),id=(e,t)=>{let s=e.inputs;En(s),e.compute(nd(e.inputs,t))}}),ad,ld,ud,ko,Gp=g(()=>{Lt(),Ot(),Jt(),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")},ld=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[o,a,i]=Or.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[o,a];if(!u)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(a/p),C=Math.ceil(o/p),k=!0,d=ze.size(u),z=[{type:12,data:k?h:d},{type:12,data:o},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],B=["type","type"];e.length===3&&(z.push(...Mt(e[2].dims)),B.push("rank")),z.push(...Mt(u));let V=ee=>{let X="";t.transA&&t.transB?X="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?X="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?X="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(X="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let me=t.alpha===1?"":"value *= uniforms.alpha;",pe=Qe("a",e[0].dataType,e[0].dims),Me=Qe("b",e[1].dataType,e[1].dims),Ae=pe.type.value,De=null,et=[pe,Me];e.length===3&&(De=Qe("c",e[2].dataType,e[2].dims.length),et.push(De));let dt=At("output",e[0].dataType,u.length);et.push(dt);let Pt=[{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` + ${ee.registerUniforms(Pt).declareVariables(...et)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${Ae}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${X} + } + + ${me} + ${De!=null?`let cOffset = ${De.broadcastedIndicesToOffset("vec2(m, n)",dt)}; value += ${Ae}(uniforms.beta) * ${De.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},Z=ee=>{let X=Qe("a",e[0].dataType,e[0].dims),me=Qe("b",e[1].dataType,e[1].dims),pe=null,Me=[X,me];e.length===3&&(pe=Qe("c",e[2].dataType,e[2].dims.length),Me.push(pe));let Ae=At("output",e[0].dataType,u.length);Me.push(Ae);let De=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],et="",dt="";t.transA&&t.transB?(dt=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${X.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${me.type.value}(0); + } + `,et="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(dt=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${X.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${me.type.value}(0); + } + `,et="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(dt=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${X.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${me.type.value}(0); + } + `,et="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(dt=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${X.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${me.type.value}(0); + } + `,et="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Pt=t.alpha===1?"":"value *= uniforms.alpha;";return` + ${ee.registerUniforms(De).declareVariables(...Me)} + var tile_a: array, ${p}>; + var tile_b: array, ${p}>; + ${ee.mainStart([p,p,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; + let num_tiles = (uniforms.K - 1) / ${p} + 1; + var k_start = 0u; + var value = ${Ae.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${dt} + k_start = k_start + ${p}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${p}; k++) { + ${et} + } + workgroupBarrier(); + } + + ${Pt} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${pe!=null?`let cOffset = ${pe.broadcastedIndicesToOffset("vec2(m, n)",Ae)}; value += ${Ae.type.value}(uniforms.beta) * ${pe.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return k?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:h*C},programUniforms:z}),getShaderSource:Z}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:z}),getShaderSource:V}},ud=e=>{let t=e.transA,s=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:s,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},ko=(e,t)=>{ad(e.inputs),e.compute(ld(e.inputs,t))}}),Pr,Dr,un,dn,dd,la,cd,pd,ua,hd,md,da,_d,fd,ca=g(()=>{Lt(),Ot(),rs(),Jt(),[Pr,Dr,un,dn]=[0,1,2,3],dd=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},la=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,cd=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,pd=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,ua=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,hd=(e,t,s)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { + var pixel = ${t}(0); + var indices = vec4(0); + indices[${Pr}] = batch; + indices[${Dr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${un}] = u32(r); + indices[${dn}] = u32(c); + } + `;case"border":return` + indices[${un}] = u32(clamp(r, 0, H - 1)); + indices[${dn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${un}] = gs_reflect(r, border[1], border[3]); + indices[${dn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,md=(e,t,s)=>(()=>{switch(s.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Pr}], indices[${Dr}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Pr}], indices[${Dr}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Pr}], indices[${Dr}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Pr}], indices[${Dr}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Pr}], indices[${Dr}], border); + + let dx2 = ${t}(f32(x2) - x); + let dx1 = ${t}(x - f32(x1)); + let dy2 = ${t}(f32(y2) - y); + let dy1 = ${t}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${t}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Pr}], indices[${Dr}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,da=(e,t)=>{let s=Qe("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Qe("grid",e[1].dataType,n.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Pr,Dr,un,dn]=[0,3,1,2]);let i=At("output",e[0].dataType,a.length),u=s.type.value,p=ze.size(a),h=[{type:12,data:p},...Mt(e[0].dims,n,a)],C=k=>` + ${k.registerUniform("output_size","u32").declareVariables(s,o,i)} + ${la} + ${cd(u)} + ${pd(t)} + ${ua(t)} + ${hd(s,u,t)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${un}]); + let W_in = i32(uniforms.x_shape[${dn}]); + + ${t.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Pr}], indices[${un}], indices[${dn}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${md(i,u,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:k=>{let d=ze.size(a);return{outputs:[{dims:a,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}},getShaderSource:C}},_d=(e,t)=>{dd(e.inputs),e.compute(da(e.inputs,t))},fd=e=>zt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),nr,gd,wd,pa,ha,cn,up,yd=g(()=>{Lt(),Ot(),rs(),ue(),pi(),Jt(),Hr(),nr=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,gd=(e,t)=>{let s=e[0],n=nr(e,1),o=nr(e,2),a=nr(e,3),i=nr(e,4),u=nr(e,5),p=nr(e,6),h=nr(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let C=s.dims[0],k=s.dims[1],d=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],z=k,B=0,V=0,Z=Math.floor(d/t.numHeads);if(p&&h&&ze.size(p.dims)&&ze.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==C||p.dims[1]!==t.numHeads||p.dims[3]!==Z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==C||h.dims[1]!==t.numHeads||h.dims[3]!==Z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');B=p.dims[2],V=p.dims[2]}else if(p&&ze.size(p.dims)||h&&ze.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee;if(n&&ze.size(n.dims)>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');ee=2,z=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==Z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');ee=5,z=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==Z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');ee=0,z=n.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');ee=3}if(a&&ze.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let X=B+z,me=0;if(i&&ze.size(i.dims)>0){me=8;let De=i.dims;throw De.length===1?De[0]===C?me=1:De[0]===3*C+2&&(me=3):De.length===2&&De[0]===C&&De[1]===X&&(me=5),me===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let pe=!1,Me=d;if(o&&ze.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(z!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Me=o.dims[2]}else{if(z!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Me=o.dims[1]*o.dims[3],pe=!0}}let Ae=!1;if(i&&ze.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(u&&ze.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==C||u.dims[1]!==t.numHeads||u.dims[2]!==k||u.dims[3]!==X)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:C,sequenceLength:k,pastSequenceLength:B,kvSequenceLength:z,totalSequenceLength:X,maxSequenceLength:V,inputHiddenSize:0,hiddenSize:d,vHiddenSize:Me,headSize:Z,vHeadSize:Math.floor(Me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:me,scale:t.scale,broadcastResPosBias:Ae,passPastInKv:pe,qkvFormat:ee}},wd=e=>zt({...e}),pa=zt({perm:[0,2,1,3]}),ha=(e,t,s,n,o,a,i)=>{let u=[n,o,a],p=ze.size(u),h=[{type:12,data:p},{type:12,data:i},{type:12,data:a}],C=k=>{let d=At("qkv_with_bias",t.dataType,u),z=Qe("qkv",t.dataType,u),B=Qe("bias",s.dataType,u),V=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${k.registerUniforms(V).declareVariables(z,B,d)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:C},{inputs:[t,s],outputs:[-1]})[0]},cn=(e,t,s,n,o,a,i,u)=>{let p=a;if(i&&ze.size(i.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=ha(e,a,i,t,n,s*o,u),p=p.reshape([t,n,s,o]),s===1||n===1?p:e.compute(pr(p,pa.perm),{inputs:[p],outputs:[-1]})[0]}else return a.dims.length===3&&(p=a.reshape([t,n,s,o])),s===1||n===1?p:e.compute(pr(p,pa.perm),{inputs:[p],outputs:[-1]})[0]},up=(e,t)=>{let s=gd(e.inputs,t),n=e.inputs[0],o=nr(e.inputs,1),a=nr(e.inputs,2),i=nr(e.inputs,3),u=nr(e.inputs,4),p=nr(e.inputs,5),h=nr(e.inputs,6),C=nr(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let k=o&&a&&o.dims.length===4&&a.dims.length===4,d=cn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,i,0);if(k)return jn(e,d,o,a,u,void 0,h,C,p,s);if(!o||!a)throw new Error("key and value must be provided");let z=cn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,o,i,s.hiddenSize),B=cn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,a,i,2*s.hiddenSize);jn(e,d,z,B,u,void 0,h,C,p,s)}}),Md,ma,bd,vd,So,Td,xd,_a=g(()=>{Lt(),Ot(),rs(),Jt(),Md=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ma=(e,t)=>{let s=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>s.push(Number(o))),n=s.length),zt({numOutputs:n,axis:t.axis,splitSizes:s})},bd=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; +}`,vd=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=ze.size(s),o=e[0].dataType,a=ze.normalizeAxis(t.axis,s.length),i=new Array(t.numOutputs),u=Qe("input",o,s.length),p=new Array(t.numOutputs),h=[],C=[],k=0,d=[{type:12,data:n}];for(let B=0;B` + ${B.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(u,...i)} + ${bd(p.length)} + ${vd(i)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",a)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${St("uniforms.size_in_split_axis","output_number - 1u",p.length)}; + ${u.indicesSet("indices",a,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:z,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:d})}},Td=(e,t)=>{Md(e.inputs);let s=e.inputs.length===1?t:ma(e.inputs,t);e.compute(So(e.inputs,s),{inputs:[0]})},xd=e=>{let t=e.axis,s=e.splitSizes,n=e.numOutputs<0?s.length:e.numOutputs;if(n!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return zt({axis:t,numOutputs:n,splitSizes:s})}}),dp,cp,$o,fa,pp=g(()=>{rs(),pi(),yd(),_a(),Hr(),dp=(e,t)=>{if(t.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],o=e[2],a=e[3],i=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,p=s.dims[0],h=s.dims[1],C=s.dims.length===3?u?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],k=h,d=0,z=!n||n.dims.length===0,B=Math.floor(z?C/(t.numHeads+2*t.kvNumHeads):C/t.numHeads);z&&(C=B*t.numHeads);let V=a&&a.dims.length!==0,Z=i&&i.dims.length!==0;if(V&&a.dims.length===4&&a.dims[0]===p&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===B)throw new Error("BSNH pastKey/pastValue is not supported");if(V&&Z){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=a.dims[2]}else if(V||Z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee=1;if(n&&n.dims.length>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(s.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');k=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==B)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');k=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==B)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');k=n.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');ee=3}let X=0,me=!1,pe=t.kvNumHeads?B*t.kvNumHeads:C;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(k!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');pe=o.dims[2]}else{if(k!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');pe=o.dims[1]*o.dims[3],me=!0}}let Me=e.length>4?e[5]:void 0;if(Me&&Me.dims.length!==1&&Me.dims[0]!==p)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:p,sequenceLength:h,pastSequenceLength:d,kvSequenceLength:k,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:C,vHiddenSize:pe,headSize:B,vHeadSize:Math.floor(pe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:me,qkvFormat:ee}},cp=zt({perm:[0,2,1,3]}),$o=(e,t,s)=>{let n=t,o=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(n=t.reshape([s.batchSize,s.kvSequenceLength,o,s.headSize]),n=e.compute(pr(n,cp.perm),{inputs:[n],outputs:[-1]})[0]),n},fa=(e,t)=>{var Z;let s=dp(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((Z=e.inputs[1])==null?void 0:Z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,C=s.kvNumHeads?s.kvNumHeads:s.numHeads,k=zt({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,C*s.headSize,C*s.headSize]}),[d,z,B]=!o&&!a?e.compute(So([n],k),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,a],V=cn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,d,void 0,0);jn(e,V,$o(e,z,s),$o(e,B,s),void 0,void 0,i,u,void 0,s,p,h)}}),ga,wa,Pd,Ed,Cd=g(()=>{Lt(),Ot(),Hr(),Jt(),ga=(e,t,s,n,o,a,i,u)=>{let p=Xt(a),h=p===1?"f32":`vec${p}f`,C=p===1?"vec2f":`mat2x${p}f`,k=o*i,d=64;k===1&&(d=256);let z=[o,i,a/p],B=[o,i,2],V=["rank","type","type"],Z=[];Z.push(...Mt(z,B));let ee=X=>{let me=Qe("x",t.dataType,3,p),pe=Qe("scale",s.dataType,s.dims),Me=Qe("bias",n.dataType,n.dims),Ae=At("output",1,3,2),De=[me,pe,Me,Ae];return` + var workgroup_shared : array<${C}, ${d}>; + const workgroup_size = ${d}u; + ${X.declareVariables(...De)} + ${X.mainStart(d)} + 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}(${me.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${C}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Gs("workgroup_shared[0][0]",p)} / f32(hight * ${p}); + let squared_sum_final = ${Gs("workgroup_shared[0][1]",p)} / f32(hight * ${p}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); + 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};${u};${d}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:B,dataType:1}],dispatchGroup:{x:k},programUniforms:Z}),getShaderSource:ee},{inputs:[t,s,n],outputs:[-1]})[0]},wa=(e,t,s)=>{let n=t[0].dims,o=n,a=2,i=n[0],u=n[1],p=ze.sizeFromDimension(n,a),h=Xt(p),C=ze.size(o)/h,k=ga(e,t[0],t[1],t[2],i,p,u,s.epsilon),d=[i,u,p/h],z=[i,u],B=["type","none"],V=Z=>{let ee=Qe("x",t[0].dataType,d.length,h),X=Qe("scale_shift",1,z.length,2),me=At("output",t[0].dataType,d.length,h),pe=[ee,X,me];return` + ${Z.registerUniform("output_size","u32").declareVariables(...pe)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${me.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${X.getByIndices("vec2(batch, channel)")}; + let value = ${ee.getByOffset("global_idx")} * ${me.type.value}(scale_shift.x) + ${me.type.value}(scale_shift.y); + ${me.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...Mt(d,z,d)]}),getShaderSource:V},{inputs:[t[0],k]})},Pd=(e,t,s)=>{let n=t[0].dims,o=n,a=n[0],i=n[n.length-1],u=ze.sizeFromDimension(n,1)/i,p=Xt(i),h=ze.size(o)/p,C=[{type:12,data:u},{type:12,data:Math.floor(i/p)}],k=["type","type"],d=!1,z=[0,n.length-1];for(let ee=0;een[z[X]])),V=ga(e,B,t[1],t[2],a,u,i,s.epsilon),Z=ee=>{let X=fs(t[0].dataType),me=p===1?"vec2f":`mat${p}x2f`,pe=De=>{let et=De===0?"x":"y",dt=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${X}(${dt}(scale.${et}))`;case 2:return`vec2<${X}>(${dt}(scale[0].${et}, scale[1].${et}))`;case 4:return`vec4<${X}>(${dt}(scale[0].${et}, scale[1].${et}, scale[2].${et}, scale[3].${et}))`;default:throw new Error(`Not supported compoents ${p}`)}},Me=Qe("input",t[0].dataType,t[0].dims,p),Ae=At("output",t[0].dataType,o,p);return` + @group(0) @binding(0) var input : array<${Me.type.storage}>; + @group(0) @binding(1) var scale_input : array<${me}>; + @group(0) @binding(2) var output : array<${Ae.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${ee.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:k},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:C}),getShaderSource:Z},{inputs:[t[0],V]})},Ed=(e,t)=>{t.format==="NHWC"?Pd(e,e.inputs,t):wa(e,e.inputs,t)}}),kd,Sd,ya,hp=g(()=>{Lt(),Ot(),Jt(),kd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Sd=(e,t,s)=>{let n=t.simplified,o=e[0].dims,a=e[1],i=!n&&e[2],u=o,p=ze.normalizeAxis(t.axis,o.length),h=ze.sizeToDimension(o,p),C=ze.sizeFromDimension(o,p),k=ze.size(a.dims),d=i?ze.size(i.dims):0;if(k!==C||i&&d!==C)throw new Error(`Size of X.shape()[axis:] == ${C}. + Size of scale and bias (if provided) must match this. + Got scale size of ${k} and bias size of ${d}`);let z=[];for(let Me=0;Me1,X=s>2,me=Me=>{let Ae=fs(e[0].dataType),De=[Qe("x",e[0].dataType,e[0].dims,B),Qe("scale",a.dataType,a.dims,B)];i&&De.push(Qe("bias",i.dataType,i.dims,B)),De.push(At("output",e[0].dataType,u,B)),ee&&De.push(At("mean_data_output",1,z)),X&&De.push(At("inv_std_output",1,z));let et=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${Me.registerUniforms(et).declareVariables(...De)} + ${Me.mainStart()} + ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${zs("f32",B)}; + var mean_square_vector = ${zs("f32",B)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${As(Ae,B,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Gs("mean_vector",B)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Gs("mean_square_vector",B)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${As(Ae,B,"x[j + offset]")}; + let f32scale = ${As(Ae,B,"scale[j]")}; + output[j + offset] = ${De[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${As(Ae,B,"bias[j]")}`:""} + ); + } + + ${ee?"mean_data_output[global_idx] = mean":""}; + ${X?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},pe=[{dims:u,dataType:e[0].dataType}];return ee&&pe.push({dims:z,dataType:1}),X&&pe.push({dims:z,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${B};${s};${n}`,inputDependencies:V},getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:Z}),getShaderSource:me}},ya=(e,t)=>{kd(e.inputs),e.compute(Sd(e.inputs,t,e.outputCount))}}),$d,Ad,mp=g(()=>{Ot(),fo(),Wi(),$d=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.")},Ad=e=>{$d(e.inputs);let t=Ws.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let s=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(s<8&&n<8)e.compute(Ni(e.inputs,{activation:""},t));else{let o=t[t.length-2],a=ze.size(e.inputs[0].dims.slice(0,-2)),i=ze.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&o===1&&i===1){let u=e.inputs[0].reshape([1,a,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,a,s],C=[u,p];e.compute(wo(C,{activation:""},t,h),{inputs:C})}else e.compute(wo(e.inputs,{activation:""},t))}}}),Id,Od,Fd,Dd,Ld,zd=g(()=>{Lt(),Ot(),rs(),Jt(),Id=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!ze.areEqual(i.dims,[t.n,o,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(ze.size(u)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(ze.size(p)!==h)throw new Error("zeroPoints input size error.")}},Od=(e,t)=>{let s=e[0].dims,n=s.length,o=s[n-2],a=t.k,i=t.n,u=s.slice(0,n-2),p=ze.size(u),h=e[1].dims[2]/4,C=e[0].dataType,k=Xt(t.k),d=Xt(h),z=Xt(i),B=u.concat([o,i]),V=o>1&&i/z%2===0?2:1,Z=ze.size(B)/z/V,ee=64,X=[],me=[p,o,a/k],pe=ze.convertShape(e[1].dims).slice();pe.splice(-1,1,h/d),X.push(...Mt(me)),X.push(...Mt(pe)),X.push(...Mt(e[2].dims)),e.length===4&&X.push(...Mt(ze.convertShape(e[3].dims)));let Me=[p,o,i/z];X.push(...Mt(Me));let Ae=De=>{let et=me.length,dt=Qe("a",e[0].dataType,et,k),Pt=Qe("b",12,pe.length,d),qt=Qe("scales",e[2].dataType,e[2].dims.length),Bt=[dt,Pt,qt],It=e.length===4?Qe("zero_points",12,e[3].dims.length):void 0;It&&Bt.push(It);let ts=Me.length,wt=At("output",e[0].dataType,ts,z),Ht=fs(e[0].dataType),ps=(()=>{switch(k){case 1:return`array<${Ht}, 8>`;case 2:return`mat4x2<${Ht}>`;case 4:return`mat2x4<${Ht}>`;default:throw new Error(`${k}-component is not supported.`)}})(),Ut=()=>{let it=` + // reuse a data + var input_offset = ${dt.indicesToOffset(`${dt.type.indices}(batch, row, word_offset)`)}; + var a_data: ${ps}; + for (var j: u32 = 0; j < ${8/k}; j++) { + a_data[j] = ${dt.getByOffset("input_offset")}; + input_offset++; + } + `;for(let Et=0;Et> 4) & b_mask); + b_quantized_values = ${ps}(${Array.from({length:4},(hs,Ns)=>`${Ht}(b_value_lower[${Ns}]), ${Ht}(b_value_upper[${Ns}])`).join(", ")}); + b_dequantized_values = ${k===1?`${ps}(${Array.from({length:8},(hs,Ns)=>`(b_quantized_values[${Ns}] - ${It?`zero_point${Et}`:"zero_point"}) * scale${Et}`).join(", ")});`:`(b_quantized_values - ${ps}(${Array(8).fill(`${It?`zero_point${Et}`:"zero_point"}`).join(",")})) * scale${Et};`}; + workgroup_shared[local_id.x * ${V} + ${Math.floor(Et/z)}]${z>1?`[${Et%z}]`:""} += ${Array.from({length:8/k},(hs,Ns)=>`${k===1?`a_data[${Ns}] * b_dequantized_values[${Ns}]`:`dot(a_data[${Ns}], b_dequantized_values[${Ns}])`}`).join(" + ")}; + `;return it},Qt=()=>{let it=` + var col_index = col * ${z}; + ${It?` + 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 = ${Ht}(8);`} + `;for(let Et=0;Et> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${It.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${Et} = ${Ht}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return it},gs=()=>{let it=`col_index = col * ${z};`;for(let Et=0;Et; + var b_value_upper: vec4; + var b_quantized_values: ${ps}; + var b_dequantized_values: ${ps};`,it};return` + var workgroup_shared: array<${wt.type.value}, ${V*ee}>; + ${De.declareVariables(...Bt,wt)} + ${De.mainStart([ee,1,1])} + let output_indices = ${wt.offsetToIndices(`(global_idx / ${ee}) * ${V}`)}; + 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 += ${ee}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/k}; + ${Qt()} + for (var word: u32 = 0; word < ${h}; word += ${d}) { + ${gs()} + for (var i: u32 = 0; i < ${d}; i++) { + ${Ut()} + word_offset += ${8/k}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${V}) { + var output_value: ${wt.type.value} = ${wt.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${ee}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${V}; + } + ${wt.setByIndices(`${wt.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${k};${d};${z};${V};${ee}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:C}],dispatchGroup:{x:Z},programUniforms:X}),getShaderSource:Ae}},Fd=(e,t)=>{let s=e[0].dims,n=s.length,o=s[n-2],a=t.k,i=t.n,u=s.slice(0,n-2),p=ze.size(u),h=e[1].dims[2]/4,C=e[0].dataType,k=Xt(t.k),d=Xt(h),z=u.concat([o,i]),B=128,V=i%8===0?8:i%4===0?4:1,Z=B/V,ee=Z*d*8,X=ee/k,me=ee/t.blockSize,pe=ze.size(z)/V,Me=[],Ae=[p,o,a/k],De=ze.convertShape(e[1].dims).slice();De.splice(-1,1,h/d),Me.push(...Mt(Ae)),Me.push(...Mt(De)),Me.push(...Mt(e[2].dims)),e.length===4&&Me.push(...Mt(ze.convertShape(e[3].dims)));let et=[p,o,i];Me.push(...Mt(et));let dt=Pt=>{let qt=Ae.length,Bt=Qe("a",e[0].dataType,qt,k),It=Qe("b",12,De.length,d),ts=Qe("scales",e[2].dataType,e[2].dims.length),wt=[Bt,It,ts],Ht=e.length===4?Qe("zero_points",12,e[3].dims.length):void 0;Ht&&wt.push(Ht);let ps=et.length,Ut=At("output",e[0].dataType,ps),Qt=fs(e[0].dataType),gs=()=>{switch(k){case 1:return` + let a_data0 = vec4<${Qt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${Qt}>(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<${Qt}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${Qt}>(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(`${k}-component is not supported.`)}};return` + var sub_a: array<${Bt.type.value}, ${X}>; + var inter_results: array, ${V}>; + ${Pt.declareVariables(...wt,Ut)} + ${Pt.mainStart([Z,V,1])} + let output_indices = ${Ut.offsetToIndices(`workgroup_index * ${V}`)}; + 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) / ${me} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${X}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${X}; a_offset += ${B}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${Bt.getByIndices(`${Bt.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${Bt.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${me} + local_id.x; + ${Ht?` + 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 = ${Ht.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${Qt}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Qt}(8);`} + let scale = ${ts.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${It.getByIndices(`${It.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize/k}; + for (var i: u32 = 0; i < ${d}; i++) { + ${gs()} + let b_value = ${d===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<${Qt}>(${Array.from({length:4},(it,Et)=>`${Qt}(b_value_lower[${Et}]), ${Qt}(b_value_upper[${Et}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${Qt}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(it,Et)=>`${`dot(a_data${Et}, b_dequantized_values[${Et}])`}`).join(" + ")}; + word_offset += ${8/k}; + } + workgroupBarrier(); + } + + if (local_idx < ${V}) { + var output_value: ${Ut.type.value} = ${Ut.type.value}(0); + for (var b = 0u; b < ${Z}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${Ut.setByIndices(`${Ut.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${k};${d};${Z};${V}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:z,dataType:C}],dispatchGroup:{x:pe},programUniforms:Me}),getShaderSource:dt}},Dd=(e,t)=>{Id(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Fd(e.inputs,t)):e.compute(Od(e.inputs,t))},Ld=e=>zt(e)}),Bd,Rd,Ma,Nd,jd,ys,_p,fp,gp,Ud=g(()=>{Lt(),Ot(),Jt(),Bd=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].")}},Rd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${St("uniforms.pads",o,s)}; + if (k < 0) { + break; + } + if (k >= i32(${St("uniforms.x_shape",o,t)})) { + break; + } + offset += k * i32(${St("uniforms.x_strides",o,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},Ma=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${St("uniforms.pads",o,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${St("uniforms.x_shape",o,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${St("uniforms.x_shape",o,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${St("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Nd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${St("uniforms.pads",o,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${St("uniforms.x_shape",o,t)})) { + k = i32(${St("uniforms.x_shape",o,t)}) - 1; + } + offset += k * i32(${St("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},jd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${St("uniforms.pads",o,s)}; + if (k < 0) { + k += i32(${St("uniforms.x_shape",o,t)}]); + } + if (k >= i32(${St("uniforms.x_shape",o,t)})) { + k -= i32(${St("uniforms.x_shape",o,t)}); + } + offset += k * i32(${St("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},ys=(e,t,s)=>{switch(s.mode){case 0:return Rd(e,t,s.pads.length);case 1:return Ma(e,t,s.pads.length);case 2:return Nd(e,t,s.pads.length);case 3:return jd(e,t,s.pads.length);default:throw new Error("Invalid mode")}},_p=(e,t)=>{let s=ze.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=ze.size(s),a=[{type:12,data:o},{type:6,data:t.pads}],i=e.length>=3&&e[2].data;t.mode===0&&a.push({type:i?e[2].dataType:1,data:t.value}),a.push(...Mt(e[0].dims,s));let u=["rank"],p=h=>{let C=At("output",e[0].dataType,s.length),k=Qe("x",e[0].dataType,n.length),d=k.type.value,z=ys(C,n.length,t),B=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&B.push({name:"constant_value",type:i?d:"f32"}),` + ${h.registerUniforms(B).declareVariables(k,C)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${C.offsetToIndices("global_idx")}; + + var value = ${d}(0); + ${z} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${i}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(s)/64)},programUniforms:a}),getShaderSource:p}},fp=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,a=new Int32Array(2*o).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let p=0;pa[Number(p)]=Number(u));let i=[];return a.forEach(u=>i.push(u)),{mode:t.mode,value:n,pads:i}}else return t},gp=(e,t)=>{Bd(e.inputs);let s=fp(e.inputs,t);e.compute(_p(e.inputs,s),{inputs:[0]})}}),Hn,ba,va,Ta,Ao,xa,wp,Pa,Ea,Ca,yp,Vd,Wd,Gd,ka,Kd,Hd,qd,Qd,Mp=g(()=>{Re(),Lt(),Ot(),Jt(),Hn=e=>{if(O.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},ba=(e,t,s)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),u=t.strides.slice(),p=a?t.dilations.slice():[],h=t.pads.slice();Zs.adjustPoolAttributes(s,o,i,u,p,h);let C=Zs.computePoolOutputShape(s,o,u,p,i,h,t.autoPad),k=Object.assign({},t);a?Object.assign(k,{kernelShape:i,strides:u,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(k,{kernelShape:i,strides:u,pads:h,cacheKey:t.cacheKey});let d=C.slice();return d.push(d.splice(1,1)[0]),[k,n?d:C]},va=(e,t)=>{let s=t.format==="NHWC",n=ze.size(e),o=ze.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:o}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],C=t.pads[t.pads.length-1],k=!!(h+C);a.push({type:12,data:u},{type:12,data:p},{type:12,data:h},{type:12,data:C}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(t.kernelShape.length===2){let z=t.kernelShape[t.kernelShape.length-2],B=t.strides[t.strides.length-2],V=t.pads[t.pads.length/2-2],Z=t.pads[t.pads.length-2];d=!!(V+Z),a.push({type:12,data:z},{type:12,data:B},{type:12,data:V},{type:12,data:Z}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,k,d]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=ze.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,C)=>h+C);return[a,i,!!p,!1,!1]}},Ta=(e,t,s,n,o,a,i,u,p,h,C,k)=>{let d=o.format==="NHWC",z=t.type.value,B=At("output",t.type.tensor,n);if(o.kernelShape.length<=2){let V="",Z="",ee="",X=s-(d?2:1);if(C?V=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${X}] < 0 || xIndices[${X}] + >= uniforms.x_shape[${X}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:V=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`,o.kernelShape.length===2){let me=s-(d?3:2);k?Z=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${me}] = indices[${me}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${me}] < 0 || xIndices[${me}] >= uniforms.x_shape[${me}]) { + pad += i32(uniforms.kw); + continue; + } + `:Z=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${me}] = indices[${me}] * uniforms.sh - uniforms.phStart + j; + `,ee=` + } + `}return` + ${e.registerUniforms(p).declareVariables(t,B)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${B.offsetToIndices("global_idx")}; + var xIndices = ${B.offsetToIndices("global_idx")}; + + var value = ${z}(${u}); + var pad = 0; + ${Z} + ${V} + ${ee} + ${i} + + output[global_idx] = value; + }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let V=o.kernelShape.length,Z=o.pads.length,ee="";return h?ee=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:ee=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + `,` + ${e.registerUniforms(p).declareVariables(t,B)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${B.offsetToIndices("global_idx")}; + var xIndices = ${B.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${z}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${V-1}u; j++) { + offsets[j] = offset / ${St("uniforms.kernelStrides","j",V)}; + offset -= offsets[j] * ${St("uniforms.kernelStrides","j",V)}; + } + offsets[${V-1}] = offset; + + isPad = false; + for (var j = ${s-V}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${St("uniforms.strides",`j - ${s-V}u`,V)} + + offsets[j - ${s-V}u] - ${St("uniforms.pads","j - 2u",Z)}; + ${ee} + } + ${i} + + output[global_idx] = value; + }`}},Ao=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,xa=e=>`${Ao(e)};${e.countIncludePad}`,wp=e=>`${Ao(e)};${e.storageOrder};${e.dilations}`,Pa=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}),Ea=(e,t,s,n)=>{let[o,a]=ba(t,n,s),i=Qe("x",t.dataType,t.dims.length),u=i.type.value,p="value += x_val;",h="";o.countIncludePad?h+=`value /= ${u}(uniforms.kernelSize);`:h+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[C,k,d,z,B]=va(a,o);C.push(...Mt(t.dims,a));let V=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${d};${z};${B}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ze.size(a)/64)},programUniforms:C}),getShaderSource:Z=>Ta(Z,i,t.dims.length,a.length,o,p,h,0,k,d,z,B)}},Ca=e=>{let t=e.count_include_pad!==0,s=Pa(e);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...s,cacheKey:""};return{...n,cacheKey:xa(n)}},yp=(e,t)=>{Hn(e.inputs),e.compute(Ea("AveragePool",e.inputs[0],!1,t))},Vd={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Wd=e=>{let t=e.format;return{format:t,...Vd,cacheKey:t}},Gd=(e,t)=>{Hn(e.inputs),e.compute(Ea("GlobalAveragePool",e.inputs[0],!0,t))},ka=(e,t,s,n)=>{let[o,a]=ba(t,n,s),i=` + value = max(x_val, value); + `,u="",p=Qe("x",t.dataType,t.dims.length),h=["rank"],[C,k,d,z,B]=va(a,o);return C.push(...Mt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${d};${z};${B}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ze.size(a)/64)},programUniforms:C}),getShaderSource:V=>Ta(V,p,t.dims.length,a.length,o,i,u,t.dataType===10?-65504:-1e5,k,d,z,B)}},Kd=(e,t)=>{Hn(e.inputs),e.compute(ka("MaxPool",e.inputs[0],!1,t))},Hd=e=>{let t=e.storage_order,s=e.dilations,n=Pa(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:s,...n,cacheKey:""};return{...o,cacheKey:wp(o)}},qd=e=>{let t=e.format;return{format:t,...Vd,cacheKey:t}},Qd=(e,t)=>{Hn(e.inputs),e.compute(ka("GlobalMaxPool",e.inputs[0],!0,t))}}),Xd,Yd,Jd,Zd,Kp=g(()=>{Lt(),Ot(),rs(),Jt(),Xd=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((s,n)=>s===e[2].dims[n]).reduce((s,n)=>s&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,a)=>a===t.axis||o===e[0].dims[a]).reduce((o,a)=>o&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let s=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(s/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Yd=(e,t)=>{let s=ze.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,a=e[0].dims,i=e[1].dataType,u=ze.size(a),p=n===3||n===2,h=p?[Math.ceil(ze.size(e[0].dims)/4)]:e[0].dims,C=e[1].dims,k=e.length>2?e[2]:void 0,d=k?p?[Math.ceil(ze.size(k.dims)/4)]:k.dims:void 0,z=C.length===0||C.length===1&&C[0]===1,B=z===!1&&C.length===1,V=Xt(u),Z=z&&(!p||V===4),ee=Z?V:1,X=Z&&!p?V:1,me=Qe("input",p?12:n,h.length,X),pe=Qe("scale",i,C.length),Me=k?Qe("zero_point",p?12:n,d.length):void 0,Ae=At("output",i,a.length,ee),De=[me,pe];Me&&De.push(Me);let et=[h,C];k&&et.push(d);let dt=[{type:12,data:u/ee},{type:12,data:s},{type:12,data:t.blockSize},...Mt(...et,a)],Pt=qt=>{let Bt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${qt.registerUniforms(Bt).declareVariables(...De,Ae)} + ${qt.mainStart()} + ${qt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Ae.offsetToIndices("global_idx")}; + + // Set input x + ${p?` + let input = ${me.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${ee===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${me.getByOffset("global_idx")};`}; + + // Set scale input + ${z?`let scale_value= ${pe.getByOffset("0")}`:B?` + let scale_index = ${Ae.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${pe.getByOffset("scale_index")};`:` + var scale_indices: ${pe.type.indices} = output_indices; + let index = ${pe.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${pe.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${pe.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${Me?z?p?` + let zero_point_input = ${Me.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Me.getByOffset("0")}`:B?p?` + let zero_point_index = ${Ae.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${Me.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Ae.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${Me.getByOffset("zero_point_index")};`:p?` + let zero_point_offset = ${pe.indicesToOffset("scale_indices")}; + let zero_point_input = ${Me.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Me.getByIndices("scale_indices")};`:`let zero_point_value = ${p?o?"i32":"u32":me.type.value}(0);`}; + // Compute and write output + ${Ae.setByOffset("global_idx",`${Ae.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:Me?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Pt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(u/ee/64),y:1,z:1},programUniforms:dt})}},Jd=(e,t)=>{Xd(e.inputs,t),e.compute(Yd(e.inputs,t))},Zd=e=>zt({axis:e.axis,blockSize:e.blockSize})}),ec,tc,sc,bp=g(()=>{Re(),Lt(),Jt(),ec=(e,t,s)=>{let n=e===t,o=et&&s>0;if(n||o||a)throw new Error("Range these inputs' contents are invalid.")},tc=(e,t,s,n)=>{let o=Math.abs(Math.ceil((t-e)/s)),a=[o],i=o,u=[{type:12,data:i},{type:n,data:e},{type:n,data:s},...Mt(a)],p=h=>{let C=At("output",n,a.length),k=C.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:k},{name:"delta",type:k}];return` + ${h.registerUniforms(d).declareVariables(C)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${k}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:u})}},sc=e=>{let t=0,s=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),O.webgpu.validateInputContent&&ec(t,s,n),e.compute(tc(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),rc,nc,vp,Sa,Tp=g(()=>{Lt(),Ot(),rs(),Jt(),rc=(e,t,s,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,a=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${t}=${s};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${s}));`:` + ${o}bitcast<${n}>(oldValue) + (${s})${a}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${s}));`:` + ${o}max(bitcast(oldValue), (${s}))${a}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${s}));`:`${o}min(bitcast<${n}>(oldValue), (${s}))${a}`;case"mul":return`${o}(bitcast<${n}>(oldValue) * (${s}))${a}`;default:throw new Error(`Reduction ${e} is not supported.`)}},nc=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s,a=1,i=Math.ceil(ze.size(n)/a),u=n[n.length-1],p=ze.sizeFromDimension(s,u),h=[{type:12,data:i},{type:12,data:u},{type:12,data:p},...Mt(e[1].dims,e[2].dims,o)],C=k=>{let d=Qe("indices",e[1].dataType,e[1].dims.length),z=Qe("updates",e[2].dataType,e[2].dims.length,a),B=t.reduction!=="none"&&t.reduction!==""?Na("output",e[0].dataType,o.length):At("output",e[0].dataType,o.length,a);return` + ${k.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(d,z,B)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var data_offset = 0u; + let indices_start = uniforms.last_index_dimension * global_idx; + let indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${e[0].dims.length===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[i - indices_start]; + let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim)); + } + + for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * global_idx + i]; + ${rc(t.reduction,"output[data_offset + i]","value",B.type.value)} + } + + }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:h}),getShaderSource:C}},vp=e=>zt({reduction:e.reduction}),Sa=(e,t)=>{e.compute(nc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),oc,ic,ac,$a,lc,uc,dc,cc,pc,hc,mc,_c,Aa,fc,gc,wc,yc,Mc,bc,vc,xp=g(()=>{Lt(),Ot(),rs(),Jt(),oc=(e,t)=>{if(e.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},ic=(e,t,s)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(s).fill(1);return t.forEach((o,a)=>n[o]=e[a]),n},ac=(e,t,s,n,o,a)=>{let[i,u,p]=s>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(C=>a.push(C));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach(C=>n.push(C)),n.length!==0&&n.length!==h&&s>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");oc(n,t),t.axes.length>0&&ic(n,t.axes,h).forEach((C,k)=>n[k]=C)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(C=>o.push(Number(C))),o.length!==0&&o.length!==h&&s>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof o<"u"&&n.length>0&&o.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},$a=(e,t,s,n)=>` + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let big = (${e}) * (${t}); + let whole = ${n}(big / (${s})); + let fract = ${n}(big % (${s})) / ${n}(${s}); + return whole + fract; +`,lc=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${t}(xResized) / ${t}(xScale); + } else { + ${$a("xResized","lengthOriginal","lengthResized",t)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${$a("xResized","lengthOriginal - 1","lengthResized - 1",t)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${t}(roiStart) * ${t}(lengthOriginal - 1) + + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / + ${t}(lengthResized - 1); + } else { + return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); + const adjustment = ${t}(lengthResized) / outputWidth; + const center = ${t}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",uc=(e,t,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",dc=(e,t,s)=>{let n=new Array(s).fill(0).concat(new Array(s).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=o[i],n[i+s]=o[t.length+i]}),n):o},cc=(e,t,s,n)=>{let o=[];if(s.length>0)if(n.length>0){if(e.forEach(a=>o.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>o[a]=s[i])}else s.forEach(a=>o.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((a,i)=>Math.round(a*t[i]))}return o},pc=(e,t,s)=>{let n=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return s.axes.length>0?(s.axes.forEach(a=>t[a]=n),s.axes.forEach(a=>o[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),o.forEach((a,i)=>o[i]=Math.round(a*t[i]))),o},hc=(e,t,s,n,o)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { + var original_indices: array<${e.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${St("uniforms.scales","i",n)}; + var roi_low = ${St("uniforms.roi","i",o)}; + var roi_hi = ${St("uniforms.roi",`i + ${t.length}`,o)}; + 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",s.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,mc=(e,t,s,n,o,a,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${St("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${St("uniforms.roi","i",a)}; + var roi_hi = ${St("uniforms.roi",`i + ${s.length}`,a)}; + var input_shape_i = ${St("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${St("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i","input_index")} + } + return input_indices; + }`,_c=(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; + }`,Aa=(e,t,s,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",s,"batch")}; +`:"",fc=(e,t,s,n,o)=>{let[a,i,u,p]=s.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${s[i]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(col, ${s[u]} - 1))`)}; + ${Aa(e,p,a,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${h} = originalIndices[${i}]; + var col:${h} = originalIndices[${u}]; + ${n?`if (row < 0 || row > (${s[i]} - 1) || col < 0 || col > (${s[u]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${s[i]} - 1)); + col = max(0, min(col, ${s[u]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; + var batch: u32 = ${s.length>2?`u32(originalIndices[${a}])`:"0"}; + var x11: ${h} = getInputValue(batch, channel, row1, col1); + var x12: ${h} = getInputValue(batch, channel, row1, col2); + var x21: ${h} = getInputValue(batch, channel, row2, col1); + var x22: ${h} = getInputValue(batch, channel, row2, col2); + var dx1: ${h} = abs(row - ${h}(row1)); + var dx2: ${h} = abs(${h}(row2) - row); + var dy1: ${h} = abs(col - ${h}(col1)); + var dy2: ${h} = abs(${h}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},gc=(e,t,s,n,o,a,i,u,p,h)=>{let C=s.length===2,[k,d]=C?[0,1]:[2,3],z=e.type.value,B=V=>{let Z=V===k?"row":"col";return` + fn ${Z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${z} { + var output_index = ${t.indicesGet("output_indices",V)}; + var originalIdx: ${z} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[V]}, + ${n[V]}, ${s[V]}, ${a[V]}, ${a[V]} + ${s.length}); + var fractOriginalIdx: ${z} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${s[V]} - 1))) { + return ${p}; + } + var data: array<${z}, 4> = array<${z}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${Z}: ${z} = originalIdx + ${z}(i); + if (${Z} < 0 || ${Z} >= ${s[V]}) { + ${h?`coefs[i + 1] = 0.0; + continue;`:u?`return ${p};`:`${Z} = max(0, min(${Z}, ${s[V]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",V,`u32(${Z})`)}; + data[i + 1] = ${V===k?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${B(k)}; + ${B(d)}; + fn getCubicInterpolationCoefs(s: ${z}) -> array<${z}, 4> { + var absS = abs(s); + var coeffs: array<${z}, 4> = array<${z}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${z} = 1.0 - absS; + var twoMinusAbsS: ${z} = 2.0 - absS; + var onePlusAbsS: ${z} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${z}, 4>, coefs: array<${z}, 4>) -> ${z} { + var coefsSum: ${z} = 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}) -> ${z} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},wc=(e,t,s,n,o)=>{let[a,i,u,p,h]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],C=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${C} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${s[i]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(height, ${s[u]} - 1))`)}; + ${e.indicesSet("input_indices",p,`max(0, min(width, ${s[p]} - 1))`)}; + ${Aa(e,h,a,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${C} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${C} = originalIndices[${i}]; + var height:${C} = originalIndices[${u}]; + var width:${C} = originalIndices[${p}]; + ${n?`if (depth < 0 || depth > (${s[i]} - 1) || height < 0 || height > (${s[u]} - 1) || width < 0 || (width > ${s[p]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${s[i]} - 1)); + height = max(0, min(height, ${s[u]} - 1)); + width = max(0, min(width, ${s[p]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${s.length>3?`u32(originalIndices[${h}])`:"0"}; + var batch: u32 = ${s.length>3?`u32(originalIndices[${a}])`:"0"}; + + var x111: ${C} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${C} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${C} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${C} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${C} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${C} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${C} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${C} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${C} = abs(depth - ${C}(depth1)); + var dx2: ${C} = abs(${C}(depth2) - depth); + var dy1: ${C} = abs(height - ${C}(height1)); + var dy2: ${C} = abs(${C}(height2) - height); + var dz1: ${C} = abs(width - ${C}(width1)); + var dz2: ${C} = abs(${C}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`},yc=(e,t,s,n,o,a)=>{let i=e.dims,u=dc(a,t.axes,i.length),p=cc(i,n,o,t.axes),h=n.slice();n.length===0&&(h=i.map((X,me)=>X===0?1:p[me]/X),t.keepAspectRatioPolicy!=="stretch"&&(p=pc(i,h,t)));let C=At("output",e.dataType,p.length),k=Qe("input",e.dataType,i.length),d=ze.size(p),z=i.length===p.length&&i.every((X,me)=>X===p[me]),B=t.coordinateTransformMode==="tf_crop_and_resize",V=t.extrapolationValue,Z=k.type.value,ee=X=>` + ${z?"":` + ${lc(t.coordinateTransformMode,Z)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${_c(k,i)}; + ${uc(t.nearestMode,s,Z)}; + ${mc(k,C,i,p,h.length,u.length,B)}; + `;case"linear":return` + ${hc(C,i,p,h.length,u.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${fc(k,C,i,B,V)}`;if(i.length===3||i.length===5)return`${wc(k,C,i,B,V)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${gc(k,C,i,p,h,u,t.cubicCoeffA,B,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${X.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",u.length).declareVariables(k,C)} + ${X.mainStart()} + ${X.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${z?"output[global_idx] = input[global_idx];":` + let output_indices = ${C.offsetToIndices("global_idx")}; + var input_indices: ${k.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${k.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${s}|${h.length>0?t.mode==="cubic"?h:h.length:""}|${o.length>0?o:""}|${u.length>0?u:""}|${z}|${t.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:ee,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:h},{type:1,data:u},...Mt(i,p)]})}},Mc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},bc=(e,t)=>{let s=[],n=[],o=[],a=Mc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");ac(e.inputs,t,a,s,n,o),e.compute(yc(e.inputs[0],t,a,s,n,o),{inputs:[0]})},vc=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,u=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return zt({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:u,mode:p,nearestMode:h})}}),Tc,xc,Pc,Pp=g(()=>{Lt(),Ot(),rs(),Jt(),Tc=(e,t)=>{let[s,n,o,a]=e,{numHeads:i,rotaryEmbeddingDim:u}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!ze.areEqual(n.dims,[])&&!ze.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!ze.areEqual(o.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=s.dims[0],h=s.dims[s.dims.length-2],C=o.dims[0],k=ze.sizeFromDimension(s.dims,1)/h,d=u===0?o.dims[1]*2:k/i;if(u>d)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(d/2!==o.dims[1]&&u/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(h>C)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},xc=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:o,scale:a}=t,i=e[0].dims[0],u=ze.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=u/p,C=e[2].dims[1],k=o===0?C*2:h/n,d=new Array(i,p,h/k,k-C),z=ze.computeStrides(d),B=[{type:1,data:a},{type:12,data:d},{type:12,data:z},...e[0].dims.length===3?new Array({type:12,data:[u,h,k,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,k,p*k,1]}):[],...Mt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],V=Z=>{let ee=Qe("input",e[0].dataType,e[0].dims.length),X=Qe("position_ids",e[1].dataType,e[1].dims.length),me=Qe("cos_cache",e[2].dataType,e[2].dims.length),pe=Qe("sin_cache",e[3].dataType,e[3].dims.length),Me=At("output",e[0].dataType,e[0].dims.length);return Z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:z.length},{name:"input_output_strides",type:"u32",length:z.length}]),` + ${Z.declareVariables(ee,X,me,pe,Me)} + + ${Z.mainStart(or)} + let half_rotary_emb_dim = uniforms.${me.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${X.broadcastedIndicesToOffset("bsnh.xy",At("",X.type.tensor,2))}; + let position_id = + u32(${X.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); + let j = i + select(half_rotary_emb_dim, 1, ${s}); + let re = ${ee.getByOffset("i")} * ${me.get("position_id","bsnh[3]")} - + ${ee.getByOffset("j")} * ${pe.get("position_id","bsnh[3]")}; + ${Me.setByOffset("i","re")} + let im = ${ee.getByOffset("i")} * ${pe.get("position_id","bsnh[3]")} + + ${ee.getByOffset("j")} * ${me.get("position_id","bsnh[3]")}; + ${Me.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${Me.setByOffset("k",ee.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:zt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:V,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(d)/or)},programUniforms:B})}},Pc=(e,t)=>{Tc(e.inputs,t),e.compute(xc(e.inputs,t))}}),Ec,Cc,Ep,Zt=g(()=>{Lt(),Ot(),Jt(),Ec=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],n=e[2];if(t.dataType!==s.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(s.dims[s.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Cc=(e,t,s,n)=>{let o=t.simplified,a=e[0].dims,i=ze.size(a),u=a,p=i,h=a.slice(-1)[0],C=n?a.slice(0,-1).concat(1):[],k=!o&&e.length>3,d=e.length>4,z=n&&s>1,B=n&&s>2,V=s>3,Z=64,ee=Xt(h),X=[{type:12,data:p},{type:12,data:ee},{type:12,data:h},{type:1,data:t.epsilon}],me=Me=>{let Ae=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],De=[Qe("x",e[0].dataType,e[0].dims,ee),Qe("skip",e[1].dataType,e[1].dims,ee),Qe("gamma",e[2].dataType,e[2].dims,ee)];k&&De.push(Qe("beta",e[3].dataType,e[3].dims,ee)),d&&De.push(Qe("bias",e[4].dataType,e[4].dims,ee)),De.push(At("output",e[0].dataType,u,ee)),z&&De.push(At("mean_output",1,C)),B&&De.push(At("inv_std_output",1,C)),V&&De.push(At("input_skip_bias_sum",e[0].dataType,u,ee));let et=fs(e[0].dataType),dt=fs(1,ee);return` + + ${Me.registerUniforms(Ae).declareVariables(...De)} + var sum_shared : array<${dt}, ${Z}>; + var sum_squared_shared : array<${dt}, ${Z}>; + + ${Me.mainStart([Z,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${Z}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${Z}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${Z-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${d?"bias[offset1d + i]":et+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${V?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${As(et,ee,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${Z}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Gs("sum",ee)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Gs("square_sum",ee)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${z?"mean_output[global_idx] = mean;":""} + ${B?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${et}(mean)`}) * + ${et}(inv_std_dev) * gamma[offset1d + i] + ${k?"+ beta[offset1d + i]":""}; + } + }`},pe=[{dims:u,dataType:e[0].dataType}];return s>1&&pe.push({dims:C,dataType:1}),s>2&&pe.push({dims:C,dataType:1}),s>3&&pe.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${ee};${z};${B};${V}`,inputDependencies:e.map((Me,Ae)=>"type")},getShaderSource:me,getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:X})}},Ep=(e,t)=>{Ec(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(Cc(e.inputs,t,e.outputCount,!1),{outputs:s})}}),kc,Ds,Ys,er,pn,Cp,Sc,$c,_=g(()=>{Lt(),Ot(),rs(),Jt(),kc=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((s,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Ds=(e,t)=>{let s=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>s.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>s.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return s},Ys=(e,t)=>{if(e.length>1){let s=Ds(e,1),n=Ds(e,2),o=Ds(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),zt({starts:s,ends:n,axes:o})}else return t},er=(e,t,s,n,o)=>{let a=e;return e<0&&(a+=s[n[t]]),o[t]<0?Math.max(0,Math.min(a,s[n[t]]-1)):Math.max(0,Math.min(a,s[n[t]]))},pn=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${s.length}; i >= 0; i--) { + let input_shape_i = ${St("uniforms.input_shape","i",s.length)}; + let steps_i = ${St("uniforms.steps","i",s.length)}; + let signs_i = ${St("uniforms.signs","i",s.length)}; + let starts_i = ${St("uniforms.starts","i",s.length)}; + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,Cp=(e,t)=>{let s=e[0].dims,n=ze.size(s),o=t.axes.length>0?ze.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],a=Ds(e,4);a.forEach(ee=>ee!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(o.length).fill(1));let i=t.starts.map((ee,X)=>er(ee,X,s,o,a)),u=t.ends.map((ee,X)=>er(ee,X,s,o,a));if(o.length!==i.length||o.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==s.length)for(let ee=0;eeMath.sign(ee));a.forEach((ee,X,me)=>{if(ee<0){let pe=(u[X]-i[X])/ee,Me=i[X],Ae=Me+pe*a[X];i[X]=Ae,u[X]=Me,me[X]=-ee}});let h=s.slice(0);o.forEach((ee,X)=>{h[ee]=Math.ceil((u[ee]-i[ee])/a[ee])});let C={dims:h,dataType:e[0].dataType},k=At("output",e[0].dataType,h.length),d=Qe("input",e[0].dataType,e[0].dims.length),z=ze.size(h),B=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:a.length}],V=[{type:12,data:z},{type:12,data:i},{type:6,data:p},{type:12,data:a},...Mt(e[0].dims,h)],Z=ee=>` + ${ee.registerUniforms(B).declareVariables(d,k)} + ${pn(d,k,s)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${k.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${k.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:Z,getRunData:()=>({outputs:[C],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:V})}},Sc=(e,t)=>{kc(e.inputs,t);let s=Ys(e.inputs,t);e.compute(Cp(e.inputs,s),{inputs:[0]})},$c=e=>{let t=e.starts,s=e.ends,n=e.axes;return zt({starts:t,ends:s,axes:n})}}),x,j,fe,Oe,Fe=g(()=>{Lt(),Ot(),rs(),Hr(),Jt(),x=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},j=(e,t)=>{let s=e.inputs[0],n=s.dims,o=ze.size(n),a=n.length,i=ze.normalizeAxis(t.axis,a),u=iet),h[i]=a-1,h[a-1]=i,p=e.compute(pr(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let C=p.dims,k=C[a-1],d=o/k,z=Xt(k),B=k/z,V=64;d===1&&(V=256);let Z=(De,et)=>et===4?`max(max(${De}.x, ${De}.y), max(${De}.z, ${De}.w))`:et===2?`max(${De}.x, ${De}.y)`:et===3?`max(max(${De}.x, ${De}.y), ${De}.z)`:De,ee=Qe("x",p.dataType,p.dims,z),X=At("result",p.dataType,p.dims,z),me=ee.type.value,pe=fs(p.dataType)==="f32"?`var threadMax = ${me}(-3.402823e+38f);`:`var threadMax = ${me}(-65504.0h);`,Me=De=>` + var rowMaxShared : ${me}; + var rowSumShared : ${me}; + var threadShared : array<${me}, ${V}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${me} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${me}) { + let index = row * row_stride + col; + result[index] = value; + } + ${De.registerUniform("packedCols","i32").declareVariables(ee,X)} + ${De.mainStart(V)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${V}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${pe} + 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 = ${me}(${Z("threadShared[0]",z)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${me}(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 = ${me}(${Gs("threadShared[0]",z)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,Ae=e.compute({name:"Softmax",shaderCache:{hint:`${z};${V}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:C,dataType:p.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:B}]}),getShaderSource:Me},{inputs:[p],outputs:[u?-1:0]})[0];u&&e.compute(pr(Ae,h),{inputs:[Ae]})},fe=(e,t)=>{x(e.inputs),j(e,t)},Oe=e=>zt({axis:e.axis})}),Ze,rt,ft,bt,Rt,Wt=g(()=>{Lt(),Ot(),Jt(),Ze=e=>Array.from(e.getBigInt64Array(),Number),rt=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(Ze(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},ft=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??Ze(e[1]),o=ft(s,n),a=ze.size(o),i=e[0].dataType,u=Qe("input",i,s.length),p=At("output",i,o.length),h=C=>` + const inputShape = ${u.indices(...s)}; + ${C.registerUniform("output_size","u32").declareVariables(u,p)} + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; + + ${u.indicesSet("input_indices","i","input_dim_value")} + } + ${p.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...Mt(e[0].dims,o)]}),getShaderSource:h}},Rt=e=>{rt(e.inputs),e.compute(bt(e.inputs),{inputs:[0]})}}),Dt,Gt,es,ns=g(()=>{Lt(),Ot(),Jt(),Dt=(e,t,s,n,o)=>{let a=At("output_data",o,s.length,4),i=Qe("a_data",t[1].dataType,t[1].dims.length,4),u=Qe("b_data",t[2].dataType,t[2].dims.length,4),p=Qe("c_data",t[0].dataType,t[0].dims.length,4),h,C=(k,d,z)=>`select(${d}, ${k}, ${z})`;if(!n)h=a.setByOffset("global_idx",C(i.getByOffset("global_idx"),u.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let k=(d,z,B="")=>{let V=`a_data[index_a${z}][component_a${z}]`,Z=`b_data[index_b${z}][component_b${z}]`,ee=`bool(c_data[index_c${z}] & (0xffu << (component_c${z} * 8)))`;return` + let output_indices${z} = ${a.offsetToIndices(`global_idx * 4u + ${z}u`)}; + let offset_a${z} = ${i.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let offset_b${z} = ${u.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let offset_c${z} = ${p.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let index_a${z} = offset_a${z} / 4u; + let index_b${z} = offset_b${z} / 4u; + let index_c${z} = offset_c${z} / 4u; + let component_a${z} = offset_a${z} % 4u; + let component_b${z} = offset_b${z} % 4u; + let component_c${z} = offset_c${z} % 4u; + ${d}[${z}] = ${B}(${C(V,Z,ee)}); + `};o===9?h=` + var data = vec4(0); + ${k("data",0,"u32")} + ${k("data",1,"u32")} + ${k("data",2,"u32")} + ${k("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` + ${k("output_data[global_idx]",0)} + ${k("output_data[global_idx]",1)} + ${k("output_data[global_idx]",2)} + ${k("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(p,i,u,a)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h} + }`},Gt=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,o=e[1].dataType,a=!(ze.areEqual(t,s)&&ze.areEqual(s,n)),i=t,u=ze.size(t);if(a){let h=Ws.calcShape(Ws.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");i=h,u=ze.size(i)}let p=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Dt(h,e,i,a,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:p},...Mt(n,t,s,i)]})}},es=e=>{e.compute(Gt(e.inputs))}}),Yt,as=g(()=>{Uc(),pi(),Vc(),Wc(),Gc(),Kc(),fu(),Xc(),Jc(),Zc(),ep(),tp(),sp(),rp(),np(),op(),ap(),lp(),Gp(),ca(),pp(),Cd(),hp(),mp(),zd(),yd(),Ud(),Mp(),Kp(),bp(),Tp(),co(),xp(),Pp(),Zt(),_(),Fe(),_a(),Wt(),Hr(),Si(),ns(),Yt=new Map([["Abs",[kl]],["Acos",[gi]],["Acosh",[Sl]],["Add",[Ai]],["ArgMax",[ai,li]],["ArgMin",[Ml,li]],["Asin",[$l]],["Asinh",[wi]],["Atan",[Al]],["Atanh",[Il]],["Attention",[Tl]],["AveragePool",[yp,Ca]],["BatchNormalization",[mi]],["BiasAdd",[Cl]],["BiasSplitGelu",[$i]],["Cast",[Ol,yi]],["Ceil",[Dl]],["Clip",[Mi]],["Concat",[mu,_u]],["Conv",[vo,Ji]],["ConvTranspose",[Ou,ta]],["Cos",[Ll]],["Cosh",[bi]],["CumSum",[Fu,Du]],["DepthToSpace",[Bu,Ru]],["DequantizeLinear",[Jd,Zd]],["Div",[ou]],["Einsum",[Vu,Wu]],["Elu",[zl,Un]],["Equal",[iu]],["Erf",[Bl]],["Exp",[vi]],["Expand",[qu]],["FastGelu",[Qu]],["Floor",[Rl]],["FusedConv",[vo,Ji]],["Gather",[Ju,Yu]],["GatherElements",[id,od]],["GatherBlockQuantized",[sd,rd]],["GatherND",[Co,ed]],["Gelu",[Nl]],["Gemm",[ko,ud]],["GlobalAveragePool",[Gd,Wd]],["GlobalMaxPool",[Qd,qd]],["Greater",[uu]],["GreaterOrEqual",[Oi]],["GridSample",[_d,fd]],["GroupQueryAttention",[fa]],["HardSigmoid",[Gl,Pi]],["InstanceNormalization",[Ed]],["LayerNormalization",[ya]],["LeakyRelu",[Ti,Un]],["Less",[du]],["LessOrEqual",[cu]],["Log",[Jl]],["MatMul",[Ad]],["MatMulNBits",[Dd,Ld]],["MaxPool",[Kd,Hd]],["Mul",[au]],["MultiHeadAttention",[up,wd]],["Neg",[Ul]],["Not",[jl]],["Pad",[gp]],["Pow",[lu]],["QuickGelu",[eu,Un]],["Range",[sc]],["Reciprocal",[xi]],["ReduceMin",[fl]],["ReduceMean",[hl]],["ReduceMax",[ni]],["ReduceSum",[oi]],["ReduceProd",[gl]],["ReduceL1",[ri]],["ReduceL2",[ml]],["ReduceLogSum",[yl]],["ReduceLogSumExp",[_l]],["ReduceSumSquare",[wl]],["Relu",[Vl]],["Resize",[bc,vc]],["RotaryEmbedding",[Pc]],["ScatterND",[Sa,vp]],["Sigmoid",[Wl]],["Sin",[Kl]],["Sinh",[Ei]],["Slice",[Sc,$c]],["SkipLayerNormalization",[Ep]],["Split",[Td,xd]],["Sqrt",[Hl]],["Softmax",[fe,Oe]],["Sub",[Ii]],["Tan",[ql]],["Tanh",[Ql]],["ThresholdedRelu",[Yl,Un]],["Tile",[Rt]],["Transpose",[Ka,Qo]],["Where",[es]]])}),Ps,Ts=g(()=>{Re(),Pe(),Jt(),Ps=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,s,n,o){Ne(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let h of t)u.push({binding:u.length,resource:{buffer:h.buffer}});for(let h of s)u.push({binding:u.length,resource:{buffer:h.buffer}});o&&u.push({binding:u.length,resource:o});let p=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}i.setPipeline(e.computePipeline),i.setBindGroup(0,p),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),je(e.programInfo.name)}dispose(){}build(e,t){Ne(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{s.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let o=Ua(t,this.backend.device.limits),a=e.getShaderSource(o),i=`${n.join(` +`)} +${o.additionalImplementations} +${a}`,u=s.createShaderModule({code:i,label:e.name});is("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let p=s.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return je(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&s<=o&&n<=o)return[t,s,n];let a=t*s*n,i=Math.ceil(Math.sqrt(a));if(i>o){if(i=Math.ceil(Math.cbrt(a)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),cs,xs,Is,tr,Hs,Er=g(()=>{Re(),Lt(),Pe(),Q(),us(),as(),Ts(),cs=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let n=0;n{var o,a;let n=e.name;return(o=e.shaderCache)!=null&&o.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+s+`:${cs(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Is=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},tr=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;!this.subgroupsSupported||!t.minSubgroupSize||!t.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]}},Hs=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 s=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s},o=a=>t.features.has(a)&&s.push(a)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups")&&o("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new tr(this.device),this.adapterInfo=new Is(t.info||await t.requestAdapterInfo()),this.gpuDataManager=_s(this),this.programManager=new Ps(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Pn(e.logLevel,!!e.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ne(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),s=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=z);let V=Number(z-this.queryTimeBase),Z=Number(B-this.queryTimeBase);if(!Number.isSafeInteger(V)||!Number.isSafeInteger(Z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:k.map(ee=>({dims:ee.dims,dataType:_r(ee.dataType)})),outputsMetadata:d.map(ee=>({dims:ee.dims,dataType:_r(ee.dataType)})),kernelId:i,kernelType:p,kernelName:h,programName:C,startTime:V,endTime:Z});else{let ee="";k.forEach((me,pe)=>{ee+=`input[${pe}]: [${me.dims}] | ${_r(me.dataType)}, `});let X="";d.forEach((me,pe)=>{X+=`output[${pe}]: [${me.dims}] | ${_r(me.dataType)}, `}),console.log(`[profiling] kernel "${i}|${p}|${h}|${C}" ${ee}${X}execution time: ${Z-V} ns`)}Ve("GPU",`${C}::${z}::${B}`)}e.unmap(),this.pendingQueries.delete(e)}),je()}run(e,t,s,n,o,a){Ne(e.name);let i=[];for(let X=0;Xme):s;if(C.length!==u.length)throw new Error(`Output size ${C.length} must be equal to ${u.length}.`);let k=[],d=[];for(let X=0;X=a)throw new Error(`Invalid output index: ${C[X]}`);if(C[X]===-3)continue;let me=C[X]===-1,pe=C[X]===-2,Me=me||pe?o(u[X].dataType,u[X].dims):n(C[X],u[X].dataType,u[X].dims);if(k.push(Me),Me.data===0)continue;let Ae=this.gpuDataManager.get(Me.data);if(!Ae)throw new Error(`no GPU data for output: ${Me.data}`);if(me&&this.temporaryData.push(Ae),pe){let De=this.kernelPersistentData.get(this.currentKernelId);De||(De=[],this.kernelPersistentData.set(this.currentKernelId,De)),De.push(Ae)}d.push(Ae)}if(i.length!==t.length||d.length!==k.length){if(d.length===0)return je(e.name),k;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let z;if(h){let X=0,me=[];h.forEach(De=>{let et=typeof De.data=="number"?[De.data]:De.data;if(et.length===0)return;let dt=De.type===10?2:4,Pt,qt;De.type===10?(qt=et.length>4?16:et.length>2?8:et.length*dt,Pt=et.length>4?16:dt*et.length):(qt=et.length<=2?et.length*dt:16,Pt=16),X=Math.ceil(X/qt)*qt,me.push(X);let Bt=De.type===10?8:4;X+=et.length>4?Math.ceil(et.length/Bt)*Pt:et.length*dt});let pe=16;X=Math.ceil(X/pe)*pe;let Me=new ArrayBuffer(X);h.forEach((De,et)=>{let dt=me[et],Pt=typeof De.data=="number"?[De.data]:De.data;if(De.type===6)new Int32Array(Me,dt,Pt.length).set(Pt);else if(De.type===12)new Uint32Array(Me,dt,Pt.length).set(Pt);else if(De.type===10)new Uint16Array(Me,dt,Pt.length).set(Pt);else if(De.type===1)new Float32Array(Me,dt,Pt.length).set(Pt);else throw new Error(`Unsupported uniform type: ${_r(De.type)}`)});let Ae=this.gpuDataManager.create(X,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ae.buffer,0,Me,0,X),this.gpuDataManager.release(Ae.id),z={offset:0,size:X,buffer:Ae.buffer}}let B=this.programManager.normalizeDispatchGroupSize(p),V=B[1]===1&&B[2]===1,Z=xs(e,t,V),ee=this.programManager.getArtifact(Z);if(ee||(ee=this.programManager.build(e,B),this.programManager.setArtifact(Z,ee),is("info",()=>`[artifact] key: ${Z}, programName: ${e.name}`)),h&&ee.uniformVariablesInfo){if(h.length!==ee.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${ee.uniformVariablesInfo.length}, got ${h.length} in program "${ee.programInfo.name}".`);for(let X=0;X`[ProgramManager] run "${e.name}" (key=${Z}) with ${B[0]}x${B[1]}x${B[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let X={kernelId:this.currentKernelId,programName:ee.programInfo.name,inputTensorViews:t,outputTensorViews:k};this.pendingKernels.push(X),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(X)}return this.programManager.run(ee,i,d,B,z),je(e.name),k}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,n){let o=Yt.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:o[0],attributes:[o[1],s]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let o=n.kernelType,a=n.kernelName,i=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),is("info",()=>`[WebGPU] Start to run kernel "[${o}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),i(t,u[1]),0}catch(h){return s.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${a}" failed. ${h}`)),1}finally{p&&s.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${o}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let a=o.get(t),i=this.gpuDataManager.registerExternalBuffer(s,n,a);return o.set(t,[i,s]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let n=await xt(this,e,t);return P(n.buffer,s)}}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(){is("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(){is("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){is("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Cn,Io,ur,br,Oo,qn,Fo,Do,Es=g(()=>{Pe(),Cn=1,Io=()=>Cn++,ur=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),br=(e,t)=>{let s=ur.get(e);if(!s)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,o)=>n*o)*s/8):0},Oo=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return br(this.dataType,this.tensorShape)}destroy(){is("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((n,o)=>n===s[o])}},qn=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s,n){if(this.wrapper){if(this.wrapper.canReuseTensor(e,t,s))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==br(t,s))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let o=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,s,o,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else is("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Fo=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Io();return this.tensorTrackersById.set(e,new qn(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,n){is("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(this.backend.currentContext,t,s,n)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){is("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,n){let o=Io(),a=new Oo({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(o,new qn(this,a)),this.externalTensors.add(a),o}async getCachedTensor(e,t,s,n,o){let a=this.backend.currentSessionId,i=this.backend.currentContext;for(let[p,h]of this.freeTensors.entries())if(h.canReuseTensor(i,e,t)){is("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let C=this.freeTensors.splice(p,1)[0];return C.sessionId=a,C}is("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let u=await i.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new Oo({sessionId:a,context:i,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Do=(...e)=>new Fo(...e)}),Bs,Qr,hn,Qn=g(()=>{Lt(),ar(),Q(),Es(),Pe(),Bs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Qr=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),n=Object.keys(t).sort();return s.length===n.length&&s.every((o,a)=>o===n[a]&&e[o]===t[o])},hn=class{constructor(e){this.tensorManager=Do(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],Pn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let s=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(s=>Qr(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(o=>o.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){is("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let o=Bs.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,o,s,n)}uploadTensor(e,t){if(!bs().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");is("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return P(s,t)}}registerMLTensor(e,t,s){let n=Bs.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(this.currentContext,e,n,s);return is("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,t,s,n,o,a){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let u=a.get(i);if(!u)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+s>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=u.slice(t,t+s).buffer,h;switch(o.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return is("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}}`),n.constant(o,h)}flush(){}}}),Lo={};v(Lo,{init:()=>Oa});var Xn,Ia,Oa,Hp=g(()=>{Lt(),Er(),Pe(),Ot(),Qn(),Xn=class s_{constructor(t,s,n,o){this.module=t,this.dataType=s,this.data=n,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=ze.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=ze.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=ze.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=ze.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(ze.size(t)!==ze.size(this.dims))throw new Error("Invalid new shape");return new s_(this.module,this.dataType,this.data,t)}},Ia=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,o=s/e.PTR_SIZE,a=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*o++,a));let i=Number(e.getValue(n*o++,a));this.outputCount=Number(e.getValue(n*o++,a)),this.customDataOffset=Number(e.getValue(n*o++,"*")),this.customDataSize=Number(e.getValue(n*o++,a));let u=[];for(let p=0;ptypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],o=(u,p,h)=>new Xn(this.module,p,this.output(u,h),h),a=(u,p)=>{let h=lr(u,p);if(!h)throw new Error(`Unsupported data type: ${u}`);let C=h>0?this.backend.gpuDataManager.create(h).id:0;return new Xn(this.module,u,C,p)};return this.backend.run(e,s,n,o,a,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,o=n===4?"i32":"i64",a=this.module.stackAlloc((1+t.length)*n);this.module.setValue(a,t.length,o);for(let i=0;i{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Hs;await a.initialize(s,n),o("webgpu",[a,i=>a.alloc(Number(i)),i=>a.free(i),(i,u,p,h=!1)=>{if(h)is("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(i)}, dst=${Number(u)}, size=${Number(p)}`),a.memcpy(Number(i),Number(u));else{is("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(i)}, gpuDataId=${Number(u)}, size=${Number(p)}`);let C=t.HEAPU8.subarray(Number(i>>>0),Number(i>>>0)+Number(p));a.upload(Number(u),C)}},async(i,u,p)=>{is("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${u}, size=${p}`),await a.download(Number(i),()=>t.HEAPU8.subarray(Number(u)>>>0,Number(u+p)>>>0))},(i,u,p)=>a.createKernel(i,Number(u),p,t.UTF8ToString(t._JsepGetNodeName(Number(u)))),i=>a.releaseKernel(i),(i,u,p,h)=>{is("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${i}, contextDataOffset=${u}`);let C=new Ia(t,a,Number(u));return a.computeKernel(Number(i),C,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new hn(s);o("webnn",[a,()=>a.reserveTensorId(),i=>a.releaseTensorId(i),async(i,u,p,h)=>a.ensureTensor(i,u,p,h),(i,u)=>{a.uploadTensor(i,u)},async(i,u)=>a.downloadTensor(i,u)])}}}),Fa,Yn,zo,Xr,Da,kn,Ac,Ic,Oc,Yr,mr,qp,vh=g(()=>{oo(),io(),Lt(),ar(),yn(),Ln(),Fa=(e,t)=>{bs()._OrtInit(e,t)!==0&&ss("Can't initialize onnxruntime.")},Yn=async e=>{Fa(e.wasm.numThreads,sn(e.logLevel))},zo=async(e,t)=>{{let s=(Hp(),y(Lo)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await s("webgpu",bs(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",bs(),e)}}},Xr=new Map,Da=e=>{let t=bs(),s=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&ss("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(s)}},kn=e=>{let t=bs(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Ac=async(e,t)=>{var k,d,z;let s,n,o=bs();Array.isArray(e)?[s,n]=e:e.buffer===o.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=kn(e);let a=0,i=0,u=0,p=[],h=[],C=[];try{if([i,p]=Dn(t),(t==null?void 0:t.externalData)&&o.mountExternalData){let Me=[];for(let Ae of t.externalData){let De=typeof Ae=="string"?Ae:Ae.path;Me.push(xn(typeof Ae=="string"?Ae:Ae.data).then(et=>{o.mountExternalData(De,et)}))}await Promise.all(Me)}for(let Me of(t==null?void 0:t.executionProviders)??[])if((typeof Me=="string"?Me:Me.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof Me!="string"){let Ae=Me,De=Ae==null?void 0:Ae.context,et=Ae==null?void 0:Ae.gpuDevice,dt=Ae==null?void 0:Ae.deviceType,Pt=Ae==null?void 0:Ae.powerPreference;De?o.currentContext=De:et?o.currentContext=await o.jsepCreateMLContext(et):o.currentContext=await o.jsepCreateMLContext({deviceType:dt,powerPreference:Pt})}else o.currentContext=await o.jsepCreateMLContext();break}a=await o._OrtCreateSession(s,n,i),a===0&&ss("Can't create a session."),(k=o.jsepOnCreateSession)==null||k.call(o),o.currentContext&&(o.jsepRegisterMLContext(a,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[B,V]=Da(a),Z=!!(t!=null&&t.enableGraphCapture),ee=[],X=[],me=[];for(let Me=0;MeMe==="gpu-buffer"||Me==="ml-tensor")&&(u=o._OrtCreateBinding(a),u===0&&ss("Can't create IO binding."),pe={handle:u,outputPreferredLocations:me,outputPreferredLocationsEncoded:me.map(Me=>Tn(Me))}),Xr.set(a,[a,h,C,pe,Z,!1]),[a,ee,X]}catch(B){throw h.forEach(V=>o._OrtFree(V)),C.forEach(V=>o._OrtFree(V)),u!==0&&o._OrtReleaseBinding(u)!==0&&ss("Can't release IO binding."),a!==0&&o._OrtReleaseSession(a)!==0&&ss("Can't release session."),B}finally{o._free(s),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&ss("Can't release session options."),p.forEach(B=>o._free(B)),(z=o.unmountExternalData)==null||z.call(o)}},Ic=e=>{var p;let t=bs(),s=Xr.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,a,i,u]=s;i&&(u&&t._OrtClearBoundOutputs(i.handle)!==0&&ss("Can't clear bound outputs."),t._OrtReleaseBinding(i.handle)!==0&&ss("Can't release IO binding.")),(p=t.jsepOnReleaseSession)==null||p.call(t,e),o.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n)!==0&&ss("Can't release session."),Xr.delete(e)},Oc=(e,t,s,n,o,a=!1)=>{if(!e){t.push(0);return}let i=bs(),u=i.PTR_SIZE,p=e[0],h=e[1],C=e[3],k,d;if(p==="string"&&(C==="gpu-buffer"||C==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&C!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(C==="gpu-buffer"){let V=e[2].gpuBuffer;d=lr(Gr(p),h);let Z=i.jsepRegisterBuffer;if(!Z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');k=Z(n,o,V,d)}else if(C==="ml-tensor"){let V=e[2].mlTensor;d=lr(Gr(p),h);let Z=i.jsepRegisterMLTensor;if(!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');k=Z(V,Gr(p),h)}else{let V=e[2];if(Array.isArray(V)){d=u*V.length,k=i._malloc(d),s.push(k);for(let Z=0;Zi.setValue(B+ee*u,Z,u===4?"i32":"i64"));let V=i._OrtCreateTensor(Gr(p),k,d,B,h.length,Tn(C));V===0&&ss(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(V)}finally{i.stackRestore(z)}},Yr=async(e,t,s,n,o,a)=>{var qt,Bt;let i=bs(),u=i.PTR_SIZE,p=Xr.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],C=p[1],k=p[2],d=p[3],z=p[4],B=p[5],V=t.length,Z=n.length,ee=0,X=[],me=[],pe=[],Me=[],Ae=i.stackSave(),De=i.stackAlloc(V*u),et=i.stackAlloc(V*u),dt=i.stackAlloc(Z*u),Pt=i.stackAlloc(Z*u);try{(qt=i.jsepOnRunStart)==null||qt.call(i,h),[ee,X]=Vr(a);for(let wt=0;wtCs*Js,1);gs=_r(hs);let zr=d==null?void 0:d.outputPreferredLocations[n[wt]];if(gs==="string"){if(zr==="gpu-buffer"||zr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Cs=[];for(let Js=0;Js0){let Cs=i.jsepGetBuffer;if(!Cs)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Js=Cs(it),Sn=lr(hs,mn);if(Sn===void 0||!bn(gs))throw new Error(`Unsupported data type: ${gs}`);Qt=!0,ts.push([gs,Lr,{gpuBuffer:Js,download:i.jsepCreateDownloader(Js,Sn,gs),dispose:()=>{i._OrtReleaseTensor(Ht)!==0&&ss("Can't release tensor.")}},"gpu-buffer"])}else if(zr==="ml-tensor"&&mn>0){let Cs=i.jsepEnsureTensor;if(!Cs)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(lr(hs,mn)===void 0||!vn(gs))throw new Error(`Unsupported data type: ${gs}`);let Js=await Cs(it,hs,Lr,!1);Qt=!0,ts.push([gs,Lr,{mlTensor:Js,download:i.jsepCreateMLTensorDownloader(it,gs),dispose:()=>{i.jsepReleaseTensorId(it),i._OrtReleaseTensor(Ht)}},"ml-tensor"])}else{let Cs=Mn(gs),Js=new Cs(mn);new Uint8Array(Js.buffer,Js.byteOffset,Js.byteLength).set(i.HEAPU8.subarray(it,it+Js.byteLength)),ts.push([gs,Lr,Js,"cpu"])}}finally{i.stackRestore(ps),gs==="string"&&it&&i._free(it),Qt||i._OrtReleaseTensor(Ht)}}return d&&!z&&(i._OrtClearBoundOutputs(d.handle)!==0&&ss("Can't clear bound outputs."),Xr.set(e,[h,C,k,d,z,!1])),ts}finally{i.stackRestore(Ae),me.forEach(It=>i._OrtReleaseTensor(It)),pe.forEach(It=>i._OrtReleaseTensor(It)),Me.forEach(It=>i._free(It)),ee!==0&&i._OrtReleaseRunOptions(ee),X.forEach(It=>i._free(It))}},mr=e=>{let t=bs(),s=Xr.get(e);if(!s)throw new Error("invalid session id");let n=s[0],o=t._OrtEndProfiling(n);o===0&&ss("Can't get an profile file name."),t._OrtFree(o)},qp=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Jn,vr,La,Fc,Dc,kp,Qp,Sp,Bo,Ro,Th,xh,Ph,Eh,Ch,kh,Sh,$h,Ah=g(()=>{Re(),vh(),ar(),jr(),Jn=()=>!!O.wasm.proxy&&typeof document<"u",La=!1,Fc=!1,Dc=!1,Sp=new Map,Bo=(e,t)=>{let s=Sp.get(e);s?s.push(t):Sp.set(e,[t])},Ro=()=>{if(La||!Fc||Dc||!vr)throw new Error("worker not ready")},Th=e=>{switch(e.data.type){case"init-wasm":La=!1,e.data.err?(Dc=!0,Qp[1](e.data.err)):(Fc=!0,Qp[0]()),kp&&(URL.revokeObjectURL(kp),kp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Sp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},xh=async()=>{if(!Fc){if(La)throw new Error("multiple calls to 'initWasm()' detected.");if(Dc)throw new Error("previous call to 'initWasm()' failed.");if(La=!0,Jn())return new Promise((e,t)=>{vr==null||vr.terminate(),Rr().then(([s,n])=>{var o;try{vr=n,vr.onerror=i=>t(i),vr.onmessage=Th,Qp=[e,t];let a={type:"init-wasm",in:O};!a.in.wasm.wasmPaths&&(s||(o=self.location.href)!=null&&o.startsWith("file:"))&&(a.in.wasm.wasmPaths={wasm:new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href}),vr.postMessage(a),kp=s}catch(a){t(a)}},t)});try{await Ir(O.wasm),await Yn(O),Fc=!0}catch(e){throw Dc=!0,e}finally{La=!1}}},Ph=async e=>{if(Jn())return Ro(),new Promise((t,s)=>{Bo("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:O}};vr.postMessage(n)});await zo(O,e)},Eh=async e=>Jn()?(Ro(),new Promise((t,s)=>{Bo("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};vr.postMessage(n,[e.buffer])})):kn(e),Ch=async(e,t)=>{if(Jn()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ro(),new Promise((s,n)=>{Bo("create",[s,n]);let o={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),vr.postMessage(o,a)})}else return Ac(e,t)},kh=async e=>{if(Jn())return Ro(),new Promise((t,s)=>{Bo("release",[t,s]);let n={type:"release",in:e};vr.postMessage(n)});Ic(e)},Sh=async(e,t,s,n,o,a)=>{if(Jn()){if(s.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ro(),new Promise((i,u)=>{Bo("run",[i,u]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:a}};vr.postMessage(h,qp(p))})}else return Yr(e,t,s,n,o,a)},$h=async e=>{if(Jn())return Ro(),new Promise((t,s)=>{Bo("end-profiling",[t,s]);let n={type:"end-profiling",in:e};vr.postMessage(n)});mr(e)}}),Xp,Ih,Oh,p_=g(()=>{Re(),Ah(),Lt(),qe(),Ln(),Xp=(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()}`)}},Ih=e=>{switch(e[3]){case"cpu":return new le(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!bn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:o}=e[2];return le.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!vn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:o}=e[2];return le.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Oh=class{async fetchModelAndCopyToWasmMemory(e){return Eh(await xn(e))}async loadModel(e,t){Ne();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await Ch(s,t),je()}async dispose(){return kh(this.sessionId)}async run(e,t,s){Ne();let n=[],o=[];Object.entries(e).forEach(k=>{let d=k[0],z=k[1],B=this.inputNames.indexOf(d);if(B===-1)throw new Error(`invalid input '${d}'`);n.push(z),o.push(B)});let a=[],i=[];Object.entries(t).forEach(k=>{let d=k[0],z=k[1],B=this.outputNames.indexOf(d);if(B===-1)throw new Error(`invalid output '${d}'`);a.push(z),i.push(B)});let u=n.map((k,d)=>Xp(k,()=>`input "${this.inputNames[o[d]]}"`)),p=a.map((k,d)=>k?Xp(k,()=>`output "${this.outputNames[i[d]]}"`):null),h=await Sh(this.sessionId,o,u,i,p,s),C={};for(let k=0;kJp,initializeFlags:()=>Yp,wasmBackend:()=>Dh});var Yp,Jp,Dh,h_=g(()=>{Re(),Ah(),p_(),Yp=()=>{if((typeof O.wasm.initTimeout!="number"||O.wasm.initTimeout<0)&&(O.wasm.initTimeout=0),O.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 O.wasm.proxy!="boolean"&&(O.wasm.proxy=!1),typeof O.wasm.trace!="boolean"&&(O.wasm.trace=!1),typeof O.wasm.numThreads!="number"||!Number.isInteger(O.wasm.numThreads)||O.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)O.wasm.numThreads=1;else{let e=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;O.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Jp=class{async init(e){Yp(),await xh(),await Ph(e)}async createInferenceSessionHandler(e,t){let s=new Oh;return await s.loadModel(e,t),Promise.resolve(s)}},Dh=new Jp});Re(),Re(),Re();var m_="1.21.0-dev.20250206-d981b153d3",__=ke;{let e=(h_(),y(Fh)).wasmBackend;H("webgpu",e,5),H("webnn",e,5),H("cpu",e,10),H("wasm",e,10)}Object.defineProperty(O.versions,"web",{value:m_,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":(Le,$,r)=>{var f;r.r($),r.d($,{Tensor:()=>R.Tensor,createInferenceSession:()=>ne,deviceToExecutionProviders:()=>H,isONNXProxy:()=>q,isONNXTensor:()=>W});var F=r("./src/env.js"),N=r("?2ce3"),Y=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96"),R=r("./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 b=Symbol.for("onnxruntime");if(b in globalThis)y=globalThis[b];else if(F.apis.IS_NODE_ENV){switch(y=N??(f||(f=r.t(N,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=Y,F.apis.IS_WEBNN_AVAILABLE&&v.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),F.apis.IS_WEBGPU_AVAILABLE&&v.push("webgpu"),v.push("wasm"),M=["wasm"];const I=y.InferenceSession;function H(A=null){if(!A)return M;switch(A){case"auto":return v;case"gpu":return v.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(v.includes(A))return[g[A]??A];throw new Error(`Unsupported device: "${A}". Should be one of: ${v.join(", ")}.`)}let se=null;async function ne(A,S,w){se&&await se;const T=I.create(A,S);se??(se=T);const O=await T;return O.config=w,O}function W(A){return A instanceof y.Tensor}const U=y==null?void 0:y.env;U!=null&&U.wasm&&(U.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${F.env.version}/dist/`,U.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(U.wasm.numThreads=1)),U!=null&&U.webgpu&&(U.webgpu.powerPreference="high-performance");function q(){var A;return(A=U==null?void 0:U.wasm)==null?void 0:A.proxy}F.env.backends.onnx=U},"./src/base/feature_extraction_utils.js":(Le,$,r)=>{r.r($),r.d($,{FeatureExtractor:()=>Y,validate_audio_inputs:()=>R});var f=r("./src/utils/constants.js"),F=r("./src/utils/generic.js"),N=r("./src/utils/hub.js");class Y extends F.Callable{constructor(v){super(),this.config=v}static async from_pretrained(v,M){const y=await(0,N.getModelJSON)(v,f.FEATURE_EXTRACTOR_NAME,!0,M);return new this(y)}}function R(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":(Le,$,r)=>{r.r($),r.d($,{ImageProcessor:()=>A,center_to_corners_format:()=>y,post_process_instance_segmentation:()=>q,post_process_object_detection:()=>b,post_process_panoptic_segmentation:()=>U,post_process_semantic_segmentation:()=>I});var f=r("./src/utils/generic.js"),F=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");r("./src/utils/image.js");var Y=r("./src/utils/core.js"),R=r("./src/utils/hub.js"),g=r("./src/utils/constants.js");function v(S,w,T=0,O=null){const ae=S/w;let oe=(0,N.bankers_round)(ae)*w;return O!==null&&oe>O&&(oe=Math.floor(ae)*w),oew&&J.push(Ce)}else{let Ce=(0,N.max)(ye.data)[1];if(Ce===re-1||(de=(0,N.softmax)(ye.data),de[Ce]Je*Se[(te+1)%2])),Ie.boxes.push(Be),Ie.classes.push(Ce),Ie.scores.push(de[Ce])}}xe.push(Ie)}return xe}function I(S,w=null){const T=S.logits,O=T.dims[0];if(w!==null&&w.length!==O)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ae=[];for(let oe=0;oeSe[J]&&(Se[J]=ye[J],Ie[J]=Ge)}const Ee=new Array(we.dims[0]);for(let Ge=0;GeGe!==void 0);ae.push({segmentation:ce,labels:tt})}return ae}function H(S,w,T,O){const ae=[],oe=[],Te=[];for(let we=0;weT&&(ae.push(xe),oe.push(Ie),Te.push(ce))}return[ae,oe,Te]}function se(S,w,T,O=.5,ae=.8){const oe=[];let Te=0,we=0;const re=w[T].data;for(let ce=0;ce=O&&++we;let xe=Te>0&&we>0;return xe&&(xe=Te/we>ae),[xe,oe]}function ne(S,w,T,O,ae,oe=null,Te=null){const[we,re]=Te??S[0].dims,xe=new F.Tensor("int32",new Int32Array(we*re),[we,re]),ce=[];if(Te!==null)for(let Ge=0;GeIe[de]&&(Se[de]=Ge,Ie[de]=J[de])}let Ee=0;const tt=xe.data;for(let Ge=0;Ge200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(S,w)/Math.min(S,w)}`);let oe=Math.round(S/T)*T,Te=Math.round(w/T)*T;if(oe*Te>ae){const we=Math.sqrt(S*w/ae);oe=Math.floor(S/we/T)*T,Te=Math.floor(w/we/T)*T}else if(oe*Teoe?xe=Math.floor(oe*re/ae):oe>ae&&(re=Math.floor(ae*xe/oe)),await w.resize(xe,re,{resample:O}))}async crop_margin(w,T=200){const O=w.clone().grayscale(),ae=(0,N.min)(O.data)[0],Te=(0,N.max)(O.data)[0]-ae;if(Te===0)return w;const we=T/255;let re=O.width,xe=O.height,ce=0,Se=0;const Ie=O.data;for(let Ee=0;Eethis.preprocess(oe)));return{pixel_values:(0,F.stack)(O.map(oe=>oe.pixel_values),0),original_sizes:O.map(oe=>oe.original_size),reshaped_input_sizes:O.map(oe=>oe.reshaped_input_size)}}static async from_pretrained(w,T){const O=await(0,R.getModelJSON)(w,g.IMAGE_PROCESSOR_NAME,!0,T);return new this(O)}}},"./src/base/processing_utils.js":(Le,$,r)=>{r.r($),r.d($,{Processor:()=>Y});var f=r("./src/utils/constants.js"),F=r("./src/utils/generic.js"),N=r("./src/utils/hub.js");class Y extends F.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)}decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.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,N.getModelJSON)(g,f.PROCESSOR_NAME,!0,v):{},Promise.all(this.classes.filter(b=>b in this).map(async b=>{const I=await this[b].from_pretrained(g,v);return[b.replace(/_class$/,""),I]})).then(Object.fromEntries)]);return new this(M,y)}}_e(Y,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),_e(Y,"uses_processor_config",!1)},"./src/configs.js":(Le,$,r)=>{r.r($),r.d($,{AutoConfig:()=>v,PretrainedConfig:()=>g,getKeyValueShapes:()=>R});var f=r("./src/utils/core.js"),F=r("./src/utils/hub.js");async function N(M,y){return await(0,F.getModelJSON)(M,"config.json",!0,y)}function Y(M){const y={};let b={};switch(M.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":b=Y(M.text_config);break;case"moondream1":b=Y(M.phi_config);break;case"musicgen":b=Y(M.decoder);break;case"multi_modality":b=Y(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"falcon":y.num_heads="num_attention_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":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":case"glm":case"helium":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"exaone":y.num_heads="num_key_value_heads",y.num_layers="num_layers",y.dim_kv="head_dim",y.num_attention_heads="num_attention_heads";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"moonshine":y.num_decoder_layers="decoder_num_hidden_layers",y.num_decoder_heads="decoder_num_key_value_heads",y.num_encoder_layers="encoder_num_hidden_layers",y.num_encoder_heads="encoder_num_key_value_heads",y.encoder_hidden_size=y.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const H=Y(M.decoder),se="num_decoder_layers"in H,ne=(0,f.pick)(M,["model_type","is_encoder_decoder"]);return se?(ne.num_decoder_layers=H.num_decoder_layers,ne.num_decoder_heads=H.num_decoder_heads,ne.decoder_hidden_size=H.decoder_hidden_size,ne.num_encoder_layers=H.num_encoder_layers,ne.num_encoder_heads=H.num_encoder_heads,ne.encoder_hidden_size=H.encoder_hidden_size):(ne.num_layers=H.num_layers,ne.num_heads=H.num_heads,ne.hidden_size=H.hidden_size),ne}const I={...b,...(0,f.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const H in y)I[H]=M[y[H]];return I}function R(M,{prefix:y="past_key_values",batch_size:b=1}={}){const I={},H=M.normalized_config;if(H.is_encoder_decoder&&"num_encoder_heads"in H&&"num_decoder_heads"in H){const se=H.encoder_dim_kv??H.encoder_hidden_size/H.num_encoder_heads,ne=H.decoder_dim_kv??H.decoder_hidden_size/H.num_decoder_heads,W=[b,H.num_encoder_heads,0,se],U=[b,H.num_decoder_heads,0,ne];for(let q=0;q{var O,ae;r.r($),r.d($,{apis:()=>ne,env:()=>w});var f=r("?569f"),F=r("?3f59"),N=r("?154a");const Y="3.3.3",R=typeof window<"u"&&typeof window.document<"u",g=typeof self<"u"&&((O=self.constructor)==null?void 0:O.name)==="DedicatedWorkerGlobalScope",v=typeof self<"u"&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,y=typeof navigator<"u"&&"ml"in navigator,b=typeof process<"u",I=b&&((ae=process==null?void 0:process.release)==null?void 0:ae.name)==="node",H=!T(f),se=!T(F),ne=Object.freeze({IS_BROWSER_ENV:R,IS_WEBWORKER_ENV:g,IS_WEB_CACHE_AVAILABLE:v,IS_WEBGPU_AVAILABLE:M,IS_WEBNN_AVAILABLE:y,IS_PROCESS_AVAILABLE:b,IS_NODE_ENV:I,IS_FS_AVAILABLE:H,IS_PATH_AVAILABLE:se}),W=H&&se;let U="./";if(W){const oe=Object({url:self.location.href}).url;oe?U=F.dirname(F.dirname(N.fileURLToPath(oe))):typeof __dirname<"u"&&(U=F.dirname(__dirname))}const q=W?F.join(U,"/.cache/"):null,A="/models/",S=W?F.join(U,A):A,w={version:Y,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(R||g),localModelPath:S,useFS:H,useBrowserCache:v,useFSCache:H,cacheDir:q,useCustomCache:!1,customCache:null};function T(oe){return Object.keys(oe).length===0}},"./src/generation/configuration_utils.js":(Le,$,r)=>{r.r($),r.d($,{GenerationConfig:()=>F});var f=r("./src/utils/core.js");class F{constructor(Y){_e(this,"max_length",20);_e(this,"max_new_tokens",null);_e(this,"min_length",0);_e(this,"min_new_tokens",null);_e(this,"early_stopping",!1);_e(this,"max_time",null);_e(this,"do_sample",!1);_e(this,"num_beams",1);_e(this,"num_beam_groups",1);_e(this,"penalty_alpha",null);_e(this,"use_cache",!0);_e(this,"temperature",1);_e(this,"top_k",50);_e(this,"top_p",1);_e(this,"typical_p",1);_e(this,"epsilon_cutoff",0);_e(this,"eta_cutoff",0);_e(this,"diversity_penalty",0);_e(this,"repetition_penalty",1);_e(this,"encoder_repetition_penalty",1);_e(this,"length_penalty",1);_e(this,"no_repeat_ngram_size",0);_e(this,"bad_words_ids",null);_e(this,"force_words_ids",null);_e(this,"renormalize_logits",!1);_e(this,"constraints",null);_e(this,"forced_bos_token_id",null);_e(this,"forced_eos_token_id",null);_e(this,"remove_invalid_values",!1);_e(this,"exponential_decay_length_penalty",null);_e(this,"suppress_tokens",null);_e(this,"streamer",null);_e(this,"begin_suppress_tokens",null);_e(this,"forced_decoder_ids",null);_e(this,"guidance_scale",null);_e(this,"num_return_sequences",1);_e(this,"output_attentions",!1);_e(this,"output_hidden_states",!1);_e(this,"output_scores",!1);_e(this,"return_dict_in_generate",!1);_e(this,"pad_token_id",null);_e(this,"bos_token_id",null);_e(this,"eos_token_id",null);_e(this,"encoder_no_repeat_ngram_size",0);_e(this,"decoder_start_token_id",null);_e(this,"generation_kwargs",{});Object.assign(this,(0,f.pick)(Y,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Le,$,r)=>{r.r($),r.d($,{ClassifierFreeGuidanceLogitsProcessor:()=>W,ForcedBOSTokenLogitsProcessor:()=>g,ForcedEOSTokenLogitsProcessor:()=>v,LogitsProcessor:()=>N,LogitsProcessorList:()=>R,LogitsWarper:()=>Y,MinLengthLogitsProcessor:()=>H,MinNewTokensLengthLogitsProcessor:()=>se,NoBadWordsLogitsProcessor:()=>ne,NoRepeatNGramLogitsProcessor:()=>b,RepetitionPenaltyLogitsProcessor:()=>I,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>U,TopKLogitsWarper:()=>A,TopPLogitsWarper:()=>q,WhisperTimeStampLogitsProcessor:()=>y});var f=r("./src/utils/generic.js");r("./src/utils/tensor.js");var F=r("./src/utils/maths.js");class N extends f.Callable{_call(w,T){throw Error("`_call` should be implemented in a subclass")}}class Y extends f.Callable{_call(w,T){throw Error("`_call` should be implemented in a subclass")}}class R extends f.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,T){let O=T;for(const ae of this.processors)O=ae(w,O);return O}[Symbol.iterator](){return this.processors.values()}}class g extends N{constructor(w){super(),this.bos_token_id=w}_call(w,T){for(let O=0;O=1&&oe[oe.length-1]>=this.timestamp_begin,we=oe.length<2||oe[oe.length-2]>=this.timestamp_begin;if(Te&&(we?ae.subarray(this.timestamp_begin).fill(-1/0):ae.subarray(0,this.eos_token_id).fill(-1/0)),w[O].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Se=this.timestamp_begin+this.max_initial_timestamp_index;ae.subarray(Se+1).fill(-1/0)}const re=(0,F.log_softmax)(ae),xe=Math.log(re.subarray(this.timestamp_begin).map(Math.exp).reduce((Se,Ie)=>Se+Ie)),ce=(0,F.max)(re.subarray(0,this.timestamp_begin))[0];xe>ce&&ae.subarray(0,this.timestamp_begin).fill(-1/0)}return T}}class b extends N{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const T=w.length,O=[];for(let oe=0;oe1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,T){if(T.dims[0]!==2*w.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${T.dims[0]} for the logits and ${w.length} for the input ids.`);const O=w.length,ae=T.slice([0,O],null),oe=T.slice([O,T.dims[0]],null);for(let Te=0;Te1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger(O)||O<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${O}`);this.top_p=w,this.filter_value=T,this.min_tokens_to_keep=O}}class A extends Y{constructor(w,{filter_value:T=-1/0,min_tokens_to_keep:O=1}={}){if(super(),!Number.isInteger(w)||w<0)throw new Error(`\`top_k\` must be a positive integer, but is ${w}`);this.top_k=Math.max(w,O),this.filter_value=T}}},"./src/generation/logits_sampler.js":(Le,$,r)=>{r.r($),r.d($,{LogitsSampler:()=>Y});var f=r("./src/utils/generic.js"),F=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class Y extends f.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,b){let I=y.dims.at(-1),H=y.data;if(b===-1)H=H.slice(-I);else{let se=b*I;H=H.slice(se,se+I)}return H}randomSelect(y){let b=0;for(let H=0;H1)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 R(y)}}class R extends Y{async sample(y){const b=(0,N.max)(y.data)[1];return[[BigInt(b),0]]}}class g extends Y{async sample(y){let b=y.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[I,H]=await(0,F.topk)(y,b),se=(0,N.softmax)(I.data);return Array.from({length:this.generation_config.num_beams},()=>{const ne=this.randomSelect(se);return[H.data[ne],Math.log(se[ne])]})}}class v extends Y{async sample(y){let b=y.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[I,H]=await(0,F.topk)(y,b),se=(0,N.softmax)(I.data);return Array.from({length:this.generation_config.num_beams},(ne,W)=>[H.data[W],Math.log(se[W])])}}},"./src/generation/stopping_criteria.js":(Le,$,r)=>{r.r($),r.d($,{EosTokenCriteria:()=>R,InterruptableStoppingCriteria:()=>g,MaxLengthCriteria:()=>Y,StoppingCriteria:()=>F,StoppingCriteriaList:()=>N});var f=r("./src/utils/generic.js");class F extends f.Callable{_call(M,y){throw Error("StoppingCriteria needs to be subclassed")}}class N extends f.Callable{constructor(){super(),this.criteria=[]}push(M){this.criteria.push(M)}extend(M){M instanceof N?M=M.criteria:M instanceof F&&(M=[M]),this.criteria.push(...M)}_call(M,y){const b=new Array(M.length).fill(!1);for(const I of this.criteria){const H=I(M,y);for(let se=0;sey.length>=this.max_length)}}class R extends F{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,y){return M.map(b=>{const I=b.at(-1);return this.eos_token_id.some(H=>I==H)})}}class g extends F{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":(Le,$,r)=>{r.r($),r.d($,{BaseStreamer:()=>Y,TextStreamer:()=>g,WhisperTextStreamer:()=>v});var f=r("./src/utils/core.js"),F=r("./src/tokenizers.js"),N=r("./src/env.js");class Y{put(y){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const R=N.apis.IS_PROCESS_AVAILABLE?M=>process.stdout.write(M):M=>console.log(M);class g extends Y{constructor(y,{skip_prompt:b=!1,callback_function:I=null,token_callback_function:H=null,skip_special_tokens:se=!0,decode_kwargs:ne={},...W}={}){super(),this.tokenizer=y,this.skip_prompt=b,this.callback_function=I??R,this.token_callback_function=H,this.decode_kwargs={skip_special_tokens:se,...ne,...W},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(y){var se;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 b=y[0];(se=this.token_callback_function)==null||se.call(this,b),this.token_cache=(0,f.mergeArrays)(this.token_cache,b);const I=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let H;I.endsWith(` +`)?(H=I.slice(this.print_len),this.token_cache=[],this.print_len=0):I.length>0&&(0,F.is_chinese_char)(I.charCodeAt(I.length-1))?(H=I.slice(this.print_len),this.print_len+=H.length):(H=I.slice(this.print_len,I.lastIndexOf(" ")+1),this.print_len+=H.length),this.on_finalized_text(H,!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,b){var I,H;y.length>0&&((I=this.callback_function)==null||I.call(this,y)),b&&this.callback_function===R&&N.apis.IS_PROCESS_AVAILABLE&&((H=this.callback_function)==null||H.call(this,` +`))}}class v extends g{constructor(y,{skip_prompt:b=!1,callback_function:I=null,token_callback_function:H=null,on_chunk_start:se=null,on_chunk_end:ne=null,on_finalize:W=null,time_precision:U=.02,skip_special_tokens:q=!0,decode_kwargs:A={}}={}){super(y,{skip_prompt:b,skip_special_tokens:q,callback_function:I,token_callback_function:H,decode_kwargs:A}),this.timestamp_begin=y.timestamp_begin,this.on_chunk_start=se,this.on_chunk_end=ne,this.on_finalize=W,this.time_precision=U,this.waiting_for_timestamp=!1}put(y){var I,H;if(y.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const b=y[0];if(b.length===1){const se=Number(b[0])-this.timestamp_begin;if(se>=0){const ne=se*this.time_precision;this.waiting_for_timestamp?(I=this.on_chunk_end)==null||I.call(this,ne):(H=this.on_chunk_start)==null||H.call(this,ne),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":(Le,$,r)=>{r.r($),r.d($,{ASTForAudioClassification:()=>Ko,ASTModel:()=>Va,ASTPreTrainedModel:()=>Jt,AlbertForMaskedLM:()=>is,AlbertForQuestionAnswering:()=>Nn,AlbertForSequenceClassification:()=>Pn,AlbertModel:()=>Rn,AlbertPreTrainedModel:()=>Kr,AutoModel:()=>Sa,AutoModelForAudioClassification:()=>Mc,AutoModelForAudioFrameClassification:()=>vc,AutoModelForCTC:()=>yc,AutoModelForCausalLM:()=>uc,AutoModelForDepthEstimation:()=>Pc,AutoModelForDocumentQuestionAnswering:()=>xp,AutoModelForImageClassification:()=>hc,AutoModelForImageFeatureExtraction:()=>Cc,AutoModelForImageMatting:()=>Tc,AutoModelForImageSegmentation:()=>mc,AutoModelForImageToImage:()=>xc,AutoModelForMaskGeneration:()=>wc,AutoModelForMaskedLM:()=>dc,AutoModelForNormalEstimation:()=>Pp,AutoModelForObjectDetection:()=>fc,AutoModelForPoseEstimation:()=>Ec,AutoModelForQuestionAnswering:()=>cc,AutoModelForSemanticSegmentation:()=>_c,AutoModelForSeq2SeqLM:()=>ic,AutoModelForSequenceClassification:()=>Tp,AutoModelForSpeechSeq2Seq:()=>ac,AutoModelForTextToSpectrogram:()=>$a,AutoModelForTextToWaveform:()=>lc,AutoModelForTokenClassification:()=>oc,AutoModelForUniversalSegmentation:()=>Aa,AutoModelForVision2Seq:()=>pc,AutoModelForXVector:()=>bc,AutoModelForZeroShotObjectDetection:()=>gc,BartForConditionalGeneration:()=>Kt,BartForSequenceClassification:()=>_s,BartModel:()=>xt,BartPretrainedModel:()=>_t,BaseModelOutput:()=>Ue,BeitForImageClassification:()=>an,BeitModel:()=>on,BeitPreTrainedModel:()=>fu,BertForMaskedLM:()=>Ve,BertForQuestionAnswering:()=>je,BertForSequenceClassification:()=>We,BertForTokenClassification:()=>Ne,BertModel:()=>be,BertPreTrainedModel:()=>le,BlenderbotForConditionalGeneration:()=>Zs,BlenderbotModel:()=>ze,BlenderbotPreTrainedModel:()=>Ws,BlenderbotSmallForConditionalGeneration:()=>Xs,BlenderbotSmallModel:()=>Ss,BlenderbotSmallPreTrainedModel:()=>Or,BloomForCausalLM:()=>Wl,BloomModel:()=>Vl,BloomPreTrainedModel:()=>xi,CLIPModel:()=>tl,CLIPPreTrainedModel:()=>nn,CLIPSegForImageSegmentation:()=>ll,CLIPSegModel:()=>al,CLIPSegPreTrainedModel:()=>Zo,CLIPTextModel:()=>Rc,CLIPTextModelWithProjection:()=>sl,CLIPVisionModel:()=>Nc,CLIPVisionModelWithProjection:()=>rl,CamembertForMaskedLM:()=>en,CamembertForQuestionAnswering:()=>tn,CamembertForSequenceClassification:()=>Sr,CamembertForTokenClassification:()=>$r,CamembertModel:()=>Nt,CamembertPreTrainedModel:()=>Tr,CausalLMOutput:()=>pn,CausalLMOutputWithPast:()=>Cp,ChineseCLIPModel:()=>gr,ChineseCLIPPreTrainedModel:()=>jc,ClapAudioModelWithProjection:()=>wd,ClapModel:()=>nr,ClapPreTrainedModel:()=>ca,ClapTextModelWithProjection:()=>gd,CodeGenForCausalLM:()=>Ml,CodeGenModel:()=>ii,CodeGenPreTrainedModel:()=>co,CohereForCausalLM:()=>$l,CohereModel:()=>Sl,CoherePreTrainedModel:()=>gi,ConvBertForMaskedLM:()=>kt,ConvBertForQuestionAnswering:()=>Ms,ConvBertForSequenceClassification:()=>$t,ConvBertForTokenClassification:()=>os,ConvBertModel:()=>vt,ConvBertPreTrainedModel:()=>ct,ConvNextForImageClassification:()=>ea,ConvNextModel:()=>Au,ConvNextPreTrainedModel:()=>Zi,ConvNextV2ForImageClassification:()=>sa,ConvNextV2Model:()=>Iu,ConvNextV2PreTrainedModel:()=>ta,DPTForDepthEstimation:()=>Qc,DPTModel:()=>vu,DPTPreTrainedModel:()=>Xi,DebertaForMaskedLM:()=>Ar,DebertaForQuestionAnswering:()=>ir,DebertaForSequenceClassification:()=>Nr,DebertaForTokenClassification:()=>jr,DebertaModel:()=>Rr,DebertaPreTrainedModel:()=>cr,DebertaV2ForMaskedLM:()=>Ft,DebertaV2ForQuestionAnswering:()=>Ir,DebertaV2ForSequenceClassification:()=>Vs,DebertaV2ForTokenClassification:()=>Ur,DebertaV2Model:()=>Tt,DebertaV2PreTrainedModel:()=>ot,DecisionTransformerModel:()=>mp,DecisionTransformerPreTrainedModel:()=>Ad,DeiTForImageClassification:()=>Ui,DeiTModel:()=>yu,DeiTPreTrainedModel:()=>go,DepthAnythingForDepthEstimation:()=>xu,DepthAnythingPreTrainedModel:()=>Tu,DepthProForDepthEstimation:()=>Ji,DepthProPreTrainedModel:()=>Mo,DetrForObjectDetection:()=>ln,DetrForSegmentation:()=>Ks,DetrModel:()=>Li,DetrObjectDetectionOutput:()=>zi,DetrPreTrainedModel:()=>Fr,DetrSegmentationOutput:()=>Bi,Dinov2ForImageClassification:()=>Jc,Dinov2Model:()=>Ou,Dinov2PreTrainedModel:()=>ra,Dinov2WithRegistersForImageClassification:()=>Du,Dinov2WithRegistersModel:()=>Fu,Dinov2WithRegistersPreTrainedModel:()=>na,DistilBertForMaskedLM:()=>yn,DistilBertForQuestionAnswering:()=>ss,DistilBertForSequenceClassification:()=>Os,DistilBertForTokenClassification:()=>xr,DistilBertModel:()=>ar,DistilBertPreTrainedModel:()=>bs,DonutSwinModel:()=>$u,DonutSwinPreTrainedModel:()=>Yc,EfficientNetForImageClassification:()=>xd,EfficientNetModel:()=>Td,EfficientNetPreTrainedModel:()=>So,ElectraForMaskedLM:()=>sr,ElectraForQuestionAnswering:()=>Us,ElectraForSequenceClassification:()=>kr,ElectraForTokenClassification:()=>Zr,ElectraModel:()=>Ls,ElectraPreTrainedModel:()=>ks,EsmForMaskedLM:()=>In,EsmForSequenceClassification:()=>On,EsmForTokenClassification:()=>Fn,EsmModel:()=>oo,EsmPreTrainedModel:()=>Vr,ExaoneForCausalLM:()=>pi,ExaoneModel:()=>Tl,ExaonePreTrainedModel:()=>ci,FalconForCausalLM:()=>fd,FalconModel:()=>_d,FalconPreTrainedModel:()=>da,FastViTForImageClassification:()=>iu,FastViTModel:()=>ou,FastViTPreTrainedModel:()=>Ai,Florence2ForConditionalGeneration:()=>Xa,Florence2PreTrainedModel:()=>Qa,GLPNForDepthEstimation:()=>Su,GLPNModel:()=>Xc,GLPNPreTrainedModel:()=>vo,GPT2LMHeadModel:()=>dl,GPT2Model:()=>ul,GPT2PreTrainedModel:()=>ei,GPTBigCodeForCausalLM:()=>yl,GPTBigCodeModel:()=>wl,GPTBigCodePreTrainedModel:()=>oi,GPTJForCausalLM:()=>gl,GPTJModel:()=>fl,GPTJPreTrainedModel:()=>ni,GPTNeoForCausalLM:()=>hl,GPTNeoModel:()=>yr,GPTNeoPreTrainedModel:()=>si,GPTNeoXForCausalLM:()=>_l,GPTNeoXModel:()=>ml,GPTNeoXPreTrainedModel:()=>ri,Gemma2ForCausalLM:()=>Fl,Gemma2Model:()=>Ol,Gemma2PreTrainedModel:()=>yi,GemmaForCausalLM:()=>Il,GemmaModel:()=>Al,GemmaPreTrainedModel:()=>wi,GlmForCausalLM:()=>jn,GlmModel:()=>vl,GlmPreTrainedModel:()=>di,GraniteForCausalLM:()=>kl,GraniteModel:()=>ds,GranitePreTrainedModel:()=>fi,GroundingDinoForObjectDetection:()=>Lu,GroundingDinoPreTrainedModel:()=>Zc,GroupViTModel:()=>Mr,GroupViTPreTrainedModel:()=>nu,HeliumForCausalLM:()=>bl,HeliumModel:()=>po,HeliumPreTrainedModel:()=>ui,HieraForImageClassification:()=>Wi,HieraModel:()=>wo,HieraPreTrainedModel:()=>Vi,HubertForCTC:()=>rd,HubertForSequenceClassification:()=>ap,HubertModel:()=>sd,HubertPreTrainedModel:()=>ip,IJepaForImageClassification:()=>Yl,IJepaModel:()=>Xl,IJepaPreTrainedModel:()=>_o,Idefics3ForConditionalGeneration:()=>Xo,Idefics3PreTrainedModel:()=>Za,ImageMattingOutput:()=>Sc,JAISLMHeadModel:()=>pl,JAISModel:()=>cl,JAISPreTrainedModel:()=>ti,JinaCLIPModel:()=>uo,JinaCLIPPreTrainedModel:()=>lo,JinaCLIPTextModel:()=>Jo,JinaCLIPVisionModel:()=>wr,LlamaForCausalLM:()=>Uc,LlamaModel:()=>li,LlamaPreTrainedModel:()=>ai,LlavaForConditionalGeneration:()=>ao,LlavaOnevisionForConditionalGeneration:()=>Ha,LlavaPreTrainedModel:()=>Hr,LongT5ForConditionalGeneration:()=>$e,LongT5Model:()=>ve,LongT5PreTrainedModel:()=>ue,M2M100ForConditionalGeneration:()=>aa,M2M100Model:()=>Uu,M2M100PreTrainedModel:()=>ia,MBartForCausalLM:()=>rr,MBartForConditionalGeneration:()=>zt,MBartForSequenceClassification:()=>rs,MBartModel:()=>Fs,MBartPreTrainedModel:()=>us,MPNetForMaskedLM:()=>sn,MPNetForQuestionAnswering:()=>Tn,MPNetForSequenceClassification:()=>bn,MPNetForTokenClassification:()=>vn,MPNetModel:()=>Mn,MPNetPreTrainedModel:()=>lr,MT5ForConditionalGeneration:()=>gt,MT5Model:()=>ht,MT5PreTrainedModel:()=>Xe,MarianMTModel:()=>ju,MarianModel:()=>Nu,MarianPreTrainedModel:()=>xo,MaskFormerForInstanceSegmentation:()=>ku,MaskFormerModel:()=>Cu,MaskFormerPreTrainedModel:()=>bo,MaskedLMOutput:()=>Ys,MgpstrForSceneTextRecognition:()=>Ld,MgpstrModelOutput:()=>Fd,MgpstrPreTrainedModel:()=>Dd,MistralForCausalLM:()=>pd,MistralModel:()=>cd,MistralPreTrainedModel:()=>la,MobileBertForMaskedLM:()=>io,MobileBertForQuestionAnswering:()=>_r,MobileBertForSequenceClassification:()=>Gr,MobileBertModel:()=>Dn,MobileBertPreTrainedModel:()=>Wr,MobileLLMForCausalLM:()=>Pl,MobileLLMModel:()=>xl,MobileLLMPreTrainedModel:()=>hi,MobileNetV1ForImageClassification:()=>ga,MobileNetV1Model:()=>pp,MobileNetV1PreTrainedModel:()=>fa,MobileNetV2ForImageClassification:()=>Ed,MobileNetV2Model:()=>Pd,MobileNetV2PreTrainedModel:()=>wa,MobileNetV3ForImageClassification:()=>Sd,MobileNetV3Model:()=>kd,MobileNetV3PreTrainedModel:()=>Cd,MobileNetV4ForImageClassification:()=>$d,MobileNetV4Model:()=>hp,MobileNetV4PreTrainedModel:()=>ya,MobileViTForImageClassification:()=>du,MobileViTModel:()=>uu,MobileViTPreTrainedModel:()=>Ii,MobileViTV2ForImageClassification:()=>Kc,MobileViTV2Model:()=>cu,MobileViTV2PreTrainedModel:()=>Oi,ModelOutput:()=>Ke,ModernBertForMaskedLM:()=>pt,ModernBertForSequenceClassification:()=>lt,ModernBertForTokenClassification:()=>mt,ModernBertModel:()=>ut,ModernBertPreTrainedModel:()=>st,Moondream1ForConditionalGeneration:()=>qa,MoonshineForConditionalGeneration:()=>Ka,MoonshineModel:()=>pr,MoonshinePreTrainedModel:()=>qo,MptForCausalLM:()=>Kl,MptModel:()=>Gl,MptPreTrainedModel:()=>Pi,MultiModalityCausalLM:()=>Od,MultiModalityPreTrainedModel:()=>Id,MusicgenForCausalLM:()=>cp,MusicgenForConditionalGeneration:()=>$o,MusicgenModel:()=>dp,MusicgenPreTrainedModel:()=>_a,NomicBertModel:()=>ie,NomicBertPreTrainedModel:()=>L,OPTForCausalLM:()=>ql,OPTModel:()=>Hl,OPTPreTrainedModel:()=>Ei,Olmo2ForCausalLM:()=>Wc,Olmo2Model:()=>Cl,Olmo2PreTrainedModel:()=>_i,OlmoForCausalLM:()=>El,OlmoModel:()=>Vc,OlmoPreTrainedModel:()=>mi,OpenELMForCausalLM:()=>Ll,OpenELMModel:()=>Dl,OpenELMPreTrainedModel:()=>Mi,OwlViTForObjectDetection:()=>hu,OwlViTModel:()=>pu,OwlViTPreTrainedModel:()=>Fi,Owlv2ForObjectDetection:()=>_u,Owlv2Model:()=>mu,Owlv2PreTrainedModel:()=>Di,PaliGemmaForConditionalGeneration:()=>Ja,PaliGemmaPreTrainedModel:()=>Ya,PatchTSMixerForPrediction:()=>jd,PatchTSMixerModel:()=>Nd,PatchTSMixerPreTrainedModel:()=>Ma,PatchTSTForPrediction:()=>Rd,PatchTSTModel:()=>Bd,PatchTSTPreTrainedModel:()=>zd,Phi3ForCausalLM:()=>Ul,Phi3Model:()=>jl,Phi3PreTrainedModel:()=>Ti,Phi3VForCausalLM:()=>hr,Phi3VPreTrainedModel:()=>el,PhiForCausalLM:()=>Nl,PhiModel:()=>Rl,PhiPreTrainedModel:()=>vi,PreTrainedModel:()=>te,PretrainedMixin:()=>ys,PvtForImageClassification:()=>Si,PvtModel:()=>eu,PvtPreTrainedModel:()=>ki,PyAnnoteForAudioFrameClassification:()=>Hu,PyAnnoteModel:()=>Ku,PyAnnotePreTrainedModel:()=>Po,QuestionAnsweringModelOutput:()=>er,Qwen2ForCausalLM:()=>zl,Qwen2Model:()=>Un,Qwen2PreTrainedModel:()=>bi,Qwen2VLForConditionalGeneration:()=>Bl,Qwen2VLPreTrainedModel:()=>ho,RTDetrForObjectDetection:()=>Vn,RTDetrModel:()=>Hc,RTDetrObjectDetectionOutput:()=>Ni,RTDetrPreTrainedModel:()=>Ri,ResNetForImageClassification:()=>qc,ResNetModel:()=>Mu,ResNetPreTrainedModel:()=>Gi,RoFormerForMaskedLM:()=>ke,RoFormerForQuestionAnswering:()=>at,RoFormerForSequenceClassification:()=>Re,RoFormerForTokenClassification:()=>qe,RoFormerModel:()=>he,RoFormerPreTrainedModel:()=>G,RobertaForMaskedLM:()=>fr,RobertaForQuestionAnswering:()=>Mt,RobertaForSequenceClassification:()=>fs,RobertaForTokenClassification:()=>$s,RobertaModel:()=>or,RobertaPreTrainedModel:()=>Ot,SamImageSegmentationOutput:()=>Gn,SamModel:()=>To,SamPreTrainedModel:()=>ep,SapiensForDepthEstimation:()=>yo,SapiensForNormalEstimation:()=>Eu,SapiensForSemanticSegmentation:()=>Pu,SapiensPreTrainedModel:()=>Yi,SegformerForImageClassification:()=>yd,SegformerForSemanticSegmentation:()=>Md,SegformerModel:()=>up,SegformerPreTrainedModel:()=>cn,Seq2SeqLMOutput:()=>Ep,SequenceClassifierOutput:()=>Zt,SiglipModel:()=>nl,SiglipPreTrainedModel:()=>Yo,SiglipTextModel:()=>ol,SiglipVisionModel:()=>il,SpeechT5ForSpeechToText:()=>Pr,SpeechT5ForTextToSpeech:()=>Dr,SpeechT5HifiGan:()=>un,SpeechT5Model:()=>Gp,SpeechT5PreTrainedModel:()=>ko,SqueezeBertForMaskedLM:()=>Ln,SqueezeBertForQuestionAnswering:()=>Bn,SqueezeBertForSequenceClassification:()=>zn,SqueezeBertModel:()=>xn,SqueezeBertPreTrainedModel:()=>Lt,StableLmForCausalLM:()=>vd,StableLmModel:()=>bd,StableLmPreTrainedModel:()=>ma,Starcoder2ForCausalLM:()=>md,Starcoder2Model:()=>hd,Starcoder2PreTrainedModel:()=>ua,StyleTextToSpeech2Model:()=>ud,StyleTextToSpeech2PreTrainedModel:()=>ld,Swin2SRForImageSuperResolution:()=>bu,Swin2SRModel:()=>Qi,Swin2SRPreTrainedModel:()=>qi,SwinForImageClassification:()=>Wn,SwinModel:()=>Hi,SwinPreTrainedModel:()=>Ki,T5ForConditionalGeneration:()=>Q,T5Model:()=>P,T5PreTrainedModel:()=>Pe,TableTransformerForObjectDetection:()=>wu,TableTransformerModel:()=>gu,TableTransformerObjectDetectionOutput:()=>ji,TableTransformerPreTrainedModel:()=>fo,TokenClassifierOutput:()=>Ds,TrOCRForCausalLM:()=>dd,TrOCRPreTrainedModel:()=>dn,UniSpeechForCTC:()=>rp,UniSpeechForSequenceClassification:()=>Xu,UniSpeechModel:()=>Qu,UniSpeechPreTrainedModel:()=>Eo,UniSpeechSatForAudioFrameClassification:()=>Zu,UniSpeechSatForCTC:()=>Ju,UniSpeechSatForSequenceClassification:()=>np,UniSpeechSatModel:()=>Yu,UniSpeechSatPreTrainedModel:()=>Kn,ViTForImageClassification:()=>Ci,ViTMAEModel:()=>su,ViTMAEPreTrainedModel:()=>tu,ViTMSNForImageClassification:()=>ru,ViTMSNModel:()=>Gc,ViTMSNPreTrainedModel:()=>$i,ViTModel:()=>Ql,ViTPreTrainedModel:()=>mo,VisionEncoderDecoderModel:()=>Qo,VitMatteForImageMatting:()=>lu,VitMattePreTrainedModel:()=>au,VitPoseForPoseEstimation:()=>Zl,VitPosePreTrainedModel:()=>Jl,VitsModel:()=>ha,VitsModelOutput:()=>$c,VitsPreTrainedModel:()=>pa,Wav2Vec2BertForCTC:()=>op,Wav2Vec2BertForSequenceClassification:()=>td,Wav2Vec2BertModel:()=>ed,Wav2Vec2BertPreTrainedModel:()=>Co,Wav2Vec2ForAudioFrameClassification:()=>Gu,Wav2Vec2ForCTC:()=>Wu,Wav2Vec2ForSequenceClassification:()=>tp,Wav2Vec2Model:()=>Vu,Wav2Vec2PreTrainedModel:()=>qr,WavLMForAudioFrameClassification:()=>ad,WavLMForCTC:()=>od,WavLMForSequenceClassification:()=>id,WavLMForXVector:()=>lp,WavLMModel:()=>nd,WavLMPreTrainedModel:()=>En,WeSpeakerResNetModel:()=>sp,WeSpeakerResNetPreTrainedModel:()=>qu,WhisperForConditionalGeneration:()=>Ga,WhisperModel:()=>Wa,WhisperPreTrainedModel:()=>Ho,XLMForQuestionAnswering:()=>rn,XLMForSequenceClassification:()=>Gs,XLMForTokenClassification:()=>St,XLMModel:()=>zs,XLMPreTrainedModel:()=>Xt,XLMRobertaForMaskedLM:()=>Na,XLMRobertaForQuestionAnswering:()=>Ua,XLMRobertaForSequenceClassification:()=>Go,XLMRobertaForTokenClassification:()=>ja,XLMRobertaModel:()=>At,XLMRobertaPreTrainedModel:()=>Qe,XLMWithLMHeadModel:()=>As,XVectorOutput:()=>kc,YolosForObjectDetection:()=>Bu,YolosModel:()=>zu,YolosObjectDetectionOutput:()=>Ru,YolosPreTrainedModel:()=>oa});var f=r("./src/configs.js"),F=r("./src/backends/onnx.js"),N=r("./src/utils/dtypes.js"),Y=r("./src/utils/generic.js"),R=r("./src/utils/core.js"),g=r("./src/utils/hub.js"),v=r("./src/utils/constants.js"),M=r("./src/generation/logits_process.js"),y=r("./src/generation/configuration_utils.js"),b=r("./src/utils/tensor.js"),I=r("./src/utils/image.js"),H=r("./src/utils/maths.js"),se=r("./src/generation/stopping_criteria.js"),ne=r("./src/generation/logits_sampler.js"),W=r("./src/env.js"),U=r("./src/models/whisper/generation_whisper.js"),q=r("./src/models/whisper/common_whisper.js");const A={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},S=new Map,w=new Map,T=new Map;async function O(_,x,j){var Ts;const fe=((Ts=j.config)==null?void 0:Ts["transformers.js_config"])??{};let Oe=j.device??fe.device;Oe&&typeof Oe!="string"&&(Oe.hasOwnProperty(x)?Oe=Oe[x]:(console.warn(`device not specified for "${x}". Using the default device.`),Oe=null));const Fe=Oe??(W.apis.IS_NODE_ENV?"cpu":"wasm"),Ze=(0,F.deviceToExecutionProviders)(Fe);let rt=j.dtype??fe.dtype;if(typeof rt!="string"&&(rt&&rt.hasOwnProperty(x)?rt=rt[x]:(rt=N.DEFAULT_DEVICE_DTYPE_MAPPING[Fe]??N.DATA_TYPES.fp32,console.warn(`dtype not specified for "${x}". Using the default dtype (${rt}) for this device (${Fe}).`))),rt===N.DATA_TYPES.auto){let cs=fe.dtype;typeof cs!="string"&&(cs=cs[x]),cs&&cs!==N.DATA_TYPES.auto&&N.DATA_TYPES.hasOwnProperty(cs)?rt=cs:rt=N.DEFAULT_DEVICE_DTYPE_MAPPING[Fe]??N.DATA_TYPES.fp32}const ft=rt;if(N.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(ft)){if(ft===N.DATA_TYPES.fp16&&Fe==="webgpu"&&!await(0,N.isWebGpuFp16Supported)())throw new Error(`The device (${Fe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${ft}. Should be one of: ${Object.keys(N.DATA_TYPES).join(", ")}`);const bt=fe.kv_cache_dtype?typeof fe.kv_cache_dtype=="string"?fe.kv_cache_dtype:fe.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 Rt={dtype:ft,kv_cache_dtype:bt},Wt=N.DEFAULT_DTYPE_SUFFIX_MAPPING[ft],Dt=`${j.subfolder??""}/${x}${Wt}.onnx`,Gt={...j.session_options};Gt.executionProviders??(Gt.executionProviders=Ze);const es=fe.free_dimension_overrides;es?Gt.freeDimensionOverrides??(Gt.freeDimensionOverrides=es):Fe.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 ns=(0,g.getModelFile)(_,Dt,!0,j),Yt=j.use_external_data_format??fe.use_external_data_format;let as=[];if(Yt&&(Yt===!0||typeof Yt=="object"&&Yt.hasOwnProperty(x)&&Yt[x]===!0)){if(W.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const cs=`${x}${Wt}.onnx_data`,xs=`${j.subfolder??""}/${cs}`;as.push(new Promise(async(Is,tr)=>{const Hs=await(0,g.getModelFile)(_,xs,!0,j);Is({path:cs,data:Hs})}))}else Gt.externalData!==void 0&&(as=Gt.externalData.map(async cs=>{if(typeof cs.data=="string"){const xs=await(0,g.getModelFile)(_,cs.data,!0,j);return{...cs,data:xs}}return cs}));if(as.length>0&&(Gt.externalData=await Promise.all(as)),Fe==="webgpu"){const cs=(0,f.getKeyValueShapes)(j.config,{prefix:"present"});if(Object.keys(cs).length>0&&!(0,F.isONNXProxy)()){const xs={};for(const Is in cs)xs[Is]="gpu-buffer";Gt.preferredOutputLocation=xs}}return{buffer:await ns,session_options:Gt,session_config:Rt}}async function ae(_,x,j){return Object.fromEntries(await Promise.all(Object.keys(x).map(async fe=>{const{buffer:Oe,session_options:Fe,session_config:Ze}=await O(_,x[fe],j),rt=await(0,F.createInferenceSession)(Oe,Fe,Ze);return[fe,rt]})))}async function oe(_,x,j){return Object.fromEntries(await Promise.all(Object.keys(x).map(async fe=>{const Oe=await(0,g.getModelJSON)(_,x[fe],!1,j);return[fe,Oe]})))}function Te(_,x){const j=Object.create(null),fe=[];for(const Ze of _.inputNames){const rt=x[Ze];if(!(rt instanceof b.Tensor)){fe.push(Ze);continue}j[Ze]=(0,F.isONNXProxy)()?rt.clone():rt}if(fe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${fe.join(", ")}.`);const Oe=Object.keys(x).length,Fe=_.inputNames.length;if(Oe>Fe){let Ze=Object.keys(x).filter(rt=>!_.inputNames.includes(rt));console.warn(`WARNING: Too many inputs were provided (${Oe} > ${Fe}). The following inputs will be ignored: "${Ze.join(", ")}".`)}return j}async function we(_,x){const j=Te(_,x);try{const fe=Object.fromEntries(Object.entries(j).map(([Fe,Ze])=>[Fe,Ze.ort_tensor]));let Oe=await _.run(fe);return Oe=re(Oe),Oe}catch(fe){const Oe=Object.fromEntries(Object.entries(j).map(([Fe,{type:Ze,dims:rt,data:ft}])=>[Fe,{type:Ze,dims:rt,data:ft}]));throw console.error(`An error occurred during model execution: "${fe}".`),console.error("Inputs given to model:",Oe),fe}}function re(_){for(let x in _)(0,F.isONNXTensor)(_[x])?_[x]=new b.Tensor(_[x]):typeof _[x]=="object"&&re(_[x]);return _}function xe(_){if(_ instanceof b.Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(x=>x.length!==_[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new b.Tensor("int64",BigInt64Array.from(_.flat().map(x=>BigInt(x))),[_.length,_[0].length])}else return new b.Tensor("int64",BigInt64Array.from(_.map(x=>BigInt(x))),[1,_.length])}function ce(_){return new b.Tensor("bool",[_],[1])}async function Se(_,x){let{encoder_outputs:j,input_ids:fe,decoder_input_ids:Oe,...Fe}=x;if(!j){const rt=(0,R.pick)(x,_.sessions.model.inputNames);j=(await Ie(_,rt)).last_hidden_state}return Fe.input_ids=Oe,Fe.encoder_hidden_states=j,_.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Fe.encoder_attention_mask=x.attention_mask),await Ee(_,Fe,!0)}async function Ie(_,x){const j=_.sessions.model,fe=(0,R.pick)(x,j.inputNames);if(j.inputNames.includes("inputs_embeds")&&!fe.inputs_embeds){if(!x.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");fe.inputs_embeds=await _.encode_text({input_ids:x.input_ids})}if(j.inputNames.includes("token_type_ids")&&!fe.token_type_ids){if(!fe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");fe.token_type_ids=(0,b.zeros_like)(fe.input_ids)}if(j.inputNames.includes("pixel_mask")&&!fe.pixel_mask){if(!fe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const Oe=fe.pixel_values.dims;fe.pixel_mask=(0,b.ones)([Oe[0],Oe[2],Oe[3]])}return await we(j,fe)}async function Ee(_,x,j=!1){const fe=_.sessions[j?"decoder_model_merged":"model"],{past_key_values:Oe,...Fe}=x;if(fe.inputNames.includes("use_cache_branch")&&(Fe.use_cache_branch=ce(!!Oe)),fe.inputNames.includes("position_ids")&&Fe.attention_mask&&!Fe.position_ids){const rt=_.config.model_type==="paligemma"?1:0;Fe.position_ids=J(Fe,Oe,rt)}_.addPastKeyValues(Fe,Oe);const Ze=(0,R.pick)(Fe,fe.inputNames);return await we(fe,Ze)}function tt({image_token_id:_,inputs_embeds:x,image_features:j,input_ids:fe,attention_mask:Oe}){const Fe=fe.tolist().map(bt=>bt.reduce((Rt,Wt,Dt)=>(Wt==_&&Rt.push(Dt),Rt),[])),Ze=Fe.reduce((bt,Rt)=>bt+Rt.length,0),rt=j.dims[0];if(Ze!==rt)throw new Error(`Image features and image tokens do not match: tokens: ${Ze}, features ${rt}`);let ft=0;for(let bt=0;btFe.dims[1])){if(Oert==_.config.image_token_index)){const rt=_.config.num_image_tokens;if(!rt)throw new Error("`num_image_tokens` is missing in the model configuration.");const ft=Fe.dims[1]-(Oe-rt);j.input_ids=Fe.slice(null,[-ft,null]),j.attention_mask=(0,b.ones)([1,Oe+ft])}}}return j}function Ce(_,x,j,fe){return j.past_key_values&&(x=x.map(Oe=>[Oe.at(-1)])),{...j,decoder_input_ids:xe(x)}}function Be(_,...x){return _.config.is_encoder_decoder?Ce(_,...x):de(_,...x)}function Je(_,x,j,fe){const Oe=!!j.past_key_values;return fe.guidance_scale!==null&&fe.guidance_scale>1&&(Oe?j.input_ids=(0,b.cat)([j.input_ids,j.input_ids],0):(j.input_ids=(0,b.cat)([j.input_ids,(0,b.full_like)(j.input_ids,BigInt(fe.pad_token_id))],0),j.attention_mask=(0,b.cat)([j.attention_mask,(0,b.full_like)(j.attention_mask,0n)],0))),(Oe||!j.pixel_values)&&(j.pixel_values=(0,b.full)([0,0,3,384,384],1)),Oe&&(j.images_seq_mask=new b.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),j.images_emb_mask=new b.Tensor("bool",new Array(0).fill(!1),[1,1,0])),j}class te extends Y.Callable{constructor(j,fe,Oe){super();_e(this,"main_input_name","input_ids");_e(this,"forward_params",["input_ids","attention_mask"]);this.config=j,this.sessions=fe,this.configs=Oe;const Fe=T.get(this.constructor),Ze=S.get(Fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ze){case A.DecoderOnly:this.can_generate=!0,this._forward=Ee,this._prepare_inputs_for_generation=de;break;case A.Seq2Seq:case A.Vision2Seq:case A.Musicgen:this.can_generate=!0,this._forward=Se,this._prepare_inputs_for_generation=Ce;break;case A.EncoderDecoder:this._forward=Se;break;case A.ImageTextToText:this.can_generate=!0,this._forward=Ge,this._prepare_inputs_for_generation=Be;break;case A.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Be;break;case A.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Je;break;default:this._forward=Ie;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var fe;const j=[];for(const Oe of Object.values(this.sessions))(fe=Oe==null?void 0:Oe.handler)!=null&&fe.dispose&&j.push(Oe.handler.dispose());return await Promise.all(j)}static async from_pretrained(j,{progress_callback:fe=null,config:Oe=null,cache_dir:Fe=null,local_files_only:Ze=!1,revision:rt="main",model_file_name:ft=null,subfolder:bt="onnx",device:Rt=null,dtype:Wt=null,use_external_data_format:Dt=null,session_options:Gt={}}={}){let es={progress_callback:fe,config:Oe,cache_dir:Fe,local_files_only:Ze,revision:rt,model_file_name:ft,subfolder:bt,device:Rt,dtype:Wt,use_external_data_format:Dt,session_options:Gt};const ns=T.get(this),Yt=S.get(ns);Oe=es.config=await f.AutoConfig.from_pretrained(j,es);let as;if(Yt===A.DecoderOnly)as=await Promise.all([ae(j,{model:es.model_file_name??"model"},es),oe(j,{generation_config:"generation_config.json"},es)]);else if(Yt===A.Seq2Seq||Yt===A.Vision2Seq)as=await Promise.all([ae(j,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},es),oe(j,{generation_config:"generation_config.json"},es)]);else if(Yt===A.MaskGeneration)as=await Promise.all([ae(j,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},es)]);else if(Yt===A.EncoderDecoder)as=await Promise.all([ae(j,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},es)]);else if(Yt===A.ImageTextToText){const Ps={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Oe.is_encoder_decoder&&(Ps.model="encoder_model"),as=await Promise.all([ae(j,Ps,es),oe(j,{generation_config:"generation_config.json"},es)])}else if(Yt===A.Musicgen)as=await Promise.all([ae(j,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},es),oe(j,{generation_config:"generation_config.json"},es)]);else if(Yt===A.MultiModality)as=await Promise.all([ae(j,{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"},es),oe(j,{generation_config:"generation_config.json"},es)]);else if(Yt===A.Phi3V)as=await Promise.all([ae(j,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},es),oe(j,{generation_config:"generation_config.json"},es)]);else{if(Yt!==A.EncoderOnly){const Ps=ns??(Oe==null?void 0:Oe.model_type);Ps!=="custom"&&console.warn(`Model type for '${Ps}' not found, assuming encoder-only architecture. Please report this at ${v.GITHUB_ISSUE_URL}.`)}as=await Promise.all([ae(j,{model:es.model_file_name??"model"},es)])}return new this(Oe,...as)}async _call(j){return await this.forward(j)}async forward(j){return await this._forward(this,j)}get generation_config(){var j;return((j=this.configs)==null?void 0:j.generation_config)??null}_get_logits_warper(j){const fe=new M.LogitsProcessorList;return j.temperature!==null&&j.temperature!==1&&fe.push(new M.TemperatureLogitsWarper(j.temperature)),j.top_k!==null&&j.top_k!==0&&fe.push(new M.TopKLogitsWarper(j.top_k)),j.top_p!==null&&j.top_p<1&&fe.push(new M.TopPLogitsWarper(j.top_p)),fe}_get_logits_processor(j,fe,Oe=null){const Fe=new M.LogitsProcessorList;if(j.repetition_penalty!==null&&j.repetition_penalty!==1&&Fe.push(new M.RepetitionPenaltyLogitsProcessor(j.repetition_penalty)),j.no_repeat_ngram_size!==null&&j.no_repeat_ngram_size>0&&Fe.push(new M.NoRepeatNGramLogitsProcessor(j.no_repeat_ngram_size)),j.bad_words_ids!==null&&Fe.push(new M.NoBadWordsLogitsProcessor(j.bad_words_ids,j.eos_token_id)),j.min_length!==null&&j.eos_token_id!==null&&j.min_length>0&&Fe.push(new M.MinLengthLogitsProcessor(j.min_length,j.eos_token_id)),j.min_new_tokens!==null&&j.eos_token_id!==null&&j.min_new_tokens>0&&Fe.push(new M.MinNewTokensLengthLogitsProcessor(fe,j.min_new_tokens,j.eos_token_id)),j.forced_bos_token_id!==null&&Fe.push(new M.ForcedBOSTokenLogitsProcessor(j.forced_bos_token_id)),j.forced_eos_token_id!==null&&Fe.push(new M.ForcedEOSTokenLogitsProcessor(j.max_length,j.forced_eos_token_id)),j.begin_suppress_tokens!==null){const Ze=fe>1||j.forced_bos_token_id===null?fe:fe+1;Fe.push(new M.SuppressTokensAtBeginLogitsProcessor(j.begin_suppress_tokens,Ze))}return j.guidance_scale!==null&&j.guidance_scale>1&&Fe.push(new M.ClassifierFreeGuidanceLogitsProcessor(j.guidance_scale)),Oe!==null&&Fe.extend(Oe),Fe}_prepare_generation_config(j,fe,Oe=y.GenerationConfig){const Fe={...this.config};for(const rt of["decoder","generator","text_config"])rt in Fe&&Object.assign(Fe,Fe[rt]);const Ze=new Oe(Fe);return Object.assign(Ze,this.generation_config??{}),j&&Object.assign(Ze,j),fe&&Object.assign(Ze,(0,R.pick)(fe,Object.getOwnPropertyNames(Ze))),Ze}_get_stopping_criteria(j,fe=null){const Oe=new se.StoppingCriteriaList;return j.max_length!==null&&Oe.push(new se.MaxLengthCriteria(j.max_length,this.config.max_position_embeddings??null)),j.eos_token_id!==null&&Oe.push(new se.EosTokenCriteria(j.eos_token_id)),fe&&Oe.extend(fe),Oe}_validate_model_class(){if(!this.can_generate){const j=[xa,Ca,Ao,Ud],fe=T.get(this.constructor),Oe=new Set,Fe=this.config.model_type;for(const rt of j){const ft=rt.get(Fe);ft&&Oe.add(ft[0])}let Ze=`The current model class (${fe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Oe.size>0&&(Ze+=` Please use the following class instead: ${[...Oe].join(", ")}`),Error(Ze)}}prepare_inputs_for_generation(...j){return this._prepare_inputs_for_generation(this,...j)}_update_model_kwargs_for_generation({generated_input_ids:j,outputs:fe,model_inputs:Oe,is_encoder_decoder:Fe}){return Oe.past_key_values=this.getPastKeyValues(fe,Oe.past_key_values),Oe.input_ids=new b.Tensor("int64",j.flat(),[j.length,1]),Fe||(Oe.attention_mask=(0,b.cat)([Oe.attention_mask,(0,b.ones)([Oe.attention_mask.dims[0],1])],1)),Oe.position_ids=null,Oe}_prepare_model_inputs({inputs:j,bos_token_id:fe,model_kwargs:Oe}){const Fe=(0,R.pick)(Oe,this.forward_params),Ze=this.main_input_name;if(Ze in Fe){if(j)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Fe[Ze]=j;return{inputs_tensor:Fe[Ze],model_inputs:Fe,model_input_name:Ze}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:j,model_inputs:fe,model_input_name:Oe,generation_config:Fe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!fe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:rt,pixel_values:ft,attention_mask:bt,...Rt}=fe,Wt=await this._prepare_inputs_embeds(fe);fe={...Rt,...(0,R.pick)(Wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ze}=await Ie(this,fe);if(Fe.guidance_scale!==null&&Fe.guidance_scale>1)Ze=(0,b.cat)([Ze,(0,b.full_like)(Ze,0)],0),"attention_mask"in fe&&(fe.attention_mask=(0,b.cat)([fe.attention_mask,(0,b.zeros_like)(fe.attention_mask)],0));else if(fe.decoder_input_ids){const rt=xe(fe.decoder_input_ids).dims[0];if(rt!==Ze.dims[0]){if(Ze.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ze.dims[0]}) than the decoder inputs (${rt}).`);Ze=(0,b.cat)(Array.from({length:rt},()=>Ze),0)}}return fe.encoder_outputs=Ze,fe}_prepare_decoder_input_ids_for_generation({batch_size:j,model_input_name:fe,model_kwargs:Oe,decoder_start_token_id:Fe,bos_token_id:Ze,generation_config:rt}){let{decoder_input_ids:ft,...bt}=Oe;if(!(ft instanceof b.Tensor)){if(ft)Array.isArray(ft[0])||(ft=Array.from({length:j},()=>ft));else if(Fe??(Fe=Ze),this.config.model_type==="musicgen")ft=Array.from({length:j*this.config.decoder.num_codebooks},()=>[Fe]);else if(Array.isArray(Fe)){if(Fe.length!==j)throw new Error(`\`decoder_start_token_id\` expcted to have length ${j} but got ${Fe.length}`);ft=Fe}else ft=Array.from({length:j},()=>[Fe]);ft=xe(ft)}return Oe.decoder_attention_mask=(0,b.ones_like)(ft),{input_ids:ft,model_inputs:bt}}async generate({inputs:j=null,generation_config:fe=null,logits_processor:Oe=null,stopping_criteria:Fe=null,streamer:Ze=null,...rt}){this._validate_model_class(),fe=this._prepare_generation_config(fe,rt);let{inputs_tensor:ft,model_inputs:bt,model_input_name:Rt}=this._prepare_model_inputs({inputs:j,model_kwargs:rt});const Wt=this.config.is_encoder_decoder;Wt&&("encoder_outputs"in bt||(bt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ft,model_inputs:bt,model_input_name:Rt,generation_config:fe})));let Dt;Wt?{input_ids:Dt,model_inputs:bt}=this._prepare_decoder_input_ids_for_generation({batch_size:bt[Rt].dims.at(0),model_input_name:Rt,model_kwargs:bt,decoder_start_token_id:fe.decoder_start_token_id,bos_token_id:fe.bos_token_id,generation_config:fe}):Dt=bt[Rt];let Gt=Dt.dims.at(-1);fe.max_new_tokens!==null&&(fe.max_length=Gt+fe.max_new_tokens);const es=this._get_logits_processor(fe,Gt,Oe),ns=this._get_stopping_criteria(fe,Fe),Yt=bt[Rt].dims.at(0),as=ne.LogitsSampler.getSampler(fe),Ps=new Array(Yt).fill(0),Ts=Dt.tolist();Ze&&Ze.put(Ts);let cs,xs={};for(;;){if(bt=this.prepare_inputs_for_generation(Ts,bt,fe),cs=await this.forward(bt),fe.output_attentions&&fe.return_dict_in_generate){const ur=this.getAttentions(cs);for(const br in ur)br in xs||(xs[br]=[]),xs[br].push(ur[br])}const Hs=cs.logits.slice(null,-1,null),Er=es(Ts,Hs),Cn=[];for(let ur=0;urur))break;bt=this._update_model_kwargs_for_generation({generated_input_ids:Cn,outputs:cs,model_inputs:bt,is_encoder_decoder:Wt})}Ze&&Ze.end();const Is=this.getPastKeyValues(cs,bt.past_key_values,!0),tr=new b.Tensor("int64",Ts.flat(),[Ts.length,Ts[0].length]);if(fe.return_dict_in_generate)return{sequences:tr,past_key_values:Is,...xs};for(const Hs of Object.values(cs))Hs.location==="gpu-buffer"&&Hs.dispose();return tr}getPastKeyValues(j,fe,Oe=!1){const Fe=Object.create(null);for(const Ze in j)if(Ze.startsWith("present")){const rt=Ze.replace("present","past_key_values"),ft=Ze.includes("encoder");if(ft&&fe?Fe[rt]=fe[rt]:Fe[rt]=j[Ze],fe&&(!ft||Oe)){const bt=fe[rt];bt.location==="gpu-buffer"&&bt.dispose()}}return Fe}getAttentions(j){const fe={};for(const Oe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Fe in j)Fe.startsWith(Oe)&&(Oe in fe||(fe[Oe]=[]),fe[Oe].push(j[Fe]));return fe}addPastKeyValues(j,fe){var Oe,Fe,Ze;if(fe)Object.assign(j,fe);else{const rt=this.sessions.decoder_model_merged??this.sessions.model,ft=((Oe=rt==null?void 0:rt.config)==null?void 0:Oe.kv_cache_dtype)??"float32",bt=ft==="float16"?new Uint16Array:[],Rt=((Ze=(Fe=j[this.main_input_name]??j.attention_mask)==null?void 0:Fe.dims)==null?void 0:Ze[0])??1,Wt=(0,f.getKeyValueShapes)(this.config,{batch_size:Rt});for(const Dt in Wt)j[Dt]=new b.Tensor(ft,bt,Wt[Dt])}}async encode_image({pixel_values:j}){const fe=(await we(this.sessions.vision_encoder,{pixel_values:j})).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 (${fe.dims[1]}).`),this.config.num_image_tokens=fe.dims[1]),fe}async encode_text({input_ids:j}){return(await we(this.sessions.embed_tokens,{input_ids:j})).inputs_embeds}}class Ke{}class Ue extends Ke{constructor({last_hidden_state:x,hidden_states:j=null,attentions:fe=null}){super(),this.last_hidden_state=x,this.hidden_states=j,this.attentions=fe}}class le extends te{}class be extends le{}class Ve extends le{async _call(x){return new Ys(await super._call(x))}}class We extends le{async _call(x){return new Zt(await super._call(x))}}class Ne extends le{async _call(x){return new Ds(await super._call(x))}}class je extends le{async _call(x){return new er(await super._call(x))}}class st extends te{}class ut extends st{}class pt extends st{async _call(x){return new Ys(await super._call(x))}}class lt extends st{async _call(x){return new Zt(await super._call(x))}}class mt extends st{async _call(x){return new Ds(await super._call(x))}}class L extends te{}class ie extends L{}class G extends te{}class he extends G{}class ke extends G{async _call(x){return new Ys(await super._call(x))}}class Re extends G{async _call(x){return new Zt(await super._call(x))}}class qe extends G{async _call(x){return new Ds(await super._call(x))}}class at extends G{async _call(x){return new er(await super._call(x))}}class ct extends te{}class vt extends ct{}class kt extends ct{async _call(x){return new Ys(await super._call(x))}}class $t extends ct{async _call(x){return new Zt(await super._call(x))}}class os extends ct{async _call(x){return new Ds(await super._call(x))}}class Ms extends ct{async _call(x){return new er(await super._call(x))}}class ks extends te{}class Ls extends ks{}class sr extends ks{async _call(x){return new Ys(await super._call(x))}}class kr extends ks{async _call(x){return new Zt(await super._call(x))}}class Zr extends ks{async _call(x){return new Ds(await super._call(x))}}class Us extends ks{async _call(x){return new er(await super._call(x))}}class Tr extends te{}class Nt extends Tr{}class en extends Tr{async _call(x){return new Ys(await super._call(x))}}class Sr extends Tr{async _call(x){return new Zt(await super._call(x))}}class $r extends Tr{async _call(x){return new Ds(await super._call(x))}}class tn extends Tr{async _call(x){return new er(await super._call(x))}}class cr extends te{}class Rr extends cr{}class Ar extends cr{async _call(x){return new Ys(await super._call(x))}}class Nr extends cr{async _call(x){return new Zt(await super._call(x))}}class jr extends cr{async _call(x){return new Ds(await super._call(x))}}class ir extends cr{async _call(x){return new er(await super._call(x))}}class ot extends te{}class Tt extends ot{}class Ft extends ot{async _call(x){return new Ys(await super._call(x))}}class Vs extends ot{async _call(x){return new Zt(await super._call(x))}}class Ur extends ot{async _call(x){return new Ds(await super._call(x))}}class Ir extends ot{async _call(x){return new er(await super._call(x))}}class bs extends te{}class ar extends bs{}class Os extends bs{async _call(x){return new Zt(await super._call(x))}}class xr extends bs{async _call(x){return new Ds(await super._call(x))}}class ss extends bs{async _call(x){return new er(await super._call(x))}}class yn extends bs{async _call(x){return new Ys(await super._call(x))}}class Vr extends te{}class oo extends Vr{}class In extends Vr{async _call(x){return new Ys(await super._call(x))}}class On extends Vr{async _call(x){return new Zt(await super._call(x))}}class Fn extends Vr{async _call(x){return new Ds(await super._call(x))}}class Wr extends te{}class Dn extends Wr{}class io extends Wr{async _call(x){return new Ys(await super._call(x))}}class Gr extends Wr{async _call(x){return new Zt(await super._call(x))}}class _r extends Wr{async _call(x){return new er(await super._call(x))}}class lr extends te{}class Mn extends lr{}class sn extends lr{async _call(x){return new Ys(await super._call(x))}}class bn extends lr{async _call(x){return new Zt(await super._call(x))}}class vn extends lr{async _call(x){return new Ds(await super._call(x))}}class Tn extends lr{async _call(x){return new er(await super._call(x))}}class Lt extends te{}class xn extends Lt{}class Ln extends Lt{async _call(x){return new Ys(await super._call(x))}}class zn extends Lt{async _call(x){return new Zt(await super._call(x))}}class Bn extends Lt{async _call(x){return new er(await super._call(x))}}class Kr extends te{}class Rn extends Kr{}class Pn extends Kr{async _call(x){return new Zt(await super._call(x))}}class Nn extends Kr{async _call(x){return new er(await super._call(x))}}class is extends Kr{async _call(x){return new Ys(await super._call(x))}}class Pe extends te{constructor(){super(...arguments);_e(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class P extends Pe{}class Q extends Pe{}class ue extends te{}class ve extends ue{}class $e extends ue{}class Xe extends te{}class ht extends Xe{}class gt extends Xe{}class _t extends te{}class xt extends _t{}class Kt extends _t{}class _s extends _t{async _call(x){return new Zt(await super._call(x))}}class us extends te{}class Fs extends us{}class zt extends us{}class rs extends us{async _call(x){return new Zt(await super._call(x))}}class rr extends us{}class Ws extends te{}class ze extends Ws{}class Zs extends Ws{}class Or extends te{}class Ss extends Or{}class Xs extends Or{}class Ot extends te{}class or extends Ot{}class fr extends Ot{async _call(x){return new Ys(await super._call(x))}}class fs extends Ot{async _call(x){return new Zt(await super._call(x))}}class $s extends Ot{async _call(x){return new Ds(await super._call(x))}}class Mt extends Ot{async _call(x){return new er(await super._call(x))}}class Xt extends te{}class zs extends Xt{}class As extends Xt{async _call(x){return new Ys(await super._call(x))}}class Gs extends Xt{async _call(x){return new Zt(await super._call(x))}}class St extends Xt{async _call(x){return new Ds(await super._call(x))}}class rn extends Xt{async _call(x){return new er(await super._call(x))}}class Qe extends te{}class At extends Qe{}class Na extends Qe{async _call(x){return new Ys(await super._call(x))}}class Go extends Qe{async _call(x){return new Zt(await super._call(x))}}class ja extends Qe{async _call(x){return new Ds(await super._call(x))}}class Ua extends Qe{async _call(x){return new er(await super._call(x))}}class Jt extends te{}class Va extends Jt{}class Ko extends Jt{}class Ho extends te{constructor(){super(...arguments);_e(this,"requires_attention_mask",!1);_e(this,"main_input_name","input_features");_e(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Wa extends Ho{}class Ga extends Ho{_prepare_generation_config(x,j){return super._prepare_generation_config(x,j,U.WhisperGenerationConfig)}_retrieve_init_tokens(x){const j=[x.decoder_start_token_id];let fe=x.language;const Oe=x.task;if(x.is_multilingual){fe||(console.warn("No language specified - defaulting to English (en)."),fe="en");const Ze=`<|${(0,q.whisper_language_to_code)(fe)}|>`;j.push(x.lang_to_id[Ze]),j.push(x.task_to_id[Oe??"transcribe"])}else if(fe||Oe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!x.return_timestamps&&x.no_timestamps_token_id&&j.at(-1)!==x.no_timestamps_token_id?j.push(x.no_timestamps_token_id):x.return_timestamps&&j.at(-1)===x.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),j.pop()),j.filter(Fe=>Fe!=null)}async generate({inputs:x=null,generation_config:j=null,logits_processor:fe=null,stopping_criteria:Oe=null,...Fe}){j=this._prepare_generation_config(j,Fe);const Ze=Fe.decoder_input_ids??this._retrieve_init_tokens(j);if(j.return_timestamps&&(fe??(fe=new M.LogitsProcessorList),fe.push(new M.WhisperTimeStampLogitsProcessor(j,Ze))),j.begin_suppress_tokens&&(fe??(fe=new M.LogitsProcessorList),fe.push(new M.SuppressTokensAtBeginLogitsProcessor(j.begin_suppress_tokens,Ze.length))),j.return_token_timestamps){if(!j.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.");j.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),j.output_attentions=!0,j.return_dict_in_generate=!0}const rt=await super.generate({inputs:x,generation_config:j,logits_processor:fe,decoder_input_ids:Ze,...Fe});return j.return_token_timestamps&&(rt.token_timestamps=this._extract_token_timestamps(rt,j.alignment_heads,j.num_frames)),rt}_extract_token_timestamps(x,j,fe=null,Oe=.02){if(!x.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");fe==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 Fe=this.config.median_filter_width;Fe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Fe=7);const Ze=x.cross_attentions,rt=Array.from({length:this.config.decoder_layers},(ns,Yt)=>(0,b.cat)(Ze.map(as=>as[Yt]),2)),ft=(0,b.stack)(j.map(([ns,Yt])=>{if(ns>=rt.length)throw new Error(`Layer index ${ns} is out of bounds for cross attentions (length ${rt.length}).`);return fe?rt[ns].slice(null,Yt,null,[0,fe]):rt[ns].slice(null,Yt)})).transpose(1,0,2,3),[bt,Rt]=(0,b.std_mean)(ft,-2,0,!0),Wt=ft.clone();for(let ns=0;nsas[tr+1]-as[tr]),cs=(0,R.mergeArrays)([1],Ts).map(Is=>!!Is),xs=[];for(let Is=0;IsDt.findIndex(Gt=>Gt==Fe)),ft=rt.every(Dt=>Dt===-1),bt=rt.every(Dt=>Dt!==-1);if(!ft&&!bt)throw new Error("Every input should contain either 0 or 1 image token.");if(ft)return{inputs_embeds:x,attention_mask:Oe};const Rt=[],Wt=[];for(let Dt=0;DtArray.from({length:x.dims[0]},Ts=>Array.from({length:x.dims[1]},cs=>1))),es=j?j.tolist():[],ns=fe?fe.tolist():[];let Yt=0,as=0;for(let Ps=0;PsDt[Ps][Bs]==1),xs=Ts.reduce((Es,Bs,Qr)=>(Bs==ft&&Es.push(Qr),Es),[]).map(Es=>Ts[Es+1]),Is=xs.filter(Es=>Es==Ze).length,tr=xs.filter(Es=>Es==rt).length;let Hs=[],Er=0,Cn=Is,Io=tr;for(let Es=0;Esmr>Er&&Yr==Ze),Qr=Ts.findIndex((Yr,mr)=>mr>Er&&Yr==rt),hn=Cn>0&&Bs!==-1?Bs:Ts.length+1,Qn=Io>0&&Qr!==-1?Qr:Ts.length+1;let Lo,Xn,Ia,Oa;hn0?(0,H.max)(Hs.at(-1))[0]+1:0;Hs.push(Array.from({length:3*zo},(Yr,mr)=>Xr+mr%zo));const Da=zo+Xr,kn=Hp*Fa*Yn,Ac=Array.from({length:kn},(Yr,mr)=>Da+Math.floor(mr/(Fa*Yn))),Ic=Array.from({length:kn},(Yr,mr)=>Da+Math.floor(mr/Yn)%Fa),Oc=Array.from({length:kn},(Yr,mr)=>Da+mr%Yn);Hs.push([Ac,Ic,Oc].flat()),Er=Lo+kn}if(Er0?(0,H.max)(Hs.at(-1))[0]+1:0,Bs=Ts.length-Er;Hs.push(Array.from({length:3*Bs},(Qr,hn)=>Es+hn%Bs))}const ur=Hs.reduce((Es,Bs)=>Es+Bs.length,0),br=new Array(ur);let Oo=0;for(let Es=0;Es<3;++Es)for(let Bs=0;BsWt[Yt%Wt.length]),es=Array.from({length:Dt[0]},(ns,Yt)=>(0,H.max)(Wt.subarray(Dt[1]*Yt,Dt[1]*(Yt+1)))[0]+1n+BigInt(Dt[1]));return[new b.Tensor("int64",Gt,[3,...Dt]),new b.Tensor("int64",es,[es.length,1])]}else{const[Wt,Dt]=x.dims,Gt=BigInt64Array.from({length:3*Wt*Dt},(es,ns)=>BigInt(Math.floor(ns%Dt/Wt)));return[new b.Tensor("int64",Gt,[3,...x.dims]),(0,b.zeros)([Wt,1])]}}async encode_image({pixel_values:x,image_grid_thw:j}){return(await we(this.sessions.vision_encoder,{pixel_values:x,grid_thw:j})).image_features}_merge_input_ids_with_image_features(x){return tt({image_token_id:this.config.image_token_id,...x})}prepare_inputs_for_generation(x,j,fe){if(j.attention_mask&&!j.position_ids)if(!j.past_key_values)[j.position_ids,j.rope_deltas]=this.get_rope_index(j.input_ids,j.image_grid_thw,j.video_grid_thw,j.attention_mask);else{j.pixel_values=null;const Oe=BigInt(Object.values(j.past_key_values)[0].dims.at(-2)),Fe=j.rope_deltas.map(Ze=>Oe+Ze);j.position_ids=(0,b.stack)([Fe,Fe,Fe],0)}return j}}class vi extends te{}class Rl extends vi{}class Nl extends vi{}class Ti extends te{}class jl extends Ti{}class Ul extends Ti{}class xi extends te{}class Vl extends xi{}class Wl extends xi{}class Pi extends te{}class Gl extends Pi{}class Kl extends Pi{}class Ei extends te{}class Hl extends Ei{}class ql extends Ei{}class mo extends te{}class Ql extends mo{}class Ci extends mo{async _call(x){return new Zt(await super._call(x))}}class _o extends te{}class Xl extends _o{}class Yl extends _o{async _call(x){return new Zt(await super._call(x))}}class Jl extends te{}class Zl extends Jl{}class ki extends te{}class eu extends ki{}class Si extends ki{async _call(x){return new Zt(await super._call(x))}}class tu extends te{}class su extends tu{}class $i extends te{}class Gc extends $i{}class ru extends $i{async _call(x){return new Zt(await super._call(x))}}class nu extends te{}class Mr extends nu{}class Ai extends te{}class ou extends Ai{}class iu extends Ai{async _call(x){return new Zt(await super._call(x))}}class au extends te{}class lu extends au{async _call(x){return new Sc(await super._call(x))}}class Ii extends te{}class uu extends Ii{}class du extends Ii{async _call(x){return new Zt(await super._call(x))}}class Oi extends te{}class cu extends Oi{}class Kc extends Oi{async _call(x){return new Zt(await super._call(x))}}class Fi extends te{}class pu extends Fi{}class hu extends Fi{}class Di extends te{}class mu extends Di{}class _u extends Di{}class fu extends te{}class on extends fu{}class an extends fu{async _call(x){return new Zt(await super._call(x))}}class Fr extends te{}class Li extends Fr{}class ln extends Fr{async _call(x){return new zi(await super._call(x))}}class Ks extends Fr{async _call(x){return new Bi(await super._call(x))}}class zi extends Ke{constructor({logits:x,pred_boxes:j}){super(),this.logits=x,this.pred_boxes=j}}class Bi extends Ke{constructor({logits:x,pred_boxes:j,pred_masks:fe}){super(),this.logits=x,this.pred_boxes=j,this.pred_masks=fe}}class Ri extends te{}class Hc extends Ri{}class Vn extends Ri{async _call(x){return new Ni(await super._call(x))}}class Ni extends Ke{constructor({logits:x,pred_boxes:j}){super(),this.logits=x,this.pred_boxes=j}}class fo extends te{}class gu extends fo{}class wu extends fo{async _call(x){return new ji(await super._call(x))}}class ji extends zi{}class go extends te{}class yu extends go{}class Ui extends go{async _call(x){return new Zt(await super._call(x))}}class Vi extends te{}class wo extends Vi{}class Wi extends Vi{async _call(x){return new Zt(await super._call(x))}}class Gi extends te{}class Mu extends Gi{}class qc extends Gi{async _call(x){return new Zt(await super._call(x))}}class Ki extends te{}class Hi extends Ki{}class Wn extends Ki{async _call(x){return new Zt(await super._call(x))}}class qi extends te{}class Qi extends qi{}class bu extends qi{}class Xi extends te{}class vu extends Xi{}class Qc extends Xi{}class Tu extends te{}class xu extends Tu{}class Yi extends te{}class Pu extends Yi{}class yo extends Yi{}class Eu extends Yi{}class Mo extends te{}class Ji extends Mo{}class bo extends te{}class Cu extends bo{}class ku extends bo{}class vo extends te{}class Xc extends vo{}class Su extends vo{}class Yc extends te{}class $u extends Yc{}class Zi extends te{}class Au extends Zi{}class ea extends Zi{async _call(x){return new Zt(await super._call(x))}}class ta extends te{}class Iu extends ta{}class sa extends ta{async _call(x){return new Zt(await super._call(x))}}class ra extends te{}class Ou extends ra{}class Jc extends ra{async _call(x){return new Zt(await super._call(x))}}class na extends te{}class Fu extends na{}class Du extends na{async _call(x){return new Zt(await super._call(x))}}class Zc extends te{}class Lu extends Zc{}class oa extends te{}class zu extends oa{}class Bu extends oa{async _call(x){return new Ru(await super._call(x))}}class Ru extends Ke{constructor({logits:x,pred_boxes:j}){super(),this.logits=x,this.pred_boxes=j}}class ep extends te{}class To extends ep{async get_image_embeddings({pixel_values:x}){return await Ie(this,{pixel_values:x})}async forward(x){if((!x.image_embeddings||!x.image_positional_embeddings)&&(x={...x,...await this.get_image_embeddings(x)}),!x.input_labels&&x.input_points){const fe=x.input_points.dims.slice(0,-1),Oe=fe.reduce((Fe,Ze)=>Fe*Ze,1);x.input_labels=new b.Tensor("int64",new BigInt64Array(Oe).fill(1n),fe)}const j={image_embeddings:x.image_embeddings,image_positional_embeddings:x.image_positional_embeddings};return x.input_points&&(j.input_points=x.input_points),x.input_labels&&(j.input_labels=x.input_labels),x.input_boxes&&(j.input_boxes=x.input_boxes),await we(this.sessions.prompt_encoder_mask_decoder,j)}async _call(x){return new Gn(await super._call(x))}}class Gn extends Ke{constructor({iou_scores:x,pred_masks:j}){super(),this.iou_scores=x,this.pred_masks=j}}class xo extends te{}class Nu extends xo{}class ju extends xo{}class ia extends te{}class Uu extends ia{}class aa extends ia{}class qr extends te{}class Vu extends qr{}class Wu extends qr{async _call(x){return new pn(await super._call(x))}}class tp extends qr{async _call(x){return new Zt(await super._call(x))}}class Gu extends qr{async _call(x){return new Ds(await super._call(x))}}class Po extends te{}class Ku extends Po{}class Hu extends Po{async _call(x){return new Ds(await super._call(x))}}class qu extends te{}class sp extends qu{}class Eo extends te{}class Qu extends Eo{}class rp extends Eo{async _call(x){return new pn(await super._call(x))}}class Xu extends Eo{async _call(x){return new Zt(await super._call(x))}}class Kn extends te{}class Yu extends Kn{}class Ju extends Kn{async _call(x){return new pn(await super._call(x))}}class np extends Kn{async _call(x){return new Zt(await super._call(x))}}class Zu extends Kn{async _call(x){return new Ds(await super._call(x))}}class Co extends te{}class ed extends Co{}class op extends Co{async _call(x){return new pn(await super._call(x))}}class td extends Co{async _call(x){return new Zt(await super._call(x))}}class ip extends te{}class sd extends qr{}class rd extends qr{async _call(x){return new pn(await super._call(x))}}class ap extends qr{async _call(x){return new Zt(await super._call(x))}}class En extends te{}class nd extends En{}class od extends En{async _call(x){return new pn(await super._call(x))}}class id extends En{async _call(x){return new Zt(await super._call(x))}}class lp extends En{async _call(x){return new kc(await super._call(x))}}class ad extends En{async _call(x){return new Ds(await super._call(x))}}class ld extends te{}class ud extends ld{}class ko extends te{}class Gp extends ko{}class Pr extends ko{}class Dr extends ko{async generate_speech(x,j,{threshold:fe=.5,minlenratio:Oe=0,maxlenratio:Fe=20,vocoder:Ze=null}={}){const rt={input_ids:x},{encoder_outputs:ft,encoder_attention_mask:bt}=await Ie(this,rt),Rt=ft.dims[1]/this.config.reduction_factor,Wt=Math.floor(Rt*Fe),Dt=Math.floor(Rt*Oe),Gt=this.config.num_mel_bins;let es=[],ns=null,Yt=null,as=0;for(;;){++as;const cs=ce(!!Yt);let xs;Yt?xs=Yt.output_sequence_out:xs=new b.Tensor("float32",new Float32Array(Gt),[1,1,Gt]);let Is={use_cache_branch:cs,output_sequence:xs,encoder_attention_mask:bt,speaker_embeddings:j,encoder_hidden_states:ft};this.addPastKeyValues(Is,ns),Yt=await we(this.sessions.decoder_model_merged,Is),ns=this.getPastKeyValues(Yt,ns);const{prob:tr,spectrum:Hs}=Yt;if(es.push(Hs),as>=Dt&&(Array.from(tr.data).filter(Er=>Er>=fe).length>0||as>=Wt))break}const Ps=(0,b.cat)(es),{waveform:Ts}=await we(Ze.sessions.model,{spectrogram:Ps});return{spectrogram:Ps,waveform:Ts}}}class un extends te{constructor(){super(...arguments);_e(this,"main_input_name","spectrogram")}}class dn extends te{}class dd extends dn{}class la extends te{}class cd extends la{}class pd extends la{}class ua extends te{}class hd extends ua{}class md extends ua{}class da extends te{}class _d extends da{}class fd extends da{}class ca extends te{}class nr extends ca{}class gd extends ca{static async from_pretrained(x,j={}){return super.from_pretrained(x,{...j,model_file_name:j.model_file_name??"text_model"})}}class wd extends ca{static async from_pretrained(x,j={}){return super.from_pretrained(x,{...j,model_file_name:j.model_file_name??"audio_model"})}}class pa extends te{}class ha extends pa{async _call(x){return new $c(await super._call(x))}}class cn extends te{}class up extends cn{}class yd extends cn{}class Md extends cn{}class ma extends te{}class bd extends ma{}class vd extends ma{}class So extends te{}class Td extends So{}class xd extends So{async _call(x){return new Zt(await super._call(x))}}class _a extends te{}class dp extends _a{}class cp extends _a{}class $o extends te{constructor(){super(...arguments);_e(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(j){const[fe,Oe]=j.dims,Fe=this.config.decoder.num_codebooks,Ze=Oe-Fe;let rt=0;for(let Rt=0;Rt0&&Gt<=Ze&&(j.data[rt++]=j.data[Rt])}const ft=Math.floor(fe/Fe),bt=rt/(ft*Fe);return new b.Tensor(j.type,j.data.slice(0,rt),[ft,Fe,bt])}prepare_inputs_for_generation(j,fe,Oe){let Fe=structuredClone(j);for(let rt=0;rt=ft&&(Fe[rt][ft]=BigInt(this.config.decoder.pad_token_id));return Oe.guidance_scale!==null&&Oe.guidance_scale>1&&(Fe=Fe.concat(Fe)),super.prepare_inputs_for_generation(Fe,fe,Oe)}async generate(j){const fe=await super.generate(j),Oe=this._apply_and_filter_by_delay_pattern_mask(fe).unsqueeze_(0),{audio_values:Fe}=await we(this.sessions.encodec_decode,{audio_codes:Oe});return Fe}}class fa extends te{}class pp extends fa{}class ga extends fa{async _call(x){return new Zt(await super._call(x))}}class wa extends te{}class Pd extends wa{}class Ed extends wa{async _call(x){return new Zt(await super._call(x))}}class Cd extends te{}class kd extends Cd{}class Sd extends Cd{async _call(x){return new Zt(await super._call(x))}}class ya extends te{}class hp extends ya{}class $d extends ya{async _call(x){return new Zt(await super._call(x))}}class Ad extends te{}class mp extends Ad{}class Id extends te{}class Od extends Id{constructor(...j){super(...j);_e(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(j){const fe=this._generation_mode??"text";let Oe;if(fe==="text"||!j.past_key_values){const bt=this.sessions.prepare_inputs_embeds,Rt=(0,R.pick)(j,bt.inputNames);Oe=await we(bt,Rt)}else{const bt=this.sessions.gen_img_embeds,Rt=(0,R.pick)({image_ids:j.input_ids},bt.inputNames);Oe=await we(bt,Rt)}const Fe={...j,...Oe},Ze=await Ee(this,Fe),rt=this.sessions[fe==="text"?"lm_head":"gen_head"];if(!rt)throw new Error(`Unable to find "${rt}" generation head`);const ft=await we(rt,(0,R.pick)(Ze,rt.inputNames));return{...Oe,...Ze,...ft}}async generate(j){return this._generation_mode="text",super.generate(j)}async generate_images(j){this._generation_mode="image";const fe=(j.inputs??j[this.main_input_name]).dims[1],Fe=(await super.generate(j)).slice(null,[fe,null]),Ze=this.sessions.image_decode,{decoded_image:rt}=await we(Ze,{generated_tokens:Fe}),ft=rt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),bt=[];for(const Rt of ft){const Wt=I.RawImage.fromTensor(Rt);bt.push(Wt)}return bt}}class Fd extends Ke{constructor({char_logits:x,bpe_logits:j,wp_logits:fe}){super(),this.char_logits=x,this.bpe_logits=j,this.wp_logits=fe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Dd extends te{}class Ld extends Dd{async _call(x){return new Fd(await super._call(x))}}class zd extends te{}class Bd extends zd{}class Rd extends zd{}class Ma extends te{}class Nd extends Ma{}class jd extends Ma{}class ys{static async from_pretrained(x,{progress_callback:j=null,config:fe=null,cache_dir:Oe=null,local_files_only:Fe=!1,revision:Ze="main",model_file_name:rt=null,subfolder:ft="onnx",device:bt=null,dtype:Rt=null,use_external_data_format:Wt=null,session_options:Dt={}}={}){const Gt={progress_callback:j,config:fe,cache_dir:Oe,local_files_only:Fe,revision:Ze,model_file_name:rt,subfolder:ft,device:bt,dtype:Rt,use_external_data_format:Wt,session_options:Dt};if(Gt.config=await f.AutoConfig.from_pretrained(x,Gt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const es of this.MODEL_CLASS_MAPPINGS){const ns=es.get(Gt.config.model_type);if(ns)return await ns[1].from_pretrained(x,Gt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Gt.config.model_type}", attempting to construct from base class.`),await te.from_pretrained(x,Gt);throw Error(`Unsupported model type: ${Gt.config.model_type}`)}}_e(ys,"MODEL_CLASS_MAPPINGS",null),_e(ys,"BASE_IF_FAIL",!1);const _p=new Map([["bert",["BertModel",be]],["modernbert",["ModernBertModel",ut]],["nomic_bert",["NomicBertModel",ie]],["roformer",["RoFormerModel",he]],["electra",["ElectraModel",Ls]],["esm",["EsmModel",oo]],["convbert",["ConvBertModel",vt]],["camembert",["CamembertModel",Nt]],["deberta",["DebertaModel",Rr]],["deberta-v2",["DebertaV2Model",Tt]],["mpnet",["MPNetModel",Mn]],["albert",["AlbertModel",Rn]],["distilbert",["DistilBertModel",ar]],["roberta",["RobertaModel",or]],["xlm",["XLMModel",zs]],["xlm-roberta",["XLMRobertaModel",At]],["clap",["ClapModel",nr]],["clip",["CLIPModel",tl]],["clipseg",["CLIPSegModel",al]],["chinese_clip",["ChineseCLIPModel",gr]],["siglip",["SiglipModel",nl]],["jina_clip",["JinaCLIPModel",uo]],["mobilebert",["MobileBertModel",Dn]],["squeezebert",["SqueezeBertModel",xn]],["wav2vec2",["Wav2Vec2Model",Vu]],["wav2vec2-bert",["Wav2Vec2BertModel",ed]],["unispeech",["UniSpeechModel",Qu]],["unispeech-sat",["UniSpeechSatModel",Yu]],["hubert",["HubertModel",sd]],["wavlm",["WavLMModel",nd]],["audio-spectrogram-transformer",["ASTModel",Va]],["vits",["VitsModel",ha]],["pyannote",["PyAnnoteModel",Ku]],["wespeaker-resnet",["WeSpeakerResNetModel",sp]],["detr",["DetrModel",Li]],["rt_detr",["RTDetrModel",Hc]],["table-transformer",["TableTransformerModel",gu]],["vit",["ViTModel",Ql]],["ijepa",["IJepaModel",Xl]],["pvt",["PvtModel",eu]],["vit_msn",["ViTMSNModel",Gc]],["vit_mae",["ViTMAEModel",su]],["groupvit",["GroupViTModel",Mr]],["fastvit",["FastViTModel",ou]],["mobilevit",["MobileViTModel",uu]],["mobilevitv2",["MobileViTV2Model",cu]],["owlvit",["OwlViTModel",pu]],["owlv2",["Owlv2Model",mu]],["beit",["BeitModel",on]],["deit",["DeiTModel",yu]],["hiera",["HieraModel",wo]],["convnext",["ConvNextModel",Au]],["convnextv2",["ConvNextV2Model",Iu]],["dinov2",["Dinov2Model",Ou]],["dinov2_with_registers",["Dinov2WithRegistersModel",Fu]],["resnet",["ResNetModel",Mu]],["swin",["SwinModel",Hi]],["swin2sr",["Swin2SRModel",Qi]],["donut-swin",["DonutSwinModel",$u]],["yolos",["YolosModel",zu]],["dpt",["DPTModel",vu]],["glpn",["GLPNModel",Xc]],["hifigan",["SpeechT5HifiGan",un]],["efficientnet",["EfficientNetModel",Td]],["decision_transformer",["DecisionTransformerModel",mp]],["patchtst",["PatchTSTForPrediction",Bd]],["patchtsmixer",["PatchTSMixerForPrediction",Nd]],["mobilenet_v1",["MobileNetV1Model",pp]],["mobilenet_v2",["MobileNetV2Model",Pd]],["mobilenet_v3",["MobileNetV3Model",kd]],["mobilenet_v4",["MobileNetV4Model",hp]],["maskformer",["MaskFormerModel",Cu]],["mgp-str",["MgpstrForSceneTextRecognition",Ld]],["style_text_to_speech_2",["StyleTextToSpeech2Model",ud]]]),fp=new Map([["t5",["T5Model",P]],["longt5",["LongT5Model",ve]],["mt5",["MT5Model",ht]],["bart",["BartModel",xt]],["mbart",["MBartModel",Fs]],["marian",["MarianModel",Nu]],["whisper",["WhisperModel",Wa]],["m2m_100",["M2M100Model",Uu]],["blenderbot",["BlenderbotModel",ze]],["blenderbot-small",["BlenderbotSmallModel",Ss]]]),gp=new Map([["bloom",["BloomModel",Vl]],["jais",["JAISModel",cl]],["gpt2",["GPT2Model",ul]],["gptj",["GPTJModel",fl]],["gpt_bigcode",["GPTBigCodeModel",wl]],["gpt_neo",["GPTNeoModel",yr]],["gpt_neox",["GPTNeoXModel",ml]],["codegen",["CodeGenModel",ii]],["llama",["LlamaModel",li]],["exaone",["ExaoneModel",Tl]],["olmo",["OlmoModel",Vc]],["olmo2",["Olmo2Model",Cl]],["mobilellm",["MobileLLMModel",xl]],["granite",["GraniteModel",ds]],["cohere",["CohereModel",Sl]],["gemma",["GemmaModel",Al]],["gemma2",["Gemma2Model",Ol]],["helium",["HeliumModel",po]],["glm",["GlmModel",vl]],["openelm",["OpenELMModel",Dl]],["qwen2",["Qwen2Model",Un]],["phi",["PhiModel",Rl]],["phi3",["Phi3Model",jl]],["mpt",["MptModel",Gl]],["opt",["OPTModel",Hl]],["mistral",["MistralModel",cd]],["starcoder2",["Starcoder2Model",hd]],["falcon",["FalconModel",_d]],["stablelm",["StableLmModel",bd]]]),Ud=new Map([["speecht5",["SpeechT5ForSpeechToText",Pr]],["whisper",["WhisperForConditionalGeneration",Ga]],["moonshine",["MoonshineForConditionalGeneration",Ka]]]),Hn=new Map([["speecht5",["SpeechT5ForTextToSpeech",Dr]]]),ba=new Map([["vits",["VitsModel",ha]],["musicgen",["MusicgenForConditionalGeneration",$o]]]),va=new Map([["bert",["BertForSequenceClassification",We]],["modernbert",["ModernBertForSequenceClassification",lt]],["roformer",["RoFormerForSequenceClassification",Re]],["electra",["ElectraForSequenceClassification",kr]],["esm",["EsmForSequenceClassification",On]],["convbert",["ConvBertForSequenceClassification",$t]],["camembert",["CamembertForSequenceClassification",Sr]],["deberta",["DebertaForSequenceClassification",Nr]],["deberta-v2",["DebertaV2ForSequenceClassification",Vs]],["mpnet",["MPNetForSequenceClassification",bn]],["albert",["AlbertForSequenceClassification",Pn]],["distilbert",["DistilBertForSequenceClassification",Os]],["roberta",["RobertaForSequenceClassification",fs]],["xlm",["XLMForSequenceClassification",Gs]],["xlm-roberta",["XLMRobertaForSequenceClassification",Go]],["bart",["BartForSequenceClassification",_s]],["mbart",["MBartForSequenceClassification",rs]],["mobilebert",["MobileBertForSequenceClassification",Gr]],["squeezebert",["SqueezeBertForSequenceClassification",zn]]]),Ta=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",mt]],["roformer",["RoFormerForTokenClassification",qe]],["electra",["ElectraForTokenClassification",Zr]],["esm",["EsmForTokenClassification",Fn]],["convbert",["ConvBertForTokenClassification",os]],["camembert",["CamembertForTokenClassification",$r]],["deberta",["DebertaForTokenClassification",jr]],["deberta-v2",["DebertaV2ForTokenClassification",Ur]],["mpnet",["MPNetForTokenClassification",vn]],["distilbert",["DistilBertForTokenClassification",xr]],["roberta",["RobertaForTokenClassification",$s]],["xlm",["XLMForTokenClassification",St]],["xlm-roberta",["XLMRobertaForTokenClassification",ja]]]),Ao=new Map([["t5",["T5ForConditionalGeneration",Q]],["longt5",["LongT5ForConditionalGeneration",$e]],["mt5",["MT5ForConditionalGeneration",gt]],["bart",["BartForConditionalGeneration",Kt]],["mbart",["MBartForConditionalGeneration",zt]],["marian",["MarianMTModel",ju]],["m2m_100",["M2M100ForConditionalGeneration",aa]],["blenderbot",["BlenderbotForConditionalGeneration",Zs]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Xs]]]),xa=new Map([["bloom",["BloomForCausalLM",Wl]],["gpt2",["GPT2LMHeadModel",dl]],["jais",["JAISLMHeadModel",pl]],["gptj",["GPTJForCausalLM",gl]],["gpt_bigcode",["GPTBigCodeForCausalLM",yl]],["gpt_neo",["GPTNeoForCausalLM",hl]],["gpt_neox",["GPTNeoXForCausalLM",_l]],["codegen",["CodeGenForCausalLM",Ml]],["llama",["LlamaForCausalLM",Uc]],["exaone",["ExaoneForCausalLM",pi]],["olmo",["OlmoForCausalLM",El]],["olmo2",["Olmo2ForCausalLM",Wc]],["mobilellm",["MobileLLMForCausalLM",Pl]],["granite",["GraniteForCausalLM",kl]],["cohere",["CohereForCausalLM",$l]],["gemma",["GemmaForCausalLM",Il]],["gemma2",["Gemma2ForCausalLM",Fl]],["helium",["HeliumForCausalLM",bl]],["glm",["GlmForCausalLM",jn]],["openelm",["OpenELMForCausalLM",Ll]],["qwen2",["Qwen2ForCausalLM",zl]],["phi",["PhiForCausalLM",Nl]],["phi3",["Phi3ForCausalLM",Ul]],["mpt",["MptForCausalLM",Kl]],["opt",["OPTForCausalLM",ql]],["mbart",["MBartForCausalLM",rr]],["mistral",["MistralForCausalLM",pd]],["starcoder2",["Starcoder2ForCausalLM",md]],["falcon",["FalconForCausalLM",fd]],["trocr",["TrOCRForCausalLM",dd]],["stablelm",["StableLmForCausalLM",vd]],["phi3_v",["Phi3VForCausalLM",hr]]]),wp=new Map([["multi_modality",["MultiModalityCausalLM",Od]]]),Pa=new Map([["bert",["BertForMaskedLM",Ve]],["modernbert",["ModernBertForMaskedLM",pt]],["roformer",["RoFormerForMaskedLM",ke]],["electra",["ElectraForMaskedLM",sr]],["esm",["EsmForMaskedLM",In]],["convbert",["ConvBertForMaskedLM",kt]],["camembert",["CamembertForMaskedLM",en]],["deberta",["DebertaForMaskedLM",Ar]],["deberta-v2",["DebertaV2ForMaskedLM",Ft]],["mpnet",["MPNetForMaskedLM",sn]],["albert",["AlbertForMaskedLM",is]],["distilbert",["DistilBertForMaskedLM",yn]],["roberta",["RobertaForMaskedLM",fr]],["xlm",["XLMWithLMHeadModel",As]],["xlm-roberta",["XLMRobertaForMaskedLM",Na]],["mobilebert",["MobileBertForMaskedLM",io]],["squeezebert",["SqueezeBertForMaskedLM",Ln]]]),Ea=new Map([["bert",["BertForQuestionAnswering",je]],["roformer",["RoFormerForQuestionAnswering",at]],["electra",["ElectraForQuestionAnswering",Us]],["convbert",["ConvBertForQuestionAnswering",Ms]],["camembert",["CamembertForQuestionAnswering",tn]],["deberta",["DebertaForQuestionAnswering",ir]],["deberta-v2",["DebertaV2ForQuestionAnswering",Ir]],["mpnet",["MPNetForQuestionAnswering",Tn]],["albert",["AlbertForQuestionAnswering",Nn]],["distilbert",["DistilBertForQuestionAnswering",ss]],["roberta",["RobertaForQuestionAnswering",Mt]],["xlm",["XLMForQuestionAnswering",rn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ua]],["mobilebert",["MobileBertForQuestionAnswering",_r]],["squeezebert",["SqueezeBertForQuestionAnswering",Bn]]]),Ca=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Qo]],["idefics3",["Idefics3ForConditionalGeneration",Xo]]]),yp=new Map([["llava",["LlavaForConditionalGeneration",ao]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Ha]],["moondream1",["Moondream1ForConditionalGeneration",qa]],["florence2",["Florence2ForConditionalGeneration",Xa]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Bl]],["idefics3",["Idefics3ForConditionalGeneration",Xo]],["paligemma",["PaliGemmaForConditionalGeneration",Ja]]]),Vd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Qo]]]),Wd=new Map([["vit",["ViTForImageClassification",Ci]],["ijepa",["IJepaForImageClassification",Yl]],["pvt",["PvtForImageClassification",Si]],["vit_msn",["ViTMSNForImageClassification",ru]],["fastvit",["FastViTForImageClassification",iu]],["mobilevit",["MobileViTForImageClassification",du]],["mobilevitv2",["MobileViTV2ForImageClassification",Kc]],["beit",["BeitForImageClassification",an]],["deit",["DeiTForImageClassification",Ui]],["hiera",["HieraForImageClassification",Wi]],["convnext",["ConvNextForImageClassification",ea]],["convnextv2",["ConvNextV2ForImageClassification",sa]],["dinov2",["Dinov2ForImageClassification",Jc]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Du]],["resnet",["ResNetForImageClassification",qc]],["swin",["SwinForImageClassification",Wn]],["segformer",["SegformerForImageClassification",yd]],["efficientnet",["EfficientNetForImageClassification",xd]],["mobilenet_v1",["MobileNetV1ForImageClassification",ga]],["mobilenet_v2",["MobileNetV2ForImageClassification",Ed]],["mobilenet_v3",["MobileNetV3ForImageClassification",Sd]],["mobilenet_v4",["MobileNetV4ForImageClassification",$d]]]),Gd=new Map([["detr",["DetrForObjectDetection",ln]],["rt_detr",["RTDetrForObjectDetection",Vn]],["table-transformer",["TableTransformerForObjectDetection",wu]],["yolos",["YolosForObjectDetection",Bu]]]),ka=new Map([["owlvit",["OwlViTForObjectDetection",hu]],["owlv2",["Owlv2ForObjectDetection",_u]],["grounding-dino",["GroundingDinoForObjectDetection",Lu]]]),Kd=new Map([["detr",["DetrForSegmentation",Ks]],["clipseg",["CLIPSegForImageSegmentation",ll]]]),Hd=new Map([["segformer",["SegformerForSemanticSegmentation",Md]],["sapiens",["SapiensForSemanticSegmentation",Pu]]]),qd=new Map([["detr",["DetrForSegmentation",Ks]],["maskformer",["MaskFormerForInstanceSegmentation",ku]]]),Qd=new Map([["sam",["SamModel",To]]]),Mp=new Map([["wav2vec2",["Wav2Vec2ForCTC",Wu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",op]],["unispeech",["UniSpeechForCTC",rp]],["unispeech-sat",["UniSpeechSatForCTC",Ju]],["wavlm",["WavLMForCTC",od]],["hubert",["HubertForCTC",rd]]]),Xd=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",tp]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",td]],["unispeech",["UniSpeechForSequenceClassification",Xu]],["unispeech-sat",["UniSpeechSatForSequenceClassification",np]],["wavlm",["WavLMForSequenceClassification",id]],["hubert",["HubertForSequenceClassification",ap]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ko]]]),Yd=new Map([["wavlm",["WavLMForXVector",lp]]]),Jd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Zu]],["wavlm",["WavLMForAudioFrameClassification",ad]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Gu]],["pyannote",["PyAnnoteForAudioFrameClassification",Hu]]]),Zd=new Map([["vitmatte",["VitMatteForImageMatting",lu]]]),Kp=new Map([["patchtst",["PatchTSTForPrediction",Rd]],["patchtsmixer",["PatchTSMixerForPrediction",jd]]]),ec=new Map([["swin2sr",["Swin2SRForImageSuperResolution",bu]]]),tc=new Map([["dpt",["DPTForDepthEstimation",Qc]],["depth_anything",["DepthAnythingForDepthEstimation",xu]],["glpn",["GLPNForDepthEstimation",Su]],["sapiens",["SapiensForDepthEstimation",yo]],["depth_pro",["DepthProForDepthEstimation",Ji]]]),sc=new Map([["sapiens",["SapiensForNormalEstimation",Eu]]]),bp=new Map([["vitpose",["VitPoseForPoseEstimation",Zl]]]),rc=new Map([["clip",["CLIPVisionModelWithProjection",rl]],["siglip",["SiglipVisionModel",il]],["jina_clip",["JinaCLIPVisionModel",wr]]]),nc=[[_p,A.EncoderOnly],[fp,A.EncoderDecoder],[gp,A.DecoderOnly],[va,A.EncoderOnly],[Ta,A.EncoderOnly],[Ao,A.Seq2Seq],[Ud,A.Seq2Seq],[xa,A.DecoderOnly],[wp,A.MultiModality],[Pa,A.EncoderOnly],[Ea,A.EncoderOnly],[Ca,A.Vision2Seq],[yp,A.ImageTextToText],[Wd,A.EncoderOnly],[Kd,A.EncoderOnly],[qd,A.EncoderOnly],[Hd,A.EncoderOnly],[Zd,A.EncoderOnly],[Kp,A.EncoderOnly],[ec,A.EncoderOnly],[tc,A.EncoderOnly],[sc,A.EncoderOnly],[bp,A.EncoderOnly],[Gd,A.EncoderOnly],[ka,A.EncoderOnly],[Qd,A.MaskGeneration],[Mp,A.EncoderOnly],[Xd,A.EncoderOnly],[Hn,A.Seq2Seq],[ba,A.EncoderOnly],[Yd,A.EncoderOnly],[Jd,A.EncoderOnly],[rc,A.EncoderOnly]];for(const[_,x]of nc)for(const[j,fe]of _.values())S.set(j,x),T.set(fe,j),w.set(j,fe);const vp=[["MusicgenForConditionalGeneration",$o,A.Musicgen],["Phi3VForCausalLM",hr,A.Phi3V],["CLIPTextModelWithProjection",sl,A.EncoderOnly],["SiglipTextModel",ol,A.EncoderOnly],["JinaCLIPTextModel",Jo,A.EncoderOnly],["ClapTextModelWithProjection",gd,A.EncoderOnly],["ClapAudioModelWithProjection",wd,A.EncoderOnly]];for(const[_,x,j]of vp)S.set(_,j),T.set(x,_),w.set(_,x);class Sa extends ys{}_e(Sa,"MODEL_CLASS_MAPPINGS",nc.map(x=>x[0])),_e(Sa,"BASE_IF_FAIL",!0);class Tp extends ys{}_e(Tp,"MODEL_CLASS_MAPPINGS",[va]);class oc extends ys{}_e(oc,"MODEL_CLASS_MAPPINGS",[Ta]);class ic extends ys{}_e(ic,"MODEL_CLASS_MAPPINGS",[Ao]);class ac extends ys{}_e(ac,"MODEL_CLASS_MAPPINGS",[Ud]);class $a extends ys{}_e($a,"MODEL_CLASS_MAPPINGS",[Hn]);class lc extends ys{}_e(lc,"MODEL_CLASS_MAPPINGS",[ba]);class uc extends ys{}_e(uc,"MODEL_CLASS_MAPPINGS",[xa]);class dc extends ys{}_e(dc,"MODEL_CLASS_MAPPINGS",[Pa]);class cc extends ys{}_e(cc,"MODEL_CLASS_MAPPINGS",[Ea]);class pc extends ys{}_e(pc,"MODEL_CLASS_MAPPINGS",[Ca]);class hc extends ys{}_e(hc,"MODEL_CLASS_MAPPINGS",[Wd]);class mc extends ys{}_e(mc,"MODEL_CLASS_MAPPINGS",[Kd]);class _c extends ys{}_e(_c,"MODEL_CLASS_MAPPINGS",[Hd]);class Aa extends ys{}_e(Aa,"MODEL_CLASS_MAPPINGS",[qd]);class fc extends ys{}_e(fc,"MODEL_CLASS_MAPPINGS",[Gd]);class gc extends ys{}_e(gc,"MODEL_CLASS_MAPPINGS",[ka]);class wc extends ys{}_e(wc,"MODEL_CLASS_MAPPINGS",[Qd]);class yc extends ys{}_e(yc,"MODEL_CLASS_MAPPINGS",[Mp]);class Mc extends ys{}_e(Mc,"MODEL_CLASS_MAPPINGS",[Xd]);class bc extends ys{}_e(bc,"MODEL_CLASS_MAPPINGS",[Yd]);class vc extends ys{}_e(vc,"MODEL_CLASS_MAPPINGS",[Jd]);class xp extends ys{}_e(xp,"MODEL_CLASS_MAPPINGS",[Vd]);class Tc extends ys{}_e(Tc,"MODEL_CLASS_MAPPINGS",[Zd]);class xc extends ys{}_e(xc,"MODEL_CLASS_MAPPINGS",[ec]);class Pc extends ys{}_e(Pc,"MODEL_CLASS_MAPPINGS",[tc]);class Pp extends ys{}_e(Pp,"MODEL_CLASS_MAPPINGS",[sc]);class Ec extends ys{}_e(Ec,"MODEL_CLASS_MAPPINGS",[bp]);class Cc extends ys{}_e(Cc,"MODEL_CLASS_MAPPINGS",[rc]);class Ep extends Ke{constructor({logits:x,past_key_values:j,encoder_outputs:fe,decoder_attentions:Oe=null,cross_attentions:Fe=null}){super(),this.logits=x,this.past_key_values=j,this.encoder_outputs=fe,this.decoder_attentions=Oe,this.cross_attentions=Fe}}class Zt extends Ke{constructor({logits:x,...j}){super(),this.logits=x;const fe=Object.values(j);fe.length>0&&(this.attentions=fe)}}class kc extends Ke{constructor({logits:x,embeddings:j}){super(),this.logits=x,this.embeddings=j}}class Ds extends Ke{constructor({logits:x}){super(),this.logits=x}}class Ys extends Ke{constructor({logits:x}){super(),this.logits=x}}class er extends Ke{constructor({start_logits:x,end_logits:j}){super(),this.start_logits=x,this.end_logits=j}}class pn extends Ke{constructor({logits:x}){super(),this.logits=x}}class Cp extends Ke{constructor({logits:x,past_key_values:j}){super(),this.logits=x,this.past_key_values=j}}class Sc extends Ke{constructor({alphas:x}){super(),this.alphas=x}}class $c extends Ke{constructor({waveform:x,spectrogram:j}){super(),this.waveform=x,this.spectrogram=j}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(Le,$,r)=>{r.r($),r.d($,{ASTFeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var F=r("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(R){super(R);const g=this.config.sampling_rate,v=(0,F.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let M=0;M{r.r($),r.d($,{AutoFeatureExtractor:()=>Y});var f=r("./src/utils/constants.js"),F=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var N=r("./src/models/feature_extractors.js");class Y{static async from_pretrained(g,v={}){const M=await(0,F.getModelJSON)(g,f.FEATURE_EXTRACTOR_NAME,!0,v),y=M.feature_extractor_type,b=N[y];if(!b)throw new Error(`Unknown feature_extractor_type: '${y}'. Please report this at ${f.GITHUB_ISSUE_URL}.`);return new b(M)}}},"./src/models/auto/image_processing_auto.js":(Le,$,r)=>{r.r($),r.d($,{AutoImageProcessor:()=>R});var f=r("./src/utils/constants.js"),F=r("./src/utils/hub.js"),N=r("./src/base/image_processors_utils.js"),Y=r("./src/models/image_processors.js");class R{static async from_pretrained(v,M={}){const y=await(0,F.getModelJSON)(v,f.IMAGE_PROCESSOR_NAME,!0,M),b=y.image_processor_type??y.feature_extractor_type;let I=Y[b];return I||(b!==void 0&&console.warn(`Image processor type '${b}' not found, assuming base ImageProcessor. Please report this at ${f.GITHUB_ISSUE_URL}.`),I=N.ImageProcessor),new I(y)}}},"./src/models/auto/processing_auto.js":(Le,$,r)=>{r.r($),r.d($,{AutoProcessor:()=>v});var f=r("./src/utils/constants.js"),F=r("./src/utils/hub.js"),N=r("./src/base/processing_utils.js"),Y=r("./src/models/processors.js"),R=r("./src/models/image_processors.js"),g=r("./src/models/feature_extractors.js");class v{static async from_pretrained(y,b={}){const I=await(0,F.getModelJSON)(y,f.IMAGE_PROCESSOR_NAME,!0,b),{image_processor_type:H,feature_extractor_type:se,processor_class:ne}=I;if(ne&&Y[ne])return Y[ne].from_pretrained(y,b);if(!H&&!se)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const W={};if(H){const q=R[H];if(!q)throw new Error(`Unknown image_processor_type: '${H}'.`);W.image_processor=new q(I)}if(se){const q=R[se];if(q)W.image_processor=new q(I);else{const A=g[se];if(!A)throw new Error(`Unknown feature_extractor_type: '${se}'.`);W.feature_extractor=new A(I)}}const U={};return new N.Processor(U,W)}}},"./src/models/beit/image_processing_beit.js":(Le,$,r)=>{r.r($),r.d($,{BeitFeatureExtractor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(Le,$,r)=>{r.r($),r.d($,{BitImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(Le,$,r)=>{r.r($),r.d($,{ChineseCLIPFeatureExtractor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(Le,$,r)=>{r.r($),r.d($,{ClapFeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var F=r("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(R){super(R),this.mel_filters=(0,F.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,F.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,F.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(R,g,v,M){let y;const b=R.length-g;if(b>0)if(v==="rand_trunc"){const I=Math.floor(Math.random()*(b+1));R=R.subarray(I,I+g),y=await this._extract_fbank_features(R,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${v}" not implemented`);else{if(b<0){let I=new Float64Array(g);if(I.set(R),M==="repeat")for(let H=R.length;H{r.r($),r.d($,{CLIPFeatureExtractor:()=>N,CLIPImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/convnext/image_processing_convnext.js":(Le,$,r)=>{r.r($),r.d($,{ConvNextFeatureExtractor:()=>N,ConvNextImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{constructor(R){super(R),this.crop_pct=this.config.crop_pct??.875}async resize(R){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,b]=this.get_resize_output_image_size(R,{shortest_edge:M});R=await R.resize(y,b,{resample:this.resample}),R=await R.center_crop(g,g)}else R=await R.resize(g,g,{resample:this.resample});return R}}class N extends F{}},"./src/models/deit/image_processing_deit.js":(Le,$,r)=>{r.r($),r.d($,{DeiTFeatureExtractor:()=>N,DeiTImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/detr/image_processing_detr.js":(Le,$,r)=>{r.r($),r.d($,{DetrFeatureExtractor:()=>Y,DetrImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),F=r("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(g){const v=await super._call(g),M=[v.pixel_values.dims[0],64,64],y=(0,F.full)(M,1n);return{...v,pixel_mask:y}}post_process_object_detection(...g){return(0,f.post_process_object_detection)(...g)}post_process_panoptic_segmentation(...g){return(0,f.post_process_panoptic_segmentation)(...g)}post_process_instance_segmentation(...g){return(0,f.post_process_instance_segmentation)(...g)}}class Y extends N{}},"./src/models/donut/image_processing_donut.js":(Le,$,r)=>{r.r($),r.d($,{DonutFeatureExtractor:()=>N,DonutImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{pad_image(R,g,v,M={}){const[y,b,I]=g;let H=this.image_mean;Array.isArray(this.image_mean)||(H=new Array(I).fill(H));let se=this.image_std;Array.isArray(se)||(se=new Array(I).fill(H));const ne=H.map((W,U)=>-W/se[U]);return super.pad_image(R,g,v,{center:!0,constant_values:ne,...M})}}class N extends F{}},"./src/models/dpt/image_processing_dpt.js":(Le,$,r)=>{r.r($),r.d($,{DPTFeatureExtractor:()=>N,DPTImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/efficientnet/image_processing_efficientnet.js":(Le,$,r)=>{r.r($),r.d($,{EfficientNetImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{constructor(Y){super(Y),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(R=>R*R))}}},"./src/models/feature_extractors.js":(Le,$,r)=>{r.r($),r.d($,{ASTFeatureExtractor:()=>f.ASTFeatureExtractor,ClapFeatureExtractor:()=>F.ClapFeatureExtractor,ImageFeatureExtractor:()=>b.ImageProcessor,MoonshineFeatureExtractor:()=>N.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>Y.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>R.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>g.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>v.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>M.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>y.WhisperFeatureExtractor});var f=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),F=r("./src/models/clap/feature_extraction_clap.js"),N=r("./src/models/moonshine/feature_extraction_moonshine.js"),Y=r("./src/models/pyannote/feature_extraction_pyannote.js"),R=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),g=r("./src/models/speecht5/feature_extraction_speecht5.js"),v=r("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),M=r("./src/models/wespeaker/feature_extraction_wespeaker.js"),y=r("./src/models/whisper/feature_extraction_whisper.js"),b=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(Le,$,r)=>{r.r($),r.d($,{Florence2Processor:()=>Y});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class Y extends f.Processor{constructor(g,v){super(g,v);const{tasks_answer_post_processing_type:M,task_prompts_without_inputs:y,task_prompts_with_input:b}=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(b??{})),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,b]of this.task_prompts_with_input)if(M.includes(y)){v.push(b.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 b;switch(y){case"pure_text":b=g;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const I=y==="ocr"?"quad_boxes":"bboxes",H=g.matchAll(this.regexes[I]),se=[],ne=[];for(const[W,U,...q]of H)se.push(U?U.trim():se.at(-1)??""),ne.push(q.map((A,S)=>(Number(A)+.5)/this.size_per_bin*M[S%2]));b={labels:se,[I]:ne};break;default:throw new Error(`Task "${v}" (of type "${y}") not yet implemented.`)}return{[v]:b}}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),b=v?this.tokenizer(v,M):{};return{...y,...b}}}_e(Y,"tokenizer_class",N.AutoTokenizer),_e(Y,"image_processor_class",F.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(Le,$,r)=>{r.r($),r.d($,{GLPNFeatureExtractor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(Le,$,r)=>{r.r($),r.d($,{GroundingDinoImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),F=r("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(R){const g=await super._call(R),v=g.pixel_values.dims,M=(0,F.ones)([v[0],v[2],v[3]]);return{...g,pixel_mask:M}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(Le,$,r)=>{r.r($),r.d($,{GroundingDinoProcessor:()=>g});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),Y=r("./src/base/image_processors_utils.js");function R(v,M){const b=v.dims.at(-1)-1,I=v.tolist();I.fill(!1,0,1),I.fill(!1,b);const H=M.tolist();return I.map((se,ne)=>se?ne:null).filter(se=>se!==null).map(se=>H[se])}class g extends f.Processor{async _call(M,y,b={}){const I=M?await this.image_processor(M,b):{};return{...y?this.tokenizer(y,b):{},...I}}post_process_grounded_object_detection(M,y,{box_threshold:b=.25,text_threshold:I=.25,target_sizes:H=null}={}){const{logits:se,pred_boxes:ne}=M,W=se.dims[0];if(H!==null&&H.length!==W)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const U=se.dims.at(1),q=se.sigmoid(),A=q.max(-1).tolist(),S=ne.tolist().map(T=>T.map(O=>(0,Y.center_to_corners_format)(O))),w=[];for(let T=0;Tre.map((xe,ce)=>xe*O[(ce+1)%2])));const ae=A[T],oe=[],Te=[],we=[];for(let re=0;re{r.r($),r.d($,{Idefics3ImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),F=r("./src/utils/tensor.js");class N extends f.ImageProcessor{constructor(R){super(R),this.do_image_splitting=R.do_image_splitting??!0,this.max_image_size=R.max_image_size}get_resize_for_vision_encoder(R,g){let[v,M]=R.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(R,{do_image_splitting:g=null,return_row_col_info:v=!1}={}){let M;if(!Array.isArray(R))M=[[R]];else{if(R.length===0||!R[0])throw new Error("No images provided.");Array.isArray(R[0])?M=R:M=[R]}let y=[],b=[],I=[];const H=[],se=[];for(const T of M){let O=await Promise.all(T.map(Te=>this.preprocess(Te)));H.push(...O.map(Te=>Te.original_size)),se.push(...O.map(Te=>Te.reshaped_input_size)),O.forEach(Te=>Te.pixel_values.unsqueeze_(0));const{longest_edge:ae}=this.max_image_size;let oe;if(g??this.do_image_splitting){let Te=new Array(O.length),we=new Array(O.length);oe=await Promise.all(O.map(async(re,xe)=>{const ce=this.get_resize_for_vision_encoder(re.pixel_values,ae),Se=await(0,F.interpolate_4d)(re.pixel_values,{size:[ce.height,ce.width]}),{frames:Ie,num_splits_h:Ee,num_splits_w:tt}=await this.split_image(Se,this.max_image_size);return Te[xe]=Ee,we[xe]=tt,(0,F.cat)(Ie,0)})),b.push(Te),I.push(we)}else{const Te=[ae,ae];oe=await Promise.all(O.map(we=>(0,F.interpolate_4d)(we.pixel_values,{size:Te}))),b.push(new Array(O.length).fill(0)),I.push(new Array(O.length).fill(0))}y.push((0,F.cat)(oe,0))}const ne=y.length,[W,U,q,A]=y[0].dims;let S,w;if(ne===1)S=y[0].unsqueeze_(0),w=(0,F.full)([ne,W,q,A],!0);else{const T=Math.max(...y.map(oe=>oe.dims.at(0)));w=(0,F.full)([ne,T,q,A],!0);const O=w.data,ae=T*q*A;for(let oe=0;oev||I>M){H=Math.ceil(b/v),se=Math.ceil(I/M);const ne=Math.ceil(b/H),W=Math.ceil(I/se);for(let A=0;A{r.r($),r.d($,{Idefics3Processor:()=>M});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");var Y=r("./src/utils/core.js");function R(y,b,I,H,se,ne){let W="";for(let U=0;U`+se.repeat(y);W+=` +`}return W+=` +${H}${ne}`+se.repeat(y)+`${H}`,W}function g(y,b,I,H){return`${b}${H}`+I.repeat(y)+`${b}`}function v(y,b,I,H,se,ne){return y===0&&b===0?g(I,H,se,ne):R(I,y,b,H,se,ne)}class M extends f.Processor{constructor(){super(...arguments);_e(this,"fake_image_token","");_e(this,"image_token","");_e(this,"global_img_token","")}async _call(I,H=null,se={}){se.return_row_col_info??(se.return_row_col_info=!0);let ne;H&&(ne=await this.image_processor(H,se)),Array.isArray(I)||(I=[I]);const W=ne.rows??[new Array(I.length).fill(0)],U=ne.cols??[new Array(I.length).fill(0)],q=this.config.image_seq_len,A=[],S=[];for(let T=0;Tv(xe,oe[ce],q,this.fake_image_token,this.image_token,this.global_img_token)),we=O.split(this.image_token);if(we.length===0)throw new Error("The image token should be present in the text.");let re=we[0];for(let xe=0;xe{r.r($),r.d($,{BeitFeatureExtractor:()=>f.BeitFeatureExtractor,BitImageProcessor:()=>F.BitImageProcessor,CLIPFeatureExtractor:()=>Y.CLIPFeatureExtractor,CLIPImageProcessor:()=>Y.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>N.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>R.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>R.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:()=>b.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>I.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>H.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>se.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>W.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>U.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>q.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>A.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>A.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>S.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>S.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>w.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>w.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>T.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>T.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>ae.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>ae.MobileViTImageProcessor,NougatImageProcessor:()=>oe.NougatImageProcessor,OwlViTFeatureExtractor:()=>we.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>we.OwlViTImageProcessor,Owlv2ImageProcessor:()=>Te.Owlv2ImageProcessor,Phi3VImageProcessor:()=>re.Phi3VImageProcessor,PvtImageProcessor:()=>xe.PvtImageProcessor,Qwen2VLImageProcessor:()=>ce.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Se.RTDetrImageProcessor,SamImageProcessor:()=>Ie.SamImageProcessor,SegformerFeatureExtractor:()=>Ee.SegformerFeatureExtractor,SegformerImageProcessor:()=>Ee.SegformerImageProcessor,SiglipImageProcessor:()=>tt.SiglipImageProcessor,Swin2SRImageProcessor:()=>Ge.Swin2SRImageProcessor,VLMImageProcessor:()=>ne.VLMImageProcessor,ViTFeatureExtractor:()=>ye.ViTFeatureExtractor,ViTImageProcessor:()=>ye.ViTImageProcessor,VitMatteImageProcessor:()=>J.VitMatteImageProcessor,VitPoseImageProcessor:()=>de.VitPoseImageProcessor,YolosFeatureExtractor:()=>Ce.YolosFeatureExtractor,YolosImageProcessor:()=>Ce.YolosImageProcessor});var f=r("./src/models/beit/image_processing_beit.js"),F=r("./src/models/bit/image_processing_bit.js"),N=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),Y=r("./src/models/clip/image_processing_clip.js"),R=r("./src/models/convnext/image_processing_convnext.js"),g=r("./src/models/deit/image_processing_deit.js"),v=r("./src/models/detr/image_processing_detr.js"),M=r("./src/models/donut/image_processing_donut.js"),y=r("./src/models/dpt/image_processing_dpt.js"),b=r("./src/models/efficientnet/image_processing_efficientnet.js"),I=r("./src/models/glpn/image_processing_glpn.js"),H=r("./src/models/grounding_dino/image_processing_grounding_dino.js"),se=r("./src/models/idefics3/image_processing_idefics3.js"),ne=r("./src/models/janus/image_processing_janus.js"),W=r("./src/models/jina_clip/image_processing_jina_clip.js"),U=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),q=r("./src/models/mask2former/image_processing_mask2former.js"),A=r("./src/models/maskformer/image_processing_maskformer.js"),S=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),w=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),T=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),O=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),ae=r("./src/models/mobilevit/image_processing_mobilevit.js"),oe=r("./src/models/nougat/image_processing_nougat.js"),Te=r("./src/models/owlv2/image_processing_owlv2.js"),we=r("./src/models/owlvit/image_processing_owlvit.js"),re=r("./src/models/phi3_v/image_processing_phi3_v.js"),xe=r("./src/models/pvt/image_processing_pvt.js"),ce=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Se=r("./src/models/rt_detr/image_processing_rt_detr.js"),Ie=r("./src/models/sam/image_processing_sam.js"),Ee=r("./src/models/segformer/image_processing_segformer.js"),tt=r("./src/models/siglip/image_processing_siglip.js"),Ge=r("./src/models/swin2sr/image_processing_swin2sr.js"),ye=r("./src/models/vit/image_processing_vit.js"),J=r("./src/models/vitmatte/image_processing_vitmatte.js"),de=r("./src/models/vitpose/image_processing_vitpose.js"),Ce=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(Le,$,r)=>{r.r($),r.d($,{VLMImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{constructor(Y){super({do_pad:!0,pad_size:{width:Y.image_size,height:Y.image_size},...Y}),this.constant_values=this.config.background_color.map(R=>R*this.rescale_factor)}pad_image(Y,R,g,v){return super.pad_image(Y,R,g,{constant_values:this.constant_values,center:!0,...v})}}},"./src/models/janus/processing_janus.js":(Le,$,r)=>{r.r($),r.d($,{VLChatProcessor:()=>v});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),Y=r("./src/utils/core.js"),R=r("./src/utils/tensor.js"),g=r("./src/utils/image.js");class v extends f.Processor{constructor(y,b){super(y,b),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(y,{images:b=null,chat_template:I="default"}={}){b?Array.isArray(b)||(b=[b]):b=await Promise.all(y.filter(oe=>oe.images).flatMap(oe=>oe.images).map(oe=>g.RawImage.read(oe)));const H=this.tokenizer,se=H.apply_chat_template(y,{tokenize:!1,add_generation_prompt:!0,chat_template:I}),ne=oe=>H.encode(oe,{add_special_tokens:!1}),W=se.split(this.image_tag),U=W.length-1;if(b.length!==U)throw new Error(`Number of images provided (${b.length}) does not match number of "${this.image_tag}" image tags (${U})`);const[q,A,S]=H.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=ne(W[0]),T=new Array(w.length).fill(!1);for(let oe=1;oe0){const oe=await this.image_processor(b);return oe.pixel_values.unsqueeze_(0),{...ae,...oe}}return ae}}_e(v,"image_processor_class",F.AutoImageProcessor),_e(v,"tokenizer_class",N.AutoTokenizer),_e(v,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(Le,$,r)=>{r.r($),r.d($,{JinaCLIPImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{constructor(Y){const{resize_mode:R,fill_color:g,interpolation:v,size:M,...y}=Y,b=R==="squash"?{width:M,height:M}:R==="shortest"?{shortest_edge:M}:{longest_edge:M},I=v==="bicubic"?3:2;super({...y,size:b,resample:I,do_center_crop:!0,crop_size:M,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(Le,$,r)=>{r.r($),r.d($,{JinaCLIPProcessor:()=>Y});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class Y extends f.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):{},b=v?await this.image_processor(v,M):{};return{...y,...b}}}_e(Y,"tokenizer_class",N.AutoTokenizer),_e(Y,"image_processor_class",F.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(Le,$,r)=>{r.r($),r.d($,{LlavaOnevisionImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(Le,$,r)=>{r.r($),r.d($,{Mask2FormerImageProcessor:()=>F});var f=r("./src/models/maskformer/image_processing_maskformer.js");class F extends f.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(Le,$,r)=>{r.r($),r.d($,{MaskFormerFeatureExtractor:()=>N,MaskFormerImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{post_process_panoptic_segmentation(...R){return(0,f.post_process_panoptic_segmentation)(...R)}post_process_instance_segmentation(...R){return(0,f.post_process_instance_segmentation)(...R)}}class N extends F{}},"./src/models/mgp_str/processing_mgp_str.js":(Le,$,r)=>{r.r($),r.d($,{MgpstrProcessor:()=>g});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),Y=r("./src/utils/maths.js");const R={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class g extends f.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(M,y){if(!R.hasOwnProperty(y))throw new Error(`Format ${y} is not supported.`);const[b,I]=R[y],H=this[b].bind(this),[se,ne]=M.dims,W=[],U=[],q=M.tolist();for(let S=0;S0?O.reduce((oe,Te)=>oe*Te,1):0;U.push(T),W.push(ae)}return[H(U),W]}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,b]){const[I,H]=this._decode_helper(M,"char"),[se,ne]=this._decode_helper(y,"bpe"),[W,U]=this._decode_helper(b,"wp"),q=[],A=[];for(let S=0;S{r.r($),r.d($,{MobileNetV1FeatureExtractor:()=>N,MobileNetV1ImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(Le,$,r)=>{r.r($),r.d($,{MobileNetV2FeatureExtractor:()=>N,MobileNetV2ImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(Le,$,r)=>{r.r($),r.d($,{MobileNetV3FeatureExtractor:()=>N,MobileNetV3ImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(Le,$,r)=>{r.r($),r.d($,{MobileNetV4FeatureExtractor:()=>N,MobileNetV4ImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/mobilevit/image_processing_mobilevit.js":(Le,$,r)=>{r.r($),r.d($,{MobileViTFeatureExtractor:()=>N,MobileViTImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/moonshine/feature_extraction_moonshine.js":(Le,$,r)=>{r.r($),r.d($,{MoonshineFeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js"),F=r("./src/utils/tensor.js");class N extends f.FeatureExtractor{async _call(R){(0,f.validate_audio_inputs)(R,"MoonshineFeatureExtractor"),R instanceof Float64Array&&(R=new Float32Array(R));const g=[1,R.length];return{input_values:new F.Tensor("float32",R,g)}}}},"./src/models/moonshine/processing_moonshine.js":(Le,$,r)=>{r.r($),r.d($,{MoonshineProcessor:()=>Y});var f=r("./src/models/auto/feature_extraction_auto.js"),F=r("./src/tokenizers.js"),N=r("./src/base/processing_utils.js");class Y extends N.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",F.AutoTokenizer),_e(Y,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(Le,$,r)=>{r.r($),r.d($,{NougatImageProcessor:()=>F});var f=r("./src/models/donut/image_processing_donut.js");class F extends f.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(Le,$,r)=>{r.r($),r.d($,{Owlv2ImageProcessor:()=>F});var f=r("./src/models/owlvit/image_processing_owlvit.js");class F extends f.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(Le,$,r)=>{r.r($),r.d($,{OwlViTFeatureExtractor:()=>N,OwlViTImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{post_process_object_detection(...R){return(0,f.post_process_object_detection)(...R)}}class N extends F{}},"./src/models/owlvit/processing_owlvit.js":(Le,$,r)=>{r.r($),r.d($,{OwlViTProcessor:()=>Y});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class Y extends f.Processor{}_e(Y,"tokenizer_class",N.AutoTokenizer),_e(Y,"image_processor_class",F.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(Le,$,r)=>{r.r($),r.d($,{PaliGemmaProcessor:()=>g});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");const Y="";function R(v,M,y,b,I){return`${b.repeat(y*I)}${M}${v} +`}class g extends f.Processor{async _call(M,y=null,b={}){y||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),y=""),Array.isArray(M)||(M=[M]),Array.isArray(y)||(y=[y]);const I=this.tokenizer.bos_token,H=this.image_processor.config.image_seq_length;let se;y.some(U=>U.includes(Y))?se=y.map(U=>{const q=U.replaceAll(Y,Y.repeat(H)),A=q.lastIndexOf(Y),S=A===-1?0:A+Y.length;return q.slice(0,S)+I+q.slice(S)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),se=y.map(U=>R(U,I,H,Y,M.length)));const ne=this.tokenizer(se,b);return{...await this.image_processor(M,b),...ne}}}_e(g,"tokenizer_class",N.AutoTokenizer),_e(g,"image_processor_class",F.AutoImageProcessor),_e(g,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(Le,$,r)=>{r.r($),r.d($,{Phi3VImageProcessor:()=>M});var f=r("./src/base/image_processors_utils.js"),F=r("./src/utils/tensor.js");const N=336,Y=[2,3],{ceil:R,floor:g,sqrt:v}=Math;class M extends f.ImageProcessor{constructor(b){super({...b,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=b.num_crops}calc_num_image_tokens_from_image_size(b,I){const{num_img_tokens:H}=this.config;return g((g(I/N)*g(b/N)+1)*H+1+(g(I/N)+1)*v(H))}get_resize_output_image_size(b,I){const H=this._num_crops,[se,ne]=b.size;let W=se/ne,U=1;for(;U*Math.ceil(U/W)<=H;)U+=1;U-=1;const q=Math.floor(U*336),A=Math.floor(q/W);return[q,A]}pad_image(b,I,H,se={}){const[ne,W]=I,U=N*R(ne/N),q=N*R(W/N),A=[1,1,1].map((S,w)=>(S-this.image_mean[w])/this.image_std[w]);return super.pad_image(b,I,{width:q,height:U},{center:!0,constant_values:A,...se})}async _call(b,{num_crops:I=null}={}){if(this._num_crops=I??(I=this.config.num_crops),I<4||v(I)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(b)||(b=[b]);const H=b.length,se=await Promise.all(b.map(T=>this.preprocess(T))),ne=se.map(T=>T.original_size),W=se.map(T=>T.reshaped_input_size),U=[];for(const{pixel_values:T}of se){T.unsqueeze_(0);const[O,ae]=T.dims.slice(-2),oe=await(0,F.interpolate_4d)(T,{size:[N,N],mode:"bicubic"});if(I>0){const Te=[],we=v(I),re=g(ae/we),xe=g(O/we);for(let Se=0;SeT.map(O=>N*R(O/N))),S=new F.Tensor("int64",A.flat(),[H,2]),w=A.map(([T,O])=>this.calc_num_image_tokens_from_image_size(O,T));return{pixel_values:q,original_sizes:ne,reshaped_input_sizes:W,image_sizes:S,num_img_tokens:w}}}},"./src/models/phi3_v/processing_phi3_v.js":(Le,$,r)=>{r.r($),r.d($,{Phi3VProcessor:()=>g});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");const Y="<|image|>",R=/<\|image_\d+\|>/g;class g extends f.Processor{async _call(M,y=null,{padding:b=!0,truncation:I=!0,num_crops:H=null}={}){Array.isArray(M)||(M=[M]);let se,ne;if(y){ne=await this.image_processor(y,{num_crops:H});const{num_img_tokens:W}=ne,U=M.map((A,S)=>A.split(R).join(Y.repeat(W[S])));se=this.tokenizer(U,{padding:b,truncation:I});const q=this.tokenizer.model.convert_tokens_to_ids([Y])[0];se.input_ids.map_(A=>A==q?-A:A)}else se=this.tokenizer(M);return{...se,...ne}}}_e(g,"image_processor_class",F.AutoImageProcessor),_e(g,"tokenizer_class",N.AutoTokenizer)},"./src/models/processors.js":(Le,$,r)=>{r.r($),r.d($,{Florence2Processor:()=>f.Florence2Processor,GroundingDinoProcessor:()=>F.GroundingDinoProcessor,Idefics3Processor:()=>N.Idefics3Processor,JinaCLIPProcessor:()=>R.JinaCLIPProcessor,MgpstrProcessor:()=>g.MgpstrProcessor,MoonshineProcessor:()=>v.MoonshineProcessor,OwlViTProcessor:()=>M.OwlViTProcessor,PaliGemmaProcessor:()=>b.PaliGemmaProcessor,Phi3VProcessor:()=>y.Phi3VProcessor,PyAnnoteProcessor:()=>I.PyAnnoteProcessor,Qwen2VLProcessor:()=>H.Qwen2VLProcessor,SamProcessor:()=>se.SamProcessor,SpeechT5Processor:()=>ne.SpeechT5Processor,VLChatProcessor:()=>Y.VLChatProcessor,Wav2Vec2Processor:()=>W.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>U.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>q.WhisperProcessor});var f=r("./src/models/florence2/processing_florence2.js"),F=r("./src/models/grounding_dino/processing_grounding_dino.js"),N=r("./src/models/idefics3/processing_idefics3.js"),Y=r("./src/models/janus/processing_janus.js"),R=r("./src/models/jina_clip/processing_jina_clip.js"),g=r("./src/models/mgp_str/processing_mgp_str.js"),v=r("./src/models/moonshine/processing_moonshine.js"),M=r("./src/models/owlvit/processing_owlvit.js"),y=r("./src/models/phi3_v/processing_phi3_v.js"),b=r("./src/models/paligemma/processing_paligemma.js"),I=r("./src/models/pyannote/processing_pyannote.js"),H=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),se=r("./src/models/sam/processing_sam.js"),ne=r("./src/models/speecht5/processing_speecht5.js"),W=r("./src/models/wav2vec2/processing_wav2vec2.js"),U=r("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),q=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(Le,$,r)=>{r.r($),r.d($,{PvtImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(Le,$,r)=>{r.r($),r.d($,{PyAnnoteFeatureExtractor:()=>Y});var f=r("./src/base/feature_extraction_utils.js"),F=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");class Y extends f.FeatureExtractor{async _call(g){(0,f.validate_audio_inputs)(g,"PyAnnoteFeatureExtractor"),g instanceof Float64Array&&(g=new Float32Array(g));const v=[1,1,g.length];return{input_values:new F.Tensor("float32",g,v)}}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 b of g.tolist()){const I=[];let H=-1;for(let se=0;se({id:se,start:ne*M,end:W*M,confidence:U/(W-ne)})))}return y}}},"./src/models/pyannote/processing_pyannote.js":(Le,$,r)=>{r.r($),r.d($,{PyAnnoteProcessor:()=>N});var f=r("./src/base/processing_utils.js"),F=r("./src/models/pyannote/feature_extraction_pyannote.js");class N extends f.Processor{async _call(R){return await this.feature_extractor(R)}post_process_speaker_diarization(...R){return this.feature_extractor.post_process_speaker_diarization(...R)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}_e(N,"feature_extractor_class",F.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(Le,$,r)=>{r.r($),r.d($,{Qwen2VLImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),F=r("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(R,...g){const{pixel_values:v,original_sizes:M,reshaped_input_sizes:y}=await super._call(R,...g);let b=v;const{temporal_patch_size:I,merge_size:H,patch_size:se}=this.config;b.dims[0]===1&&(b=(0,F.cat)(Array.from({length:I},()=>b),0));const ne=b.dims[0]/I,W=b.dims[1],U=Math.floor(b.dims[2]/se),q=Math.floor(b.dims[3]/se),A=b.view(ne,I,W,Math.floor(U/H),H,se,Math.floor(q/H),H,se).permute(0,3,6,4,7,2,1,5,8).view(ne*U*q,W*I*se*se),S=new F.Tensor("int64",[ne,U,q],[1,3]);return{pixel_values:A,image_grid_thw:S,original_sizes:M,reshaped_input_sizes:y}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(Le,$,r)=>{r.r($),r.d($,{Qwen2VLProcessor:()=>Y});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");class Y extends f.Processor{async _call(g,v=null,...M){Array.isArray(g)||(g=[g]);let y,b;if(v&&(y=await this.image_processor(v),b=y.image_grid_thw),b){let H=this.image_processor.config.merge_size**2,se=0;const ne=b.tolist();g=g.map(W=>{for(;W.includes("<|image_pad|>");){const U=Number(ne[se++].reduce((q,A)=>q*A,1n));W=W.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(U/H)))}return W.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(g),...y}}}_e(Y,"image_processor_class",F.AutoImageProcessor),_e(Y,"tokenizer_class",N.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(Le,$,r)=>{r.r($),r.d($,{RTDetrImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{post_process_object_detection(...Y){return(0,f.post_process_object_detection)(...Y)}}},"./src/models/sam/image_processing_sam.js":(Le,$,r)=>{r.r($),r.d($,{SamImageProcessor:()=>Y});var f=r("./src/base/image_processors_utils.js"),F=r("./src/utils/core.js"),N=r("./src/utils/tensor.js");class Y extends f.ImageProcessor{reshape_input_points(g,v,M,y=!1){g=structuredClone(g);let b=(0,F.calculateDimensions)(g);if(b.length===3)y||(b=[1,...b]),g=[g];else if(b.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let I=0;Iy!==v.dims[b]))throw Error(`The first ${M.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N.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 b=await super._call(g);if(v&&(b.input_points=this.reshape_input_points(v,b.original_sizes,b.reshaped_input_sizes)),M){if(!b.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");b.input_labels=this.add_input_labels(M,b.input_points)}return y&&(b.input_boxes=this.reshape_input_points(y,b.original_sizes,b.reshaped_input_sizes,!0)),b}async post_process_masks(g,v,M,{mask_threshold:y=0,binarize:b=!0,pad_size:I=null}={}){const H=[];I=I??this.pad_size;const se=[I.height,I.width];for(let ne=0;ney&&(S[w]=1);q=new N.Tensor("bool",S,q.dims)}H.push(q)}return H}generate_crop_boxes(g,v,{crop_n_layers:M=0,overlap_ratio:y=.3413333333333333,points_per_crop:b=32,crop_n_points_downscale_factor:I=1}={}){}}},"./src/models/sam/processing_sam.js":(Le,$,r)=>{r.r($),r.d($,{SamProcessor:()=>N});var f=r("./src/base/processing_utils.js"),F=r("./src/models/auto/image_processing_auto.js");class N extends f.Processor{async _call(...R){return await this.image_processor(...R)}post_process_masks(...R){return this.image_processor.post_process_masks(...R)}reshape_input_points(...R){return this.image_processor.reshape_input_points(...R)}}_e(N,"image_processor_class",F.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(Le,$,r)=>{r.r($),r.d($,{SeamlessM4TFeatureExtractor:()=>Y});var f=r("./src/base/feature_extraction_utils.js"),F=r("./src/utils/tensor.js"),N=r("./src/utils/audio.js");class Y extends f.FeatureExtractor{constructor(g){super(g);const v=this.config.sampling_rate,M=(0,N.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,N.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:b=!0}={}){(0,f.validate_audio_inputs)(g,"SeamlessM4TFeatureExtractor");let I=await this._extract_fbank_features(g,this.config.max_length);if(y){const[S,w]=I.dims,T=I.data;for(let O=0;O0){const ae=new Float32Array(w*(S+O));ae.set(T),ae.fill(this.config.padding_value,T.length);const oe=S+O;I=new F.Tensor(I.type,ae,[oe,w]),b&&(H=new F.Tensor("int64",new BigInt64Array(oe),[1,oe]),H.data.fill(1n,0,S))}}const[se,ne]=I.dims,W=this.config.stride;if(se%W!==0)throw new Error(`The number of frames (${se}) must be a multiple of the stride (${W}).`);const q=I.view(1,Math.floor(se/W),ne*W),A={input_features:q};if(b){const S=q.dims[1],w=new BigInt64Array(S);if(H){const T=H.data;for(let O=1,ae=0;O{r.r($),r.d($,{SegformerFeatureExtractor:()=>N,SegformerImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{post_process_semantic_segmentation(...R){return(0,f.post_process_semantic_segmentation)(...R)}}class N extends F{}},"./src/models/siglip/image_processing_siglip.js":(Le,$,r)=>{r.r($),r.d($,{SiglipImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(Le,$,r)=>{r.r($),r.d($,{SpeechT5FeatureExtractor:()=>F});var f=r("./src/base/feature_extraction_utils.js");class F extends f.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(Le,$,r)=>{r.r($),r.d($,{SpeechT5Processor:()=>Y});var f=r("./src/base/processing_utils.js"),F=r("./src/tokenizers.js"),N=r("./src/models/auto/feature_extraction_auto.js");class Y extends f.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",F.AutoTokenizer),_e(Y,"feature_extractor_class",N.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(Le,$,r)=>{r.r($),r.d($,{Swin2SRImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{pad_image(Y,R,g,v={}){const[M,y,b]=R;return super.pad_image(Y,R,{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":(Le,$,r)=>{r.r($),r.d($,{ViTFeatureExtractor:()=>N,ViTImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{}class N extends F{}},"./src/models/vitmatte/image_processing_vitmatte.js":(Le,$,r)=>{r.r($),r.d($,{VitMatteImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),F=r("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(R,g){Array.isArray(R)||(R=[R]),Array.isArray(g)||(g=[g]);const v=await Promise.all(R.map(b=>this.preprocess(b))),M=await Promise.all(g.map(b=>this.preprocess(b,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,F.stack)(v.map((b,I)=>(0,F.cat)([b.pixel_values,M[I].pixel_values],0)),0),original_sizes:v.map(b=>b.original_size),reshaped_input_sizes:v.map(b=>b.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(Le,$,r)=>{r.r($),r.d($,{VitPoseImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{post_process_pose_estimation(Y,R,{threshold:g=null}={}){const v=Y.tolist(),[M,y,b,I]=Y.dims,H=[];for(let se=0;se{r.r($),r.d($,{Wav2Vec2FeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js"),F=r("./src/utils/tensor.js");class N extends f.FeatureExtractor{_zero_mean_unit_var_norm(R){const v=R.reduce((y,b)=>y+b,0)/R.length,M=R.reduce((y,b)=>y+(b-v)**2,0)/R.length;return R.map(y=>(y-v)/Math.sqrt(M+1e-7))}async _call(R){(0,f.validate_audio_inputs)(R,"Wav2Vec2FeatureExtractor"),R instanceof Float64Array&&(R=new Float32Array(R));let g=R;this.config.do_normalize&&(g=this._zero_mean_unit_var_norm(g));const v=[1,g.length];return{input_values:new F.Tensor("float32",g,v),attention_mask:new F.Tensor("int64",new BigInt64Array(g.length).fill(1n),v)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(Le,$,r)=>{r.r($),r.d($,{Wav2Vec2Processor:()=>Y});var f=r("./src/tokenizers.js"),F=r("./src/models/auto/feature_extraction_auto.js"),N=r("./src/base/processing_utils.js");class Y extends N.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",f.AutoTokenizer),_e(Y,"feature_extractor_class",F.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(Le,$,r)=>{r.r($),r.d($,{Wav2Vec2ProcessorWithLM:()=>Y});var f=r("./src/tokenizers.js"),F=r("./src/models/auto/feature_extraction_auto.js"),N=r("./src/base/processing_utils.js");class Y extends N.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",f.AutoTokenizer),_e(Y,"feature_extractor_class",F.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(Le,$,r)=>{r.r($),r.d($,{WeSpeakerFeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var F=r("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(R){super(R);const g=this.config.sampling_rate,v=(0,F.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,F.spectrogram)(R,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(R){(0,f.validate_audio_inputs)(R,"WeSpeakerFeatureExtractor");const g=(await this._extract_fbank_features(R)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const v=g.mean(1).data,M=g.data,[y,b,I]=g.dims;for(let H=0;H{r.r($),r.d($,{WHISPER_LANGUAGE_MAPPING:()=>F,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>N,whisper_language_to_code:()=>Y});const f=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],F=new Map(f),N=new Map([...f.map(([R,g])=>[g,R]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Y(R){R=R.toLowerCase();let g=N.get(R);if(g===void 0)if(F.has(R))g=R;else{const M=R.length===2?F.keys():F.values();throw new Error(`Language "${R}" is not supported. Must be one of: ${JSON.stringify(M)}`)}return g}},"./src/models/whisper/feature_extraction_whisper.js":(Le,$,r)=>{r.r($),r.d($,{WhisperFeatureExtractor:()=>Y});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var F=r("./src/utils/audio.js"),N=r("./src/utils/maths.js");class Y extends f.FeatureExtractor{constructor(g){var v;super(g),(v=this.config).mel_filters??(v.mel_filters=(0,F.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,F.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(g){const v=await(0,F.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,N.max)(M)[0];for(let b=0;bthis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),v=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":(Le,$,r)=>{r.r($),r.d($,{WhisperGenerationConfig:()=>F});var f=r("./src/generation/configuration_utils.js");class F extends f.GenerationConfig{constructor(){super(...arguments);_e(this,"return_timestamps",null);_e(this,"return_token_timestamps",null);_e(this,"num_frames",null);_e(this,"alignment_heads",null);_e(this,"task",null);_e(this,"language",null);_e(this,"no_timestamps_token_id",null);_e(this,"prompt_ids",null);_e(this,"is_multilingual",null);_e(this,"lang_to_id",null);_e(this,"task_to_id",null);_e(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(Le,$,r)=>{r.r($),r.d($,{WhisperProcessor:()=>Y});var f=r("./src/models/auto/feature_extraction_auto.js"),F=r("./src/tokenizers.js"),N=r("./src/base/processing_utils.js");class Y extends N.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",F.AutoTokenizer),_e(Y,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(Le,$,r)=>{r.r($),r.d($,{YolosFeatureExtractor:()=>N,YolosImageProcessor:()=>F});var f=r("./src/base/image_processors_utils.js");class F extends f.ImageProcessor{post_process_object_detection(...R){return(0,f.post_process_object_detection)(...R)}}class N extends F{}},"./src/ops/registry.js":(Le,$,r)=>{r.r($),r.d($,{TensorOpRegistry:()=>g});var f=r("./src/backends/onnx.js"),F=r("./src/utils/tensor.js"),N=r("./src/env.js");const Y=N.apis.IS_BROWSER_ENV||N.apis.IS_WEBWORKER_ENV,R=async(v,M,y)=>{const b=await(0,f.createInferenceSession)(new Uint8Array(v),M);let I=Promise.resolve();return async H=>{const se=(0,f.isONNXProxy)(),ne=Object.fromEntries(Object.entries(H).map(([U,q])=>[U,(se?q.clone():q).ort_tensor])),W=await(I=Y?I.then(()=>b.run(ne)):b.run(ne));return Array.isArray(y)?y.map(U=>new F.Tensor(W[U])):new F.Tensor(W[y])}};class g{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=R([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=R([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=R([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=R([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=R([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=R([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=R([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=R([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}_e(g,"session_options",{})},"./src/pipelines.js":(Le,$,r)=>{r.r($),r.d($,{AudioClassificationPipeline:()=>we,AutomaticSpeechRecognitionPipeline:()=>xe,DepthEstimationPipeline:()=>Ce,DocumentQuestionAnsweringPipeline:()=>ye,FeatureExtractionPipeline:()=>oe,FillMaskPipeline:()=>q,ImageClassificationPipeline:()=>Se,ImageFeatureExtractionPipeline:()=>Te,ImageSegmentationPipeline:()=>Ie,ImageToImagePipeline:()=>de,ImageToTextPipeline:()=>ce,ObjectDetectionPipeline:()=>tt,Pipeline:()=>se,QuestionAnsweringPipeline:()=>U,SummarizationPipeline:()=>S,Text2TextGenerationPipeline:()=>A,TextClassificationPipeline:()=>ne,TextGenerationPipeline:()=>O,TextToAudioPipeline:()=>J,TokenClassificationPipeline:()=>W,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>re,ZeroShotClassificationPipeline:()=>ae,ZeroShotImageClassificationPipeline:()=>Ee,ZeroShotObjectDetectionPipeline:()=>Ge,pipeline:()=>te});var f=r("./src/tokenizers.js"),F=r("./src/models.js"),N=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var Y=r("./src/utils/generic.js"),R=r("./src/utils/core.js"),g=r("./src/utils/maths.js"),v=r("./src/utils/audio.js"),M=r("./src/utils/tensor.js"),y=r("./src/utils/image.js");async function b(Ue){return Array.isArray(Ue)||(Ue=[Ue]),await Promise.all(Ue.map(le=>y.RawImage.read(le)))}async function I(Ue,le){return Array.isArray(Ue)||(Ue=[Ue]),await Promise.all(Ue.map(be=>typeof be=="string"||be instanceof URL?(0,v.read_audio)(be,le):be instanceof Float64Array?new Float32Array(be):be))}function H(Ue,le){le&&(Ue=Ue.map(je=>je|0));const[be,Ve,We,Ne]=Ue;return{xmin:be,ymin:Ve,xmax:We,ymax:Ne}}class se extends Y.Callable{constructor({task:le,model:be,tokenizer:Ve=null,processor:We=null}){super(),this.task=le,this.model=be,this.tokenizer=Ve,this.processor=We}async dispose(){await this.model.dispose()}}class ne extends se{constructor(le){super(le)}async _call(le,{top_k:be=1}={}){const Ve=this.tokenizer(le,{padding:!0,truncation:!0}),We=await this.model(Ve),Ne=this.model.config.problem_type==="multi_label_classification"?ut=>ut.sigmoid():ut=>new M.Tensor("float32",(0,g.softmax)(ut.data),ut.dims),je=this.model.config.id2label,st=[];for(const ut of We.logits){const pt=Ne(ut),lt=await(0,M.topk)(pt,be),mt=lt[0].tolist(),ie=lt[1].tolist().map((G,he)=>({label:je?je[G]:`LABEL_${G}`,score:mt[he]}));be===1?st.push(...ie):st.push(ie)}return Array.isArray(le)||be===1?st:st[0]}}class W extends se{constructor(le){super(le)}async _call(le,{ignore_labels:be=["O"]}={}){const Ve=Array.isArray(le),We=this.tokenizer(Ve?le:[le],{padding:!0,truncation:!0}),je=(await this.model(We)).logits,st=this.model.config.id2label,ut=[];for(let pt=0;ptat==this.tokenizer.sep_token_id);ut[mt].map((at,ct)=>at==1&&(ct===0||ct>ie&&pt.findIndex(vt=>vt==L[ct])===-1));const G=Ne[mt].tolist(),he=je[mt].tolist();for(let at=1;atct==L[at])!==-1)&&(G[at]=-1/0,he[at]=-1/0);const ke=(0,g.softmax)(G).map((at,ct)=>[at,ct]),Re=(0,g.softmax)(he).map((at,ct)=>[at,ct]);ke[0][0]=0,Re[0][0]=0;const qe=(0,R.product)(ke,Re).filter(at=>at[0][1]<=at[1][1]).map(at=>[at[0][1],at[1][1],at[0][0]*at[1][0]]).sort((at,ct)=>ct[2]-at[2]);for(let at=0;atG==this.tokenizer.mask_token_id);if(pt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const lt=We[st][pt],mt=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(lt.data),lt.dims),be),L=mt[0].tolist(),ie=mt[1].tolist();Ne.push(ie.map((G,he)=>{const ke=ut.slice();return ke[pt]=G,{score:L[he],token:Number(G),token_str:this.tokenizer.decode([G]),sequence:this.tokenizer.decode(ke,{skip_special_tokens:!0})}}))}return Array.isArray(le)?Ne:Ne[0]}}class A extends se{constructor(be){super(be);_e(this,"_key","generated_text")}async _call(be,Ve={}){Array.isArray(be)||(be=[be]),this.model.config.prefix&&(be=be.map(pt=>this.model.config.prefix+pt));const We=this.model.config.task_specific_params;We&&We[this.task]&&We[this.task].prefix&&(be=be.map(pt=>We[this.task].prefix+pt));const Ne=this.tokenizer,je={padding:!0,truncation:!0};let st;this instanceof w&&"_build_translation_inputs"in Ne?st=Ne._build_translation_inputs(be,je,Ve):st=Ne(be,je);const ut=await this.model.generate({...st,...Ve});return Ne.batch_decode(ut,{skip_special_tokens:!0}).map(pt=>({[this._key]:pt}))}}class S extends A{constructor(be){super(be);_e(this,"_key","summary_text")}}class w extends A{constructor(be){super(be);_e(this,"_key","translation_text")}}function T(Ue){return Array.isArray(Ue)&&Ue.every(le=>"role"in le&&"content"in le)}class O extends se{constructor(le){super(le)}async _call(le,be={}){let Ve=!1,We=!1,Ne;if(typeof le=="string")Ne=le=[le];else if(Array.isArray(le)&&le.every(ie=>typeof ie=="string"))Ve=!0,Ne=le;else{if(T(le))le=[le];else if(Array.isArray(le)&&le.every(T))Ve=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");We=!0,Ne=le.map(ie=>this.tokenizer.apply_chat_template(ie,{tokenize:!1,add_generation_prompt:!0}))}const je=be.add_special_tokens??!1,st=We?!1:be.return_full_text??!0;this.tokenizer.padding_side="left";const ut=this.tokenizer(Ne,{add_special_tokens:je,padding:!0,truncation:!0}),pt=await this.model.generate({...ut,...be}),lt=this.tokenizer.batch_decode(pt,{skip_special_tokens:!0});let mt;!st&&ut.input_ids.dims.at(-1)>0&&(mt=this.tokenizer.batch_decode(ut.input_ids,{skip_special_tokens:!0}).map(ie=>ie.length));const L=Array.from({length:le.length},ie=>[]);for(let ie=0;ie[be.toLowerCase(),Ve])),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(le,be,{hypothesis_template:Ve="This example is {}.",multi_label:We=!1}={}){const Ne=Array.isArray(le);Ne||(le=[le]),Array.isArray(be)||(be=[be]);const je=be.map(pt=>Ve.replace("{}",pt)),st=We||be.length===1,ut=[];for(const pt of le){const lt=[];for(const ie of je){const G=this.tokenizer(pt,{text_pair:ie,padding:!0,truncation:!0}),he=await this.model(G);st?lt.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):lt.push(he.logits.data[this.entailment_id])}const L=(st?lt.map(ie=>(0,g.softmax)(ie)[1]):(0,g.softmax)(lt)).map((ie,G)=>[ie,G]).sort((ie,G)=>G[0]-ie[0]);ut.push({sequence:pt,labels:L.map(ie=>be[ie[1]]),scores:L.map(ie=>ie[0])})}return Ne?ut:ut[0]}}class oe extends se{constructor(le){super(le)}async _call(le,{pooling:be="none",normalize:Ve=!1,quantize:We=!1,precision:Ne="binary"}={}){const je=this.tokenizer(le,{padding:!0,truncation:!0}),st=await this.model(je);let ut=st.last_hidden_state??st.logits??st.token_embeddings;if(be!=="none")if(be==="mean")ut=(0,M.mean_pooling)(ut,je.attention_mask);else if(be==="cls")ut=ut.slice(null,0);else throw Error(`Pooling method '${be}' not supported.`);return Ve&&(ut=ut.normalize(2,-1)),We&&(ut=(0,M.quantize_embeddings)(ut,Ne)),ut}}class Te extends se{constructor(le){super(le)}async _call(le,{pool:be=null}={}){const Ve=await b(le),{pixel_values:We}=await this.processor(Ve),Ne=await this.model({pixel_values:We});let je;if(be){if(!("pooler_output"in Ne))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");je=Ne.pooler_output}else je=Ne.last_hidden_state??Ne.logits??Ne.image_embeds;return je}}class we extends se{constructor(le){super(le)}async _call(le,{top_k:be=5}={}){const Ve=this.processor.feature_extractor.config.sampling_rate,We=await I(le,Ve),Ne=this.model.config.id2label,je=[];for(const st of We){const ut=await this.processor(st),lt=(await this.model(ut)).logits[0],mt=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(lt.data),lt.dims),be),L=mt[0].tolist(),G=mt[1].tolist().map((he,ke)=>({label:Ne?Ne[he]:`LABEL_${he}`,score:L[ke]}));je.push(G)}return Array.isArray(le)?je:je[0]}}class re extends se{constructor(le){super(le)}async _call(le,be,{hypothesis_template:Ve="This is a sound of {}."}={}){const We=!Array.isArray(le);We&&(le=[le]);const Ne=be.map(lt=>Ve.replace("{}",lt)),je=this.tokenizer(Ne,{padding:!0,truncation:!0}),st=this.processor.feature_extractor.config.sampling_rate,ut=await I(le,st),pt=[];for(const lt of ut){const mt=await this.processor(lt),L=await this.model({...je,...mt}),ie=(0,g.softmax)(L.logits_per_audio.data);pt.push([...ie].map((G,he)=>({score:G,label:be[he]})))}return We?pt[0]:pt}}class xe extends se{constructor(le){super(le)}async _call(le,be={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(le,be);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(le,be);case"moonshine":return this._call_moonshine(le,be);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(le,be){be.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),be.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ve=!Array.isArray(le);Ve&&(le=[le]);const We=this.processor.feature_extractor.config.sampling_rate,Ne=await I(le,We),je=[];for(const st of Ne){const ut=await this.processor(st),lt=(await this.model(ut)).logits[0],mt=[];for(const ie of lt)mt.push((0,g.max)(ie.data)[1]);const L=this.tokenizer.decode(mt);je.push({text:L})}return Ve?je[0]:je}async _call_whisper(le,be){const Ve=be.return_timestamps??!1,We=be.chunk_length_s??0,Ne=be.force_full_sequences??!1;let je=be.stride_length_s??null;const st={...be};Ve==="word"&&(st.return_token_timestamps=!0,st.return_timestamps=!1);const ut=!Array.isArray(le);ut&&(le=[le]);const pt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,lt=this.processor.feature_extractor.config.hop_length,mt=this.processor.feature_extractor.config.sampling_rate,L=await I(le,mt),ie=[];for(const G of L){let he=[];if(We>0){if(je===null)je=We/6;else if(We<=je)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const qe=mt*We,at=mt*je,ct=qe-2*at;let vt=0;for(;;){const kt=vt+qe,$t=G.subarray(vt,kt),os=await this.processor($t),Ms=vt===0,ks=kt>=G.length;if(he.push({stride:[$t.length,Ms?0:at,ks?0:at],input_features:os.input_features,is_last:ks}),ks)break;vt+=ct}}else he=[{stride:[G.length,0,0],input_features:(await this.processor(G)).input_features,is_last:!0}];for(const qe of he){st.num_frames=Math.floor(qe.stride[0]/lt);const at=await this.model.generate({inputs:qe.input_features,...st});Ve==="word"?(qe.tokens=at.sequences.tolist()[0],qe.token_timestamps=at.token_timestamps.tolist()[0].map(ct=>(0,g.round)(ct,2))):qe.tokens=at[0].tolist(),qe.stride=qe.stride.map(ct=>ct/mt)}const[ke,Re]=this.tokenizer._decode_asr(he,{time_precision:pt,return_timestamps:Ve,force_full_sequences:Ne});ie.push({text:ke,...Re})}return ut?ie[0]:ie}async _call_moonshine(le,be){const Ve=!Array.isArray(le);Ve&&(le=[le]);const We=this.processor.feature_extractor.config.sampling_rate,Ne=await I(le,We),je=[];for(const st of Ne){const ut=await this.processor(st),pt=Math.floor(st.length/We)*6,lt=await this.model.generate({max_new_tokens:pt,...be,...ut}),mt=this.processor.batch_decode(lt,{skip_special_tokens:!0})[0];je.push({text:mt})}return Ve?je[0]:je}}class ce extends se{constructor(le){super(le)}async _call(le,be={}){const Ve=Array.isArray(le),We=await b(le),{pixel_values:Ne}=await this.processor(We),je=[];for(const st of Ne){st.dims=[1,...st.dims];const ut=await this.model.generate({inputs:st,...be}),pt=this.tokenizer.batch_decode(ut,{skip_special_tokens:!0}).map(lt=>({generated_text:lt.trim()}));je.push(pt)}return Ve?je:je[0]}}class Se extends se{constructor(le){super(le)}async _call(le,{top_k:be=5}={}){const Ve=await b(le),{pixel_values:We}=await this.processor(Ve),Ne=await this.model({pixel_values:We}),je=this.model.config.id2label,st=[];for(const ut of Ne.logits){const pt=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(ut.data),ut.dims),be),lt=pt[0].tolist(),L=pt[1].tolist().map((ie,G)=>({label:je?je[ie]:`LABEL_${ie}`,score:lt[G]}));st.push(L)}return Array.isArray(le)?st:st[0]}}class Ie extends se{constructor(le){super(le),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(le,{threshold:be=.5,mask_threshold:Ve=.5,overlap_mask_area_threshold:We=.8,label_ids_to_fuse:Ne=null,target_sizes:je=null,subtask:st=null}={}){if(Array.isArray(le)&&le.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const pt=await b(le),lt=pt.map(Re=>[Re.height,Re.width]),{pixel_values:mt,pixel_mask:L}=await this.processor(pt),ie=await this.model({pixel_values:mt,pixel_mask:L});let G=null;if(st!==null)G=this.subtasks_mapping[st];else for(let[Re,qe]of Object.entries(this.subtasks_mapping))if(qe in this.processor.image_processor){G=this.processor.image_processor[qe].bind(this.processor.image_processor),st=Re;break}const he=this.model.config.id2label,ke=[];if(st==="panoptic"||st==="instance"){const Re=G(ie,be,Ve,We,Ne,je??lt)[0],qe=Re.segmentation;for(const at of Re.segments_info){const ct=new Uint8ClampedArray(qe.data.length);for(let kt=0;ktVe.replace("{}",L)),st=this.tokenizer(je,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ut}=await this.processor(Ne),pt=await this.model({...st,pixel_values:ut}),lt=this.model.config.model_type==="siglip"?L=>L.sigmoid().data:L=>(0,g.softmax)(L.data),mt=[];for(const L of pt.logits_per_image){const G=[...lt(L)].map((he,ke)=>({score:he,label:be[ke]}));G.sort((he,ke)=>ke.score-he.score),mt.push(G)}return We?mt:mt[0]}}class tt extends se{constructor(le){super(le)}async _call(le,{threshold:be=.9,percentage:Ve=!1}={}){const We=Array.isArray(le);if(We&&le.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ne=await b(le),je=Ve?null:Ne.map(ie=>[ie.height,ie.width]),{pixel_values:st,pixel_mask:ut}=await this.processor(Ne),pt=await this.model({pixel_values:st,pixel_mask:ut}),lt=this.processor.image_processor.post_process_object_detection(pt,be,je),mt=this.model.config.id2label,L=lt.map(ie=>ie.boxes.map((G,he)=>({score:ie.scores[he],label:mt[ie.classes[he]],box:H(G,!Ve)})));return We?L:L[0]}}class Ge extends se{constructor(le){super(le)}async _call(le,be,{threshold:Ve=.1,top_k:We=null,percentage:Ne=!1}={}){const je=Array.isArray(le),st=await b(le),ut=this.tokenizer(be,{padding:!0,truncation:!0}),pt=await this.processor(st),lt=[];for(let mt=0;mt({score:Re.scores[at],label:Re.labels[at],box:H(qe,!Ne)}))}else{const Re=this.processor.image_processor.post_process_object_detection(he,Ve,ie,!0)[0];ke=Re.boxes.map((qe,at)=>({score:Re.scores[at],label:be[Re.classes[at]],box:H(qe,!Ne)}))}ke.sort((Re,qe)=>qe.score-Re.score),We!==null&&(ke=ke.slice(0,We)),lt.push(ke)}return je?lt:lt[0]}}class ye extends se{constructor(le){super(le)}async _call(le,be,Ve={}){const We=(await b(le))[0],{pixel_values:Ne}=await this.processor(We),je=`${be}`,st=this.tokenizer(je,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ut=await this.model.generate({inputs:Ne,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:st,...Ve}),lt=this.tokenizer.batch_decode(ut)[0].match(/(.*?)<\/s_answer>/);let mt=null;return lt&<.length>=2&&(mt=lt[1].trim()),[{answer:mt}]}}class J extends se{constructor(be){super(be);_e(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=be.vocoder??null}async _call(be,{speaker_embeddings:Ve=null}={}){return this.processor?this._call_text_to_spectrogram(be,{speaker_embeddings:Ve}):this._call_text_to_waveform(be)}async _call_text_to_waveform(be){const Ve=this.tokenizer(be,{padding:!0,truncation:!0}),{waveform:We}=await this.model(Ve),Ne=this.model.config.sampling_rate;return new v.RawAudio(We.data,Ne)}async _call_text_to_spectrogram(be,{speaker_embeddings:Ve}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await F.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ve=="string"||Ve instanceof URL)&&(Ve=new Float32Array(await(await fetch(Ve)).arrayBuffer())),Ve instanceof Float32Array)Ve=new M.Tensor("float32",Ve,[1,Ve.length]);else if(!(Ve instanceof M.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:We}=this.tokenizer(be,{padding:!0,truncation:!0}),{waveform:Ne}=await this.model.generate_speech(We,Ve,{vocoder:this.vocoder}),je=this.processor.feature_extractor.config.sampling_rate;return new v.RawAudio(Ne.data,je)}}class de extends se{constructor(le){super(le)}async _call(le){const be=await b(le),Ve=await this.processor(be),We=await this.model(Ve),Ne=[];for(const je of We.reconstruction){const st=je.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ne.push(y.RawImage.fromTensor(st))}return Ne.length>1?Ne:Ne[0]}}class Ce extends se{constructor(le){super(le)}async _call(le){const be=await b(le),Ve=await this.processor(be),{predicted_depth:We}=await this.model(Ve),Ne=[];for(let je=0;je1?Ne:Ne[0]}}const Be=Object.freeze({"text-classification":{tokenizer:f.AutoTokenizer,pipeline:ne,model:F.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:f.AutoTokenizer,pipeline:W,model:F.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:f.AutoTokenizer,pipeline:U,model:F.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:f.AutoTokenizer,pipeline:q,model:F.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:f.AutoTokenizer,pipeline:S,model:F.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:f.AutoTokenizer,pipeline:w,model:F.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:f.AutoTokenizer,pipeline:A,model:F.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:f.AutoTokenizer,pipeline:O,model:F.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:f.AutoTokenizer,pipeline:ae,model:F.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:we,model:F.AutoModelForAudioClassification,processor:N.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:f.AutoTokenizer,pipeline:re,model:F.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:f.AutoTokenizer,pipeline:xe,model:[F.AutoModelForSpeechSeq2Seq,F.AutoModelForCTC],processor:N.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:f.AutoTokenizer,pipeline:J,model:[F.AutoModelForTextToWaveform,F.AutoModelForTextToSpectrogram],processor:[N.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:f.AutoTokenizer,pipeline:ce,model:F.AutoModelForVision2Seq,processor:N.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Se,model:F.AutoModelForImageClassification,processor:N.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Ie,model:[F.AutoModelForImageSegmentation,F.AutoModelForSemanticSegmentation,F.AutoModelForUniversalSegmentation],processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:f.AutoTokenizer,pipeline:Ee,model:F.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:tt,model:F.AutoModelForObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:f.AutoTokenizer,pipeline:Ge,model:F.AutoModelForZeroShotObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:f.AutoTokenizer,pipeline:ye,model:F.AutoModelForDocumentQuestionAnswering,processor:N.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:de,model:F.AutoModelForImageToImage,processor:N.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ce,model:F.AutoModelForDepthEstimation,processor:N.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:f.AutoTokenizer,pipeline:oe,model:F.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:N.AutoProcessor,pipeline:Te,model:[F.AutoModelForImageFeatureExtraction,F.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Je=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function te(Ue,le=null,{progress_callback:be=null,config:Ve=null,cache_dir:We=null,local_files_only:Ne=!1,revision:je="main",device:st=null,dtype:ut=null,model_file_name:pt=null,session_options:lt={}}={}){Ue=Je[Ue]??Ue;const mt=Be[Ue.split("_",1)[0]];if(!mt)throw Error(`Unsupported pipeline: ${Ue}. Must be one of [${Object.keys(Be)}]`);le||(le=mt.default.model,console.log(`No model specified. Using default model: "${le}".`));const L={progress_callback:be,config:Ve,cache_dir:We,local_files_only:Ne,revision:je,device:st,dtype:ut,model_file_name:pt,session_options:lt},ie=new Map([["tokenizer",mt.tokenizer],["model",mt.model],["processor",mt.processor]]),G=await Ke(ie,le,L);G.task=Ue,(0,R.dispatchCallback)(be,{status:"ready",task:Ue,model:le});const he=mt.pipeline;return new he(G)}async function Ke(Ue,le,be){const Ve=Object.create(null),We=[];for(const[Ne,je]of Ue.entries()){if(!je)continue;let st;Array.isArray(je)?st=new Promise(async(ut,pt)=>{var mt,L;let lt;for(const ie of je){if(ie===null){ut(null);return}try{ut(await ie.from_pretrained(le,be));return}catch(G){if((mt=G.message)!=null&&mt.includes("Unsupported model type"))lt=G;else if((L=G.message)!=null&&L.includes("Could not locate file"))lt=G;else{pt(G);return}}}pt(lt)}):st=je.from_pretrained(le,be),Ve[Ne]=st,We.push(st)}await Promise.all(We);for(const[Ne,je]of Object.entries(Ve))Ve[Ne]=await je;return Ve}},"./src/tokenizers.js":(Le,$,r)=>{r.r($),r.d($,{AlbertTokenizer:()=>Sr,AutoTokenizer:()=>is,BartTokenizer:()=>Ir,BertTokenizer:()=>en,BlenderbotSmallTokenizer:()=>zn,BlenderbotTokenizer:()=>Ln,BloomTokenizer:()=>xr,CLIPTokenizer:()=>vn,CamembertTokenizer:()=>ot,CodeGenTokenizer:()=>bn,CodeLlamaTokenizer:()=>Vr,CohereTokenizer:()=>Pn,ConvBertTokenizer:()=>Nr,DebertaTokenizer:()=>cr,DebertaV2Tokenizer:()=>Rr,DistilBertTokenizer:()=>ir,ElectraTokenizer:()=>Ft,EsmTokenizer:()=>Wr,FalconTokenizer:()=>On,GPT2Tokenizer:()=>Ur,GPTNeoXTokenizer:()=>Fn,GemmaTokenizer:()=>io,Grok1Tokenizer:()=>Gr,HerbertTokenizer:()=>Ar,LlamaTokenizer:()=>yn,M2M100Tokenizer:()=>Mn,MBart50Tokenizer:()=>ar,MBartTokenizer:()=>bs,MPNetTokenizer:()=>In,MarianTokenizer:()=>Lt,MgpstrTokenizer:()=>Nn,MobileBertTokenizer:()=>$r,NllbTokenizer:()=>lr,NougatTokenizer:()=>Kr,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>Dn,RoFormerTokenizer:()=>jr,RobertaTokenizer:()=>Os,SiglipTokenizer:()=>Tn,SpeechT5Tokenizer:()=>Bn,SqueezeBertTokenizer:()=>tn,T5Tokenizer:()=>Vs,TokenizerModel:()=>Te,VitsTokenizer:()=>Rn,Wav2Vec2CTCTokenizer:()=>xn,WhisperTokenizer:()=>sn,XLMRobertaTokenizer:()=>oo,XLMTokenizer:()=>Tt,is_chinese_char:()=>q});var f=r("./src/utils/generic.js"),F=r("./src/utils/core.js"),N=r("./src/utils/hub.js"),Y=r("./src/utils/maths.js"),R=r("./src/utils/tensor.js"),g=r("./src/utils/data-structures.js"),v=r("./node_modules/@huggingface/jinja/dist/index.js"),M=r("./src/models/whisper/common_whisper.js");async function y(Pe,P){const Q=await Promise.all([(0,N.getModelJSON)(Pe,"tokenizer.json",!0,P),(0,N.getModelJSON)(Pe,"tokenizer_config.json",!0,P)]);return P.legacy!==null&&(Q[1].legacy=P.legacy),Q}function b(Pe,P){const Q=[];let ue=0;for(const ve of Pe.matchAll(P)){const $e=ve[0];ue0&&Q.push($e),ue=ve.index+$e.length}return ue=19968&&Pe<=40959||Pe>=13312&&Pe<=19903||Pe>=131072&&Pe<=173791||Pe>=173824&&Pe<=177983||Pe>=177984&&Pe<=178207||Pe>=178208&&Pe<=183983||Pe>=63744&&Pe<=64255||Pe>=194560&&Pe<=195103}function A(Pe,P,Q){const ue=[];let ve=0;for(;vethis.tokens_to_ids.get(Q)??this.unk_token_id)}convert_ids_to_tokens(P){return P.map(Q=>this.vocab[Q]??this.unk_token)}}class we extends Te{constructor(P){super(P),this.tokens_to_ids=H(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.max_input_chars_per_word=P.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ue]of this.tokens_to_ids)this.vocab[ue]=Q}encode(P){const Q=[];for(const ue of P){const ve=[...ue];if(ve.length>this.max_input_chars_per_word){Q.push(this.unk_token);continue}let $e=!1,Xe=0;const ht=[];for(;Xe0&&(xt=this.config.continuing_subword_prefix+xt),this.tokens_to_ids.has(xt)){_t=xt;break}--gt}if(_t===null){$e=!0;break}ht.push(_t),Xe=gt}$e?Q.push(this.unk_token):Q.push(...ht)}return Q}}class re extends Te{constructor(P,Q){super(P);const ue=P.vocab.length;this.vocab=new Array(ue),this.scores=new Array(ue);for(let ve=0;ve[ve,$e])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Q.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,Y.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(P){const Q=P.chars,ue=1;let ve=0;for(;ve{const Pe=[...Array.from({length:94},(ve,$e)=>$e+33),...Array.from({length:12},(ve,$e)=>$e+161),...Array.from({length:82},(ve,$e)=>$e+174)],P=Pe.slice();let Q=0;for(let ve=0;ve<256;++ve)Pe.includes(ve)||(Pe.push(ve),P.push(256+Q),Q+=1);const ue=P.map(ve=>String.fromCharCode(ve));return Object.fromEntries(Pe.map((ve,$e)=>[ve,ue[$e]]))})(),ce=(0,F.reverseDictionary)(xe);class Se extends Te{constructor(P){super(P),this.tokens_to_ids=H(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ue,ve]of this.tokens_to_ids)this.vocab[ve]=ue;const Q=Array.isArray(P.merges[0]);this.merges=Q?P.merges:P.merges.map(ue=>ue.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ue,ve)=>[JSON.stringify(ue),ve])),this.end_of_word_suffix=P.end_of_word_suffix,this.continuing_subword_suffix=P.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(P){if(P.length===0)return[];const Q=this.cache.get(P);if(Q!==void 0)return Q;const ue=Array.from(P);this.end_of_word_suffix&&(ue[ue.length-1]+=this.end_of_word_suffix);let ve=[];if(ue.length>1){const $e=new g.PriorityQueue((gt,_t)=>gt.score<_t.score);let Xe={token:ue[0],bias:0,prev:null,next:null},ht=Xe;for(let gt=1;gt`<0x${ht.toString(16).toUpperCase().padStart(2,"0")}>`);Xe.every(ht=>this.tokens_to_ids.has(ht))?Q.push(...Xe):Q.push(this.unk_token)}else Q.push(this.unk_token)}return Q}}class Ie extends Te{constructor(P,Q){super(P),this.tokens_to_ids=H(Q.target_lang?P.vocab[Q.target_lang]:P.vocab),this.bos_token=Q.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=Q.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=Q.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[ue,ve]of this.tokens_to_ids)this.vocab[ve]=ue}encode(P){return P}}class Ee extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"BertNormalizer":return new Ke(P);case"Precompiled":return new Ms(P);case"Sequence":return new te(P);case"Replace":return new tt(P);case"NFC":return new Ge(P);case"NFKC":return new ye(P);case"NFKD":return new J(P);case"Strip":return new de(P);case"StripAccents":return new Ce(P);case"Lowercase":return new Be(P);case"Prepend":return new Je(P);default:throw new Error(`Unknown Normalizer type: ${P.type}`)}}normalize(P){throw Error("normalize should be implemented in subclass.")}_call(P){return this.normalize(P)}}class tt extends Ee{normalize(P){const Q=I(this.config.pattern);return Q===null?P:P.replaceAll(Q,this.config.content)}}class Ge extends Ee{normalize(P){return P=P.normalize("NFC"),P}}class ye extends Ee{normalize(P){return P=P.normalize("NFKC"),P}}class J extends Ee{normalize(P){return P=P.normalize("NFKD"),P}}class de extends Ee{normalize(P){return this.config.strip_left&&this.config.strip_right?P=P.trim():(this.config.strip_left&&(P=P.trimStart()),this.config.strip_right&&(P=P.trimEnd())),P}}class Ce extends Ee{normalize(P){return P=W(P),P}}class Be extends Ee{normalize(P){return P=P.toLowerCase(),P}}class Je extends Ee{normalize(P){return P=this.config.prepend+P,P}}class te extends Ee{constructor(P){super(P),this.normalizers=P.normalizers.map(Q=>Ee.fromConfig(Q))}normalize(P){return this.normalizers.reduce((Q,ue)=>ue.normalize(Q),P)}}class Ke extends Ee{_tokenize_chinese_chars(P){const Q=[];for(let ue=0;uethis.pre_tokenize_text(ue,Q)):this.pre_tokenize_text(P,Q)).flat()}_call(P,Q){return this.pre_tokenize(P,Q)}}class le extends Ue{constructor(P){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(P,Q){return P.trim().match(this.pattern)||[]}}class be extends Ue{constructor(P){super(),this.config=P,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=xe,this.text_encoder=new TextEncoder}pre_tokenize_text(P,Q){return this.add_prefix_space&&!P.startsWith(" ")&&(P=" "+P),(this.use_regex?P.match(this.pattern)||[]:[P]).map(ve=>Array.from(this.text_encoder.encode(ve),$e=>this.byte_encoder[$e]).join(""))}}class Ve extends Ue{constructor(P){super(),this.config=P,this.pattern=I(this.config.pattern,this.config.invert)}pre_tokenize_text(P,Q){var ue;return this.pattern===null?[]:this.config.invert?P.match(this.pattern)||[]:((ue=this.config.behavior)==null?void 0:ue.toLowerCase())==="removed"?P.split(this.pattern).filter(ve=>ve):b(P,this.pattern)}}class We extends Ue{constructor(P){super(),this.config=P,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(P,Q){return P.match(this.pattern)||[]}}class Ne extends Ue{constructor(P){super(),this.config=P;const Q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(Q,"gu")}pre_tokenize_text(P,Q){return P.match(this.pattern)||[]}}class je extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"TemplateProcessing":return new pt(P);case"ByteLevel":return new lt(P);case"RobertaProcessing":return new ut(P);case"BertProcessing":return new st(P);case"Sequence":return new mt(P);default:throw new Error(`Unknown PostProcessor type: ${P.type}`)}}post_process(P,...Q){throw Error("post_process should be implemented in subclass.")}_call(P,...Q){return this.post_process(P,...Q)}}class st extends je{constructor(P){super(P),this.cls=P.cls[0],this.sep=P.sep[0]}post_process(P,Q=null,{add_special_tokens:ue=!0}={}){ue&&(P=(0,F.mergeArrays)([this.cls],P,[this.sep]));let ve=new Array(P.length).fill(0);if(Q!==null){const $e=ue&&this instanceof ut?[this.sep]:[],Xe=ue?[this.sep]:[];P=(0,F.mergeArrays)(P,$e,Q,Xe),ve=(0,F.mergeArrays)(ve,new Array(Q.length+$e.length+Xe.length).fill(1))}return{tokens:P,token_type_ids:ve}}}class ut extends st{}class pt extends je{constructor(P){super(P),this.single=P.single,this.pair=P.pair}post_process(P,Q=null,{add_special_tokens:ue=!0}={}){const ve=Q===null?this.single:this.pair;let $e=[],Xe=[];for(const ht of ve)"SpecialToken"in ht?ue&&($e.push(ht.SpecialToken.id),Xe.push(ht.SpecialToken.type_id)):"Sequence"in ht&&(ht.Sequence.id==="A"?($e=(0,F.mergeArrays)($e,P),Xe=(0,F.mergeArrays)(Xe,new Array(P.length).fill(ht.Sequence.type_id))):ht.Sequence.id==="B"&&($e=(0,F.mergeArrays)($e,Q),Xe=(0,F.mergeArrays)(Xe,new Array(Q.length).fill(ht.Sequence.type_id))));return{tokens:$e,token_type_ids:Xe}}}class lt extends je{post_process(P,Q=null){return Q&&(P=(0,F.mergeArrays)(P,Q)),{tokens:P}}}class mt extends je{constructor(P){super(P),this.processors=P.processors.map(Q=>je.fromConfig(Q))}post_process(P,Q=null,ue={}){let ve;for(const $e of this.processors)if($e instanceof lt)P=$e.post_process(P).tokens,Q&&(Q=$e.post_process(Q).tokens);else{const Xe=$e.post_process(P,Q,ue);P=Xe.tokens,ve=Xe.token_type_ids}return{tokens:P,token_type_ids:ve}}}class L extends f.Callable{constructor(P){super(),this.config=P,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=P.trim_offsets}static fromConfig(P){if(P===null)return null;switch(P.type){case"WordPiece":return new Re(P);case"Metaspace":return new os(P);case"ByteLevel":return new qe(P);case"Replace":return new ie(P);case"ByteFallback":return new G(P);case"Fuse":return new he(P);case"Strip":return new ke(P);case"Sequence":return new ct(P);case"CTC":return new at(P);case"BPEDecoder":return new vt(P);default:throw new Error(`Unknown Decoder type: ${P.type}`)}}_call(P){return this.decode(P)}decode(P){return this.decode_chain(P).join("")}decode_chain(P){throw Error("`decode_chain` should be implemented in subclass.")}}class ie extends L{decode_chain(P){const Q=I(this.config.pattern);return Q===null?P:P.map(ue=>ue.replaceAll(Q,this.config.content))}}class G extends L{constructor(P){super(P),this.text_decoder=new TextDecoder}decode_chain(P){const Q=[];let ue=[];for(const ve of P){let $e=null;if(ve.length===6&&ve.startsWith("<0x")&&ve.endsWith(">")){const Xe=parseInt(ve.slice(3,5),16);isNaN(Xe)||($e=Xe)}if($e!==null)ue.push($e);else{if(ue.length>0){const Xe=this.text_decoder.decode(Uint8Array.from(ue));Q.push(Xe),ue=[]}Q.push(ve)}}if(ue.length>0){const ve=this.text_decoder.decode(Uint8Array.from(ue));Q.push(ve),ue=[]}return Q}}class he extends L{decode_chain(P){return[P.join("")]}}class ke extends L{constructor(P){super(P),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(P){return P.map(Q=>{let ue=0;for(let $e=0;$e(ue!==0&&(Q.startsWith(this.config.prefix)?Q=Q.replace(this.config.prefix,""):Q=" "+Q),this.cleanup&&(Q=ne(Q)),Q))}}class qe extends L{constructor(P){super(P),this.byte_decoder=ce,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(P){const Q=P.join(""),ue=new Uint8Array([...Q].map($e=>this.byte_decoder[$e]));return this.text_decoder.decode(ue)}decode_chain(P){const Q=[];let ue=[];for(const ve of P)this.added_tokens.find($e=>$e.content===ve)!==void 0?(ue.length>0&&(Q.push(this.convert_tokens_to_string(ue)),ue=[]),Q.push(ve)):ue.push(ve);return ue.length>0&&Q.push(this.convert_tokens_to_string(ue)),Q}}class at extends L{constructor(P){super(P),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(P){if(P.length===0)return"";const Q=[P[0]];for(let $e=1;$e$e!==this.pad_token).join("");return this.cleanup&&(ve=ne(ve).replaceAll(this.word_delimiter_token," ").trim()),ve}decode_chain(P){return[this.convert_tokens_to_string(P)]}}class ct extends L{constructor(P){super(P),this.decoders=P.decoders.map(Q=>L.fromConfig(Q))}decode_chain(P){return this.decoders.reduce((Q,ue)=>ue.decode_chain(Q),P)}}class vt extends L{constructor(P){super(P),this.suffix=this.config.suffix}decode_chain(P){return P.map((Q,ue)=>Q.replaceAll(this.suffix,ue===P.length-1?"":" "))}}class kt extends L{decode_chain(P){let Q="";for(let ue=1;ueue.normalize("NFKC")).join("~"):P=P.normalize("NFKC"),P}}class ks extends Ue{constructor(P){super(),this.tokenizers=P.pretokenizers.map(Q=>Ue.fromConfig(Q))}pre_tokenize_text(P,Q){return this.tokenizers.reduce((ue,ve)=>ve.pre_tokenize(ue,Q),[P])}}class Ls extends Ue{constructor(P){super()}pre_tokenize_text(P,Q){return P.match(/\w+|[^\w\s]+/g)||[]}}class sr extends Ue{constructor(P){super()}pre_tokenize_text(P,Q){return S(P)}}class kr extends Ue{constructor(P){super(),this.config=P,this.pattern=I(this.config.pattern),this.content=this.config.content}pre_tokenize_text(P,Q){return this.pattern===null?[P]:[P.replaceAll(this.pattern,this.config.content)]}}const Zr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Us(Pe,P,Q,ue){for(const ve of Object.keys(Pe)){const $e=P-Pe[ve].length,Xe=Q(ve),ht=new Array($e).fill(Xe);Pe[ve]=ue==="right"?(0,F.mergeArrays)(Pe[ve],ht):(0,F.mergeArrays)(ht,Pe[ve])}}function Tr(Pe,P){for(const Q of Object.keys(Pe))Pe[Q].length=P}class Nt extends f.Callable{constructor(Q,ue){super();_e(this,"return_token_type_ids",!1);_e(this,"padding_side","right");this._tokenizer_config=ue,this.normalizer=Ee.fromConfig(Q.normalizer),this.pre_tokenizer=Ue.fromConfig(Q.pre_tokenizer),this.model=Te.fromConfig(Q.model,ue),this.post_processor=je.fromConfig(Q.post_processor),this.decoder=L.fromConfig(Q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ve of Q.added_tokens){const $e=new oe(ve);this.added_tokens.push($e),this.model.tokens_to_ids.set($e.content,$e.id),this.model.vocab[$e.id]=$e.content,$e.special&&(this.special_tokens.push($e.content),this.all_special_ids.push($e.id))}if(this.additional_special_tokens=ue.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((ve,$e)=>$e.content.length-ve.content.length).map(ve=>`${ve.lstrip?"\\s*":""}(${(0,F.escapeRegExp)(ve.content)})${ve.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=ue.model_max_length,this.remove_space=ue.remove_space,this.clean_up_tokenization_spaces=ue.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ue.do_lowercase_and_remove_accent??!1,ue.padding_side&&(this.padding_side=ue.padding_side),this.legacy=!1,this.chat_template=ue.chat_template??null,Array.isArray(this.chat_template)){const ve=Object.create(null);for(const{name:$e,template:Xe}of this.chat_template){if(typeof $e!="string"||typeof Xe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ve[$e]=Xe}this.chat_template=ve}this._compiled_template_cache=new Map}getToken(...Q){for(const ue of Q){const ve=this._tokenizer_config[ue];if(ve)if(typeof ve=="object"){if(ve.__type==="AddedToken")return ve.content;throw Error(`Unknown token: ${ve}`)}else return ve}return null}static async from_pretrained(Q,{progress_callback:ue=null,config:ve=null,cache_dir:$e=null,local_files_only:Xe=!1,revision:ht="main",legacy:gt=null}={}){const _t=await y(Q,{progress_callback:ue,config:ve,cache_dir:$e,local_files_only:Xe,revision:ht,legacy:gt});return new this(..._t)}_call(Q,{text_pair:ue=null,add_special_tokens:ve=!0,padding:$e=!1,truncation:Xe=null,max_length:ht=null,return_tensor:gt=!0,return_token_type_ids:_t=null}={}){const xt=Array.isArray(Q);let Kt;if(xt){if(Q.length===0)throw Error("text array must be non-empty");if(ue!==null){if(Array.isArray(ue)){if(Q.length!==ue.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Kt=Q.map((us,Fs)=>this._encode_plus(us,{text_pair:ue[Fs],add_special_tokens:ve,return_token_type_ids:_t}))}else Kt=Q.map(us=>this._encode_plus(us,{add_special_tokens:ve,return_token_type_ids:_t}))}else{if(Q==null)throw Error("text may not be null or undefined");if(Array.isArray(ue))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Kt=[this._encode_plus(Q,{text_pair:ue,add_special_tokens:ve,return_token_type_ids:_t})]}if(ht===null?$e==="max_length"?ht=this.model_max_length:ht=(0,Y.max)(Kt.map(us=>us.input_ids.length))[0]:Xe||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."),ht=Math.min(ht,this.model_max_length??1/0),$e||Xe)for(let us=0;usht?Xe&&Tr(Kt[us],ht):$e&&Us(Kt[us],ht,Fs=>Fs==="input_ids"?this.pad_token_id:0,this.padding_side));const _s={};if(gt){if(!($e&&Xe)&&Kt.some(Fs=>{var zt;for(const rs of Object.keys(Fs))if(Fs[rs].length!==((zt=Kt[0][rs])==null?void 0:zt.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 us=[Kt.length,Kt[0].input_ids.length];for(const Fs of Object.keys(Kt[0]))_s[Fs]=new R.Tensor("int64",BigInt64Array.from(Kt.flatMap(zt=>zt[Fs]).map(BigInt)),us)}else{for(const us of Object.keys(Kt[0]))_s[us]=Kt.map(Fs=>Fs[us]);if(!xt)for(const us of Object.keys(_s))_s[us]=_s[us][0]}return _s}_encode_text(Q){return Q===null?null:(this.added_tokens_regex?Q.split(this.added_tokens_regex).filter($e=>$e):[Q]).map(($e,Xe)=>{if(this.added_tokens.find(gt=>gt.content===$e)!==void 0)return $e;{if(this.remove_space===!0&&($e=$e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&($e=U($e)),this.normalizer!==null&&($e=this.normalizer($e)),$e.length===0)return[];const gt=this.pre_tokenizer!==null?this.pre_tokenizer($e,{section_index:Xe}):[$e];return this.model(gt)}}).flat()}_encode_plus(Q,{text_pair:ue=null,add_special_tokens:ve=!0,return_token_type_ids:$e=null}={}){const{tokens:Xe,token_type_ids:ht}=this._tokenize_helper(Q,{pair:ue,add_special_tokens:ve}),gt=this.model.convert_tokens_to_ids(Xe),_t={input_ids:gt,attention_mask:new Array(gt.length).fill(1)};return($e??this.return_token_type_ids)&&ht&&(_t.token_type_ids=ht),_t}_tokenize_helper(Q,{pair:ue=null,add_special_tokens:ve=!1}={}){const $e=this._encode_text(Q),Xe=this._encode_text(ue);return this.post_processor?this.post_processor($e,Xe,{add_special_tokens:ve}):{tokens:(0,F.mergeArrays)($e??[],Xe??[])}}tokenize(Q,{pair:ue=null,add_special_tokens:ve=!1}={}){return this._tokenize_helper(Q,{pair:ue,add_special_tokens:ve}).tokens}encode(Q,{text_pair:ue=null,add_special_tokens:ve=!0,return_token_type_ids:$e=null}={}){return this._encode_plus(Q,{text_pair:ue,add_special_tokens:ve,return_token_type_ids:$e}).input_ids}batch_decode(Q,ue={}){return Q instanceof R.Tensor&&(Q=Q.tolist()),Q.map(ve=>this.decode(ve,ue))}decode(Q,ue={}){if(Q instanceof R.Tensor&&(Q=se(Q)),!Array.isArray(Q)||Q.length===0||!(0,F.isIntegralNumber)(Q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(Q,ue)}decode_single(Q,{skip_special_tokens:ue=!1,clean_up_tokenization_spaces:ve=null}){let $e=this.model.convert_ids_to_tokens(Q);ue&&($e=$e.filter(ht=>!this.special_tokens.includes(ht)));let Xe=this.decoder?this.decoder($e):$e.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Xe=Xe.replaceAll(this.decoder.end_of_word_suffix," "),ue&&(Xe=Xe.trim())),(ve??this.clean_up_tokenization_spaces)&&(Xe=ne(Xe)),Xe}get_chat_template({chat_template:Q=null,tools:ue=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ve=this.chat_template;if(Q!==null&&Object.hasOwn(ve,Q))Q=ve[Q];else if(Q===null)if(ue!==null&&"tool_use"in ve)Q=ve.tool_use;else if("default"in ve)Q=ve.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(ve).sort()}.`)}else if(Q===null)if(this.chat_template)Q=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 Q}apply_chat_template(Q,{tools:ue=null,documents:ve=null,chat_template:$e=null,add_generation_prompt:Xe=!1,tokenize:ht=!0,padding:gt=!1,truncation:_t=!1,max_length:xt=null,return_tensor:Kt=!0,return_dict:_s=!1,tokenizer_kwargs:us={},...Fs}={}){if($e=this.get_chat_template({chat_template:$e,tools:ue}),typeof $e!="string")throw Error(`chat_template must be a string, but got ${typeof $e}`);let zt=this._compiled_template_cache.get($e);zt===void 0&&(zt=new v.Template($e),this._compiled_template_cache.set($e,zt));const rs=Object.create(null);for(const Ws of Zr){const ze=this.getToken(Ws);ze&&(rs[Ws]=ze)}const rr=zt.render({messages:Q,add_generation_prompt:Xe,tools:ue,documents:ve,...rs,...Fs});if(ht){const Ws=this._call(rr,{add_special_tokens:!1,padding:gt,truncation:_t,max_length:xt,return_tensor:Kt,...us});return _s?Ws:Ws.input_ids}return rr}}class en extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Sr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class $r extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class tn extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class cr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Rr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Ar extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Nr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class jr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class ir extends Nt{}class ot extends Nt{}class Tt extends Nt{constructor(Q,ue){super(Q,ue);_e(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 Ft extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Vs extends Nt{}class Ur extends Nt{}class Ir extends Nt{}class bs extends Nt{constructor(P,Q){super(P,Q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)),this.lang_to_token=ue=>ue}_build_translation_inputs(P,Q,ue){return _r(this,P,Q,ue)}}class ar extends bs{}class Os extends Nt{}class xr extends Nt{}const ss="▁";class yn extends Nt{constructor(Q,ue){super(Q,ue);_e(this,"padding_side","left");this.legacy=ue.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new $t({replacement:ss,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(Q){if(Q===null)return null;if(this.legacy||Q.length===0)return super._encode_text(Q);let ue=super._encode_text(ss+Q.replaceAll(ss," "));return ue.length>1&&ue[0]===ss&&this.special_tokens.includes(ue[1])&&(ue=ue.slice(1)),ue}}class Vr extends Nt{}class oo extends Nt{}class In extends Nt{}class On extends Nt{}class Fn extends Nt{}class Wr extends Nt{}class Dn extends Nt{}class io extends Nt{}class Gr extends Nt{}function _r(Pe,P,Q,ue){if(!("language_codes"in Pe)||!Array.isArray(Pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Pe)||!(Pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Pe)||typeof Pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ve=ue.src_lang,$e=ue.tgt_lang;if(!Pe.language_codes.includes($e))throw new Error(`Target language code "${$e}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);if(ve!==void 0){if(!Pe.language_codes.includes(ve))throw new Error(`Source language code "${ve}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);for(const Xe of Pe.post_processor.config.single)if("SpecialToken"in Xe&&Pe.languageRegex.test(Xe.SpecialToken.id)){Xe.SpecialToken.id=Pe.lang_to_token(ve);break}}return ue.forced_bos_token_id=Pe.model.convert_tokens_to_ids([Pe.lang_to_token($e)])[0],Pe._call(P,Q)}class lr extends Nt{constructor(P,Q){super(P,Q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)),this.lang_to_token=ue=>ue}_build_translation_inputs(P,Q,ue){return _r(this,P,Q,ue)}}class Mn extends Nt{constructor(P,Q){super(P,Q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)).map(ue=>ue.slice(2,-2)),this.lang_to_token=ue=>`__${ue}__`}_build_translation_inputs(P,Q,ue){return _r(this,P,Q,ue)}}class sn extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(P,{return_timestamps:Q=!1,return_language:ue=!1,time_precision:ve=null,force_full_sequences:$e=!0}={}){if(ve===null)throw Error("Must specify time_precision");let Xe=null;const ht=Q==="word";function gt(){return{language:Xe,timestamp:[null,null],text:""}}const _t=[];let xt=gt(),Kt=0;const _s=this.timestamp_begin,Fs=_s+1500;let zt=[],rs=[],rr=!1,Ws=null;const ze=new Set(this.all_special_ids);for(const Ss of P){const Xs=Ss.tokens,Ot=ht?Ss.token_timestamps:null;let or=null,fr=_s;if("stride"in Ss){const[Mt,Xt,zs]=Ss.stride;if(Kt-=Xt,Ws=Mt-zs,Xt&&(fr=Xt/ve+_s),zs)for(let As=Xs.length-1;As>=0;--As){const Gs=Number(Xs[As]);if(Gs>=_s){if(or!==null&&(Gs-_s)*ve=_s&&Xt<=Fs){const zs=(Xt-_s)*ve+Kt,As=(0,Y.round)(zs,2);if(or!==null&&Xt>=or)rr=!0;else if(rr||zt.length>0&&Xt0?(zt.push(fs),ht&&rs.push($s)):zt.every(Mt=>Mt.length===0)&&(xt=gt(),zt=[],fs=[],rs=[],$s=[])}if(zt.length>0){if($e&&Q)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[Ss,Xs]=this.findLongestCommonSequence(zt,rs),Ot=this.decode(Ss);xt.text=Ot,ht&&(xt.words=this.collateWordTimestamps(Ss,Xs,Xe)),_t.push(xt)}let Zs=Object.create(null);const Or=_t.map(Ss=>Ss.text).join("");if(Q||ue){for(let Ss=0;Ss<_t.length;++Ss){const Xs=_t[Ss];Q||delete Xs.timestamp,ue||delete Xs.language}if(ht){const Ss=[];for(const Xs of _t)for(const Ot of Xs.words)Ss.push(Ot);Zs={chunks:Ss}}else Zs={chunks:_t}}return[Or,Zs]}findLongestCommonSequence(P,Q=null){let ue=P[0],ve=ue.length,$e=[];const Xe=Array.isArray(Q)&&Q.length>0;let ht=Xe?[]:null,gt=Xe?Q[0]:null;for(let _t=1;_tXt===fr[zs]&>[Or+zs]<=Q[_t][Ot+zs]).length:fs=Xs.filter((Xt,zs)=>Xt===fr[zs]).length;const $s=Zs/1e4,Mt=fs/Zs+$s;fs>1&&Mt>Kt&&(Kt=Mt,_s=[Or,Ss,Ot,or])}const[Fs,zt,rs,rr]=_s,Ws=Math.floor((zt+Fs)/2),ze=Math.floor((rr+rs)/2);$e.push(...ue.slice(0,Ws)),ue=xt.slice(ze),ve=ue.length,Xe&&(ht.push(...gt.slice(0,Ws)),gt=Q[_t].slice(ze))}return $e.push(...ue),Xe?(ht.push(...gt),[$e,ht]):[$e,[]]}collateWordTimestamps(P,Q,ue){const[ve,$e,Xe]=this.combineTokensIntoWords(P,ue),ht=[];for(let gt=0;gt=ve){const ht=((Xe-ve)*ue).toFixed(2);$e.push(`<|${ht}|>`),$e.push([])}else $e[$e.length-1].push(Xe);return $e=$e.map(Xe=>typeof Xe=="string"?Xe:super.decode(Xe,Q)),$e.join("")}splitTokensOnUnicode(P){const Q=this.decode(P,{decode_with_timestamps:!0}),ue="�",ve=[],$e=[],Xe=[];let ht=[],gt=[],_t=0;for(let xt=0;xt=this.model.tokens_to_ids.get("<|endoftext|>"),Fs=xt.startsWith(" "),zt=xt.trim(),rs=gt.test(zt);if(us||Fs||rs||$e.length===0)$e.push(xt),Xe.push(Kt),ht.push(_s);else{const rr=$e.length-1;$e[rr]+=xt,Xe[rr].push(...Kt),ht[rr].push(..._s)}}return[$e,Xe,ht]}mergePunctuations(P,Q,ue,ve,$e){const Xe=structuredClone(P),ht=structuredClone(Q),gt=structuredClone(ue);let _t=Xe.length-2,xt=Xe.length-1;for(;_t>=0;)Xe[_t].startsWith(" ")&&ve.includes(Xe[_t].trim())?(Xe[xt]=Xe[_t]+Xe[xt],ht[xt]=(0,F.mergeArrays)(ht[_t],ht[xt]),gt[xt]=(0,F.mergeArrays)(gt[_t],gt[xt]),Xe[_t]="",ht[_t]=[],gt[_t]=[]):xt=_t,--_t;for(_t=0,xt=1;xtKt),ht.filter(Kt=>Kt.length>0),gt.filter(Kt=>Kt.length>0)]}}class bn extends Nt{}class vn extends Nt{}class Tn extends Nt{}class Lt extends Nt{constructor(P,Q){super(P,Q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ue=>this.languageRegex.test(ue)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(P){if(P===null)return null;const[Q,...ue]=P.trim().split(this.languageRegex);if(ue.length===0)return super._encode_text(Q);if(ue.length===2){const[ve,$e]=ue;return this.supported_language_codes.includes(ve)||console.warn(`Unsupported language code "${ve}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,F.mergeArrays)([ve],super._encode_text($e))}}}class xn extends Nt{}class Ln extends Nt{}class zn extends Nt{}class Bn extends Nt{}class Kr extends Nt{}class Rn extends Nt{constructor(P,Q){super(P,Q),this.decoder=new kt({})}}class Pn extends Nt{}class Nn extends Nt{}class is{static async from_pretrained(P,{progress_callback:Q=null,config:ue=null,cache_dir:ve=null,local_files_only:$e=!1,revision:Xe="main",legacy:ht=null}={}){var _s;const[gt,_t]=await y(P,{progress_callback:Q,config:ue,cache_dir:ve,local_files_only:$e,revision:Xe,legacy:ht}),xt=((_s=_t.tokenizer_class)==null?void 0:_s.replace(/Fast$/,""))??"PreTrainedTokenizer";let Kt=this.TOKENIZER_CLASS_MAPPING[xt];return Kt||(console.warn(`Unknown tokenizer class "${xt}", attempting to construct from base class.`),Kt=Nt),new Kt(gt,_t)}}_e(is,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Vs,DistilBertTokenizer:ir,CamembertTokenizer:ot,DebertaTokenizer:cr,DebertaV2Tokenizer:Rr,BertTokenizer:en,HerbertTokenizer:Ar,ConvBertTokenizer:Nr,RoFormerTokenizer:jr,XLMTokenizer:Tt,ElectraTokenizer:Ft,MobileBertTokenizer:$r,SqueezeBertTokenizer:tn,AlbertTokenizer:Sr,GPT2Tokenizer:Ur,BartTokenizer:Ir,MBartTokenizer:bs,MBart50Tokenizer:ar,RobertaTokenizer:Os,WhisperTokenizer:sn,CodeGenTokenizer:bn,CLIPTokenizer:vn,SiglipTokenizer:Tn,MarianTokenizer:Lt,BloomTokenizer:xr,NllbTokenizer:lr,M2M100Tokenizer:Mn,LlamaTokenizer:yn,CodeLlamaTokenizer:Vr,XLMRobertaTokenizer:oo,MPNetTokenizer:In,FalconTokenizer:On,GPTNeoXTokenizer:Fn,EsmTokenizer:Wr,Wav2Vec2CTCTokenizer:xn,BlenderbotTokenizer:Ln,BlenderbotSmallTokenizer:zn,SpeechT5Tokenizer:Bn,NougatTokenizer:Kr,VitsTokenizer:Rn,Qwen2Tokenizer:Dn,GemmaTokenizer:io,Grok1Tokenizer:Gr,CohereTokenizer:Pn,MgpstrTokenizer:Nn,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(Le,$,r)=>{r.r($),r.d($,{RawAudio:()=>we,hamming:()=>b,hanning:()=>y,mel_filter_bank:()=>q,read_audio:()=>v,spectrogram:()=>O,window_function:()=>ae});var f=r("./src/utils/hub.js"),F=r("./src/utils/maths.js"),N=r("./src/utils/core.js"),Y=r("./src/env.js"),R=r("?7a2c"),g=r("./src/utils/tensor.js");async function v(re,xe){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 ce=await(await(0,f.getFile)(re)).arrayBuffer(),Se=new AudioContext({sampleRate:xe});typeof xe>"u"&&console.warn(`No sampling rate provided, using default of ${Se.sampleRate}Hz.`);const Ie=await Se.decodeAudioData(ce);let Ee;if(Ie.numberOfChannels===2){const tt=Math.sqrt(2),Ge=Ie.getChannelData(0),ye=Ie.getChannelData(1);Ee=new Float32Array(Ge.length);for(let J=0;J2595*Math.log10(1+re/700),kaldi:re=>1127*Math.log(1+re/700),slaney:(re,xe=1e3,ce=15,Se=27/Math.log(6.4))=>re>=xe?ce+Math.log(re/xe)*Se:3*re/200};function H(re,xe="htk"){const ce=I[xe];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?ce(re):re.map(Se=>ce(Se))}const se={htk:re=>700*(10**(re/2595)-1),kaldi:re=>700*(Math.exp(re/1127)-1),slaney:(re,xe=1e3,ce=15,Se=Math.log(6.4)/27)=>re>=ce?xe*Math.exp(Se*(re-ce)):200*re/3};function ne(re,xe="htk"){const ce=se[xe];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?ce(re):re.map(Se=>ce(Se))}function W(re,xe){const ce=Float64Array.from({length:xe.length-1},(tt,Ge)=>xe[Ge+1]-xe[Ge]),Se=Array.from({length:re.length},()=>new Array(xe.length));for(let tt=0;ttnew Array(re.length));for(let tt=0;ttre+Se*Ee)}function q(re,xe,ce,Se,Ie,Ee=null,tt="htk",Ge=!1){if(Ee!==null&&Ee!=="slaney")throw new Error('norm must be one of null or "slaney"');const ye=H(ce,tt),J=H(Se,tt),de=U(ye,J,xe+2);let Ce=ne(de,tt),Be;if(Ge){const te=Ie/(re*2);Be=H(Float64Array.from({length:re},(Ke,Ue)=>Ue*te),tt),Ce=de}else Be=U(0,Math.floor(Ie/2),re);const Je=W(Be,Ce);if(Ee!==null&&Ee==="slaney")for(let te=0;teIe)throw Error(`frame_length (${ce}) may not be larger than fft_length (${Ie})`);if(Ne!==ce)throw new Error(`Length of the window (${Ne}) must equal frame_length (${ce})`);if(Se<=0)throw new Error("hop_length must be greater than zero");if(Ee===null&&de!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(tt){if(Ge!=="reflect")throw new Error(`pad_mode="${Ge}" not implemented yet.`);const Re=Math.floor((Ie-1)/2)+1;re=A(re,Re,Re)}let je=Math.floor(1+Math.floor((re.length-ce)/Se));le!==null&&jeje?Ve&&(pt=be):pt=ut=be);const lt=new F.FFT(Ie),mt=new Float64Array(Ie),L=new Float64Array(lt.outputBufferSize),ie=new Float32Array(st*pt);for(let Re=0;Re=1;--ct)mt[ct]-=J*mt[ct-1];mt[0]*=1-J}for(let ct=0;ctMath.pow(Ge,.85));break;default:throw new Error(`Unknown window type ${xe}.`)}if(ce&&(tt=tt.subarray(0,re)),Se===null)return tt;if(re>Se)throw new Error(`Length of the window (${re}) may not be larger than frame_length (${Se})`);return tt}function oe(re,xe){let ce=44;const Se=new ArrayBuffer(ce+re.length*4),Ie=new DataView(Se);Te(Ie,0,"RIFF"),Ie.setUint32(4,36+re.length*4,!0),Te(Ie,8,"WAVE"),Te(Ie,12,"fmt "),Ie.setUint32(16,16,!0),Ie.setUint16(20,3,!0),Ie.setUint16(22,1,!0),Ie.setUint32(24,xe,!0),Ie.setUint32(28,xe*4,!0),Ie.setUint16(32,4,!0),Ie.setUint16(34,32,!0),Te(Ie,36,"data"),Ie.setUint32(40,re.length*4,!0);for(let Ee=0;Ee{let Ee=await Ie.arrayBuffer();R.writeFileSync(Se,Buffer.from(Ee))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await ce(xe,this.toBlob())}}},"./src/utils/constants.js":(Le,$,r)=>{r.r($),r.d($,{CHAT_TEMPLATE_NAME:()=>g,CONFIG_NAME:()=>F,FEATURE_EXTRACTOR_NAME:()=>N,GENERATION_CONFIG_NAME:()=>v,GITHUB_ISSUE_URL:()=>f,IMAGE_PROCESSOR_NAME:()=>Y,PROCESSOR_NAME:()=>R});const f="https://github.com/huggingface/transformers.js/issues/new/choose",F="config.json",N="preprocessor_config.json",Y=N,R="processor_config.json",g="chat_template.json",v="generation_config.json"},"./src/utils/core.js":(Le,$,r)=>{r.r($),r.d($,{calculateDimensions:()=>v,calculateReflectOffset:()=>I,count:()=>W,dispatchCallback:()=>f,escapeRegExp:()=>N,isIntegralNumber:()=>R,isNullishDimension:()=>g,isTypedArray:()=>Y,len:()=>ne,mergeArrays:()=>y,pick:()=>se,pop:()=>M,product:()=>b,reverseDictionary:()=>F,saveBlob:()=>H});function f(U,q){U&&U(q)}function F(U){return Object.fromEntries(Object.entries(U).map(([q,A])=>[A,q]))}function N(U){return U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(U){var q,A,S;return((S=(A=(q=U==null?void 0:U.prototype)==null?void 0:q.__proto__)==null?void 0:A.constructor)==null?void 0:S.name)==="TypedArray"}function R(U){return Number.isInteger(U)||typeof U=="bigint"}function g(U){return U==null||U===-1}function v(U){const q=[];let A=U;for(;Array.isArray(A);)q.push(A.length),A=A[0];return q}function M(U,q,A=void 0){const S=U[q];if(S!==void 0)return delete U[q],S;if(A===void 0)throw Error(`Key ${q} does not exist in object.`);return A}function y(...U){return Array.prototype.concat.apply([],U)}function b(...U){return U.reduce((q,A)=>q.flatMap(S=>A.map(w=>[S,w])))}function I(U,q){return Math.abs((U+q)%(2*q)-q)}function H(U,q){const A=URL.createObjectURL(q),S=document.createElement("a");S.href=A,S.download=U,S.click(),S.remove(),URL.revokeObjectURL(A)}function se(U,q){return Object.assign({},...q.map(A=>{if(U[A]!==void 0)return{[A]:U[A]}}))}function ne(U){let q=0;for(const A of U)++q;return q}function W(U,q){let A=0;for(const S of U)S===q&&++A;return A}},"./src/utils/data-structures.js":(Le,$,r)=>{r.r($),r.d($,{CharTrie:()=>F,PriorityQueue:()=>f,TokenLattice:()=>Y});class f{constructor(v=(y,b)=>y>b,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 b=new R(this.bosTokenId,0,0,0,0),I=new R(this.eosTokenId,1,this.len,0,0);this.nodes.push(b.clone()),this.nodes.push(I.clone()),this.beginNodes[this.len].push(I),this.endNodes[0].push(b)}insert(v,M,y,b){const I=this.nodes.length,H=new R(b,I,v,M,y);this.beginNodes[v].push(H),this.endNodes[v+M].push(H),this.nodes.push(H)}viterbi(){const v=this.len;let M=0;for(;M<=v;){if(this.beginNodes[M].length==0)return[];for(let se of this.beginNodes[M]){se.prev=null;let ne=0,W=null;for(let U of this.endNodes[M]){const q=U.backtraceScore+se.score;(W===null||q>ne)&&(W=U.clone(),ne=q)}if(W!==null)se.prev=W,se.backtraceScore=ne;else return[]}++M}const y=[],I=this.beginNodes[v][0].prev;if(I===null)return[];let H=I.clone();for(;H.prev!==null;)y.push(H.clone()),H=H.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 R{constructor(v,M,y,b,I){this.tokenId=v,this.nodeId=M,this.pos=y,this.length=b,this.score=I,this.prev=null,this.backtraceScore=0}clone(){const v=new R(this.tokenId,this.nodeId,this.pos,this.length,this.score);return v.prev=this.prev,v.backtraceScore=this.backtraceScore,v}}},"./src/utils/devices.js":(Le,$,r)=>{r.r($),r.d($,{DEVICE_TYPES:()=>f});const f=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(Le,$,r)=>{r.r($),r.d($,{DATA_TYPES:()=>Y,DEFAULT_DEVICE_DTYPE_MAPPING:()=>R,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>g,isWebGpuFp16Supported:()=>N});var f=r("./src/env.js"),F=r("./src/utils/devices.js");const N=function(){let v;return async function(){if(v===void 0)if(!f.apis.IS_WEBGPU_AVAILABLE)v=!1;else try{v=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{v=!1}return v}}(),Y=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),R=Object.freeze({[F.DEVICE_TYPES.wasm]:Y.q8}),g=Object.freeze({[Y.fp32]:"",[Y.fp16]:"_fp16",[Y.int8]:"_int8",[Y.uint8]:"_uint8",[Y.q8]:"_quantized",[Y.q4]:"_q4",[Y.q4f16]:"_q4f16",[Y.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Le,$,r)=>{r.r($),r.d($,{Callable:()=>f});const f=class{constructor(){let F=function(...N){return F._call(...N)};return Object.setPrototypeOf(F,new.target.prototype)}_call(...F){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Le,$,r)=>{r.r($),r.d($,{getFile:()=>M,getModelFile:()=>se,getModelJSON:()=>ne});var f=r("?7a2c"),F=r("?a42a"),N=r("./src/env.js"),Y=r("./src/utils/core.js");const R={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(A){if(this.filePath=A,this.headers=new Headers,this.exists=f.existsSync(A),this.exists){this.status=200,this.statusText="OK";let S=f.statSync(A);this.headers.set("content-length",S.size.toString()),this.updateContentType();let w=this;this.body=new ReadableStream({start(T){w.arrayBuffer().then(O=>{T.enqueue(new Uint8Array(O)),T.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const A=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",R[A]??"application/octet-stream")}clone(){let A=new g(this.filePath);return A.exists=this.exists,A.status=this.status,A.statusText=this.statusText,A.headers=new Headers(this.headers),A}async arrayBuffer(){return(await f.promises.readFile(this.filePath)).buffer}async blob(){const A=await f.promises.readFile(this.filePath);return new Blob([A],{type:this.headers.get("content-type")})}async text(){return await f.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function v(q,A=null,S=null){let w;try{w=new URL(q)}catch{return!1}return!(A&&!A.includes(w.protocol)||S&&!S.includes(w.hostname))}async function M(q){var A;if(N.env.useFS&&!v(q,["http:","https:","blob:"]))return new g(q);if(typeof process<"u"&&((A=process==null?void 0:process.release)==null?void 0:A.name)==="node"){const S=!!(dr!=null&&dr.TESTING_REMOTELY),w=N.env.version,T=new Headers;if(T.set("User-Agent",`transformers.js/${w}; is_ci/${S};`),v(q,["http:","https:"],["huggingface.co","hf.co"])){const ae=(dr==null?void 0:dr.HF_TOKEN)??(dr==null?void 0:dr.HF_ACCESS_TOKEN);ae&&T.set("Authorization",`Bearer ${ae}`)}return fetch(q,{headers:T})}else return fetch(q)}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 b(q,A,S){if(!S)return null;const w=y[q]??`Error (${q}) occurred while trying to load file`;throw Error(`${w}: "${A}".`)}class I{constructor(A){this.path=A}async match(A){let S=F.join(this.path,A),w=new g(S);if(w.exists)return w}async put(A,S){const w=Buffer.from(await S.arrayBuffer());let T=F.join(this.path,A);try{await f.promises.mkdir(F.dirname(T),{recursive:!0}),await f.promises.writeFile(T,w)}catch(O){console.warn("An error occurred while writing the file to cache:",O)}}}async function H(q,...A){for(let S of A)try{let w=await q.match(S);if(w)return w}catch{continue}}async function se(q,A,S=!0,w={}){if(!N.env.allowLocalModels){if(w.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!N.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,Y.dispatchCallback)(w.progress_callback,{status:"initiate",name:q,file:A});let T;if(!T&&N.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{T=await caches.open("transformers-cache")}catch(tt){console.warn("An error occurred while opening the browser cache:",tt)}}if(!T&&N.env.useFSCache&&(T=new I(w.cache_dir??N.env.cacheDir)),!T&&N.env.useCustomCache){if(!N.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!N.env.customCache.match||!N.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");T=N.env.customCache}const O=w.revision??"main";let ae=U(q,A),oe=U(N.env.localModelPath,ae),Te=U(N.env.remoteHost,N.env.remotePathTemplate.replaceAll("{model}",q).replaceAll("{revision}",encodeURIComponent(O)),A),we=O==="main"?ae:U(q,O,A),re,xe=T instanceof I?we:Te,ce=!1,Se;T&&(Se=await H(T,oe,xe));const Ie=Se!==void 0;if(Se===void 0){if(N.env.allowLocalModels)if(v(ae,["http:","https:"])){if(w.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ae}.`);if(!N.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ae}.`)}else try{Se=await M(oe),re=oe}catch(Ge){console.warn(`Unable to load from local path "${oe}": "${Ge}"`)}if(Se===void 0||Se.status===404){if(w.local_files_only||!N.env.allowRemoteModels){if(S)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${oe}".`);return null}if(Se=await M(Te),Se.status!==200)return b(Se.status,Te,S);re=xe}ce=T&&typeof Response<"u"&&Se instanceof Response&&Se.status===200}(0,Y.dispatchCallback)(w.progress_callback,{status:"download",name:q,file:A});let Ee;return w.progress_callback?Ie&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ee=new Uint8Array(await Se.arrayBuffer()),(0,Y.dispatchCallback)(w.progress_callback,{status:"progress",name:q,file:A,progress:100,loaded:Ee.length,total:Ee.length})):Ee=await W(Se,tt=>{(0,Y.dispatchCallback)(w.progress_callback,{status:"progress",name:q,file:A,...tt})}):Ee=new Uint8Array(await Se.arrayBuffer()),ce&&re&&await T.match(re)===void 0&&await T.put(re,new Response(Ee,{headers:Se.headers})).catch(tt=>{console.warn(`Unable to add response to browser cache: ${tt}.`)}),(0,Y.dispatchCallback)(w.progress_callback,{status:"done",name:q,file:A}),Ee}async function ne(q,A,S=!0,w={}){let T=await se(q,A,S,w);if(T===null)return{};let ae=new TextDecoder("utf-8").decode(T);return JSON.parse(ae)}async function W(q,A){const S=q.headers.get("Content-Length");S===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let w=parseInt(S??"0"),T=new Uint8Array(w),O=0;const ae=q.body.getReader();async function oe(){const{done:Te,value:we}=await ae.read();if(Te)return;let re=O+we.length;if(re>w){w=re;let ce=new Uint8Array(w);ce.set(T),T=ce}T.set(we,O),O=re;const xe=O/w*100;return A({progress:xe,loaded:O,total:w}),oe()}return await oe(),T}function U(...q){return q=q.map((A,S)=>(S&&(A=A.replace(new RegExp("^/"),"")),S!==q.length-1&&(A=A.replace(new RegExp("/$"),"")),A)),q.join("/")}},"./src/utils/image.js":(Le,$,r)=>{r.r($),r.d($,{RawImage:()=>H,load_image:()=>se});var f=r("./src/utils/core.js"),F=r("./src/utils/hub.js"),N=r("./src/env.js"),Y=r("./src/utils/tensor.js"),R=r("?2b25");let g,v,M;const y=N.apis.IS_BROWSER_ENV||N.apis.IS_WEBWORKER_ENV;if(y)g=(ne,W)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ne,W)},M=self.createImageBitmap,v=self.ImageData;else if(R)M=async ne=>{const U=(await ne.metadata()).channels,{data:q,info:A}=await ne.rotate().raw().toBuffer({resolveWithObject:!0}),S=new H(new Uint8ClampedArray(q),A.width,A.height,A.channels);return U!==void 0&&U!==A.channels&&S.convert(U),S};else throw new Error("Unable to load image processing library.");const b={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},I=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class H{constructor(W,U,q,A){this.data=W,this.width=U,this.height=q,this.channels=A}get size(){return[this.width,this.height]}static async read(W){if(W instanceof H)return W;if(typeof W=="string"||W instanceof URL)return await this.fromURL(W);throw new Error(`Unsupported input type: ${typeof W}`)}static fromCanvas(W){if(!y)throw new Error("fromCanvas() is only supported in browser environments.");const q=W.getContext("2d").getImageData(0,0,W.width,W.height).data;return new H(q,W.width,W.height,4)}static async fromURL(W){const U=await(0,F.getFile)(W);if(U.status!==200)throw new Error(`Unable to read image from "${W}" (${U.status} ${U.statusText})`);const q=await U.blob();return this.fromBlob(q)}static async fromBlob(W){if(y){const U=await M(W),q=g(U.width,U.height).getContext("2d");return q.drawImage(U,0,0),new this(q.getImageData(0,0,U.width,U.height).data,U.width,U.height,4)}else{const U=R(await W.arrayBuffer());return await M(U)}}static fromTensor(W,U="CHW"){if(W.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${W.dims.length} dimensions.`);if(U==="CHW")W=W.transpose(1,2,0);else if(U!=="HWC")throw new Error(`Unsupported channel format: ${U}`);if(!(W.data instanceof Uint8ClampedArray||W.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${W.type}`);switch(W.dims[2]){case 1:case 2:case 3:case 4:return new H(W.data,W.dims[1],W.dims[0],W.dims[2]);default:throw new Error(`Unsupported number of channels: ${W.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const W=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let U=0,q=0;U=0?O=q:oe=-q,A>=0?ae=A:Te=-A,T.drawImage(w,O,ae,W,U,oe,Te,W,U),new H(T.getImageData(0,0,W,U).data,W,U,4).convert(S)}else{let S=this.toSharp();if(q>=0&&A>=0)S=S.extract({left:Math.floor(q),top:Math.floor(A),width:W,height:U});else if(q<=0&&A<=0){const w=Math.floor(-A),T=Math.floor(-q);S=S.extend({top:w,left:T,right:W-this.width-T,bottom:U-this.height-w})}else{let w=[0,0],T=0;A<0?(w[0]=Math.floor(-A),w[1]=U-this.height-w[0]):T=Math.floor(A);let O=[0,0],ae=0;q<0?(O[0]=Math.floor(-q),O[1]=W-this.width-O[0]):ae=Math.floor(q),S=S.extend({top:w[0],bottom:w[1],left:O[0],right:O[1]}).extract({left:ae,top:T,width:W,height:U})}return await M(S)}}async toBlob(W="image/png",U=1){if(!y)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:W,quality:U})}toTensor(W="CHW"){let U=new Y.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(W!=="HWC")if(W==="CHW")U=U.permute(2,0,1);else throw new Error(`Unsupported channel format: ${W}`);return U}toCanvas(){if(!y)throw new Error("toCanvas() is only supported in browser environments.");const W=this.clone().rgba(),U=g(W.width,W.height),q=new v(W.data,W.width,W.height);return U.getContext("2d").putImageData(q,0,0),U}split(){const{data:W,width:U,height:q,channels:A}=this,S=W.constructor,w=W.length/A,T=Array.from({length:A},()=>new S(w));for(let O=0;Onew H(O,U,q,1))}_update(W,U,q,A=null){return this.data=W,this.width=U,this.height=q,A!==null&&(this.channels=A),this}clone(){return new H(this.data.slice(),this.width,this.height,this.channels)}convert(W){if(this.channels===W)return this;switch(W){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(W){if(y){if(N.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const U=W.split(".").pop().toLowerCase(),q=I.get(U)??"image/png",A=await this.toBlob(q);(0,f.saveBlob)(W,A)}else{if(N.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(W);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 R(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const se=H.read.bind(H)},"./src/utils/maths.js":(Le,$,r)=>{r.r($),r.d($,{FFT:()=>se,bankers_round:()=>U,cos_sim:()=>g,dot:()=>R,dynamic_time_warping:()=>q,interpolate_data:()=>f,log_softmax:()=>Y,magnitude:()=>v,max:()=>y,medianFilter:()=>ne,min:()=>M,permute_data:()=>F,round:()=>W,softmax:()=>N});function f(A,[S,w,T],[O,ae],oe="bilinear",Te=!1){const we=ae/T,re=O/w,xe=new A.constructor(O*ae*S),ce=w*T,Se=O*ae;for(let Ie=0;Ie=0;--Te)O[Te]=we,T[Te]=S[w[Te]],we*=T[Te];const ae=w.map((Te,we)=>O[w.indexOf(we)]),oe=new A.constructor(A.length);for(let Te=0;Te=0;--re)we+=xe%S[re]*ae[re],xe=Math.floor(xe/S[re]);oe[we]=A[Te]}return[oe,T]}function N(A){const S=y(A)[0],w=A.map(ae=>Math.exp(ae-S)),T=w.reduce((ae,oe)=>ae+oe,0);return w.map(ae=>ae/T)}function Y(A){const S=y(A)[0];let w=0;for(let ae=0;aeae-S-T)}function R(A,S){let w=0;for(let T=0;TS+w*w,0))}function M(A){if(A.length===0)throw Error("Array must not be empty");let S=A[0],w=0;for(let T=1;TS&&(S=A[T],w=T);return[S,w]}function b(A){return A>0&&(A&A-1)===0}class I{constructor(S){if(this.size=S|0,this.size<=1||!b(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=S<<1,this.table=new Float64Array(this.size*2);for(let T=0;TT;T<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>O&3)<>>1);for(let O=0;O>>1]=S[O];return T}toComplexArray(S,w){const T=w||this.createComplexArray();for(let O=0;O>>1],T[O+1]=0;return T}transform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,1)}realTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._realTransform4(S,w,1)}inverseTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,-1);for(let T=0;T>=2;oe>=2;oe>>=2){Te=O/oe<<1;const Se=Te>>>2;for(we=0;we>>1,oe>>>1)}else for(we=0,re=0;we>>1,oe>>>1,T)}const ce=this.table;for(oe>>=2;oe>=2;oe>>=2){Te=O/oe<<1;const Ie=Te>>>1,Ee=Ie>>>1,tt=Ee>>>1;for(we=0;we>>1;for(let Ie=2;Ie>1;++xe){const ce=(xe+1-S)**2/2,Se=Math.sqrt(we**2+re**2)**ce,Ie=ce*Math.atan2(re,we),Ee=2*xe;ae[Ee]=Se*Math.cos(Ie),ae[Ee+1]=Se*Math.sin(Ie),oe[Ee]=ae[Ee],oe[Ee+1]=-ae[Ee+1]}this._slicedChirpBuffer=ae.subarray(w,T),this._f=new I(O>>1),this._f.transform(this._chirpBuffer,oe)}_transform(S,w,T){const O=this._buffer1,ae=this._buffer2,oe=this._outBuffer1,Te=this._outBuffer2,we=this._chirpBuffer,re=this._slicedChirpBuffer,xe=this._a;if(T)for(let ce=0;ce>1,Ee=w[Ie];O[ce]=Ee*re[ce],O[Se]=Ee*re[Se]}else for(let ce=0;ce=A.length&&(we=2*(A.length-1)-we),T[oe++]=A[we]}T.sort(),w[ae]=T[O]}return w}function W(A,S){const w=Math.pow(10,S);return Math.round(A*w)/w}function U(A){const S=Math.round(A);return Math.abs(A)%1===.5?S%2===0?S:S-1:S}function q(A){const S=A.length,w=A[0].length,T=[S+1,w+1],O=Array.from({length:T[0]},()=>Array(T[1]).fill(1/0));O[0][0]=0;const ae=Array.from({length:T[0]},()=>Array(T[1]).fill(-1));for(let xe=1;xe0||Te>0;)switch(we.push(oe-1),re.push(Te-1),ae[oe][Te]){case 0:--oe,--Te;break;case 1:--oe;break;case 2:--Te;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${oe}, ${Te}]. Please file a bug report.`)}return we.reverse(),re.reverse(),[we,re]}},"./src/utils/tensor.js":(Le,$,r)=>{r.r($),r.d($,{Tensor:()=>R,cat:()=>w,full:()=>re,full_like:()=>xe,interpolate:()=>M,interpolate_4d:()=>y,layer_norm:()=>U,matmul:()=>b,mean:()=>oe,mean_pooling:()=>W,ones:()=>ce,ones_like:()=>Se,permute:()=>v,quantize_embeddings:()=>Ge,rand:()=>tt,rfft:()=>I,slice:()=>ne,stack:()=>T,std_mean:()=>ae,topk:()=>H,zeros:()=>Ie,zeros_like:()=>Ee});var f=r("./src/utils/maths.js"),F=r("./src/backends/onnx.js"),N=r("./src/ops/registry.js");const Y=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 R{constructor(...J){_e(this,"ort_tensor");return(0,F.isONNXTensor)(J[0])?this.ort_tensor=J[0]:this.ort_tensor=new F.Tensor(J[0],J[1],J[2]),new Proxy(this,{get:(de,Ce)=>{if(typeof Ce=="string"){let Be=Number(Ce);if(Number.isInteger(Be))return de._getitem(Be)}return de[Ce]},set:(de,Ce,Be)=>de[Ce]=Be})}get dims(){return this.ort_tensor.dims}set dims(J){this.ort_tensor.dims=J}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[J,...de]=this.dims;if(de.length>0){const Ce=de.reduce((Be,Je)=>Be*Je);for(let Be=0;Be0){const Be=Ce.reduce((Je,te)=>Je*te);return this._subarray(J,Be,Ce)}else return new R(this.type,[this.data[J]],Ce)}indexOf(J){const de=this.data;for(let Ce=0;CeWe)throw new Error(`Invalid slice: ${be}`);const Ne=[Math.max(Ve,0),Math.min(We,this.dims[le])];Ce.push(Ne),de.push(Ne[1]-Ne[0])}else throw new Error(`Invalid slice: ${be}`)}const Be=Ce.map(([le,be])=>be-le),Je=Be.reduce((le,be)=>le*be),te=this.data,Ke=new te.constructor(Je),Ue=this.stride();for(let le=0;le=0;--Ve){const Ne=Be[Ve];be+=(We%Ne+Ce[Ve][0])*Ue[Ve],We=Math.floor(We/Ne)}Ke[le]=te[be]}return new R(this.type,Ke,de)}permute(...J){return v(this,J)}transpose(...J){return this.permute(...J)}sum(J=null,de=!1){return this.norm(1,J,de)}norm(J="fro",de=null,Ce=!1){if(J==="fro")J=2;else if(typeof J=="string")throw Error(`Unsupported norm: ${J}`);const Be=this.data,Je=(le,be)=>le+be**J;if(de===null){const le=Be.reduce(Je,0)**(1/J);return new R(this.type,[le],[])}const[te,Ke,Ue]=O(Je,this,de,Ce);if(J!==1)for(let le=0;le=0;--Ue){const Ve=this.dims[Ue];if(Ue!==de){const We=le%Ve;Ke+=We*be,be*=this.dims[Ue]}le=Math.floor(le/Ve)}Be[te]/=Je[Ke]}return this}normalize(J=2,de=1){return this.clone().normalize_(J,de)}stride(){return Te(this.dims)}squeeze(J=null){return new R(this.type,this.data,q(this.dims,J))}squeeze_(J=null){return this.dims=q(this.dims,J),this}unsqueeze(J=null){return new R(this.type,this.data,A(this.dims,J))}unsqueeze_(J=null){return this.dims=A(this.dims,J),this}flatten_(J=0,de=-1){de=(de+this.dims.length)%this.dims.length;let Ce=this.dims.slice(0,J),Be=this.dims.slice(J,de+1),Je=this.dims.slice(de+1);return this.dims=[...Ce,Be.reduce((te,Ke)=>te*Ke,1),...Je],this}flatten(J=0,de=-1){return this.clone().flatten_(J,de)}view(...J){let de=-1;for(let Be=0;BeKe!==de?Je*te:Je,1);J[de]=Ce.length/Be}return new R(this.type,Ce,J)}neg_(){const J=this.data;for(let de=0;deJ?1:0;return new R("bool",de,this.dims)}lt(J){const de=new Uint8Array(this.data.length),Ce=this.data;for(let Be=0;BeMath.min(te,Ke),this,J,de,1/0);return new R(Ce,Be,Je)}max(J=null,de=!1){if(J===null){const te=(0,f.max)(this.data)[0];return new R(this.type,[te],[])}const[Ce,Be,Je]=O((te,Ke)=>Math.max(te,Ke),this,J,de,-1/0);return new R(Ce,Be,Je)}argmin(J=null,de=!1){if(J!==null)throw new Error("`dim !== null` not yet implemented.");const Ce=(0,f.min)(this.data)[1];return new R("int64",[BigInt(Ce)],[])}argmax(J=null,de=!1){if(J!==null)throw new Error("`dim !== null` not yet implemented.");const Ce=(0,f.max)(this.data)[1];return new R("int64",[BigInt(Ce)],[])}to(J){if(this.type===J)return this;if(!Y.hasOwnProperty(J))throw new Error(`Unsupported type: ${J}`);let de;const Ce=["int64","uint64"].includes(this.type),Be=["int64","uint64"].includes(J);return Ce&&!Be?de=Number:!Ce&&Be&&(de=BigInt),new R(J,Y[J].from(this.data,de),this.dims)}}function g(ye,J){const de=ye.length,Ce=J.reduce((Je,te)=>Je*te);if(de!==Ce)throw Error(`cannot reshape array of size ${de} into shape (${J})`);let Be=ye;for(let Je=J.length-1;Je>=0;Je--)Be=Be.reduce((te,Ke)=>{let Ue=te[te.length-1];return Ue.lengthnew R("int64",ye,[ye.length]);async function ne(ye,J,de,Ce,Be){return await(await N.TensorOpRegistry.slice)({x:ye,s:se(J),e:se(de),a:se(Ce),t:se(Be??new Array(Ce.length).fill(1))})}function W(ye,J){const de=ye.data,Ce=J.data,Be=[ye.dims[0],ye.dims[2]],Je=new de.constructor(Be[0]*Be[1]),[te,Ke,Ue]=ye.dims;let le=0;for(let be=0;bede!==1):typeof J=="number"?ye[J]===1&&ye.splice(J,1):Array.isArray(J)&&(ye=ye.filter((de,Ce)=>de!==1||!J.includes(Ce))),ye}function A(ye,J){return J=S(J,ye.length+1),ye=ye.slice(),ye.splice(J,0,1),ye}function S(ye,J,de=null,Ce=!0){if(Ce&&(ye<-J||ye>=J))throw new Error(`IndexError: index ${ye} is out of bounds for dimension${de===null?"":" "+de} with size ${J}`);return ye<0&&(ye=(ye%J+J)%J),ye}function w(ye,J=0){J=S(J,ye[0].dims.length);const de=ye[0].dims.slice();de[J]=ye.reduce((te,Ke)=>te+Ke.dims[J],0);const Ce=de.reduce((te,Ke)=>te*Ke,1),Be=new ye[0].data.constructor(Ce),Je=ye[0].type;if(J===0){let te=0;for(const Ke of ye){const Ue=Ke.data;Be.set(Ue,te),te+=Ue.length}}else{let te=0;for(let Ke=0;Ke=0;--We){const st=le[We];let ut=Ne%st;We===J&&(ut+=te),Ve+=ut*je,je*=de[We],Ne=Math.floor(Ne/st)}Be[Ve]=Ue[be]}te+=le[J]}}return new R(Je,Be,de)}function T(ye,J=0){return w(ye.map(de=>de.unsqueeze(J)),J)}function O(ye,J,de=null,Ce=!1,Be=null){const Je=J.data,te=J.dims;de=S(de,te.length);const Ke=te.slice();Ke[de]=1;const Ue=new Je.constructor(Je.length/te[de]);Be!==null&&Ue.fill(Be);for(let le=0;le=0;--Ve){const je=te[Ve];if(Ve!==de){const st=We%je;be+=st*Ne,Ne*=Ke[Ve]}We=Math.floor(We/je)}Ue[be]=ye(Ue[be],Je[le],le,be)}return Ce||Ke.splice(de,1),[J.type,Ue,Ke]}function ae(ye,J=null,de=1,Ce=!1){const Be=ye.data,Je=ye.dims;if(J===null){const Ne=Be.reduce((pt,lt)=>pt+lt,0)/Be.length,je=Math.sqrt(Be.reduce((pt,lt)=>pt+(lt-Ne)**2,0)/(Be.length-de)),st=new R(ye.type,[Ne],[]);return[new R(ye.type,[je],[]),st]}J=S(J,Je.length);const te=oe(ye,J,Ce),Ke=te.data,[Ue,le,be]=O((We,Ne,je,st)=>We+(Ne-Ke[st])**2,ye,J,Ce);for(let We=0;Wele+be,0);return new R(ye.type,[Ue/Be.length],[])}J=S(J,Ce.length);const[Je,te,Ke]=O((Ue,le)=>Ue+le,ye,J,de);if(Ce[J]!==1)for(let Ue=0;Ue=0;--de)J[de]=Ce,Ce*=ye[de];return J}function we(ye,J,de,Ce){const Be=ye.reduce((Je,te)=>Je*te,1);return new R(de,new Ce(Be).fill(J),ye)}function re(ye,J){let de,Ce;if(typeof J=="number")de="float32",Ce=Float32Array;else if(typeof J=="bigint")de="int64",Ce=BigInt64Array;else if(typeof J=="boolean")de="bool",Ce=Uint8Array;else throw new Error(`Unsupported data type: ${typeof J}`);return we(ye,J,de,Ce)}function xe(ye,J){return re(ye.dims,J)}function ce(ye){return we(ye,1n,"int64",BigInt64Array)}function Se(ye){return ce(ye.dims)}function Ie(ye){return we(ye,0n,"int64",BigInt64Array)}function Ee(ye){return Ie(ye.dims)}function tt(ye){const J=ye.reduce((de,Ce)=>de*Ce,1);return new R("float32",Float32Array.from({length:J},()=>Math.random()),ye)}function Ge(ye,J){if(ye.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ye.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(J))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=J==="binary",Ce=de?"int8":"uint8",Be=de?Int8Array:Uint8Array,Je=ye.data,te=new Be(Je.length/8);for(let Ke=0;Ke0?1:0,le=Math.floor(Ke/8),be=Ke%8;te[le]|=Ue<<7-be,de&&be===0&&(te[le]-=128)}return new R(Ce,te,[ye.dims[0],ye.dims[1]/8])}}},no={};function ws(Le){var $=no[Le];if($!==void 0)return $.exports;var r=no[Le]={exports:{}};return Jr[Le](r,r.exports,ws),r.exports}ws.m=Jr,(()=>{var Le=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,$;ws.t=function(r,f){if(f&1&&(r=this(r)),f&8||typeof r=="object"&&r&&(f&4&&r.__esModule||f&16&&typeof r.then=="function"))return r;var F=Object.create(null);ws.r(F);var N={};$=$||[null,Le({}),Le([]),Le(Le)];for(var Y=f&2&&r;typeof Y=="object"&&!~$.indexOf(Y);Y=Le(Y))Object.getOwnPropertyNames(Y).forEach(R=>N[R]=()=>r[R]);return N.default=()=>r,ws.d(F,N),F}})(),ws.d=(Le,$)=>{for(var r in $)ws.o($,r)&&!ws.o(Le,r)&&Object.defineProperty(Le,r,{enumerable:!0,get:$[r]})},ws.o=(Le,$)=>Object.prototype.hasOwnProperty.call(Le,$),ws.r=Le=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Le,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Le,"__esModule",{value:!0})},(()=>{var Le;if(typeof self.location.href=="string"&&(Le=self.location.href),!Le)throw new Error("Automatic publicPath is not supported in this browser");Le=Le.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),ws.p=Le})(),ws.b=new URL(self.location.href);var c={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/ws.r(c),ws.d(c,{ASTFeatureExtractor:()=>M.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>f.AlbertTokenizer,AudioClassificationPipeline:()=>$.AudioClassificationPipeline,AutoConfig:()=>F.AutoConfig,AutoFeatureExtractor:()=>y.AutoFeatureExtractor,AutoImageProcessor:()=>H.AutoImageProcessor,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>r.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>r.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>r.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>W.AutoProcessor,AutoTokenizer:()=>f.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>$.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>f.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>U.BaseStreamer,BeitFeatureExtractor:()=>I.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>f.BertTokenizer,BitImageProcessor:()=>I.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>f.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>f.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>f.BloomTokenizer,CLIPFeatureExtractor:()=>I.CLIPFeatureExtractor,CLIPImageProcessor:()=>I.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModel:()=>r.CLIPTextModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>f.CLIPTokenizer,CLIPVisionModel:()=>r.CLIPVisionModel,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>f.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>I.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>M.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>A.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>f.CodeGenTokenizer,CodeLlamaTokenizer:()=>f.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>f.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>f.ConvBertTokenizer,ConvNextFeatureExtractor:()=>I.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>I.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>I.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>I.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>f.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>f.DebertaV2Tokenizer,DecisionTransformerModel:()=>r.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>r.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>I.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>I.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>$.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>I.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>I.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>r.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>r.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>r.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>f.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>$.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>I.DonutFeatureExtractor,DonutImageProcessor:()=>I.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>I.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>f.ElectraTokenizer,EosTokenCriteria:()=>q.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>f.EsmTokenizer,ExaoneForCausalLM:()=>r.ExaoneForCausalLM,ExaoneModel:()=>r.ExaoneModel,ExaonePreTrainedModel:()=>r.ExaonePreTrainedModel,FFT:()=>g.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>f.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>$.FeatureExtractionPipeline,FeatureExtractor:()=>v.FeatureExtractor,FillMaskPipeline:()=>$.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>ne.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>A.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>A.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>I.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>f.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>f.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>f.GemmaTokenizer,GlmForCausalLM:()=>r.GlmForCausalLM,GlmModel:()=>r.GlmModel,GlmPreTrainedModel:()=>r.GlmPreTrainedModel,GraniteForCausalLM:()=>r.GraniteForCausalLM,GraniteModel:()=>r.GraniteModel,GranitePreTrainedModel:()=>r.GranitePreTrainedModel,Grok1Tokenizer:()=>f.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>r.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>I.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>r.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>ne.GroundingDinoProcessor,GroupViTModel:()=>r.GroupViTModel,GroupViTPreTrainedModel:()=>r.GroupViTPreTrainedModel,HeliumForCausalLM:()=>r.HeliumForCausalLM,HeliumModel:()=>r.HeliumModel,HeliumPreTrainedModel:()=>r.HeliumPreTrainedModel,HerbertTokenizer:()=>f.HerbertTokenizer,HieraForImageClassification:()=>r.HieraForImageClassification,HieraModel:()=>r.HieraModel,HieraPreTrainedModel:()=>r.HieraPreTrainedModel,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,IJepaForImageClassification:()=>r.IJepaForImageClassification,IJepaModel:()=>r.IJepaModel,IJepaPreTrainedModel:()=>r.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>r.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>I.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>ne.Idefics3Processor,ImageClassificationPipeline:()=>$.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>$.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>M.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>b.ImageProcessor,ImageSegmentationPipeline:()=>$.ImageSegmentationPipeline,ImageToImagePipeline:()=>$.ImageToImagePipeline,ImageToTextPipeline:()=>$.ImageToTextPipeline,InterruptableStoppingCriteria:()=>q.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>I.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ne.JinaCLIPProcessor,JinaCLIPTextModel:()=>r.JinaCLIPTextModel,JinaCLIPVisionModel:()=>r.JinaCLIPVisionModel,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>f.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>r.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>I.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>A.LogitsProcessor,LogitsProcessorList:()=>A.LogitsProcessorList,LogitsWarper:()=>A.LogitsWarper,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>f.M2M100Tokenizer,MBart50Tokenizer:()=>f.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>f.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>f.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>f.MarianTokenizer,Mask2FormerImageProcessor:()=>I.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>I.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>I.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>q.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>ne.MgpstrProcessor,MgpstrTokenizer:()=>f.MgpstrTokenizer,MinLengthLogitsProcessor:()=>A.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>A.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>f.MobileBertTokenizer,MobileLLMForCausalLM:()=>r.MobileLLMForCausalLM,MobileLLMModel:()=>r.MobileLLMModel,MobileLLMPreTrainedModel:()=>r.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>I.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>I.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>I.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>I.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>I.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>I.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>I.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>I.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>I.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>I.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,ModernBertForMaskedLM:()=>r.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>r.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>r.ModernBertForTokenClassification,ModernBertModel:()=>r.ModernBertModel,ModernBertPreTrainedModel:()=>r.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>M.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>ne.MoonshineProcessor,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MultiModalityCausalLM:()=>r.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>r.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>f.NllbTokenizer,NoBadWordsLogitsProcessor:()=>A.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>A.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>I.NougatImageProcessor,NougatTokenizer:()=>f.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>$.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>r.Olmo2ForCausalLM,Olmo2Model:()=>r.Olmo2Model,Olmo2PreTrainedModel:()=>r.Olmo2PreTrainedModel,OlmoForCausalLM:()=>r.OlmoForCausalLM,OlmoModel:()=>r.OlmoModel,OlmoPreTrainedModel:()=>r.OlmoPreTrainedModel,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>I.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>I.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>ne.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>I.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ne.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>r.PatchTSMixerForPrediction,PatchTSMixerModel:()=>r.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>r.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>r.PatchTSTForPrediction,PatchTSTModel:()=>r.PatchTSTModel,PatchTSTPreTrainedModel:()=>r.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,Phi3VForCausalLM:()=>r.Phi3VForCausalLM,Phi3VImageProcessor:()=>I.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>ne.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>$.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>f.PreTrainedTokenizer,PretrainedConfig:()=>F.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>se.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>I.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>M.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ne.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>$.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>f.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>I.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ne.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>I.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawAudio:()=>N.RawAudio,RawImage:()=>Y.RawImage,RepetitionPenaltyLogitsProcessor:()=>A.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>f.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>f.RobertaTokenizer,SamImageProcessor:()=>I.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>ne.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>M.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>I.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>I.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>I.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>f.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>M.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>ne.SpeechT5Processor,SpeechT5Tokenizer:()=>f.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>f.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>q.StoppingCriteria,StoppingCriteriaList:()=>q.StoppingCriteriaList,StyleTextToSpeech2Model:()=>r.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>r.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>$.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>A.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>I.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>f.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>A.TemperatureLogitsWarper,Tensor:()=>R.Tensor,Text2TextGenerationPipeline:()=>$.Text2TextGenerationPipeline,TextClassificationPipeline:()=>$.TextClassificationPipeline,TextGenerationPipeline:()=>$.TextGenerationPipeline,TextStreamer:()=>U.TextStreamer,TextToAudioPipeline:()=>$.TextToAudioPipeline,TokenClassificationPipeline:()=>$.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>f.TokenizerModel,TopKLogitsWarper:()=>A.TopKLogitsWarper,TopPLogitsWarper:()=>A.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>$.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>ne.VLChatProcessor,VLMImageProcessor:()=>I.VLMImageProcessor,ViTFeatureExtractor:()=>I.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>I.ViTImageProcessor,ViTMAEModel:()=>r.ViTMAEModel,ViTMAEPreTrainedModel:()=>r.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>r.ViTMSNForImageClassification,ViTMSNModel:()=>r.ViTMSNModel,ViTMSNPreTrainedModel:()=>r.ViTMSNPreTrainedModel,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>I.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>I.VitPoseImageProcessor,VitPosePreTrainedModel:()=>r.VitPosePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>f.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>f.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>M.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>ne.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>ne.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>M.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>ne.WhisperProcessor,WhisperTextStreamer:()=>U.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>A.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>f.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>f.XLMRobertaTokenizer,XLMTokenizer:()=>f.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>I.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>I.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>$.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>$.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>$.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>$.ZeroShotObjectDetectionPipeline,bankers_round:()=>g.bankers_round,cat:()=>R.cat,cos_sim:()=>g.cos_sim,dot:()=>g.dot,dynamic_time_warping:()=>g.dynamic_time_warping,env:()=>Le.env,full:()=>R.full,full_like:()=>R.full_like,getKeyValueShapes:()=>F.getKeyValueShapes,hamming:()=>N.hamming,hanning:()=>N.hanning,interpolate:()=>R.interpolate,interpolate_4d:()=>R.interpolate_4d,interpolate_data:()=>g.interpolate_data,is_chinese_char:()=>f.is_chinese_char,layer_norm:()=>R.layer_norm,load_image:()=>Y.load_image,log_softmax:()=>g.log_softmax,magnitude:()=>g.magnitude,matmul:()=>R.matmul,max:()=>g.max,mean:()=>R.mean,mean_pooling:()=>R.mean_pooling,medianFilter:()=>g.medianFilter,mel_filter_bank:()=>N.mel_filter_bank,min:()=>g.min,ones:()=>R.ones,ones_like:()=>R.ones_like,permute:()=>R.permute,permute_data:()=>g.permute_data,pipeline:()=>$.pipeline,quantize_embeddings:()=>R.quantize_embeddings,rand:()=>R.rand,read_audio:()=>N.read_audio,rfft:()=>R.rfft,round:()=>g.round,slice:()=>R.slice,softmax:()=>g.softmax,spectrogram:()=>N.spectrogram,stack:()=>R.stack,std_mean:()=>R.std_mean,topk:()=>R.topk,window_function:()=>N.window_function,zeros:()=>R.zeros,zeros_like:()=>R.zeros_like});var Le=ws("./src/env.js"),$=ws("./src/pipelines.js"),r=ws("./src/models.js"),f=ws("./src/tokenizers.js"),F=ws("./src/configs.js"),N=ws("./src/utils/audio.js"),Y=ws("./src/utils/image.js"),R=ws("./src/utils/tensor.js"),g=ws("./src/utils/maths.js"),v=ws("./src/base/feature_extraction_utils.js"),M=ws("./src/models/feature_extractors.js"),y=ws("./src/models/auto/feature_extraction_auto.js"),b=ws("./src/base/image_processors_utils.js"),I=ws("./src/models/image_processors.js"),H=ws("./src/models/auto/image_processing_auto.js"),se=ws("./src/base/processing_utils.js"),ne=ws("./src/models/processors.js"),W=ws("./src/models/auto/processing_auto.js"),U=ws("./src/generation/streamers.js"),q=ws("./src/generation/stopping_criteria.js"),A=ws("./src/generation/logits_process.js")})(),c.ASTFeatureExtractor,c.ASTForAudioClassification,c.ASTModel,c.ASTPreTrainedModel,c.AlbertForMaskedLM,c.AlbertForQuestionAnswering,c.AlbertForSequenceClassification,c.AlbertModel,c.AlbertPreTrainedModel,c.AlbertTokenizer,c.AudioClassificationPipeline,c.AutoConfig,c.AutoFeatureExtractor,c.AutoImageProcessor,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC,c.AutoModelForCausalLM,c.AutoModelForDepthEstimation,c.AutoModelForDocumentQuestionAnswering,c.AutoModelForImageClassification,c.AutoModelForImageFeatureExtraction,c.AutoModelForImageMatting,c.AutoModelForImageSegmentation,c.AutoModelForImageToImage,c.AutoModelForMaskGeneration,c.AutoModelForMaskedLM,c.AutoModelForNormalEstimation,c.AutoModelForObjectDetection,c.AutoModelForPoseEstimation,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation,c.AutoModelForVision2Seq,c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection;var r_=c.AutoProcessor,n_=c.AutoTokenizer;c.AutomaticSpeechRecognitionPipeline,c.BartForConditionalGeneration,c.BartForSequenceClassification,c.BartModel,c.BartPretrainedModel,c.BartTokenizer,c.BaseModelOutput,c.BaseStreamer,c.BeitFeatureExtractor,c.BeitForImageClassification,c.BeitModel,c.BeitPreTrainedModel,c.BertForMaskedLM,c.BertForQuestionAnswering,c.BertForSequenceClassification,c.BertForTokenClassification,c.BertModel,c.BertPreTrainedModel,c.BertTokenizer,c.BitImageProcessor,c.BlenderbotForConditionalGeneration,c.BlenderbotModel,c.BlenderbotPreTrainedModel,c.BlenderbotSmallForConditionalGeneration,c.BlenderbotSmallModel,c.BlenderbotSmallPreTrainedModel,c.BlenderbotSmallTokenizer,c.BlenderbotTokenizer,c.BloomForCausalLM,c.BloomModel,c.BloomPreTrainedModel,c.BloomTokenizer,c.CLIPFeatureExtractor,c.CLIPImageProcessor,c.CLIPModel,c.CLIPPreTrainedModel,c.CLIPSegForImageSegmentation,c.CLIPSegModel,c.CLIPSegPreTrainedModel,c.CLIPTextModel,c.CLIPTextModelWithProjection,c.CLIPTokenizer,c.CLIPVisionModel,c.CLIPVisionModelWithProjection,c.CamembertForMaskedLM,c.CamembertForQuestionAnswering,c.CamembertForSequenceClassification,c.CamembertForTokenClassification,c.CamembertModel,c.CamembertPreTrainedModel,c.CamembertTokenizer,c.CausalLMOutput,c.CausalLMOutputWithPast,c.ChineseCLIPFeatureExtractor,c.ChineseCLIPModel,c.ChineseCLIPPreTrainedModel,c.ClapAudioModelWithProjection,c.ClapFeatureExtractor,c.ClapModel,c.ClapPreTrainedModel,c.ClapTextModelWithProjection,c.ClassifierFreeGuidanceLogitsProcessor,c.CodeGenForCausalLM,c.CodeGenModel,c.CodeGenPreTrainedModel,c.CodeGenTokenizer,c.CodeLlamaTokenizer,c.CohereForCausalLM,c.CohereModel,c.CoherePreTrainedModel,c.CohereTokenizer,c.ConvBertForMaskedLM,c.ConvBertForQuestionAnswering,c.ConvBertForSequenceClassification,c.ConvBertForTokenClassification,c.ConvBertModel,c.ConvBertPreTrainedModel,c.ConvBertTokenizer,c.ConvNextFeatureExtractor,c.ConvNextForImageClassification,c.ConvNextImageProcessor,c.ConvNextModel,c.ConvNextPreTrainedModel,c.ConvNextV2ForImageClassification,c.ConvNextV2Model,c.ConvNextV2PreTrainedModel,c.DPTFeatureExtractor,c.DPTForDepthEstimation,c.DPTImageProcessor,c.DPTModel,c.DPTPreTrainedModel,c.DebertaForMaskedLM,c.DebertaForQuestionAnswering,c.DebertaForSequenceClassification,c.DebertaForTokenClassification,c.DebertaModel,c.DebertaPreTrainedModel,c.DebertaTokenizer,c.DebertaV2ForMaskedLM,c.DebertaV2ForQuestionAnswering,c.DebertaV2ForSequenceClassification,c.DebertaV2ForTokenClassification,c.DebertaV2Model,c.DebertaV2PreTrainedModel,c.DebertaV2Tokenizer,c.DecisionTransformerModel,c.DecisionTransformerPreTrainedModel,c.DeiTFeatureExtractor,c.DeiTForImageClassification,c.DeiTImageProcessor,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DepthProForDepthEstimation,c.DepthProPreTrainedModel,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrImageProcessor,c.DetrModel,c.DetrObjectDetectionOutput,c.DetrPreTrainedModel,c.DetrSegmentationOutput,c.Dinov2ForImageClassification,c.Dinov2Model,c.Dinov2PreTrainedModel,c.Dinov2WithRegistersForImageClassification,c.Dinov2WithRegistersModel,c.Dinov2WithRegistersPreTrainedModel,c.DistilBertForMaskedLM,c.DistilBertForQuestionAnswering,c.DistilBertForSequenceClassification,c.DistilBertForTokenClassification,c.DistilBertModel,c.DistilBertPreTrainedModel,c.DistilBertTokenizer,c.DocumentQuestionAnsweringPipeline,c.DonutFeatureExtractor,c.DonutImageProcessor,c.DonutSwinModel,c.DonutSwinPreTrainedModel,c.EfficientNetForImageClassification,c.EfficientNetImageProcessor,c.EfficientNetModel,c.EfficientNetPreTrainedModel,c.ElectraForMaskedLM,c.ElectraForQuestionAnswering,c.ElectraForSequenceClassification,c.ElectraForTokenClassification,c.ElectraModel,c.ElectraPreTrainedModel,c.ElectraTokenizer,c.EosTokenCriteria,c.EsmForMaskedLM,c.EsmForSequenceClassification,c.EsmForTokenClassification,c.EsmModel,c.EsmPreTrainedModel,c.EsmTokenizer,c.ExaoneForCausalLM,c.ExaoneModel,c.ExaonePreTrainedModel,c.FFT,c.FalconForCausalLM,c.FalconModel,c.FalconPreTrainedModel,c.FalconTokenizer,c.FastViTForImageClassification,c.FastViTModel,c.FastViTPreTrainedModel,c.FeatureExtractionPipeline,c.FeatureExtractor,c.FillMaskPipeline,c.Florence2ForConditionalGeneration,c.Florence2PreTrainedModel,c.Florence2Processor,c.ForcedBOSTokenLogitsProcessor,c.ForcedEOSTokenLogitsProcessor,c.GLPNFeatureExtractor,c.GLPNForDepthEstimation,c.GLPNModel,c.GLPNPreTrainedModel,c.GPT2LMHeadModel,c.GPT2Model,c.GPT2PreTrainedModel,c.GPT2Tokenizer,c.GPTBigCodeForCausalLM,c.GPTBigCodeModel,c.GPTBigCodePreTrainedModel,c.GPTJForCausalLM,c.GPTJModel,c.GPTJPreTrainedModel,c.GPTNeoForCausalLM,c.GPTNeoModel,c.GPTNeoPreTrainedModel,c.GPTNeoXForCausalLM,c.GPTNeoXModel,c.GPTNeoXPreTrainedModel,c.GPTNeoXTokenizer,c.Gemma2ForCausalLM,c.Gemma2Model,c.Gemma2PreTrainedModel,c.GemmaForCausalLM,c.GemmaModel,c.GemmaPreTrainedModel,c.GemmaTokenizer,c.GlmForCausalLM,c.GlmModel,c.GlmPreTrainedModel,c.GraniteForCausalLM,c.GraniteModel,c.GranitePreTrainedModel,c.Grok1Tokenizer,c.GroundingDinoForObjectDetection,c.GroundingDinoImageProcessor,c.GroundingDinoPreTrainedModel,c.GroundingDinoProcessor,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HeliumForCausalLM,c.HeliumModel,c.HeliumPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.IJepaForImageClassification,c.IJepaModel,c.IJepaPreTrainedModel,c.Idefics3ForConditionalGeneration,c.Idefics3ImageProcessor,c.Idefics3PreTrainedModel,c.Idefics3Processor,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageProcessor,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline,c.InterruptableStoppingCriteria,c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.JinaCLIPImageProcessor,c.JinaCLIPModel,c.JinaCLIPPreTrainedModel,c.JinaCLIPProcessor,c.JinaCLIPTextModel,c.JinaCLIPVisionModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaOnevisionForConditionalGeneration,c.LlavaOnevisionImageProcessor,c.LlavaPreTrainedModel,c.LogitsProcessor,c.LogitsProcessorList,c.LogitsWarper,c.LongT5ForConditionalGeneration,c.LongT5Model,c.LongT5PreTrainedModel,c.M2M100ForConditionalGeneration,c.M2M100Model,c.M2M100PreTrainedModel,c.M2M100Tokenizer,c.MBart50Tokenizer,c.MBartForCausalLM,c.MBartForConditionalGeneration,c.MBartForSequenceClassification,c.MBartModel,c.MBartPreTrainedModel,c.MBartTokenizer,c.MPNetForMaskedLM,c.MPNetForQuestionAnswering,c.MPNetForSequenceClassification,c.MPNetForTokenClassification,c.MPNetModel,c.MPNetPreTrainedModel,c.MPNetTokenizer,c.MT5ForConditionalGeneration,c.MT5Model,c.MT5PreTrainedModel,c.MarianMTModel,c.MarianModel,c.MarianPreTrainedModel,c.MarianTokenizer,c.Mask2FormerImageProcessor,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerImageProcessor,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MgpstrForSceneTextRecognition,c.MgpstrModelOutput,c.MgpstrPreTrainedModel,c.MgpstrProcessor,c.MgpstrTokenizer,c.MinLengthLogitsProcessor,c.MinNewTokensLengthLogitsProcessor,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileLLMForCausalLM,c.MobileLLMModel,c.MobileLLMPreTrainedModel,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1ImageProcessor,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2ImageProcessor,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3ImageProcessor,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4ImageProcessor,c.MobileNetV4Model,c.MobileNetV4PreTrainedModel,c.MobileViTFeatureExtractor,c.MobileViTForImageClassification,c.MobileViTImageProcessor,c.MobileViTModel,c.MobileViTPreTrainedModel,c.MobileViTV2ForImageClassification,c.MobileViTV2Model,c.MobileViTV2PreTrainedModel,c.ModelOutput,c.ModernBertForMaskedLM,c.ModernBertForSequenceClassification,c.ModernBertForTokenClassification,c.ModernBertModel,c.ModernBertPreTrainedModel,c.Moondream1ForConditionalGeneration,c.MoonshineFeatureExtractor,c.MoonshineForConditionalGeneration,c.MoonshineModel,c.MoonshinePreTrainedModel,c.MoonshineProcessor,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MultiModalityCausalLM,c.MultiModalityPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NoBadWordsLogitsProcessor,c.NoRepeatNGramLogitsProcessor,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.Olmo2ForCausalLM,c.Olmo2Model,c.Olmo2PreTrainedModel,c.OlmoForCausalLM,c.OlmoModel,c.OlmoPreTrainedModel,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTImageProcessor,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.PaliGemmaForConditionalGeneration,c.PaliGemmaPreTrainedModel,c.PaliGemmaProcessor,c.PatchTSMixerForPrediction,c.PatchTSMixerModel,c.PatchTSMixerPreTrainedModel,c.PatchTSTForPrediction,c.PatchTSTModel,c.PatchTSTPreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.Phi3VForCausalLM,c.Phi3VImageProcessor,c.Phi3VPreTrainedModel,c.Phi3VProcessor,c.PhiForCausalLM,c.PhiModel,c.PhiPreTrainedModel,c.Pipeline,c.PreTrainedModel,c.PreTrainedTokenizer,c.PretrainedConfig,c.PretrainedMixin,c.Processor,c.PvtForImageClassification,c.PvtImageProcessor,c.PvtModel,c.PvtPreTrainedModel,c.PyAnnoteFeatureExtractor,c.PyAnnoteForAudioFrameClassification,c.PyAnnoteModel,c.PyAnnotePreTrainedModel,c.PyAnnoteProcessor,c.QuestionAnsweringModelOutput,c.QuestionAnsweringPipeline,c.Qwen2ForCausalLM,c.Qwen2Model,c.Qwen2PreTrainedModel,c.Qwen2Tokenizer,c.Qwen2VLForConditionalGeneration,c.Qwen2VLImageProcessor,c.Qwen2VLPreTrainedModel,c.Qwen2VLProcessor,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel,c.RawAudio,c.RawImage,c.RepetitionPenaltyLogitsProcessor,c.ResNetForImageClassification,c.ResNetModel,c.ResNetPreTrainedModel,c.RoFormerForMaskedLM,c.RoFormerForQuestionAnswering,c.RoFormerForSequenceClassification,c.RoFormerForTokenClassification,c.RoFormerModel,c.RoFormerPreTrainedModel,c.RoFormerTokenizer,c.RobertaForMaskedLM,c.RobertaForQuestionAnswering,c.RobertaForSequenceClassification,c.RobertaForTokenClassification,c.RobertaModel,c.RobertaPreTrainedModel,c.RobertaTokenizer,c.SamImageProcessor,c.SamImageSegmentationOutput,c.SamModel,c.SamPreTrainedModel,c.SamProcessor,c.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerImageProcessor,c.SegformerModel,c.SegformerPreTrainedModel,c.Seq2SeqLMOutput,c.SequenceClassifierOutput,c.SiglipImageProcessor,c.SiglipModel,c.SiglipPreTrainedModel,c.SiglipTextModel,c.SiglipTokenizer,c.SiglipVisionModel,c.SpeechT5FeatureExtractor,c.SpeechT5ForSpeechToText,c.SpeechT5ForTextToSpeech,c.SpeechT5HifiGan,c.SpeechT5Model,c.SpeechT5PreTrainedModel,c.SpeechT5Processor,c.SpeechT5Tokenizer,c.SqueezeBertForMaskedLM,c.SqueezeBertForQuestionAnswering,c.SqueezeBertForSequenceClassification,c.SqueezeBertModel,c.SqueezeBertPreTrainedModel,c.SqueezeBertTokenizer,c.StableLmForCausalLM,c.StableLmModel,c.StableLmPreTrainedModel,c.Starcoder2ForCausalLM,c.Starcoder2Model,c.Starcoder2PreTrainedModel,c.StoppingCriteria,c.StoppingCriteriaList,c.StyleTextToSpeech2Model,c.StyleTextToSpeech2PreTrainedModel,c.SummarizationPipeline,c.SuppressTokensAtBeginLogitsProcessor,c.Swin2SRForImageSuperResolution,c.Swin2SRImageProcessor,c.Swin2SRModel,c.Swin2SRPreTrainedModel,c.SwinForImageClassification,c.SwinModel,c.SwinPreTrainedModel,c.T5ForConditionalGeneration,c.T5Model,c.T5PreTrainedModel,c.T5Tokenizer,c.TableTransformerForObjectDetection,c.TableTransformerModel,c.TableTransformerObjectDetectionOutput,c.TableTransformerPreTrainedModel,c.TemperatureLogitsWarper,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline;var o_=c.TextStreamer;c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TopKLogitsWarper,c.TopPLogitsWarper,c.TrOCRForCausalLM,c.TrOCRPreTrainedModel,c.TranslationPipeline,c.UniSpeechForCTC,c.UniSpeechForSequenceClassification,c.UniSpeechModel,c.UniSpeechPreTrainedModel,c.UniSpeechSatForAudioFrameClassification,c.UniSpeechSatForCTC,c.UniSpeechSatForSequenceClassification,c.UniSpeechSatModel,c.UniSpeechSatPreTrainedModel,c.VLChatProcessor,c.VLMImageProcessor,c.ViTFeatureExtractor,c.ViTForImageClassification,c.ViTImageProcessor,c.ViTMAEModel,c.ViTMAEPreTrainedModel,c.ViTMSNForImageClassification,c.ViTMSNModel,c.ViTMSNPreTrainedModel,c.ViTModel,c.ViTPreTrainedModel,c.VisionEncoderDecoderModel,c.VitMatteForImageMatting,c.VitMatteImageProcessor,c.VitMattePreTrainedModel,c.VitPoseForPoseEstimation,c.VitPoseImageProcessor,c.VitPosePreTrainedModel,c.VitsModel,c.VitsModelOutput,c.VitsPreTrainedModel,c.VitsTokenizer,c.Wav2Vec2BertForCTC,c.Wav2Vec2BertForSequenceClassification,c.Wav2Vec2BertModel,c.Wav2Vec2BertPreTrainedModel,c.Wav2Vec2CTCTokenizer,c.Wav2Vec2FeatureExtractor,c.Wav2Vec2ForAudioFrameClassification,c.Wav2Vec2ForCTC,c.Wav2Vec2ForSequenceClassification,c.Wav2Vec2Model,c.Wav2Vec2PreTrainedModel,c.Wav2Vec2Processor,c.Wav2Vec2ProcessorWithLM,c.WavLMForAudioFrameClassification,c.WavLMForCTC,c.WavLMForSequenceClassification,c.WavLMForXVector,c.WavLMModel,c.WavLMPreTrainedModel,c.WeSpeakerFeatureExtractor,c.WeSpeakerResNetModel,c.WeSpeakerResNetPreTrainedModel,c.WhisperFeatureExtractor;var i_=c.WhisperForConditionalGeneration;c.WhisperModel,c.WhisperPreTrainedModel,c.WhisperProcessor,c.WhisperTextStreamer,c.WhisperTimeStampLogitsProcessor,c.WhisperTokenizer,c.XLMForQuestionAnswering,c.XLMForSequenceClassification,c.XLMForTokenClassification,c.XLMModel,c.XLMPreTrainedModel,c.XLMRobertaForMaskedLM,c.XLMRobertaForQuestionAnswering,c.XLMRobertaForSequenceClassification,c.XLMRobertaForTokenClassification,c.XLMRobertaModel,c.XLMRobertaPreTrainedModel,c.XLMRobertaTokenizer,c.XLMTokenizer,c.XLMWithLMHeadModel,c.XVectorOutput,c.YolosFeatureExtractor,c.YolosForObjectDetection,c.YolosImageProcessor,c.YolosModel,c.YolosObjectDetectionOutput,c.YolosPreTrainedModel,c.ZeroShotAudioClassificationPipeline,c.ZeroShotClassificationPipeline,c.ZeroShotImageClassificationPipeline,c.ZeroShotObjectDetectionPipeline,c.bankers_round,c.cat,c.cos_sim,c.dot,c.dynamic_time_warping,c.env;var a_=c.full;c.full_like,c.getKeyValueShapes,c.hamming,c.hanning,c.interpolate,c.interpolate_4d,c.interpolate_data,c.is_chinese_char,c.layer_norm,c.load_image,c.log_softmax,c.magnitude,c.matmul,c.max,c.mean,c.mean_pooling,c.medianFilter,c.mel_filter_bank,c.min,c.ones,c.ones_like,c.permute,c.permute_data,c.pipeline,c.quantize_embeddings,c.rand,c.read_audio,c.rfft,c.round,c.slice,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;const l_=64;class Wo{static async getInstance($){return this.model_id="onnx-community/whisper-large-v3-turbo",this.tokenizer??(this.tokenizer=n_.from_pretrained(this.model_id,{progress_callback:$})),this.processor??(this.processor=r_.from_pretrained(this.model_id,{progress_callback:$})),this.model??(this.model=i_.from_pretrained(this.model_id,{dtype:{encoder_model:"fp16",decoder_model_merged:"q4"},device:"webgpu",progress_callback:$})),Promise.all([this.tokenizer,this.processor,this.model])}}_e(Wo,"model_id",null),_e(Wo,"tokenizer"),_e(Wo,"processor"),_e(Wo,"model");async function u_(Le){const $=atob(Le),r=new Uint8Array($.length);for(let N=0;N<$.length;N++)r[N]=$.charCodeAt(N);const f=new Int16Array(r.buffer.slice(44)),F=new Float32Array(f.length);for(let N=0;N{Y??(Y=performance.now());let H;R++>0&&(H=R/(performance.now()-Y)*1e3),globalThis.postMessage({status:"update",output:I,tps:H,numTokens:R})},v=new o_(f,{skip_prompt:!0,decode_kwargs:{skip_special_tokens:!0},callback_function:g}),M=await F(r),y=await N.generate({...M,max_new_tokens:l_,language:$,streamer:v}),b=f.batch_decode(y,{skip_special_tokens:!0});globalThis.postMessage({status:"complete",output:b}),Wp=!1}async function c_(){globalThis.postMessage({status:"loading",data:"Loading model..."});const[Le,$,r]=await Wo.getInstance(f=>{globalThis.postMessage(f)});globalThis.postMessage({status:"loading",data:"Compiling shaders and warming up model..."}),await r.generate({input_features:a_([1,128,3e3],0),max_new_tokens:1}),globalThis.postMessage({status:"ready"})}globalThis.addEventListener("message",async Le=>{const{type:$,data:r}=Le.data;switch($){case"load":c_();break;case"generate":d_(r);break}})})();