var F_=Object.defineProperty;var O_=(_s,ln,co)=>ln in _s?F_(_s,ln,{enumerable:!0,configurable:!0,writable:!0,value:co}):_s[ln]=co;var Te=(_s,ln,co)=>O_(_s,typeof ln!="symbol"?ln+"":ln,co);(function(){"use strict";var _s={},ln={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Oe,B,c)=>{Oe.exports=c.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Oe,B,c)=>{c.r(B),c.d(B,{Environment:()=>nt,Interpreter:()=>ut,Template:()=>ft,parse:()=>$e,tokenize:()=>$});var w=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),R=Object.freeze({set:w.Set,for:w.For,in:w.In,is:w.Is,if:w.If,else:w.Else,endif:w.EndIf,elif:w.ElseIf,endfor:w.EndFor,and:w.And,or:w.Or,not:w.Not,"not in":w.NotIn,macro:w.Macro,endmacro:w.EndMacro,true:w.BooleanLiteral,false:w.BooleanLiteral,none:w.NullLiteral,True:w.BooleanLiteral,False:w.BooleanLiteral,None:w.NullLiteral}),H=class{constructor(A,re){this.value=A,this.type=re}};function J(A){return/\w/.test(A)}function q(A){return/[0-9]/.test(A)}var g=[["{%",w.OpenStatement],["%}",w.CloseStatement],["{{",w.OpenExpression],["}}",w.CloseExpression],["(",w.OpenParen],[")",w.CloseParen],["{",w.OpenCurlyBracket],["}",w.CloseCurlyBracket],["[",w.OpenSquareBracket],["]",w.CloseSquareBracket],[",",w.Comma],[".",w.Dot],[":",w.Colon],["|",w.Pipe],["<=",w.ComparisonBinaryOperator],[">=",w.ComparisonBinaryOperator],["==",w.ComparisonBinaryOperator],["!=",w.ComparisonBinaryOperator],["<",w.ComparisonBinaryOperator],[">",w.ComparisonBinaryOperator],["+",w.AdditiveBinaryOperator],["-",w.AdditiveBinaryOperator],["*",w.MultiplicativeBinaryOperator],["/",w.MultiplicativeBinaryOperator],["%",w.MultiplicativeBinaryOperator],["=",w.Equals]],x=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function E(A,re={}){return A.endsWith(` `)&&(A=A.slice(0,-1)),A=A.replace(/{#.*?#}/gs,"{##}"),re.lstrip_blocks&&(A=A.replace(/^[ \t]*({[#%])/gm,"$1")),re.trim_blocks&&(A=A.replace(/([#%]})\n/g,"$1")),A.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function $(A,re={}){var ot,dt,$t;const V=[],de=E(A,re);let ke=0;const Ye=Et=>{let Tt="";for(;Et(de[ke]);){if(de[ke]==="\\"){if(++ke,ke>=de.length)throw new SyntaxError("Unexpected end of input");const Pt=de[ke++],ar=x.get(Pt);if(ar===void 0)throw new SyntaxError(`Unexpected escaped character: ${Pt}`);Tt+=ar;continue}if(Tt+=de[ke++],ke>=de.length)throw new SyntaxError("Unexpected end of input")}return Tt};e:for(;ke0){V.push(new H(Pt,w.Text));continue}}Ye(Pt=>/\s/.test(Pt));const Tt=de[ke];if(Tt==="-"||Tt==="+"){const Pt=(dt=V.at(-1))==null?void 0:dt.type;if(Pt===w.Text||Pt===void 0)throw new SyntaxError(`Unexpected character: ${Tt}`);switch(Pt){case w.Identifier:case w.NumericLiteral:case w.BooleanLiteral:case w.NullLiteral:case w.StringLiteral:case w.CloseParen:case w.CloseSquareBracket:break;default:{++ke;const ar=Ye(q);V.push(new H(`${Tt}${ar}`,ar.length>0?w.NumericLiteral:w.UnaryOperator));continue}}}for(const[Pt,ar]of g)if(de.slice(ke,ke+Pt.length)===Pt){V.push(new H(Pt,ar)),ke+=Pt.length;continue e}if(Tt==="'"||Tt==='"'){++ke;const Pt=Ye(ar=>ar!==Tt);V.push(new H(Pt,w.StringLiteral)),++ke;continue}if(q(Tt)){const Pt=Ye(q);V.push(new H(Pt,w.NumericLiteral));continue}if(J(Tt)){const Pt=Ye(J),ar=Object.hasOwn(R,Pt)?R[Pt]:w.Identifier;ar===w.In&&(($t=V.at(-1))==null?void 0:$t.type)===w.Not?(V.pop(),V.push(new H("not in",w.NotIn))):V.push(new H(Pt,ar));continue}throw new SyntaxError(`Unexpected character: ${Tt}`)}return V}var P=class{constructor(){Te(this,"type","Statement")}},Y=class extends P{constructor(re){super();Te(this,"type","Program");this.body=re}},se=class extends P{constructor(re,V,de){super();Te(this,"type","If");this.test=re,this.body=V,this.alternate=de}},ue=class extends P{constructor(re,V,de,ke){super();Te(this,"type","For");this.loopvar=re,this.iterable=V,this.body=de,this.defaultBlock=ke}},le=class extends P{constructor(re,V){super();Te(this,"type","Set");this.assignee=re,this.value=V}},U=class extends P{constructor(re,V,de){super();Te(this,"type","Macro");this.name=re,this.args=V,this.body=de}},Q=class extends P{constructor(){super(...arguments);Te(this,"type","Expression")}},ne=class extends Q{constructor(re,V,de){super();Te(this,"type","MemberExpression");this.object=re,this.property=V,this.computed=de}},N=class extends Q{constructor(re,V){super();Te(this,"type","CallExpression");this.callee=re,this.args=V}},O=class extends Q{constructor(re){super();Te(this,"type","Identifier");this.value=re}},_=class extends Q{constructor(re){super();Te(this,"type","Literal");this.value=re}},k=class extends _{constructor(){super(...arguments);Te(this,"type","NumericLiteral")}},C=class extends _{constructor(){super(...arguments);Te(this,"type","StringLiteral")}},Z=class extends _{constructor(){super(...arguments);Te(this,"type","BooleanLiteral")}},ee=class extends _{constructor(){super(...arguments);Te(this,"type","NullLiteral")}},_e=class extends _{constructor(){super(...arguments);Te(this,"type","ArrayLiteral")}},ge=class extends _{constructor(){super(...arguments);Te(this,"type","TupleLiteral")}},be=class extends _{constructor(){super(...arguments);Te(this,"type","ObjectLiteral")}},Se=class extends Q{constructor(re,V,de){super();Te(this,"type","BinaryExpression");this.operator=re,this.left=V,this.right=de}},Pe=class extends Q{constructor(re,V){super();Te(this,"type","FilterExpression");this.operand=re,this.filter=V}},Le=class extends Q{constructor(re,V){super();Te(this,"type","SelectExpression");this.iterable=re,this.test=V}},me=class extends Q{constructor(re,V,de){super();Te(this,"type","TestExpression");this.operand=re,this.negate=V,this.test=de}},j=class extends Q{constructor(re,V){super();Te(this,"type","UnaryExpression");this.operator=re,this.argument=V}},he=class extends Q{constructor(re=void 0,V=void 0,de=void 0){super();Te(this,"type","SliceExpression");this.start=re,this.stop=V,this.step=de}},pe=class extends Q{constructor(re,V){super();Te(this,"type","KeywordArgumentExpression");this.key=re,this.value=V}};function $e(A){const re=new Y([]);let V=0;function de(et,vt){const It=A[V++];if(!It||It.type!==et)throw new Error(`Parser Error: ${vt}. ${It.type} !== ${et}.`);return It}function ke(){switch(A[V].type){case w.Text:return dt();case w.OpenStatement:return $t();case w.OpenExpression:return Et();default:throw new SyntaxError(`Unexpected token type: ${A[V].type}`)}}function Ye(...et){return V+et.length<=A.length&&et.some((vt,It)=>vt!==A[V+It].type)}function ot(...et){return V+et.length<=A.length&&et.every((vt,It)=>vt===A[V+It].type)}function dt(){return new C(de(w.Text,"Expected text token").value)}function $t(){de(w.OpenStatement,"Expected opening statement token");let et;switch(A[V].type){case w.Set:++V,et=Tt(),de(w.CloseStatement,"Expected closing statement token");break;case w.If:++V,et=Pt(),de(w.OpenStatement,"Expected {% token"),de(w.EndIf,"Expected endif token"),de(w.CloseStatement,"Expected %} token");break;case w.Macro:++V,et=ar(),de(w.OpenStatement,"Expected {% token"),de(w.EndMacro,"Expected endmacro token"),de(w.CloseStatement,"Expected %} token");break;case w.For:++V,et=Fr(),de(w.OpenStatement,"Expected {% token"),de(w.EndFor,"Expected endfor token"),de(w.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${A[V].type}`)}return et}function Et(){de(w.OpenExpression,"Expected opening expression token");const et=Br();return de(w.CloseExpression,"Expected closing expression token"),et}function Tt(){const et=Br();if(ot(w.Equals)){++V;const vt=Tt();return new le(et,vt)}return et}function Pt(){var Wr,en,js,xr,cs,Lr,Fs,br;const et=Br();de(w.CloseStatement,"Expected closing statement token");const vt=[],It=[];for(;!(((Wr=A[V])==null?void 0:Wr.type)===w.OpenStatement&&(((en=A[V+1])==null?void 0:en.type)===w.ElseIf||((js=A[V+1])==null?void 0:js.type)===w.Else||((xr=A[V+1])==null?void 0:xr.type)===w.EndIf));)vt.push(ke());if(((cs=A[V])==null?void 0:cs.type)===w.OpenStatement&&((Lr=A[V+1])==null?void 0:Lr.type)!==w.EndIf)if(++V,ot(w.ElseIf))de(w.ElseIf,"Expected elseif token"),It.push(Pt());else for(de(w.Else,"Expected else token"),de(w.CloseStatement,"Expected closing statement token");!(((Fs=A[V])==null?void 0:Fs.type)===w.OpenStatement&&((br=A[V+1])==null?void 0:br.type)===w.EndIf);)It.push(ke());return new se(et,vt,It)}function ar(){const et=ds();if(et.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const vt=Ys();de(w.CloseStatement,"Expected closing statement token");const It=[];for(;Ye(w.OpenStatement,w.EndMacro);)It.push(ke());return new U(et,vt,It)}function Mr(et=!1){const vt=et?ds:Br,It=[vt()],Wr=ot(w.Comma);for(;Wr&&(++V,It.push(vt()),!!ot(w.Comma)););return Wr?new ge(It):It[0]}function Fr(){const et=Mr(!0);if(!(et instanceof O||et instanceof ge))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${et.type} instead`);de(w.In,"Expected `in` keyword following loop variable");const vt=Br();de(w.CloseStatement,"Expected closing statement token");const It=[];for(;Ye(w.OpenStatement,w.EndFor)&&Ye(w.OpenStatement,w.Else);)It.push(ke());const Wr=[];if(ot(w.OpenStatement,w.Else))for(++V,++V,de(w.CloseStatement,"Expected closing statement token");Ye(w.OpenStatement,w.EndFor);)Wr.push(ke());return new ue(et,vt,It,Wr)}function Br(){return os()}function os(){const et=Qs();if(ot(w.If)){++V;const vt=Qs();if(ot(w.Else)){++V;const It=Qs();return new se(vt,[et],[It])}else return new Le(et,vt)}return et}function Qs(){let et=Xs();for(;ot(w.Or);){const vt=A[V];++V;const It=Xs();et=new Se(vt,et,It)}return et}function Xs(){let et=zs();for(;ot(w.And);){const vt=A[V];++V;const It=zs();et=new Se(vt,et,It)}return et}function zs(){let et;for(;ot(w.Not);){const vt=A[V];++V;const It=zs();et=new j(vt,It)}return et??Is()}function Is(){let et=Nt();for(;ot(w.ComparisonBinaryOperator)||ot(w.In)||ot(w.NotIn);){const vt=A[V];++V;const It=Nt();et=new Se(vt,et,It)}return et}function Nt(){let et=Js();for(;ot(w.AdditiveBinaryOperator);){const vt=A[V];++V;const It=Js();et=new Se(vt,et,It)}return et}function Ts(){const et=dn();return ot(w.OpenParen)?Bs(et):et}function Bs(et){let vt=new N(et,Ys());return ot(w.OpenParen)&&(vt=Bs(vt)),vt}function Ys(){de(w.OpenParen,"Expected opening parenthesis for arguments list");const et=un();return de(w.CloseParen,"Expected closing parenthesis for arguments list"),et}function un(){const et=[];for(;!ot(w.CloseParen);){let vt=Br();if(ot(w.Equals)){if(++V,!(vt instanceof O))throw new SyntaxError("Expected identifier for keyword argument");const It=Br();vt=new pe(vt,It)}et.push(vt),ot(w.Comma)&&++V}return et}function gs(){const et=[];let vt=!1;for(;!ot(w.CloseSquareBracket);)ot(w.Colon)?(et.push(void 0),++V,vt=!0):(et.push(Br()),ot(w.Colon)&&(++V,vt=!0));if(et.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(vt){if(et.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new he(...et)}return et[0]}function dn(){let et=ds();for(;ot(w.Dot)||ot(w.OpenSquareBracket);){const vt=A[V];++V;let It;const Wr=vt.type!==w.Dot;if(Wr)It=gs(),de(w.CloseSquareBracket,"Expected closing square bracket");else if(It=ds(),It.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");et=new ne(et,It,Wr)}return et}function Js(){let et=Zs();for(;ot(w.MultiplicativeBinaryOperator);){const vt=A[V];++V;const It=Zs();et=new Se(vt,et,It)}return et}function Zs(){let et=Rs();for(;ot(w.Is);){++V;const vt=ot(w.Not);vt&&++V;let It=ds();if(It instanceof Z?It=new O(It.value.toString()):It instanceof ee&&(It=new O("none")),!(It instanceof O))throw new SyntaxError("Expected identifier for the test");et=new me(et,vt,It)}return et}function Rs(){let et=Ts();for(;ot(w.Pipe);){++V;let vt=ds();if(!(vt instanceof O))throw new SyntaxError("Expected identifier for the filter");ot(w.OpenParen)&&(vt=Bs(vt)),et=new Pe(et,vt)}return et}function ds(){const et=A[V];switch(et.type){case w.NumericLiteral:return++V,new k(Number(et.value));case w.StringLiteral:return++V,new C(et.value);case w.BooleanLiteral:return++V,new Z(et.value.toLowerCase()==="true");case w.NullLiteral:return++V,new ee(null);case w.Identifier:return++V,new O(et.value);case w.OpenParen:{++V;const vt=Mr();if(A[V].type!==w.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${A[V].type} instead`);return++V,vt}case w.OpenSquareBracket:{++V;const vt=[];for(;!ot(w.CloseSquareBracket);)vt.push(Br()),ot(w.Comma)&&++V;return++V,new _e(vt)}case w.OpenCurlyBracket:{++V;const vt=new Map;for(;!ot(w.CloseCurlyBracket);){const It=Br();de(w.Colon,"Expected colon between key and value in object literal");const Wr=Br();vt.set(It,Wr),ot(w.Comma)&&++V}return++V,new be(vt)}default:throw new SyntaxError(`Unexpected token: ${et.type}`)}}for(;V=0?(re=(re??(re=0))<0?Math.max(A.length+re,0):Math.min(re,A.length),V=(V??(V=A.length))<0?Math.max(A.length+V,0):Math.min(V,A.length)):(re=(re??(re=A.length-1))<0?Math.max(A.length+re,-1):Math.min(re,A.length-1),V=(V??(V=-1))<-1?Math.max(A.length+V,-1):Math.min(V,A.length-1));const Ye=[];for(let ot=re;ke*otre.toUpperCase())}var lt=class{constructor(A=void 0){Te(this,"type","RuntimeValue");Te(this,"value");Te(this,"builtins",new Map);this.value=A}__bool__(){return new st(!!this.value)}},ie=class extends lt{constructor(){super(...arguments);Te(this,"type","NumericValue")}},je=class extends lt{constructor(){super(...arguments);Te(this,"type","StringValue");Te(this,"builtins",new Map([["upper",new Qe(()=>new je(this.value.toUpperCase()))],["lower",new Qe(()=>new je(this.value.toLowerCase()))],["strip",new Qe(()=>new je(this.value.trim()))],["title",new Qe(()=>new je(Je(this.value)))],["length",new ie(this.value.length)],["rstrip",new Qe(()=>new je(this.value.trimEnd()))],["lstrip",new Qe(()=>new je(this.value.trimStart()))]]))}},st=class extends lt{constructor(){super(...arguments);Te(this,"type","BooleanValue")}},ze=class extends lt{constructor(){super(...arguments);Te(this,"type","ObjectValue");Te(this,"builtins",new Map([["get",new Qe(([re,V])=>{if(!(re instanceof je))throw new Error(`Object key must be a string: got ${re.type}`);return this.value.get(re.value)??V??new He})],["items",new Qe(()=>new Ce(Array.from(this.value.entries()).map(([re,V])=>new Ce([new je(re),V]))))]]))}__bool__(){return new st(this.value.size>0)}},we=class extends ze{constructor(){super(...arguments);Te(this,"type","KeywordArgumentsValue")}},Ce=class extends lt{constructor(){super(...arguments);Te(this,"type","ArrayValue");Te(this,"builtins",new Map([["length",new ie(this.value.length)]]))}__bool__(){return new st(this.value.length>0)}},Ze=class extends Ce{constructor(){super(...arguments);Te(this,"type","TupleValue")}},Qe=class extends lt{constructor(){super(...arguments);Te(this,"type","FunctionValue")}},He=class extends lt{constructor(){super(...arguments);Te(this,"type","NullValue")}},Be=class extends lt{constructor(){super(...arguments);Te(this,"type","UndefinedValue")}},nt=class{constructor(A){Te(this,"variables",new Map([["namespace",new Qe(A=>{if(A.length===0)return new ze(new Map);if(A.length!==1||!(A[0]instanceof ze))throw new Error("`namespace` expects either zero arguments or a single object argument");return A[0]})]]));Te(this,"tests",new Map([["boolean",A=>A.type==="BooleanValue"],["callable",A=>A instanceof Qe],["odd",A=>{if(A.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${A.type}`);return A.value%2!==0}],["even",A=>{if(A.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${A.type}`);return A.value%2===0}],["false",A=>A.type==="BooleanValue"&&!A.value],["true",A=>A.type==="BooleanValue"&&A.value],["none",A=>A.type==="NullValue"],["string",A=>A.type==="StringValue"],["number",A=>A.type==="NumericValue"],["integer",A=>A.type==="NumericValue"&&Number.isInteger(A.value)],["iterable",A=>A.type==="ArrayValue"||A.type==="StringValue"],["mapping",A=>A.type==="ObjectValue"],["lower",A=>{const re=A.value;return A.type==="StringValue"&&re===re.toLowerCase()}],["upper",A=>{const re=A.value;return A.type==="StringValue"&&re===re.toUpperCase()}],["none",A=>A.type==="NullValue"],["defined",A=>A.type!=="UndefinedValue"],["undefined",A=>A.type==="UndefinedValue"],["equalto",(A,re)=>A.value===re.value],["eq",(A,re)=>A.value===re.value]]));this.parent=A}set(A,re){return this.declareVariable(A,wt(re))}declareVariable(A,re){if(this.variables.has(A))throw new SyntaxError(`Variable already declared: ${A}`);return this.variables.set(A,re),re}setVariable(A,re){return this.variables.set(A,re),re}resolve(A){if(this.variables.has(A))return this;if(this.parent)return this.parent.resolve(A);throw new Error(`Unknown variable: ${A}`)}lookupVariable(A){try{return this.resolve(A).variables.get(A)??new Be}catch{return new Be}}},ut=class{constructor(A){Te(this,"global");this.global=A??new nt}run(A){return this.evaluate(A,this.global)}evaluateBinaryExpression(A,re){const V=this.evaluate(A.left,re);switch(A.operator.value){case"and":return V.__bool__().value?this.evaluate(A.right,re):V;case"or":return V.__bool__().value?V:this.evaluate(A.right,re)}const de=this.evaluate(A.right,re);switch(A.operator.value){case"==":return new st(V.value==de.value);case"!=":return new st(V.value!=de.value)}if(V instanceof Be||de instanceof Be)throw new Error("Cannot perform operation on undefined values");if(V instanceof He||de instanceof He)throw new Error("Cannot perform operation on null values");if(V instanceof ie&&de instanceof ie)switch(A.operator.value){case"+":return new ie(V.value+de.value);case"-":return new ie(V.value-de.value);case"*":return new ie(V.value*de.value);case"/":return new ie(V.value/de.value);case"%":return new ie(V.value%de.value);case"<":return new st(V.value":return new st(V.value>de.value);case">=":return new st(V.value>=de.value);case"<=":return new st(V.value<=de.value)}else if(V instanceof Ce&&de instanceof Ce)switch(A.operator.value){case"+":return new Ce(V.value.concat(de.value))}else if(de instanceof Ce){const ke=de.value.find(Ye=>Ye.value===V.value)!==void 0;switch(A.operator.value){case"in":return new st(ke);case"not in":return new st(!ke)}}if(V instanceof je||de instanceof je)switch(A.operator.value){case"+":return new je(V.value.toString()+de.value.toString())}if(V instanceof je&&de instanceof je)switch(A.operator.value){case"in":return new st(de.value.includes(V.value));case"not in":return new st(!de.value.includes(V.value))}if(V instanceof je&&de instanceof ze)switch(A.operator.value){case"in":return new st(de.value.has(V.value));case"not in":return new st(!de.value.has(V.value))}throw new SyntaxError(`Unknown operator "${A.operator.value}" between ${V.type} and ${de.type}`)}evaluateArguments(A,re){const V=[],de=new Map;for(const ke of A)if(ke.type==="KeywordArgumentExpression"){const Ye=ke;de.set(Ye.key.value,this.evaluate(Ye.value,re))}else{if(de.size>0)throw new Error("Positional arguments must come before keyword arguments");V.push(this.evaluate(ke,re))}return[V,de]}evaluateFilterExpression(A,re){const V=this.evaluate(A.operand,re);if(A.filter.type==="Identifier"){const de=A.filter;if(de.value==="tojson")return new je(ht(V));if(V instanceof Ce)switch(de.value){case"list":return V;case"first":return V.value[0];case"last":return V.value[V.value.length-1];case"length":return new ie(V.value.length);case"reverse":return new Ce(V.value.reverse());case"sort":return new Ce(V.value.sort((ke,Ye)=>{if(ke.type!==Ye.type)throw new Error(`Cannot compare different types: ${ke.type} and ${Ye.type}`);switch(ke.type){case"NumericValue":return ke.value-Ye.value;case"StringValue":return ke.value.localeCompare(Ye.value);default:throw new Error(`Cannot compare type: ${ke.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${de.value}`)}else if(V instanceof je)switch(de.value){case"length":return new ie(V.value.length);case"upper":return new je(V.value.toUpperCase());case"lower":return new je(V.value.toLowerCase());case"title":return new je(Je(V.value));case"capitalize":return new je(V.value.charAt(0).toUpperCase()+V.value.slice(1));case"trim":return new je(V.value.trim());case"indent":return new je(V.value.split(` `).map((ke,Ye)=>Ye===0||ke.length===0?ke:" "+ke).join(` `));case"string":return V;default:throw new Error(`Unknown StringValue filter: ${de.value}`)}else if(V instanceof ie)switch(de.value){case"abs":return new ie(Math.abs(V.value));default:throw new Error(`Unknown NumericValue filter: ${de.value}`)}else if(V instanceof ze)switch(de.value){case"items":return new Ce(Array.from(V.value.entries()).map(([ke,Ye])=>new Ce([new je(ke),Ye])));case"length":return new ie(V.value.size);default:throw new Error(`Unknown ObjectValue filter: ${de.value}`)}throw new Error(`Cannot apply filter "${de.value}" to type: ${V.type}`)}else if(A.filter.type==="CallExpression"){const de=A.filter;if(de.callee.type!=="Identifier")throw new Error(`Unknown filter: ${de.callee.type}`);const ke=de.callee.value;if(ke==="tojson"){const[,Ye]=this.evaluateArguments(de.args,re),ot=Ye.get("indent")??new He;if(!(ot instanceof ie||ot instanceof He))throw new Error("If set, indent must be a number");return new je(ht(V,ot.value))}if(V instanceof Ce){switch(ke){case"selectattr":case"rejectattr":{const Ye=ke==="selectattr";if(V.value.some(Pt=>!(Pt instanceof ze)))throw new Error(`\`${ke}\` can only be applied to array of objects`);if(de.args.some(Pt=>Pt.type!=="StringLiteral"))throw new Error(`arguments of \`${ke}\` must be strings`);const[ot,dt,$t]=de.args.map(Pt=>this.evaluate(Pt,re));let Et;if(dt){const Pt=re.tests.get(dt.value);if(!Pt)throw new Error(`Unknown test: ${dt.value}`);Et=Pt}else Et=(...Pt)=>Pt[0].__bool__().value;const Tt=V.value.filter(Pt=>{const ar=Pt.value.get(ot.value),Mr=ar?Et(ar,$t):!1;return Ye?Mr:!Mr});return new Ce(Tt)}case"map":{const[,Ye]=this.evaluateArguments(de.args,re);if(Ye.has("attribute")){const ot=Ye.get("attribute");if(!(ot instanceof je))throw new Error("attribute must be a string");const dt=Ye.get("default"),$t=V.value.map(Et=>{if(!(Et instanceof ze))throw new Error("items in map must be an object");return Et.value.get(ot.value)??dt??new Be});return new Ce($t)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${ke}`)}else if(V instanceof je){switch(ke){case"indent":{const[Ye,ot]=this.evaluateArguments(de.args,re),dt=Ye.at(0)??ot.get("width")??new ie(4);if(!(dt instanceof ie))throw new Error("width must be a number");const $t=Ye.at(1)??ot.get("first")??new st(!1),Et=Ye.at(2)??ot.get("blank")??new st(!1),Tt=V.value.split(` `),Pt=" ".repeat(dt.value),ar=Tt.map((Mr,Fr)=>!$t.value&&Fr===0||!Et.value&&Mr.length===0?Mr:Pt+Mr);return new je(ar.join(` `))}}throw new Error(`Unknown StringValue filter: ${ke}`)}else throw new Error(`Cannot apply filter "${ke}" to type: ${V.type}`)}throw new Error(`Unknown filter: ${A.filter.type}`)}evaluateTestExpression(A,re){const V=this.evaluate(A.operand,re),de=re.tests.get(A.test.value);if(!de)throw new Error(`Unknown test: ${A.test.value}`);const ke=de(V);return new st(A.negate?!ke:ke)}evaluateUnaryExpression(A,re){const V=this.evaluate(A.argument,re);switch(A.operator.value){case"not":return new st(!V.value);default:throw new SyntaxError(`Unknown operator: ${A.operator.value}`)}}evalProgram(A,re){return this.evaluateBlock(A.body,re)}evaluateBlock(A,re){let V="";for(const de of A){const ke=this.evaluate(de,re);ke.type!=="NullValue"&&ke.type!=="UndefinedValue"&&(V+=ke.value)}return new je(V)}evaluateIdentifier(A,re){return re.lookupVariable(A.value)}evaluateCallExpression(A,re){const[V,de]=this.evaluateArguments(A.args,re);de.size>0&&V.push(new we(de));const ke=this.evaluate(A.callee,re);if(ke.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${ke.type}`);return ke.value(V,re)}evaluateSliceExpression(A,re,V){if(!(A instanceof Ce||A instanceof je))throw new Error("Slice object must be an array or string");const de=this.evaluate(re.start,V),ke=this.evaluate(re.stop,V),Ye=this.evaluate(re.step,V);if(!(de instanceof ie||de instanceof Be))throw new Error("Slice start must be numeric or undefined");if(!(ke instanceof ie||ke instanceof Be))throw new Error("Slice stop must be numeric or undefined");if(!(Ye instanceof ie||Ye instanceof Be))throw new Error("Slice step must be numeric or undefined");return A instanceof Ce?new Ce(Ke(A.value,de.value,ke.value,Ye.value)):new je(Ke(Array.from(A.value),de.value,ke.value,Ye.value).join(""))}evaluateMemberExpression(A,re){const V=this.evaluate(A.object,re);let de;if(A.computed){if(A.property.type==="SliceExpression")return this.evaluateSliceExpression(V,A.property,re);de=this.evaluate(A.property,re)}else de=new je(A.property.value);let ke;if(V instanceof ze){if(!(de instanceof je))throw new Error(`Cannot access property with non-string: got ${de.type}`);ke=V.value.get(de.value)??V.builtins.get(de.value)}else if(V instanceof Ce||V instanceof je)if(de instanceof ie)ke=V.value.at(de.value),V instanceof je&&(ke=new je(V.value.at(de.value)));else if(de instanceof je)ke=V.builtins.get(de.value);else throw new Error(`Cannot access property with non-string/non-number: got ${de.type}`);else{if(!(de instanceof je))throw new Error(`Cannot access property with non-string: got ${de.type}`);ke=V.builtins.get(de.value)}return ke instanceof lt?ke:new Be}evaluateSet(A,re){const V=this.evaluate(A.value,re);if(A.assignee.type==="Identifier"){const de=A.assignee.value;re.setVariable(de,V)}else if(A.assignee.type==="MemberExpression"){const de=A.assignee,ke=this.evaluate(de.object,re);if(!(ke instanceof ze))throw new Error("Cannot assign to member of non-object");if(de.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");ke.value.set(de.property.value,V)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(A.assignee)}`);return new He}evaluateIf(A,re){const V=this.evaluate(A.test,re);return this.evaluateBlock(V.__bool__().value?A.body:A.alternate,re)}evaluateFor(A,re){const V=new nt(re);let de,ke;if(A.iterable.type==="SelectExpression"){const Et=A.iterable;ke=this.evaluate(Et.iterable,V),de=Et.test}else ke=this.evaluate(A.iterable,V);if(!(ke instanceof Ce))throw new Error(`Expected iterable type in for loop: got ${ke.type}`);const Ye=[],ot=[];for(let Et=0;EtMr.setVariable(A.loopvar.value,Pt);else if(A.loopvar.type==="TupleLiteral"){const Mr=A.loopvar;if(Pt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Pt.type}`);const Fr=Pt;if(Mr.value.length!==Fr.value.length)throw new Error(`Too ${Mr.value.length>Fr.value.length?"few":"many"} items to unpack`);ar=Br=>{for(let os=0;os0?Ye[Et-1]:new Be],["nextitem",Et{var ot;const ke=new nt(de);V=V.slice();let Ye;((ot=V.at(-1))==null?void 0:ot.type)==="KeywordArgumentsValue"&&(Ye=V.pop());for(let dt=0;dtthis.evaluate(V,re)));case"TupleLiteral":return new Ze(A.value.map(V=>this.evaluate(V,re)));case"ObjectLiteral":{const V=new Map;for(const[de,ke]of A.value){const Ye=this.evaluate(de,re);if(!(Ye instanceof je))throw new Error(`Object keys must be strings: got ${Ye.type}`);V.set(Ye.value,this.evaluate(ke,re))}return new ze(V)}case"Identifier":return this.evaluateIdentifier(A,re);case"CallExpression":return this.evaluateCallExpression(A,re);case"MemberExpression":return this.evaluateMemberExpression(A,re);case"UnaryExpression":return this.evaluateUnaryExpression(A,re);case"BinaryExpression":return this.evaluateBinaryExpression(A,re);case"FilterExpression":return this.evaluateFilterExpression(A,re);case"TestExpression":return this.evaluateTestExpression(A,re);default:throw new SyntaxError(`Unknown node type: ${A.type}`)}}};function wt(A){switch(typeof A){case"number":return new ie(A);case"string":return new je(A);case"boolean":return new st(A);case"undefined":return new Be;case"object":return A===null?new He:Array.isArray(A)?new Ce(A.map(wt)):new ze(new Map(Object.entries(A).map(([re,V])=>[re,wt(V)])));case"function":return new Qe((re,V)=>{const de=A(...re.map(ke=>ke.value))??null;return wt(de)});default:throw new Error(`Cannot convert to runtime value: ${A}`)}}function ht(A,re,V){const de=V??0;switch(A.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(A.value);case"ArrayValue":case"ObjectValue":{const ke=re?" ".repeat(re):"",Ye=` `+ke.repeat(de),ot=Ye+ke;if(A.type==="ArrayValue"){const dt=A.value.map($t=>ht($t,re,de+1));return re?`[${ot}${dt.join(`,${ot}`)}${Ye}]`:`[${dt.join(", ")}]`}else{const dt=Array.from(A.value.entries()).map(([$t,Et])=>{const Tt=`"${$t}": ${ht(Et,re,de+1)}`;return re?`${ot}${Tt}`:Tt});return re?`{${dt.join(",")}${Ye}}`:`{${dt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${A.type}`)}}var ft=class{constructor(A){Te(this,"parsed");const re=$(A,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=$e(re)}render(A){const re=new nt;re.set("false",!1),re.set("true",!0),re.set("raise_exception",ke=>{throw new Error(ke)}),re.set("range",Ne);for(const[ke,Ye]of Object.entries(A))re.set(ke,Ye);return new ut(re).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Oe,B,c)=>{c.r(B),c.d(B,{registerBackend:()=>H,resolveBackendAndExecutionProviders:()=>q});const w=new Map,R=[],H=(g,x,E)=>{if(x&&typeof x.init=="function"&&typeof x.createInferenceSessionHandler=="function"){const $=w.get(g);if($===void 0)w.set(g,{backend:x,priority:E});else{if($.priority>E)return;if($.priority===E&&$.backend!==x)throw new Error(`cannot register backend "${g}" using priority ${E}`)}if(E>=0){const P=R.indexOf(g);P!==-1&&R.splice(P,1);for(let Y=0;Y{const x=w.get(g);if(!x)return"backend not found.";if(x.initialized)return x.backend;if(x.aborted)return x.error;{const E=!!x.initPromise;try{return E||(x.initPromise=x.backend.init(g)),await x.initPromise,x.initialized=!0,x.backend}catch($){return E||(x.error=`${$}`,x.aborted=!0),x.error}finally{delete x.initPromise}}},q=async g=>{const x=g.executionProviders||[],E=x.map(le=>typeof le=="string"?le:le.name),$=E.length===0?R:E;let P;const Y=[],se=new Set;for(const le of $){const U=await J(le);typeof U=="string"?Y.push({name:le,err:U}):(P||(P=U),P===U&&se.add(le))}if(!P)throw new Error(`no available backend found. ERR: ${Y.map(le=>`[${le.name}] ${le.err}`).join(", ")}`);for(const{name:le,err:U}of Y)E.includes(le)&&console.warn(`removing requested execution provider "${le}" from session options because it is not available: ${U}`);const ue=x.filter(le=>se.has(typeof le=="string"?le:le.name));return[P,new Proxy(g,{get:(le,U)=>U==="executionProviders"?ue:Reflect.get(le,U)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Oe,B,c)=>{c.r(B),c.d(B,{registerBackend:()=>w.registerBackend});var w=c("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Oe,B,c)=>{c.r(B),c.d(B,{env:()=>H});var w=c("./node_modules/onnxruntime-common/dist/esm/version.js");let R="warning";const H={wasm:{},webgl:{},webgpu:{},versions:{common:w.version},set logLevel(J){if(J!==void 0){if(typeof J!="string"||["verbose","info","warning","error","fatal"].indexOf(J)===-1)throw new Error(`Unsupported logging level: ${J}`);R=J}},get logLevel(){return R}};Object.defineProperty(H,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Oe,B,c)=>{c.r(B),c.d(B,{env:()=>R});var w=c("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const R=w.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Oe,B,c)=>{c.r(B),c.d(B,{InferenceSession:()=>H.InferenceSession,TRACE:()=>q.TRACE,TRACE_FUNC_BEGIN:()=>q.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>q.TRACE_FUNC_END,Tensor:()=>J.Tensor,TrainingSession:()=>g.TrainingSession,env:()=>R.env,registerBackend:()=>w.registerBackend});var w=c("./node_modules/onnxruntime-common/dist/esm/backend.js"),R=c("./node_modules/onnxruntime-common/dist/esm/env.js"),H=c("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),J=c("./node_modules/onnxruntime-common/dist/esm/tensor.js");c("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),c("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var q=c("./node_modules/onnxruntime-common/dist/esm/trace.js");c("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),c("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var g=c("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Oe,B,c)=>{c.r(B),c.d(B,{InferenceSession:()=>J});var w=c("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),R=c("./node_modules/onnxruntime-common/dist/esm/tensor.js"),H=c("./node_modules/onnxruntime-common/dist/esm/trace.js");class J{constructor(g){this.handler=g}async run(g,x,E){(0,H.TRACE_FUNC_BEGIN)();const $={};let P={};if(typeof g!="object"||g===null||g instanceof R.Tensor||Array.isArray(g))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Y=!0;if(typeof x=="object"){if(x===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(x instanceof R.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(x)){if(x.length===0)throw new TypeError("'fetches' cannot be an empty array.");Y=!1;for(const le of x){if(typeof le!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(le)===-1)throw new RangeError(`'fetches' contains invalid output name: ${le}.`);$[le]=null}if(typeof E=="object"&&E!==null)P=E;else if(typeof E<"u")throw new TypeError("'options' must be an object.")}else{let le=!1;const U=Object.getOwnPropertyNames(x);for(const Q of this.outputNames)if(U.indexOf(Q)!==-1){const ne=x[Q];(ne===null||ne instanceof R.Tensor)&&(le=!0,Y=!1,$[Q]=ne)}if(le){if(typeof E=="object"&&E!==null)P=E;else if(typeof E<"u")throw new TypeError("'options' must be an object.")}else P=x}}else if(typeof x<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const le of this.inputNames)if(typeof g[le]>"u")throw new Error(`input '${le}' is missing in 'feeds'.`);if(Y)for(const le of this.outputNames)$[le]=null;const se=await this.handler.run(g,$,P),ue={};for(const le in se)if(Object.hasOwnProperty.call(se,le)){const U=se[le];U instanceof R.Tensor?ue[le]=U:ue[le]=new R.Tensor(U.type,U.data,U.dims)}return(0,H.TRACE_FUNC_END)(),ue}async release(){return this.handler.dispose()}static async create(g,x,E,$){(0,H.TRACE_FUNC_BEGIN)();let P,Y={};if(typeof g=="string"){if(P=g,typeof x=="object"&&x!==null)Y=x;else if(typeof x<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof Uint8Array){if(P=g,typeof x=="object"&&x!==null)Y=x;else if(typeof x<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&g instanceof SharedArrayBuffer){const U=g;let Q=0,ne=g.byteLength;if(typeof x=="object"&&x!==null)Y=x;else if(typeof x=="number"){if(Q=x,!Number.isSafeInteger(Q))throw new RangeError("'byteOffset' must be an integer.");if(Q<0||Q>=U.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${U.byteLength}).`);if(ne=g.byteLength-Q,typeof E=="number"){if(ne=E,!Number.isSafeInteger(ne))throw new RangeError("'byteLength' must be an integer.");if(ne<=0||Q+ne>U.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${U.byteLength-Q}].`);if(typeof $=="object"&&$!==null)Y=$;else if(typeof $<"u")throw new TypeError("'options' must be an object.")}else if(typeof E<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof x<"u")throw new TypeError("'options' must be an object.");P=new Uint8Array(U,Q,ne)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[se,ue]=await(0,w.resolveBackendAndExecutionProviders)(Y),le=await se.createInferenceSessionHandler(P,ue);return(0,H.TRACE_FUNC_END)(),new J(le)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(Oe,B,c)=>{c.r(B),c.d(B,{InferenceSession:()=>R});var w=c("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const R=w.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Oe,B,c)=>{c.r(B)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Oe,B,c)=>{c.r(B)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Oe,B,c)=>{c.r(B),c.d(B,{tensorToDataURL:()=>w,tensorToImageData:()=>R});const w=(H,J)=>{const q=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);q.width=H.dims[3],q.height=H.dims[2];const g=q.getContext("2d");if(g!=null){let x,E;(J==null?void 0:J.tensorLayout)!==void 0&&J.tensorLayout==="NHWC"?(x=H.dims[2],E=H.dims[3]):(x=H.dims[3],E=H.dims[2]);const $=(J==null?void 0:J.format)!==void 0?J.format:"RGB",P=J==null?void 0:J.norm;let Y,se;P===void 0||P.mean===void 0?Y=[255,255,255,255]:typeof P.mean=="number"?Y=[P.mean,P.mean,P.mean,P.mean]:(Y=[P.mean[0],P.mean[1],P.mean[2],0],P.mean[3]!==void 0&&(Y[3]=P.mean[3])),P===void 0||P.bias===void 0?se=[0,0,0,0]:typeof P.bias=="number"?se=[P.bias,P.bias,P.bias,P.bias]:(se=[P.bias[0],P.bias[1],P.bias[2],0],P.bias[3]!==void 0&&(se[3]=P.bias[3]));const ue=E*x;let le=0,U=ue,Q=ue*2,ne=-1;$==="RGBA"?(le=0,U=ue,Q=ue*2,ne=ue*3):$==="RGB"?(le=0,U=ue,Q=ue*2):$==="RBG"&&(le=0,Q=ue,U=ue*2);for(let N=0;N{const q=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let g;if(q!=null){let x,E,$;(J==null?void 0:J.tensorLayout)!==void 0&&J.tensorLayout==="NHWC"?(x=H.dims[2],E=H.dims[1],$=H.dims[3]):(x=H.dims[3],E=H.dims[2],$=H.dims[1]);const P=J!==void 0&&J.format!==void 0?J.format:"RGB",Y=J==null?void 0:J.norm;let se,ue;Y===void 0||Y.mean===void 0?se=[255,255,255,255]:typeof Y.mean=="number"?se=[Y.mean,Y.mean,Y.mean,Y.mean]:(se=[Y.mean[0],Y.mean[1],Y.mean[2],255],Y.mean[3]!==void 0&&(se[3]=Y.mean[3])),Y===void 0||Y.bias===void 0?ue=[0,0,0,0]:typeof Y.bias=="number"?ue=[Y.bias,Y.bias,Y.bias,Y.bias]:(ue=[Y.bias[0],Y.bias[1],Y.bias[2],0],Y.bias[3]!==void 0&&(ue[3]=Y.bias[3]));const le=E*x;if(J!==void 0&&(J.format!==void 0&&$===4&&J.format!=="RGBA"||$===3&&J.format!=="RGB"&&J.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const U=4;let Q=0,ne=1,N=2,O=3,_=0,k=le,C=le*2,Z=-1;P==="RGBA"?(_=0,k=le,C=le*2,Z=le*3):P==="RGB"?(_=0,k=le,C=le*2):P==="RBG"&&(_=0,C=le,k=le*2),g=q.createImageData(x,E);for(let ee=0;ee{c.r(B)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Oe,B,c)=>{c.r(B),c.d(B,{bufferToTensor:()=>R,tensorFromGpuBuffer:()=>q,tensorFromImage:()=>H,tensorFromMLTensor:()=>g,tensorFromPinnedBuffer:()=>x,tensorFromTexture:()=>J});var w=c("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const R=(E,$)=>{if(E===void 0)throw new Error("Image buffer must be defined");if($.height===void 0||$.width===void 0)throw new Error("Image height and width must be defined");if($.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:P,width:Y}=$,se=$.norm??{mean:255,bias:0};let ue,le;typeof se.mean=="number"?ue=[se.mean,se.mean,se.mean,se.mean]:ue=[se.mean[0],se.mean[1],se.mean[2],se.mean[3]??255],typeof se.bias=="number"?le=[se.bias,se.bias,se.bias,se.bias]:le=[se.bias[0],se.bias[1],se.bias[2],se.bias[3]??0];const U=$.format!==void 0?$.format:"RGBA",Q=$.tensorFormat!==void 0&&$.tensorFormat!==void 0?$.tensorFormat:"RGB",ne=P*Y,N=Q==="RGBA"?new Float32Array(ne*4):new Float32Array(ne*3);let O=4,_=0,k=1,C=2,Z=3,ee=0,_e=ne,ge=ne*2,be=-1;U==="RGB"&&(O=3,_=0,k=1,C=2,Z=-1),Q==="RGBA"?be=ne*3:Q==="RBG"?(ee=0,ge=ne,_e=ne*2):Q==="BGR"&&(ge=0,_e=ne,ee=ne*2);for(let Pe=0;Pe{const P=typeof HTMLImageElement<"u"&&E instanceof HTMLImageElement,Y=typeof ImageData<"u"&&E instanceof ImageData,se=typeof ImageBitmap<"u"&&E instanceof ImageBitmap,ue=typeof E=="string";let le,U=$??{};const Q=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},ne=N=>typeof HTMLCanvasElement<"u"&&N instanceof HTMLCanvasElement||N instanceof OffscreenCanvas?N.getContext("2d"):null;if(P){const N=Q();N.width=E.width,N.height=E.height;const O=ne(N);if(O!=null){let _=E.height,k=E.width;if($!==void 0&&$.resizedHeight!==void 0&&$.resizedWidth!==void 0&&(_=$.resizedHeight,k=$.resizedWidth),$!==void 0){if(U=$,$.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");U.tensorFormat="RGBA",U.height=_,U.width=k}else U.tensorFormat="RGBA",U.height=_,U.width=k;O.drawImage(E,0,0),le=O.getImageData(0,0,k,_).data}else throw new Error("Can not access image data")}else if(Y){let N,O;if($!==void 0&&$.resizedWidth!==void 0&&$.resizedHeight!==void 0?(N=$.resizedHeight,O=$.resizedWidth):(N=E.height,O=E.width),$!==void 0&&(U=$),U.format="RGBA",U.height=N,U.width=O,$!==void 0){const _=Q();_.width=O,_.height=N;const k=ne(_);if(k!=null)k.putImageData(E,0,0),le=k.getImageData(0,0,O,N).data;else throw new Error("Can not access image data")}else le=E.data}else if(se){if($===void 0)throw new Error("Please provide image config with format for Imagebitmap");const N=Q();N.width=E.width,N.height=E.height;const O=ne(N);if(O!=null){const _=E.height,k=E.width;return O.drawImage(E,0,0,k,_),le=O.getImageData(0,0,k,_).data,U.height=_,U.width=k,R(le,U)}else throw new Error("Can not access image data")}else{if(ue)return new Promise((N,O)=>{const _=Q(),k=ne(_);if(!E||!k)return O();const C=new Image;C.crossOrigin="Anonymous",C.src=E,C.onload=()=>{_.width=C.width,_.height=C.height,k.drawImage(C,0,0,_.width,_.height);const Z=k.getImageData(0,0,_.width,_.height);U.height=_.height,U.width=_.width,N(R(Z.data,U))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(le!==void 0)return R(le,U);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(E,$)=>{const{width:P,height:Y,download:se,dispose:ue}=$,le=[1,Y,P,4];return new w.Tensor({location:"texture",type:"float32",texture:E,dims:le,download:se,dispose:ue})},q=(E,$)=>{const{dataType:P,dims:Y,download:se,dispose:ue}=$;return new w.Tensor({location:"gpu-buffer",type:P??"float32",gpuBuffer:E,dims:Y,download:se,dispose:ue})},g=(E,$)=>{const{dataType:P,dims:Y,download:se,dispose:ue}=$;return new w.Tensor({location:"ml-tensor",type:P??"float32",mlTensor:E,dims:Y,download:se,dispose:ue})},x=(E,$,P)=>new w.Tensor({location:"cpu-pinned",type:E,data:$,dims:P??[$.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Oe,B,c)=>{c.r(B)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Oe,B,c)=>{c.r(B),c.d(B,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>R,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>w,checkTypedArray:()=>J});const w=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),R=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let H=!1;const J=()=>{if(!H){H=!0;const q=typeof BigInt64Array<"u"&&BigInt64Array.from,g=typeof BigUint64Array<"u"&&BigUint64Array.from,x=typeof Float16Array<"u"&&Float16Array.from;q&&(w.set("int64",BigInt64Array),R.set(BigInt64Array,"int64")),g&&(w.set("uint64",BigUint64Array),R.set(BigUint64Array,"uint64")),x?(w.set("float16",Float16Array),R.set(Float16Array,"float16")):w.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Oe,B,c)=>{c.r(B),c.d(B,{Tensor:()=>q});var w=c("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),R=c("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),H=c("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),J=c("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class q{constructor(x,E,$){(0,H.checkTypedArray)();let P,Y;if(typeof x=="object"&&"location"in x)switch(this.dataLocation=x.location,P=x.type,Y=x.dims,x.location){case"cpu-pinned":{const ue=H.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(P);if(!ue)throw new TypeError(`unsupported type "${P}" to create tensor from pinned buffer`);if(!(x.data instanceof ue))throw new TypeError(`buffer should be of type ${ue.name}`);this.cpuData=x.data;break}case"texture":{if(P!=="float32")throw new TypeError(`unsupported type "${P}" to create tensor from texture`);this.gpuTextureData=x.texture,this.downloader=x.download,this.disposer=x.dispose;break}case"gpu-buffer":{if(P!=="float32"&&P!=="float16"&&P!=="int32"&&P!=="int64"&&P!=="uint32"&&P!=="uint8"&&P!=="bool"&&P!=="uint4"&&P!=="int4")throw new TypeError(`unsupported type "${P}" to create tensor from gpu buffer`);this.gpuBufferData=x.gpuBuffer,this.downloader=x.download,this.disposer=x.dispose;break}case"ml-tensor":{if(P!=="float32"&&P!=="float16"&&P!=="int32"&&P!=="int64"&&P!=="uint32"&&P!=="uint64"&&P!=="int8"&&P!=="uint8"&&P!=="bool")throw new TypeError(`unsupported type "${P}" to create tensor from MLTensor`);this.mlTensorData=x.mlTensor,this.downloader=x.download,this.disposer=x.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ue,le;if(typeof x=="string")if(P=x,le=$,x==="string"){if(!Array.isArray(E))throw new TypeError("A string tensor's data must be a string array.");ue=E}else{const U=H.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(x);if(U===void 0)throw new TypeError(`Unsupported tensor type: ${x}.`);if(Array.isArray(E)){if(x==="float16"&&U===Uint16Array||x==="uint4"||x==="int4")throw new TypeError(`Creating a ${x} tensor from number array is not supported. Please use ${U.name} as data.`);x==="uint64"||x==="int64"?ue=U.from(E,BigInt):ue=U.from(E)}else if(E instanceof U)ue=E;else if(E instanceof Uint8ClampedArray)if(x==="uint8")ue=Uint8Array.from(E);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${P} tensor's data must be type of ${U}`)}else if(le=E,Array.isArray(x)){if(x.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const U=typeof x[0];if(U==="string")P="string",ue=x;else if(U==="boolean")P="bool",ue=Uint8Array.from(x);else throw new TypeError(`Invalid element type of data array: ${U}.`)}else if(x instanceof Uint8ClampedArray)P="uint8",ue=Uint8Array.from(x);else{const U=H.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(x.constructor);if(U===void 0)throw new TypeError(`Unsupported type for tensor data: ${x.constructor}.`);P=U,ue=x}if(le===void 0)le=[ue.length];else if(!Array.isArray(le))throw new TypeError("A tensor's dims must be a number array");Y=le,this.cpuData=ue,this.dataLocation="cpu"}const se=(0,J.calculateSize)(Y);if(this.cpuData&&se!==this.cpuData.length&&!((P==="uint4"||P==="int4")&&Math.ceil(se/2)===this.cpuData.length))throw new Error(`Tensor's size(${se}) does not match data length(${this.cpuData.length}).`);this.type=P,this.dims=Y,this.size=se}static async fromImage(x,E){return(0,R.tensorFromImage)(x,E)}static fromTexture(x,E){return(0,R.tensorFromTexture)(x,E)}static fromGpuBuffer(x,E){return(0,R.tensorFromGpuBuffer)(x,E)}static fromMLTensor(x,E){return(0,R.tensorFromMLTensor)(x,E)}static fromPinnedBuffer(x,E,$){return(0,R.tensorFromPinnedBuffer)(x,E,$)}toDataURL(x){return(0,w.tensorToDataURL)(this,x)}toImageData(x){return(0,w.tensorToImageData)(this,x)}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(x){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 E=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=E,x&&this.disposer&&(this.disposer(),this.disposer=void 0),E}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(x){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,J.tensorReshape)(this,x)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Oe,B,c)=>{c.r(B),c.d(B,{calculateSize:()=>R,tensorReshape:()=>H});var w=c("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const R=J=>{let q=1;for(let g=0;g{switch(J.location){case"cpu":return new w.Tensor(J.type,J.data,q);case"cpu-pinned":return new w.Tensor({location:"cpu-pinned",data:J.data,type:J.type,dims:q});case"texture":return new w.Tensor({location:"texture",texture:J.texture,type:J.type,dims:q});case"gpu-buffer":return new w.Tensor({location:"gpu-buffer",gpuBuffer:J.gpuBuffer,type:J.type,dims:q});case"ml-tensor":return new w.Tensor({location:"ml-tensor",mlTensor:J.mlTensor,type:J.type,dims:q});default:throw new Error(`tensorReshape: tensor location ${J.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Oe,B,c)=>{c.r(B),c.d(B,{Tensor:()=>R});var w=c("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const R=w.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Oe,B,c)=>{c.r(B),c.d(B,{TRACE:()=>R,TRACE_FUNC_BEGIN:()=>J,TRACE_FUNC_END:()=>q});var w=c("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const R=(g,x)=>{(typeof w.env.trace>"u"?!w.env.wasm.trace:!w.env.trace)||console.timeStamp(`${g}::ORT::${x}`)},H=(g,x)=>{var P;const E=((P=new Error().stack)==null?void 0:P.split(/\r\n|\r|\n/g))||[];let $=!1;for(let Y=0;Y{(typeof w.env.trace>"u"?!w.env.wasm.trace:!w.env.trace)||H("BEGIN",g)},q=g=>{(typeof w.env.trace>"u"?!w.env.wasm.trace:!w.env.trace)||H("END",g)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Oe,B,c)=>{c.r(B),c.d(B,{TrainingSession:()=>J});var w=c("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),R=c("./node_modules/onnxruntime-common/dist/esm/tensor.js");const H="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class J{constructor(g,x,E){this.handler=g,this.hasOptimizerModel=x,this.hasEvalModel=E}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,x){const E=g.evalModel||"",$=g.optimizerModel||"",P=x||{},[Y,se]=await(0,w.resolveBackendAndExecutionProviders)(P);if(Y.createTrainingSessionHandler){const ue=await Y.createTrainingSessionHandler(g.checkpointState,g.trainModel,E,$,se);return new J(ue,!!g.optimizerModel,!!g.evalModel)}else throw new Error(H)}typeNarrowingForRunStep(g,x,E,$,P){const Y={};let se={};if(typeof E!="object"||E===null||E instanceof R.Tensor||Array.isArray(E))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ue=!0;if(typeof $=="object"){if($===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if($ instanceof R.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray($)){if($.length===0)throw new TypeError("'fetches' cannot be an empty array.");ue=!1;for(const le of $){if(typeof le!="string")throw new TypeError("'fetches' must be a string array or an object.");if(x.indexOf(le)===-1)throw new RangeError(`'fetches' contains invalid output name: ${le}.`);Y[le]=null}if(typeof P=="object"&&P!==null)se=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else{let le=!1;const U=Object.getOwnPropertyNames($);for(const Q of x)if(U.indexOf(Q)!==-1){const ne=$[Q];(ne===null||ne instanceof R.Tensor)&&(le=!0,ue=!1,Y[Q]=ne)}if(le){if(typeof P=="object"&&P!==null)se=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else se=$}}else if(typeof $<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const le of g)if(typeof E[le]>"u")throw new Error(`input '${le}' is missing in 'feeds'.`);if(ue)for(const le of x)Y[le]=null;return[Y,se]}convertHandlerReturnTypeToMapOfTensors(g){const x={};for(const E in g)if(Object.hasOwnProperty.call(g,E)){const $=g[E];$ instanceof R.Tensor?x[E]=$:x[E]=new R.Tensor($.type,$.data,$.dims)}return x}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(g,x,E){const[$,P]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,g,x,E),Y=await this.handler.runTrainStep(g,$,P);return this.convertHandlerReturnTypeToMapOfTensors(Y)}async runOptimizerStep(g){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(g||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(g,x,E){if(this.hasEvalModel){const[$,P]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,g,x,E),Y=await this.handler.runEvalStep(g,$,P);return this.convertHandlerReturnTypeToMapOfTensors(Y)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(g=!0){return this.handler.getParametersSize(g)}async loadParametersBuffer(g,x=!0){const E=await this.getParametersSize(x);if(g.length!==4*E)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,x)}async getContiguousParameters(g=!0){return this.handler.getContiguousParameters(g)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Oe,B,c)=>{c.r(B),c.d(B,{TrainingSession:()=>R});var w=c("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const R=w.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Oe,B,c)=>{c.r(B),c.d(B,{version:()=>w});const w="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(Oe,B,c)=>{c.r(B),c.d(B,{InferenceSession:()=>ht,TRACE:()=>Ze,TRACE_FUNC_BEGIN:()=>He,TRACE_FUNC_END:()=>Be,Tensor:()=>we,TrainingSession:()=>dt,default:()=>ff,env:()=>C,registerBackend:()=>se});/*! * ONNX Runtime Web v1.20.1 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var w=Object.defineProperty,R=Object.getOwnPropertyDescriptor,H=Object.getOwnPropertyNames,J=Object.prototype.hasOwnProperty,q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),g=(e,t)=>()=>(e&&(t=e(e=0)),t),x=(e,t)=>{for(var r in t)w(e,r,{get:t[r],enumerable:!0})},E=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of H(t))!J.call(e,n)&&n!==r&&w(e,n,{get:()=>t[n],enumerable:!(s=R(t,n))||s.enumerable});return e},$=e=>E(w({},"__esModule",{value:!0}),e),P,Y,se,ue,le,U=g(()=>{P=new Map,Y=[],se=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let s=P.get(e);if(s===void 0)P.set(e,{backend:t,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=Y.indexOf(e);n!==-1&&Y.splice(n,1);for(let i=0;i{let t=P.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(s){return r||(t.error=`${s}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},le=async e=>{let t=e.executionProviders||[],r=t.map(p=>typeof p=="string"?p:p.name),s=r.length===0?Y:r,n,i=[],o=new Set;for(let p of s){let h=await ue(p);typeof h=="string"?i.push({name:p,err:h}):(n||(n=h),n===h&&o.add(p))}if(!n)throw new Error(`no available backend found. ERR: ${i.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of i)r.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let u=t.filter(p=>o.has(typeof p=="string"?p:p.name));return[n,new Proxy(e,{get:(p,h)=>h==="executionProviders"?u:Reflect.get(p,h)})]}}),Q=g(()=>{U()}),ne,N=g(()=>{ne="1.20.1"}),O,_,k=g(()=>{N(),O="warning",_={wasm:{},webgl:{},webgpu:{},versions:{common:ne},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}`);O=e}},get logLevel(){return O}},Object.defineProperty(_,"logLevel",{enumerable:!0})}),C,Z=g(()=>{k(),C=_}),ee,_e,ge=g(()=>{ee=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let s=r.getContext("2d");if(s!=null){let n,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],i=e.dims[3]):(n=e.dims[3],i=e.dims[2]);let o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",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 v=i*n,b=0,l=v,F=v*2,D=-1;o==="RGBA"?(b=0,l=v,F=v*2,D=v*3):o==="RGB"?(b=0,l=v,F=v*2):o==="RBG"&&(b=0,F=v,l=v*2);for(let z=0;z{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,i,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],i=e.dims[1],o=e.dims[3]):(n=e.dims[3],i=e.dims[2],o=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,v;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?v=[0,0,0,0]:typeof p.bias=="number"?v=[p.bias,p.bias,p.bias,p.bias]:(v=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(v[3]=p.bias[3]));let b=i*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,F=0,D=1,z=2,X=3,te=0,K=b,ce=b*2,ae=-1;u==="RGBA"?(te=0,K=b,ce=b*2,ae=b*3):u==="RGB"?(te=0,K=b,ce=b*2):u==="RBG"&&(te=0,ce=b,K=b*2),s=r.createImageData(n,i);for(let fe=0;fe{ze(),be=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=t,n=t.norm??{mean:255,bias:0},i,o;typeof n.mean=="number"?i=[n.mean,n.mean,n.mean,n.mean]:i=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*s,v=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),b=4,l=0,F=1,D=2,z=3,X=0,te=h,K=h*2,ce=-1;u==="RGB"&&(b=3,l=0,F=1,D=2,z=-1),p==="RGBA"?ce=h*3:p==="RBG"?(X=0,K=h,te=h*2):p==="BGR"&&(K=0,te=h,X=h*2);for(let ae=0;ae{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",o,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=v=>typeof HTMLCanvasElement<"u"&&v instanceof HTMLCanvasElement||v instanceof OffscreenCanvas?v.getContext("2d"):null;if(r){let v=p();v.width=e.width,v.height=e.height;let b=h(v);if(b!=null){let l=e.height,F=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,F=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=l,u.width=F}else u.tensorFormat="RGBA",u.height=l,u.width=F;b.drawImage(e,0,0),o=b.getImageData(0,0,F,l).data}else throw new Error("Can not access image data")}else if(s){let v,b;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(v=t.resizedHeight,b=t.resizedWidth):(v=e.height,b=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=v,u.width=b,t!==void 0){let l=p();l.width=b,l.height=v;let F=h(l);if(F!=null)F.putImageData(e,0,0),o=F.getImageData(0,0,b,v).data;else throw new Error("Can not access image data")}else o=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let v=p();v.width=e.width,v.height=e.height;let b=h(v);if(b!=null){let l=e.height,F=e.width;return b.drawImage(e,0,0,F,l),o=b.getImageData(0,0,F,l).data,u.height=l,u.width=F,be(o,u)}else throw new Error("Can not access image data")}else{if(i)return new Promise((v,b)=>{let l=p(),F=h(l);if(!e||!F)return b();let D=new Image;D.crossOrigin="Anonymous",D.src=e,D.onload=()=>{l.width=D.width,l.height=D.height,F.drawImage(D,0,0,l.width,l.height);let z=F.getImageData(0,0,l.width,l.height);u.height=l.height,u.width=l.width,v(be(z.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return be(o,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Pe=(e,t)=>{let{width:r,height:s,download:n,dispose:i}=t,o=[1,s,r,4];return new st({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:i})},Le=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:i}=t;return new st({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:i})},me=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:i}=t;return new st({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:i})},j=(e,t,r)=>new st({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),pe,$e,Ne,Ke,Je=g(()=>{pe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),$e=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ne=!1,Ke=()=>{if(!Ne){Ne=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(pe.set("int64",BigInt64Array),$e.set(BigInt64Array,"int64")),t&&(pe.set("uint64",BigUint64Array),$e.set(BigUint64Array,"uint64")),r?(pe.set("float16",Float16Array),$e.set(Float16Array,"float16")):pe.set("float16",Uint16Array)}}}),lt,ie,je=g(()=>{ze(),lt=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new st(e.type,e.data,t);case"cpu-pinned":return new st({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new st({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new st({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new st({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),st,ze=g(()=>{ge(),he(),Je(),je(),st=class{constructor(e,t,r){Ke();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let o=pe.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,u;if(typeof e=="string")if(s=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let p=pe.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?o=p.from(t,BigInt):o=p.from(t)}else if(t instanceof p)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${s} tensor's data must be type of ${p}`)}else if(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")s="string",o=e;else if(p==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let p=$e.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=p,o=e}if(u===void 0)u=[o.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");n=u,this.cpuData=o,this.dataLocation="cpu"}let i=lt(n);if(this.cpuData&&i!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=i}static async fromImage(e,t){return Se(e,t)}static fromTexture(e,t){return Pe(e,t)}static fromGpuBuffer(e,t){return Le(e,t)}static fromMLTensor(e,t){return me(e,t)}static fromPinnedBuffer(e,t,r){return j(e,t,r)}toDataURL(e){return ee(this,e)}toImageData(e){return _e(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 ie(this,e)}}}),we,Ce=g(()=>{ze(),we=st}),Ze,Qe,He,Be,nt=g(()=>{k(),Ze=(e,t)=>{(typeof _.trace>"u"?!_.wasm.trace:!_.trace)||console.timeStamp(`${e}::ORT::${t}`)},Qe=(e,t)=>{var n;let r=((n=new Error().stack)==null?void 0:n.split(/\r\n|\r|\n/g))||[],s=!1;for(let i=0;i{(typeof _.trace>"u"?!_.wasm.trace:!_.trace)||Qe("BEGIN",e)},Be=e=>{(typeof _.trace>"u"?!_.wasm.trace:!_.trace)||Qe("END",e)}}),ut,wt=g(()=>{U(),Ce(),nt(),ut=class Wm{constructor(t){this.handler=t}async run(t,r,s){He();let n={},i={};if(typeof t!="object"||t===null||t instanceof we||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof we)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let h of r){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);n[h]=null}if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,v=Object.getOwnPropertyNames(r);for(let b of this.outputNames)if(v.indexOf(b)!==-1){let l=r[b];(l===null||l instanceof we)&&(h=!0,o=!1,n[b]=l)}if(h){if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else i=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(o)for(let h of this.outputNames)n[h]=null;let u=await this.handler.run(t,n,i),p={};for(let h in u)if(Object.hasOwnProperty.call(u,h)){let v=u[h];v instanceof we?p[h]=v:p[h]=new we(v.type,v.data,v.dims)}return Be(),p}async release(){return this.handler.dispose()}static async create(t,r,s,n){He();let i,o={};if(typeof t=="string"){if(i=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let v=t,b=0,l=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(b=r,!Number.isSafeInteger(b))throw new RangeError("'byteOffset' must be an integer.");if(b<0||b>=v.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${v.byteLength}).`);if(l=t.byteLength-b,typeof s=="number"){if(l=s,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||b+l>v.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${v.byteLength-b}].`);if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(v,b,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,p]=await le(o),h=await u.createInferenceSessionHandler(i,p);return Be(),new Wm(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),ht,ft=g(()=>{wt(),ht=ut}),A=g(()=>{}),re=g(()=>{}),V=g(()=>{}),de=g(()=>{}),ke,Ye,ot=g(()=>{U(),Ce(),ke="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Ye=class Gm{constructor(t,r,s){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=s}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let s=t.evalModel||"",n=t.optimizerModel||"",i=r||{},[o,u]=await le(i);if(o.createTrainingSessionHandler){let p=await o.createTrainingSessionHandler(t.checkpointState,t.trainModel,s,n,u);return new Gm(p,!!t.optimizerModel,!!t.evalModel)}else throw new Error(ke)}typeNarrowingForRunStep(t,r,s,n,i){let o={},u={};if(typeof s!="object"||s===null||s instanceof we||Array.isArray(s))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let p=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof we)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");p=!1;for(let h of n){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);o[h]=null}if(typeof i=="object"&&i!==null)u=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,v=Object.getOwnPropertyNames(n);for(let b of r)if(v.indexOf(b)!==-1){let l=n[b];(l===null||l instanceof we)&&(h=!0,p=!1,o[b]=l)}if(h){if(typeof i=="object"&&i!==null)u=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else u=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of t)if(typeof s[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(p)for(let h of r)o[h]=null;return[o,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let s in t)if(Object.hasOwnProperty.call(t,s)){let n=t[s];n instanceof we?r[s]=n:r[s]=new we(n.type,n.data,n.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,s){let[n,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,s),o=await this.handler.runTrainStep(t,n,i);return this.convertHandlerReturnTypeToMapOfTensors(o)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,s){if(this.hasEvalModel){let[n,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,s),o=await this.handler.runEvalStep(t,n,i);return this.convertHandlerReturnTypeToMapOfTensors(o)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let s=await this.getParametersSize(r);if(t.length!==4*s)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),dt,$t=g(()=>{ot(),dt=Ye}),Et={};x(Et,{InferenceSession:()=>ht,TRACE:()=>Ze,TRACE_FUNC_BEGIN:()=>He,TRACE_FUNC_END:()=>Be,Tensor:()=>we,TrainingSession:()=>dt,env:()=>C,registerBackend:()=>se});var Tt=g(()=>{Q(),Z(),ft(),Ce(),A(),re(),nt(),V(),de(),$t()}),Pt=g(()=>{}),ar={};x(ar,{default:()=>Br});var Mr,Fr,Br,os=g(()=>{var e;ph(),cs(),Rs(),Mr="ort-wasm-proxy-worker",Fr=((e=globalThis.self)==null?void 0:e.name)===Mr,Fr&&(self.onmessage=t=>{let{type:r,in:s}=t.data;try{switch(r){case"init-wasm":js(s.wasm).then(()=>{$p(s).then(()=>{postMessage({type:r})},n=>{postMessage({type:r,err:n})})},n=>{postMessage({type:r,err:n})});break;case"init-ep":{let{epName:n,env:i}=s;kp(i,n).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:n}=s,i=np(n);postMessage({type:r,out:i});break}case"create":{let{model:n,options:i}=s;Ap(n,i).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":Ip(s),postMessage({type:r});break;case"run":{let{sessionId:n,inputIndices:i,inputs:o,outputIndices:u,options:p}=s;Op(n,i,o,u,new Array(u.length).fill(null),p).then(h=>{h.some(v=>v[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:h},Lp([...o,...h]))},h=>{postMessage({type:r,err:h})});break}case"end-profiling":Dp(s),postMessage({type:r});break;default:}}catch(n){postMessage({type:r,err:n})}}),Br=Fr?null:t=>new Worker(t??Ts,{type:"module",name:Mr})}),Qs={};x(Qs,{default:()=>Is});var Xs,zs,Is,Nt=g(()=>{var e;zs=(Xs=self.location.href,async function(t={}){function r(){return nr.buffer!=Vt.buffer&&ns(),Vt}function s(){return nr.buffer!=Vt.buffer&&ns(),pr}function n(){return nr.buffer!=Vt.buffer&&ns(),We}function i(){return nr.buffer!=Vt.buffer&&ns(),ct}function o(){return nr.buffer!=Vt.buffer&&ns(),Gt}function u(){return nr.buffer!=Vt.buffer&&ns(),Tr}function p(){return nr.buffer!=Vt.buffer&&ns(),Kr}function h(){return nr.buffer!=Vt.buffer&&ns(),ap}var v,b,l=Object.assign({},t),F=new Promise((a,m)=>{v=a,b=m}),D=typeof window=="object",z=typeof importScripts=="function",X=z&&self.name=="em-pthread";l.mountExternalData=(a,m)=>{a.startsWith("./")&&(a=a.substring(2)),(l.Fb||(l.Fb=new Map)).set(a,m)},l.unmountExternalData=()=>{delete l.Fb};var te=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let K=()=>{let a=(T,I,W)=>(...ye)=>{let Ge=wn,rt=I==null?void 0:I();ye=T(...ye);let yt=I==null?void 0:I();return rt!==yt&&(T=yt,W(rt),I=W=null),wn!=Ge?new Promise((xt,jt)=>{rh={resolve:xt,reject:jt}}):ye},m=T=>async(...I)=>{var W;try{if(l.Eb)throw Error("Session already started");let ye=l.Eb={fc:I[0],errors:[]},Ge=await T(...I);if(l.Eb!==ye)throw Error("Session mismatch");(W=l.Gb)==null||W.flush();let rt=ye.errors;if(0xt),0l._OrtCreateSession,T=>l._OrtCreateSession=T),l._OrtRun=m(a(l._OrtRun,()=>l._OrtRun,T=>l._OrtRun=T)),l._OrtRunWithBinding=m(a(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,T=>l._OrtRunWithBinding=T)),l._OrtBindInput=a(l._OrtBindInput,()=>l._OrtBindInput,T=>l._OrtBindInput=T),K=void 0};l.jsepInit=(a,m)=>{if(K==null||K(),a==="webgpu"){[l.Gb,l.Ub,l.Yb,l.Nb,l.Xb,l.jb,l.Zb,l.bc,l.Vb,l.Wb,l.$b]=m;let T=l.Gb;l.jsepRegisterBuffer=(I,W,ye,Ge)=>T.registerBuffer(I,W,ye,Ge),l.jsepGetBuffer=I=>T.getBuffer(I),l.jsepCreateDownloader=(I,W,ye)=>T.createDownloader(I,W,ye),l.jsepOnReleaseSession=I=>{T.onReleaseSession(I)},l.jsepOnRunStart=I=>T.onRunStart(I),l.cc=(I,W)=>{T.upload(I,W)}}else if(a==="webnn"){[l.Gb,l.ac,l.Ob,l.jsepEnsureTensor,l.dc,l.jsepDownloadTensor]=m,l.jsepReleaseTensorId=l.Ob;let T=l.Gb;l.jsepOnRunStart=I=>T.onRunStart(I),l.jsepRegisterMLContext=(I,W)=>{T.registerMLContext(I,W)},l.jsepOnReleaseSession=I=>{T.onReleaseSession(I)},l.jsepCreateMLTensorDownloader=(I,W)=>T.createMLTensorDownloader(I,W),l.jsepRegisterMLTensor=(I,W,ye)=>T.registerMLTensor(I,W,ye)}};var ce,ae,fe=Object.assign({},l),Ue="./this.program",Ie=(a,m)=>{throw m},tt="";(D||z)&&(z?tt=self.location.href:typeof document<"u"&&document.currentScript&&(tt=document.currentScript.src),Xs&&(tt=Xs),tt=tt.startsWith("blob:")?"":tt.substr(0,tt.replace(/[?#].*/,"").lastIndexOf("/")+1),z&&(ae=a=>{var m=new XMLHttpRequest;return m.open("GET",a,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),ce=(a,m,T)=>{var I=new XMLHttpRequest;I.open("GET",a,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?m(I.response):T()},I.onerror=T,I.send(null)});var Mt,St=console.log.bind(console),Zt=console.error.bind(console),tr=St,zt=Zt;if(Object.assign(l,fe),fe=null,X){let a=function(m){try{var T=m.data,I=T.cmd;if(I==="load"){let W=[];self.onmessage=ye=>W.push(ye),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ye of W)a(ye);self.onmessage=a};for(let ye of T.handlers)l[ye]&&!l[ye].proxy||(l[ye]=(...Ge)=>{postMessage({Mb:"callHandler",oc:ye,args:Ge})},ye=="print"&&(tr=l[ye]),ye=="printErr"&&(zt=l[ye]));nr=T.wasmMemory,ns(),vr(T.wasmModule)}else if(I==="run"){ih(T.pthread_ptr,0,0,1,0,0),Zp(T.pthread_ptr),wf(),Dh(),Ar||(Im(),Ar=!0);try{yf(T.start_routine,T.arg)}catch(W){if(W!="unwind")throw W}}else I==="cancel"?za()&&yp(-1):T.target!=="setimmediate"&&(I==="checkMailbox"?Ar&&dp():I&&(zt(`worker: received unknown command ${I}`),zt(T)))}catch(W){throw Fm(),W}};var vr,Ar=!1;zt=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Mb:"alert",text:m.join(" "),qc:za()})},l.instantiateWasm=(m,T)=>new Promise(I=>{vr=W=>{W=new WebAssembly.Instance(W,kh()),T(W),I()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=a}l.wasmBinary&&(Mt=l.wasmBinary);var nr,Er,Ft,Vt,pr,We,ct,Gt,Tr,Kr,Xr,no,ap,bs=!1;function ns(){var a=nr.buffer;l.HEAP8=Vt=new Int8Array(a),l.HEAP16=We=new Int16Array(a),l.HEAPU8=pr=new Uint8Array(a),l.HEAPU16=ct=new Uint16Array(a),l.HEAP32=Gt=new Int32Array(a),l.HEAPU32=Tr=new Uint32Array(a),l.HEAPF32=Kr=new Float32Array(a),l.HEAPF64=ap=new Float64Array(a),l.HEAP64=Xr=new BigInt64Array(a),l.HEAPU64=no=new BigUint64Array(a)}if(!X){if(!((nr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof te))throw zt("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");ns()}var Vo=[],es=[],ls=[],Gs=0,oo=null;function lp(){if(--Gs==0&&oo){var a=oo;oo=null,a()}}function Oa(a){throw zt(a="Aborted("+a+")"),bs=!0,Ft=1,a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info."),b(a),a}var Np,Ph=a=>a.startsWith("data:application/octet-stream;base64,"),Ch=a=>a.startsWith("file://");function Sh(a){if(a==Np&&Mt)return new Uint8Array(Mt);if(ae)return ae(a);throw"both async and sync fetching of the wasm failed"}function $h(a,m,T){return function(I){if(!Mt&&(D||z)){if(typeof fetch=="function"&&!Ch(I))return fetch(I,{credentials:"same-origin"}).then(W=>{if(!W.ok)throw`failed to load wasm binary file at '${I}'`;return W.arrayBuffer()}).catch(()=>Sh(I));if(ce)return new Promise((W,ye)=>{ce(I,Ge=>W(new Uint8Array(Ge)),ye)})}return Promise.resolve().then(()=>Sh(I))}(a).then(I=>WebAssembly.instantiate(I,m)).then(T,I=>{zt(`failed to asynchronously prepare wasm: ${I}`),Oa(I)})}function kh(){return{a:{O:gf,Aa:_f,b:bf,aa:Rh,B:Uh,qa:Vh,Y:Gh,_:Kh,ra:Hh,oa:qh,ha:Qh,na:Xh,L:Yh,Z:Jh,W:Zh,pa:em,X:tm,wa:vf,F:Tf,Q:xf,P:Pf,E:Sf,u:$f,q:kf,G:Af,A:Bf,R:Rf,ua:jf,ka:Nf,U:Uf,ba:Vf,H:Wf,ja:Zp,ta:Gf,t:Kf,x:Qf,o:Xf,l:Jf,c:Yp,n:Zf,j:r_,w:s_,p:n_,g:o_,s:i_,m:a_,e:l_,k:u_,i:d_,h:c_,d:p_,ea:h_,fa:m_,ga:f_,ca:fm,da:_m,T:__,f:g_,D:w_,I:y_,M:M_,y:b_,sa:v_,V:T_,v:wm,z:x_,N:E_,S:P_,za:C_,ya:S_,la:bm,ma:vm,$:Kp,C:Tm,K:xm,ia:Em,J:Pm,a:nr,xa:Gp,va:$m,r:A_}}}var Up={868340:(a,m,T,I,W)=>{if(l===void 0||!l.Fb)return 1;if((a=is(a>>>0)).startsWith("./")&&(a=a.substring(2)),!(a=l.Fb.get(a)))return 2;if(I>>>=0,(m>>>=0)+(T>>>=0)>a.byteLength)return 3;try{let ye=a.subarray(m,m+T);switch(W){case 0:s().set(ye,I>>>0);break;case 1:l.cc(I,ye);break;default:return 4}return 0}catch{return 4}},869023:(a,m,T)=>{l.dc(a,s().subarray(m>>>0,m+T>>>0))},869086:()=>l.ac(),869127:a=>{l.Ob(a)},869163:()=>{l.Vb()},869194:()=>{l.Wb()},869223:()=>{l.$b()},869248:a=>l.Ub(a),869281:a=>l.Yb(a),869313:(a,m,T)=>{l.Nb(a,m,T,!0)},869352:(a,m,T)=>{l.Nb(a,m,T)},869385:()=>typeof wasmOffsetConverter<"u",869442:a=>{l.jb("Abs",a,void 0)},869493:a=>{l.jb("Neg",a,void 0)},869544:a=>{l.jb("Floor",a,void 0)},869597:a=>{l.jb("Ceil",a,void 0)},869649:a=>{l.jb("Reciprocal",a,void 0)},869707:a=>{l.jb("Sqrt",a,void 0)},869759:a=>{l.jb("Exp",a,void 0)},869810:a=>{l.jb("Erf",a,void 0)},869861:a=>{l.jb("Sigmoid",a,void 0)},869916:(a,m,T)=>{l.jb("HardSigmoid",a,{alpha:m,beta:T})},869995:a=>{l.jb("Log",a,void 0)},870046:a=>{l.jb("Sin",a,void 0)},870097:a=>{l.jb("Cos",a,void 0)},870148:a=>{l.jb("Tan",a,void 0)},870199:a=>{l.jb("Asin",a,void 0)},870251:a=>{l.jb("Acos",a,void 0)},870303:a=>{l.jb("Atan",a,void 0)},870355:a=>{l.jb("Sinh",a,void 0)},870407:a=>{l.jb("Cosh",a,void 0)},870459:a=>{l.jb("Asinh",a,void 0)},870512:a=>{l.jb("Acosh",a,void 0)},870565:a=>{l.jb("Atanh",a,void 0)},870618:a=>{l.jb("Tanh",a,void 0)},870670:a=>{l.jb("Not",a,void 0)},870721:(a,m,T)=>{l.jb("Clip",a,{min:m,max:T})},870790:a=>{l.jb("Clip",a,void 0)},870842:(a,m)=>{l.jb("Elu",a,{alpha:m})},870900:a=>{l.jb("Gelu",a,void 0)},870952:a=>{l.jb("Relu",a,void 0)},871004:(a,m)=>{l.jb("LeakyRelu",a,{alpha:m})},871068:(a,m)=>{l.jb("ThresholdedRelu",a,{alpha:m})},871138:(a,m)=>{l.jb("Cast",a,{to:m})},871196:a=>{l.jb("Add",a,void 0)},871247:a=>{l.jb("Sub",a,void 0)},871298:a=>{l.jb("Mul",a,void 0)},871349:a=>{l.jb("Div",a,void 0)},871400:a=>{l.jb("Pow",a,void 0)},871451:a=>{l.jb("Equal",a,void 0)},871504:a=>{l.jb("Greater",a,void 0)},871559:a=>{l.jb("GreaterOrEqual",a,void 0)},871621:a=>{l.jb("Less",a,void 0)},871673:a=>{l.jb("LessOrEqual",a,void 0)},871732:(a,m,T,I,W)=>{l.jb("ReduceMean",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},871891:(a,m,T,I,W)=>{l.jb("ReduceMax",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},872049:(a,m,T,I,W)=>{l.jb("ReduceMin",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},872207:(a,m,T,I,W)=>{l.jb("ReduceProd",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},872366:(a,m,T,I,W)=>{l.jb("ReduceSum",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},872524:(a,m,T,I,W)=>{l.jb("ReduceL1",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},872681:(a,m,T,I,W)=>{l.jb("ReduceL2",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},872838:(a,m,T,I,W)=>{l.jb("ReduceLogSum",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},872999:(a,m,T,I,W)=>{l.jb("ReduceSumSquare",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},873163:(a,m,T,I,W)=>{l.jb("ReduceLogSumExp",a,{keepDims:!!m,noopWithEmptyAxes:!!T,axes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},873327:a=>{l.jb("Where",a,void 0)},873380:(a,m,T)=>{l.jb("Transpose",a,{perm:m?Array.from(o().subarray(m>>>0,T>>>0)):[]})},873488:(a,m,T,I)=>{l.jb("DepthToSpace",a,{blocksize:m,mode:is(T),format:I?"NHWC":"NCHW"})},873621:(a,m,T,I)=>{l.jb("DepthToSpace",a,{blocksize:m,mode:is(T),format:I?"NHWC":"NCHW"})},873754:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re,dr)=>{l.jb("ConvTranspose",a,{format:yt?"NHWC":"NCHW",autoPad:m,dilations:[T],group:I,kernelShape:[W],pads:[ye,Ge],strides:[rt],wIsConst:()=>!!r()[xt>>>0],outputPadding:jt?Array.from(o().subarray(jt>>>0,hr>>>0)):[],outputShape:Pr?Array.from(o().subarray(Pr>>>0,Re>>>0)):[],activation:is(dr)})},874155:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re)=>{l.jb("ConvTranspose",a,{format:rt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(T>>>0,2+(T>>>0)>>>0)),group:I,kernelShape:Array.from(o().subarray(W>>>0,2+(W>>>0)>>>0)),pads:Array.from(o().subarray(ye>>>0,4+(ye>>>0)>>>0)),strides:Array.from(o().subarray(Ge>>>0,2+(Ge>>>0)>>>0)),wIsConst:()=>!!r()[yt>>>0],outputPadding:xt?Array.from(o().subarray(xt>>>0,jt>>>0)):[],outputShape:hr?Array.from(o().subarray(hr>>>0,Pr>>>0)):[],activation:is(Re)})},874720:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re,dr)=>{l.jb("ConvTranspose",a,{format:yt?"NHWC":"NCHW",autoPad:m,dilations:[T],group:I,kernelShape:[W],pads:[ye,Ge],strides:[rt],wIsConst:()=>!!r()[xt>>>0],outputPadding:jt?Array.from(o().subarray(jt>>>0,hr>>>0)):[],outputShape:Pr?Array.from(o().subarray(Pr>>>0,Re>>>0)):[],activation:is(dr)})},875121:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re)=>{l.jb("ConvTranspose",a,{format:rt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(T>>>0,2+(T>>>0)>>>0)),group:I,kernelShape:Array.from(o().subarray(W>>>0,2+(W>>>0)>>>0)),pads:Array.from(o().subarray(ye>>>0,4+(ye>>>0)>>>0)),strides:Array.from(o().subarray(Ge>>>0,2+(Ge>>>0)>>>0)),wIsConst:()=>!!r()[yt>>>0],outputPadding:xt?Array.from(o().subarray(xt>>>0,jt>>>0)):[],outputShape:hr?Array.from(o().subarray(hr>>>0,Pr>>>0)):[],activation:is(Re)})},875686:(a,m)=>{l.jb("GlobalAveragePool",a,{format:m?"NHWC":"NCHW"})},875777:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re)=>{l.jb("AveragePool",a,{format:Re?"NHWC":"NCHW",auto_pad:m,ceil_mode:T,count_include_pad:I,storage_order:W,dilations:ye?Array.from(o().subarray(ye>>>0,Ge>>>0)):[],kernel_shape:rt?Array.from(o().subarray(rt>>>0,yt>>>0)):[],pads:xt?Array.from(o().subarray(xt>>>0,jt>>>0)):[],strides:hr?Array.from(o().subarray(hr>>>0,Pr>>>0)):[]})},876192:(a,m)=>{l.jb("GlobalAveragePool",a,{format:m?"NHWC":"NCHW"})},876283:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re)=>{l.jb("AveragePool",a,{format:Re?"NHWC":"NCHW",auto_pad:m,ceil_mode:T,count_include_pad:I,storage_order:W,dilations:ye?Array.from(o().subarray(ye>>>0,Ge>>>0)):[],kernel_shape:rt?Array.from(o().subarray(rt>>>0,yt>>>0)):[],pads:xt?Array.from(o().subarray(xt>>>0,jt>>>0)):[],strides:hr?Array.from(o().subarray(hr>>>0,Pr>>>0)):[]})},876698:(a,m)=>{l.jb("GlobalMaxPool",a,{format:m?"NHWC":"NCHW"})},876785:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re)=>{l.jb("MaxPool",a,{format:Re?"NHWC":"NCHW",auto_pad:m,ceil_mode:T,count_include_pad:I,storage_order:W,dilations:ye?Array.from(o().subarray(ye>>>0,Ge>>>0)):[],kernel_shape:rt?Array.from(o().subarray(rt>>>0,yt>>>0)):[],pads:xt?Array.from(o().subarray(xt>>>0,jt>>>0)):[],strides:hr?Array.from(o().subarray(hr>>>0,Pr>>>0)):[]})},877196:(a,m)=>{l.jb("GlobalMaxPool",a,{format:m?"NHWC":"NCHW"})},877283:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re)=>{l.jb("MaxPool",a,{format:Re?"NHWC":"NCHW",auto_pad:m,ceil_mode:T,count_include_pad:I,storage_order:W,dilations:ye?Array.from(o().subarray(ye>>>0,Ge>>>0)):[],kernel_shape:rt?Array.from(o().subarray(rt>>>0,yt>>>0)):[],pads:xt?Array.from(o().subarray(xt>>>0,jt>>>0)):[],strides:hr?Array.from(o().subarray(hr>>>0,Pr>>>0)):[]})},877694:(a,m,T,I,W)=>{l.jb("Gemm",a,{alpha:m,beta:T,transA:I,transB:W})},877798:a=>{l.jb("MatMul",a,void 0)},877852:(a,m,T,I)=>{l.jb("ArgMax",a,{keepDims:!!m,selectLastIndex:!!T,axis:I})},877960:(a,m,T,I)=>{l.jb("ArgMin",a,{keepDims:!!m,selectLastIndex:!!T,axis:I})},878068:(a,m)=>{l.jb("Softmax",a,{axis:m})},878131:(a,m)=>{l.jb("Concat",a,{axis:m})},878191:(a,m,T,I,W)=>{l.jb("Split",a,{axis:m,numOutputs:T,splitSizes:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},878331:a=>{l.jb("Expand",a,void 0)},878385:(a,m)=>{l.jb("Gather",a,{axis:Number(m)})},878456:(a,m)=>{l.jb("GatherElements",a,{axis:Number(m)})},878535:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt)=>{l.jb("Resize",a,{antialias:m,axes:T?Array.from(o().subarray(T>>>0,I>>>0)):[],coordinateTransformMode:is(W),cubicCoeffA:ye,excludeOutside:Ge,extrapolationValue:rt,keepAspectRatioPolicy:is(yt),mode:is(xt),nearestMode:is(jt)})},878881:(a,m,T,I,W,ye,Ge)=>{l.jb("Slice",a,{starts:m?Array.from(o().subarray(m>>>0,T>>>0)):[],ends:I?Array.from(o().subarray(I>>>0,W>>>0)):[],axes:ye?Array.from(o().subarray(ye>>>0,Ge>>>0)):[]})},879097:a=>{l.jb("Tile",a,void 0)},879149:(a,m,T)=>{l.jb("InstanceNormalization",a,{epsilon:m,format:T?"NHWC":"NCHW"})},879263:(a,m,T)=>{l.jb("InstanceNormalization",a,{epsilon:m,format:T?"NHWC":"NCHW"})},879377:a=>{l.jb("Range",a,void 0)},879430:(a,m)=>{l.jb("Einsum",a,{equation:is(m)})},879511:(a,m,T,I,W)=>{l.jb("Pad",a,{mode:m,value:T,pads:I?Array.from(o().subarray(I>>>0,W>>>0)):[]})},879638:(a,m,T,I,W,ye)=>{l.jb("BatchNormalization",a,{epsilon:m,momentum:T,spatial:!!W,trainingMode:!!I,format:ye?"NHWC":"NCHW"})},879807:(a,m,T,I,W,ye)=>{l.jb("BatchNormalization",a,{epsilon:m,momentum:T,spatial:!!W,trainingMode:!!I,format:ye?"NHWC":"NCHW"})},879976:(a,m,T)=>{l.jb("CumSum",a,{exclusive:Number(m),reverse:Number(T)})},880073:(a,m,T)=>{l.jb("DequantizeLinear",a,{axis:m,blockSize:T})},880163:(a,m,T,I,W,ye,Ge,rt,yt)=>{l.jb("Attention",a,{numHeads:m,isUnidirectional:T,maskFilterValue:I,scale:W,doRotary:ye,qkvHiddenSizes:Ge?Array.from(o().subarray(Number(rt)>>>0,Number(rt)+Ge>>>0)):[],pastPresentShareBuffer:!!yt})},880435:a=>{l.jb("BiasAdd",a,void 0)},880490:a=>{l.jb("BiasSplitGelu",a,void 0)},880551:a=>{l.jb("FastGelu",a,void 0)},880607:(a,m,T,I,W,ye,Ge,rt,yt,xt,jt,hr,Pr,Re,dr,Vr)=>{l.jb("Conv",a,{format:hr?"NHWC":"NCHW",auto_pad:m,dilations:T?Array.from(o().subarray(T>>>0,I>>>0)):[],group:W,kernel_shape:ye?Array.from(o().subarray(ye>>>0,Ge>>>0)):[],pads:rt?Array.from(o().subarray(rt>>>0,yt>>>0)):[],strides:xt?Array.from(o().subarray(xt>>>0,jt>>>0)):[],w_is_const:()=>!!r()[Pr>>>0],activation:is(Re),activation_params:dr?Array.from(p().subarray(dr>>>0,Vr>>>0)):[]})},881103:a=>{l.jb("Gelu",a,void 0)},881155:(a,m,T,I)=>{l.jb("GroupQueryAttention",a,{numHeads:m,kvNumHeads:T,scale:I})},881268:(a,m,T,I)=>{l.jb("LayerNormalization",a,{axis:m,epsilon:T,simplified:!!I})},881379:(a,m,T,I)=>{l.jb("LayerNormalization",a,{axis:m,epsilon:T,simplified:!!I})},881490:(a,m,T,I,W,ye)=>{l.jb("MatMulNBits",a,{k:m,n:T,accuracyLevel:I,bits:W,blockSize:ye})},881617:(a,m,T,I,W,ye)=>{l.jb("MultiHeadAttention",a,{numHeads:m,isUnidirectional:T,maskFilterValue:I,scale:W,doRotary:ye})},881776:(a,m)=>{l.jb("QuickGelu",a,{alpha:m})},881840:(a,m,T,I,W)=>{l.jb("RotaryEmbedding",a,{interleaved:!!m,numHeads:T,rotaryEmbeddingDim:I,scale:W})},881979:(a,m,T)=>{l.jb("SkipLayerNormalization",a,{epsilon:m,simplified:!!T})},882081:(a,m,T)=>{l.jb("SkipLayerNormalization",a,{epsilon:m,simplified:!!T})},882183:(a,m,T,I)=>{l.jb("GatherBlockQuantized",a,{gatherAxis:m,quantizeAxis:T,blockSize:I})},882304:a=>{l.Zb(a)},882338:(a,m)=>l.bc(a,m,l.Eb.fc,l.Eb.errors)};function _f(a,m,T){return dm(async()=>{await l.Xb(a,m,T)})}function gf(){return typeof wasmOffsetConverter<"u"}function Vp(a){this.name="ExitStatus",this.message=`Program terminated with exit(${a})`,this.status=a}var Wp=a=>{a.terminate(),a.onmessage=()=>{}},Ah=a=>{io.length==0&&(zh(),Lh(io[0]));var m=io.pop();if(!m)return 6;Go.push(m),_n[a.Ab]=m,m.Ab=a.Ab;var T={cmd:"run",start_routine:a.hc,arg:a.Qb,pthread_ptr:a.Ab};return m.postMessage(T,a.mc),0},Wo=0,jr=(a,m,...T)=>{for(var I=2*T.length,W=uh(),ye=lh(8*I),Ge=ye>>>3,rt=0;rt>>0]=yt)}return a=Om(a,0,I,ye,m),Mp(W),a};function Gp(a){if(X)return jr(0,1,a);if(Ft=a,!(0{if(Ft=a,X)throw Ih(a),"unwind";Gp(a)},io=[],Go=[],Fh=[],_n={},Oh=a=>{var m=a.Ab;delete _n[m],io.push(a),Go.splice(Go.indexOf(a),1),a.Ab=0,ah(m)};function Dh(){Fh.forEach(a=>a())}var Lh=a=>new Promise(m=>{a.onmessage=W=>{var ye=(W=W.data).cmd;if(W.targetThread&&W.targetThread!=za()){var Ge=_n[W.targetThread];Ge?Ge.postMessage(W,W.transferList):zt(`Internal error! Worker sent a message "${ye}" to target pthread ${W.targetThread}, but that thread no longer exists!`)}else ye==="checkMailbox"?dp():ye==="spawnThread"?Ah(W):ye==="cleanupThread"?Oh(_n[W.thread]):ye==="killThread"?(W=W.thread,ye=_n[W],delete _n[W],Wp(ye),ah(W),Go.splice(Go.indexOf(ye),1),ye.Ab=0):ye==="cancelThread"?_n[W.thread].postMessage({cmd:"cancel"}):ye==="loaded"?(a.loaded=!0,m(a)):ye==="alert"?alert(`Thread ${W.threadId}: ${W.text}`):W.target==="setimmediate"?a.postMessage(W):ye==="callHandler"?l[W.handler](...W.args):ye&&zt(`worker sent an unknown command ${ye}`)},a.onerror=W=>{throw zt(`worker sent an error! ${W.filename}:${W.lineno}: ${W.message}`),W};var T,I=[];for(T of[])l.hasOwnProperty(T)&&I.push(T);a.postMessage({cmd:"load",handlers:I,wasmMemory:nr,wasmModule:Er})});function zh(){var a=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});io.push(a)}var up=a=>{for(;0{var a=za(),m=u()[a+52>>>2>>>0];a=u()[a+56>>>2>>>0],Lm(m,m-a),Mp(m)},yf=(a,m)=>{Wo=0,a=zm(a,m),0>>=0);throw m>>>=0,T>>>=0,u()[I.Jb+16>>>2>>>0]=0,u()[I.Jb+4>>>2>>>0]=m,u()[I.Jb+8>>>2>>>0]=T,a}function Bh(a,m,T,I){return X?jr(2,1,a,m,T,I):Rh(a,m,T,I)}function Rh(a,m,T,I){if(a>>>=0,m>>>=0,T>>>=0,I>>>=0,te===void 0)return zt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var W=[];return X&&W.length===0?Bh(a,m,T,I):(a={hc:T,Ab:a,Qb:I,mc:W},X?(a.Mb="spawnThread",postMessage(a,W),0):Ah(a))}var jh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Nh=(a,m,T)=>{var I=(m>>>=0)+T;for(T=m;a[T]&&!(T>=I);)++T;if(16(W=(240&W)==224?(15&W)<<12|ye<<6|Ge:(7&W)<<18|ye<<12|Ge<<6|63&a[m++])?I+=String.fromCharCode(W):(W-=65536,I+=String.fromCharCode(55296|W>>10,56320|1023&W))}}else I+=String.fromCharCode(W)}return I},is=(a,m)=>(a>>>=0)?Nh(s(),a,m):"";function Uh(a,m,T){return X?jr(3,1,a,m,T):0}function Vh(a,m){if(X)return jr(4,1,a,m)}var Hp=a=>{for(var m=0,T=0;T=I?m++:2047>=I?m+=2:55296<=I&&57343>=I?(m+=4,++T):m+=3}return m},Wh=(a,m,T,I)=>{if(!(0>>=0;I=T+I-1;for(var ye=0;ye=Ge&&(Ge=65536+((1023&Ge)<<10)|1023&a.charCodeAt(++ye)),127>=Ge){if(T>=I)break;m[T++>>>0]=Ge}else{if(2047>=Ge){if(T+1>=I)break;m[T++>>>0]=192|Ge>>6}else{if(65535>=Ge){if(T+2>=I)break;m[T++>>>0]=224|Ge>>12}else{if(T+3>=I)break;m[T++>>>0]=240|Ge>>18,m[T++>>>0]=128|Ge>>12&63}m[T++>>>0]=128|Ge>>6&63}m[T++>>>0]=128|63&Ge}}return m[T>>>0]=0,T-W},Da=(a,m,T)=>Wh(a,s(),m,T);function Gh(a,m){if(X)return jr(5,1,a,m)}function Kh(a,m,T){if(X)return jr(6,1,a,m,T)}function Hh(a,m,T){return X?jr(7,1,a,m,T):0}function qh(a,m){if(X)return jr(8,1,a,m)}function Qh(a,m,T){if(X)return jr(9,1,a,m,T)}function Xh(a,m,T,I){if(X)return jr(10,1,a,m,T,I)}function Yh(a,m,T,I){if(X)return jr(11,1,a,m,T,I)}function Jh(a,m,T,I){if(X)return jr(12,1,a,m,T,I)}function Zh(a){if(X)return jr(13,1,a)}function em(a,m){if(X)return jr(14,1,a,m)}function tm(a,m,T){if(X)return jr(15,1,a,m,T)}var rm,ao,vf=()=>{Oa("")},gn=a=>{for(var m="";s()[a>>>0];)m+=rm[s()[a++>>>0]];return m},qp={},Qp={};function An(a,m,T={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(I,W,ye={}){var Ge=W.name;if(!I)throw new ao(`type "${Ge}" must have a positive integer typeid pointer`);if(Qp.hasOwnProperty(I)){if(ye.Sb)return;throw new ao(`Cannot register type '${Ge}' twice`)}Qp[I]=W,qp.hasOwnProperty(I)&&(W=qp[I],delete qp[I],W.forEach(rt=>rt()))}(a,m,T)}var sm=(a,m,T)=>{switch(m){case 1:return T?I=>r()[I>>>0]:I=>s()[I>>>0];case 2:return T?I=>n()[I>>>1>>>0]:I=>i()[I>>>1>>>0];case 4:return T?I=>o()[I>>>2>>>0]:I=>u()[I>>>2>>>0];case 8:return T?I=>Xr[I>>>3]:I=>no[I>>>3];default:throw new TypeError(`invalid integer width (${m}): ${a}`)}};function Tf(a,m,T){T>>>=0,An(a>>>=0,{name:m=gn(m>>>0),fromWireType:I=>I,toWireType:function(I,W){if(typeof W!="bigint"&&typeof W!="number")throw W=W===null?"null":(I=typeof W)=="object"||I==="array"||I==="function"?W.toString():""+W,new TypeError(`Cannot convert "${W}" to ${this.name}`);return typeof W=="number"&&(W=BigInt(W)),W},argPackAdvance:lo,readValueFromPointer:sm(m,T,m.indexOf("u")==-1),Db:null})}var lo=8;function xf(a,m,T,I){An(a>>>=0,{name:m=gn(m>>>0),fromWireType:function(W){return!!W},toWireType:function(W,ye){return ye?T:I},argPackAdvance:lo,readValueFromPointer:function(W){return this.fromWireType(s()[W>>>0])},Db:null})}var Xp=[],In=[];function Yp(a){9<(a>>>=0)&&--In[a+1]==0&&(In[a]=void 0,Xp.push(a))}var Ks=a=>{if(!a)throw new ao("Cannot use deleted val. handle = "+a);return In[a]},Hs=a=>{switch(a){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=Xp.pop()||In.length;return In[m]=a,In[m+1]=1,m}};function Jp(a){return this.fromWireType(u()[a>>>2>>>0])}var Ef={name:"emscripten::val",fromWireType:a=>{var m=Ks(a);return Yp(a),m},toWireType:(a,m)=>Hs(m),argPackAdvance:lo,readValueFromPointer:Jp,Db:null};function Pf(a){return An(a>>>0,Ef)}var Cf=(a,m)=>{switch(m){case 4:return function(T){return this.fromWireType(p()[T>>>2>>>0])};case 8:return function(T){return this.fromWireType(h()[T>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${a}`)}};function Sf(a,m,T){T>>>=0,An(a>>>=0,{name:m=gn(m>>>0),fromWireType:I=>I,toWireType:(I,W)=>W,argPackAdvance:lo,readValueFromPointer:Cf(m,T),Db:null})}function $f(a,m,T,I,W){if(a>>>=0,T>>>=0,m=gn(m>>>0),W===-1&&(W=4294967295),W=rt=>rt,I===0){var ye=32-8*T;W=rt=>rt<>>ye}var Ge=m.includes("unsigned")?function(rt,yt){return yt>>>0}:function(rt,yt){return yt};An(a,{name:m,fromWireType:W,toWireType:Ge,argPackAdvance:lo,readValueFromPointer:sm(m,T,I!==0),Db:null})}function kf(a,m,T){function I(ye){var Ge=u()[ye>>>2>>>0];return ye=u()[ye+4>>>2>>>0],new W(r().buffer,ye,Ge)}var W=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];An(a>>>=0,{name:T=gn(T>>>0),fromWireType:I,argPackAdvance:lo,readValueFromPointer:I},{Sb:!0})}function Af(a,m){a>>>=0;var T=(m=gn(m>>>0))==="std::string";An(a,{name:m,fromWireType:function(I){var W=u()[I>>>2>>>0],ye=I+4;if(T)for(var Ge=ye,rt=0;rt<=W;++rt){var yt=ye+rt;if(rt==W||s()[yt>>>0]==0){if(Ge=is(Ge,yt-Ge),xt===void 0)var xt=Ge;else xt+="\0",xt+=Ge;Ge=yt+1}}else{for(xt=Array(W),rt=0;rt>>0]);xt=xt.join("")}return yn(I),xt},toWireType:function(I,W){W instanceof ArrayBuffer&&(W=new Uint8Array(W));var ye=typeof W=="string";if(!(ye||W instanceof Uint8Array||W instanceof Uint8ClampedArray||W instanceof Int8Array))throw new ao("Cannot pass non-string to std::string");var Ge=T&&ye?Hp(W):W.length,rt=wp(4+Ge+1),yt=rt+4;if(u()[rt>>>2>>>0]=Ge,T&&ye)Da(W,yt,Ge+1);else if(ye)for(ye=0;ye>>0]=xt}else for(ye=0;ye>>0]=W[ye];return I!==null&&I.push(yn,rt),rt},argPackAdvance:lo,readValueFromPointer:Jp,Db(I){yn(I)}})}var nm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,If=(a,m)=>{for(var T=a>>1,I=T+m/2;!(T>=I)&&i()[T>>>0];)++T;if(32<(T<<=1)-a&&nm)return nm.decode(s().slice(a,T));for(T="",I=0;!(I>=m/2);++I){var W=n()[a+2*I>>>1>>>0];if(W==0)break;T+=String.fromCharCode(W)}return T},Ff=(a,m,T)=>{if(T??(T=2147483647),2>T)return 0;var I=m;T=(T-=2)<2*a.length?T/2:a.length;for(var W=0;W>>1>>>0]=ye,m+=2}return n()[m>>>1>>>0]=0,m-I},Of=a=>2*a.length,Df=(a,m)=>{for(var T=0,I="";!(T>=m/4);){var W=o()[a+4*T>>>2>>>0];if(W==0)break;++T,65536<=W?(W-=65536,I+=String.fromCharCode(55296|W>>10,56320|1023&W)):I+=String.fromCharCode(W)}return I},Lf=(a,m,T)=>{if(m>>>=0,T??(T=2147483647),4>T)return 0;var I=m;T=I+T-4;for(var W=0;W=ye&&(ye=65536+((1023&ye)<<10)|1023&a.charCodeAt(++W)),o()[m>>>2>>>0]=ye,(m+=4)+4>T)break}return o()[m>>>2>>>0]=0,m-I},zf=a=>{for(var m=0,T=0;T=I&&++T,m+=4}return m};function Bf(a,m,T){if(a>>>=0,m>>>=0,T=gn(T>>>=0),m===2)var I=If,W=Ff,ye=Of,Ge=rt=>i()[rt>>>1>>>0];else m===4&&(I=Df,W=Lf,ye=zf,Ge=rt=>u()[rt>>>2>>>0]);An(a,{name:T,fromWireType:rt=>{for(var yt,xt=u()[rt>>>2>>>0],jt=rt+4,hr=0;hr<=xt;++hr){var Pr=rt+4+hr*m;hr!=xt&&Ge(Pr)!=0||(jt=I(jt,Pr-jt),yt===void 0?yt=jt:(yt+="\0",yt+=jt),jt=Pr+m)}return yn(rt),yt},toWireType:(rt,yt)=>{if(typeof yt!="string")throw new ao(`Cannot pass non-string to C++ string type ${T}`);var xt=ye(yt),jt=wp(4+xt+m);return u()[jt>>>2>>>0]=xt/m,W(yt,jt+4,xt+m),rt!==null&&rt.push(yn,jt),jt},argPackAdvance:lo,readValueFromPointer:Jp,Db(rt){yn(rt)}})}function Rf(a,m){An(a>>>=0,{Tb:!0,name:m=gn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var jf=()=>1;function Nf(a){ih(a>>>0,!z,1,!D,131072,!1),Dh()}var om=a=>{if(!bs)try{if(a(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(o(),a>>>2,a).value.then(dp),a+=128,Atomics.store(o(),a>>>2,1))}var dp=()=>{var a=za();a&&(Zp(a),om(Dm))};function Uf(a,m){(a>>>=0)==m>>>0?setTimeout(dp):X?postMessage({targetThread:a,cmd:"checkMailbox"}):(a=_n[a])&&a.postMessage({cmd:"checkMailbox"})}var eh=[];function Vf(a,m,T,I,W){for(m>>>=0,I/=2,eh.length=I,T=W>>>0>>>3,W=0;W>>0];return(m?Up[m]:I_[a])(...eh)}function Wf(a){a>>>=0,X?postMessage({cmd:"cleanupThread",thread:a}):Oh(_n[a])}function Gf(a){}var th=(a,m)=>{var T=Qp[a];if(T===void 0)throw a=Am(a),T=gn(a),yn(a),new ao(`${m} has unknown type ${T}`);return T},im=(a,m,T)=>{var I=[];return a=a.toWireType(I,T),I.length&&(u()[m>>>2>>>0]=Hs(I)),a};function Kf(a,m,T){return m>>>=0,T>>>=0,a=Ks(a>>>0),m=th(m,"emval::as"),im(m,T,a)}var cp=a=>{try{a()}catch(m){Oa(m)}},uo=0,wn=null,am=0,pp=[],lm={},um={},Hf=0,rh=null,qf=[];function dm(a){return function(m){if(!bs){if(uo===0){var T=!1,I=!1;m((W=0)=>{if(!bs&&(am=W,T=!0,I)){uo=2,cp(()=>jm(wn)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),W=!1;try{var ye=function(){var yt=o()[wn+8>>>2>>>0];return yt=Bt[um[yt]],--Wo,yt()}()}catch(yt){ye=yt,W=!0}var Ge=!1;if(!wn){var rt=rh;rt&&(rh=null,(W?rt.reject:rt.resolve)(ye),Ge=!0)}if(W&&!Ge)throw ye}}),I=!0,T||(uo=1,wn=function(){var W=wp(65548),ye=W+12;u()[W>>>2>>>0]=ye,u()[W+4>>>2>>>0]=ye+65536,ye=pp[0];var Ge=lm[ye];return Ge===void 0&&(Ge=Hf++,lm[ye]=Ge,um[Ge]=ye),ye=Ge,o()[W+8>>>2>>>0]=ye,W}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),cp(()=>Bm(wn)))}else uo===2?(uo=0,cp(Nm),yn(wn),wn=null,qf.forEach(om)):Oa(`invalid state: ${uo}`);return am}}(m=>{a().then(m)})}function Qf(a){return a>>>=0,dm(()=>(a=Ks(a)).then(Hs))}var hp=[];function Xf(a,m,T,I){return T>>>=0,I>>>=0,(a=hp[a>>>0])(null,m=Ks(m>>>0),T,I)}var Yf={},mp=a=>{var m=Yf[a];return m===void 0?gn(a):m};function Jf(a,m,T,I,W){return T>>>=0,I>>>=0,W>>>=0,(a=hp[a>>>0])(m=Ks(m>>>0),m[T=mp(T)],I,W)}var cm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Zf(a){return(a>>>=0)==0?Hs(cm()):(a=mp(a),Hs(cm()[a]))}var e_=a=>{var m=hp.length;return hp.push(a),m},t_=(a,m)=>{for(var T=Array(a),I=0;I>>2>>>0],"parameter "+I);return T},pm=(a,m)=>Object.defineProperty(m,"name",{value:a});function r_(a,m,T){var I=(m=t_(a,m>>>0)).shift();a--;var W=`return function (obj, func, destructorsRef, args) { `,ye=0,Ge=[];T===0&&Ge.push("obj");for(var rt=["retType"],yt=[I],xt=0;xtjt.name).join(", ")}) => ${I.name}>`,e_(pm(T,a))}function s_(a){return a=mp(a>>>0),Hs(l[a])}function n_(a,m){return m>>>=0,a=Ks(a>>>0),m=Ks(m),Hs(a[m])}function o_(a){9<(a>>>=0)&&(In[a+1]+=1)}function i_(){return Hs([])}function a_(a){a=Ks(a>>>0);for(var m=Array(a.length),T=0;T>>0))}function u_(){return Hs({})}function d_(a){for(var m=Ks(a>>>=0);m.length;){var T=m.pop();m.pop()(T)}Yp(a)}function c_(a,m,T){m>>>=0,T>>>=0,a=Ks(a>>>0),m=Ks(m),T=Ks(T),a[m]=T}function p_(a,m){return m>>>=0,a=(a=th(a>>>0,"_emval_take_value")).readValueFromPointer(m),Hs(a)}function h_(a,m){a=-9007199254740992>a||9007199254740992>>=0,a=new Date(1e3*a),o()[m>>>2>>>0]=a.getUTCSeconds(),o()[m+4>>>2>>>0]=a.getUTCMinutes(),o()[m+8>>>2>>>0]=a.getUTCHours(),o()[m+12>>>2>>>0]=a.getUTCDate(),o()[m+16>>>2>>>0]=a.getUTCMonth(),o()[m+20>>>2>>>0]=a.getUTCFullYear()-1900,o()[m+24>>>2>>>0]=a.getUTCDay(),a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[m+28>>>2>>>0]=a}var La=a=>a%4==0&&(a%100!=0||a%400==0),hm=[0,31,60,91,121,152,182,213,244,274,305,335],mm=[0,31,59,90,120,151,181,212,243,273,304,334];function m_(a,m){a=-9007199254740992>a||9007199254740992>>=0,a=new Date(1e3*a),o()[m>>>2>>>0]=a.getSeconds(),o()[m+4>>>2>>>0]=a.getMinutes(),o()[m+8>>>2>>>0]=a.getHours(),o()[m+12>>>2>>>0]=a.getDate(),o()[m+16>>>2>>>0]=a.getMonth(),o()[m+20>>>2>>>0]=a.getFullYear()-1900,o()[m+24>>>2>>>0]=a.getDay();var T=(La(a.getFullYear())?hm:mm)[a.getMonth()]+a.getDate()-1|0;o()[m+28>>>2>>>0]=T,o()[m+36>>>2>>>0]=-60*a.getTimezoneOffset(),T=new Date(a.getFullYear(),6,1).getTimezoneOffset();var I=new Date(a.getFullYear(),0,1).getTimezoneOffset();a=0|(T!=I&&a.getTimezoneOffset()==Math.min(I,T)),o()[m+32>>>2>>>0]=a}function f_(a){a>>>=0;var m=new Date(o()[a+20>>>2>>>0]+1900,o()[a+16>>>2>>>0],o()[a+12>>>2>>>0],o()[a+8>>>2>>>0],o()[a+4>>>2>>>0],o()[a>>>2>>>0],0),T=o()[a+32>>>2>>>0],I=m.getTimezoneOffset(),W=new Date(m.getFullYear(),6,1).getTimezoneOffset(),ye=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Ge=Math.min(ye,W);return 0>T?o()[a+32>>>2>>>0]=+(W!=ye&&Ge==I):0>>2>>>0]=m.getDay(),T=(La(m.getFullYear())?hm:mm)[m.getMonth()]+m.getDate()-1|0,o()[a+28>>>2>>>0]=T,o()[a>>>2>>>0]=m.getSeconds(),o()[a+4>>>2>>>0]=m.getMinutes(),o()[a+8>>>2>>>0]=m.getHours(),o()[a+12>>>2>>>0]=m.getDate(),o()[a+16>>>2>>>0]=m.getMonth(),o()[a+20>>>2>>>0]=m.getYear(),a=m.getTime(),BigInt(isNaN(a)?-1:a/1e3)}function fm(a,m,T,I,W,ye,Ge){return X?jr(16,1,a,m,T,I,W,ye,Ge):-52}function _m(a,m,T,I,W,ye){if(X)return jr(17,1,a,m,T,I,W,ye)}function __(a,m,T,I){a>>>=0,m>>>=0,T>>>=0,I>>>=0;var W=new Date().getFullYear(),ye=new Date(W,0,1),Ge=new Date(W,6,1);W=ye.getTimezoneOffset();var rt=Ge.getTimezoneOffset(),yt=Math.max(W,rt);u()[a>>>2>>>0]=60*yt,o()[m>>>2>>>0]=+(W!=rt),ye=(a=xt=>xt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ye),Ge=a(Ge),rt{sh.length=0;for(var T;T=s()[a++>>>0];){var I=T!=105;m+=(I&=T!=112)&&m%8?4:0,sh.push(T==112?u()[m>>>2>>>0]:T==106?Xr[m>>>3]:T==105?o()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=I?8:4}return sh};function g_(a,m,T){return a>>>=0,m=gm(m>>>0,T>>>0),Up[a](...m)}function w_(a,m,T){return a>>>=0,m=gm(m>>>0,T>>>0),Up[a](...m)}var y_=()=>{},M_=()=>Date.now();function b_(a,m){return zt(is(a>>>0,m>>>0))}var wm,v_=()=>{throw Wo+=1,"unwind"};function T_(){return 4294901760}wm=()=>performance.timeOrigin+performance.now();var x_=()=>navigator.hardwareConcurrency;function E_(){return Oa("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function P_(a){a>>>=0;var m=s().length;if(a<=m||4294901760=T;T*=2){var I=m*(1+.2/T);I=Math.min(I,a+100663296);var W=Math;I=Math.max(a,I);e:{W=(W.min.call(W,4294901760,I+(65536-I%65536)%65536)-nr.buffer.byteLength+65535)/65536;try{nr.grow(W),ns();var ye=1;break e}catch{}ye=void 0}if(ye)return!0}return!1}var fp=()=>(Oa("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),hc={},ym=a=>{a.forEach(m=>{fp()})};function C_(){var a=Error().stack.toString().split(` `);return a[0]=="Error"&&a.shift(),ym(a),hc.Pb=fp(),hc.ec=a,hc.Pb}function S_(a,m,T){if(a>>>=0,m>>>=0,hc.Pb==a)var I=hc.ec;else(I=Error().stack.toString().split(` `))[0]=="Error"&&I.shift(),ym(I);for(var W=3;I[W]&&fp()!=a;)++W;for(a=0;a>>2>>>0]=fp();return a}var nh,oh={},Mm=()=>{if(!nh){var a,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:Ue};for(a in oh)oh[a]===void 0?delete m[a]:m[a]=oh[a];var T=[];for(a in m)T.push(`${a}=${m[a]}`);nh=T}return nh};function bm(a,m){if(X)return jr(18,1,a,m);a>>>=0,m>>>=0;var T=0;return Mm().forEach((I,W)=>{var ye=m+T;for(W=u()[a+4*W>>>2>>>0]=ye,ye=0;ye>>0]=I.charCodeAt(ye);r()[W>>>0]=0,T+=I.length+1}),0}function vm(a,m){if(X)return jr(19,1,a,m);a>>>=0,m>>>=0;var T=Mm();u()[a>>>2>>>0]=T.length;var I=0;return T.forEach(W=>I+=W.length+1),u()[m>>>2>>>0]=I,0}function Tm(a){return X?jr(20,1,a):52}function xm(a,m,T,I){return X?jr(21,1,a,m,T,I):52}function Em(a,m,T,I){return X?jr(22,1,a,m,T,I):70}var $_=[null,[],[]];function Pm(a,m,T,I){if(X)return jr(23,1,a,m,T,I);m>>>=0,T>>>=0,I>>>=0;for(var W=0,ye=0;ye>>2>>>0],rt=u()[m+4>>>2>>>0];m+=8;for(var yt=0;yt>>0],jt=$_[a];xt===0||xt===10?((a===1?tr:zt)(Nh(jt,0)),jt.length=0):jt.push(xt)}W+=rt}return u()[I>>>2>>>0]=W,0}var Cm=[31,29,31,30,31,30,31,31,30,31,30,31],Sm=[31,28,31,30,31,30,31,31,30,31,30,31],k_=(a,m)=>{r().set(a,m>>>0)};function $m(a,m,T,I){function W(Re,dr,Vr){for(Re=typeof Re=="number"?Re.toString():Re||"";Re.lengthVm?-1:0Ko-Re.getDate())){Re.setDate(Re.getDate()+dr);break}dr-=Ko-Re.getDate()+1,Re.setDate(1),11>Vr?Re.setMonth(Vr+1):(Re.setMonth(0),Re.setFullYear(Re.getFullYear()+1))}return Vr=new Date(Re.getFullYear()+1,0,4),dr=rt(new Date(Re.getFullYear(),0,4)),Vr=rt(Vr),0>=Ge(dr,Re)?0>=Ge(Vr,Re)?Re.getFullYear()+1:Re.getFullYear():Re.getFullYear()-1}a>>>=0,m>>>=0,T>>>=0,I>>>=0;var xt=u()[I+40>>>2>>>0];for(var jt in I={kc:o()[I>>>2>>>0],jc:o()[I+4>>>2>>>0],Hb:o()[I+8>>>2>>>0],Lb:o()[I+12>>>2>>>0],Ib:o()[I+16>>>2>>>0],Cb:o()[I+20>>>2>>>0],ub:o()[I+24>>>2>>>0],Bb:o()[I+28>>>2>>>0],rc:o()[I+32>>>2>>>0],ic:o()[I+36>>>2>>>0],lc:xt?is(xt):""},T=is(T),xt={"%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"})T=T.replace(new RegExp(jt,"g"),xt[jt]);var hr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Pr="January February March April May June July August September October November December".split(" ");for(jt in xt={"%a":Re=>hr[Re.ub].substring(0,3),"%A":Re=>hr[Re.ub],"%b":Re=>Pr[Re.Ib].substring(0,3),"%B":Re=>Pr[Re.Ib],"%C":Re=>ye((Re.Cb+1900)/100|0,2),"%d":Re=>ye(Re.Lb,2),"%e":Re=>W(Re.Lb,2," "),"%g":Re=>yt(Re).toString().substring(2),"%G":yt,"%H":Re=>ye(Re.Hb,2),"%I":Re=>((Re=Re.Hb)==0?Re=12:12{for(var dr=0,Vr=0;Vr<=Re.Ib-1;dr+=(La(Re.Cb+1900)?Cm:Sm)[Vr++]);return ye(Re.Lb+dr,3)},"%m":Re=>ye(Re.Ib+1,2),"%M":Re=>ye(Re.jc,2),"%n":()=>` `,"%p":Re=>0<=Re.Hb&&12>Re.Hb?"AM":"PM","%S":Re=>ye(Re.kc,2),"%t":()=>" ","%u":Re=>Re.ub||7,"%U":Re=>ye(Math.floor((Re.Bb+7-Re.ub)/7),2),"%V":Re=>{var dr=Math.floor((Re.Bb+7-(Re.ub+6)%7)/7);if(2>=(Re.ub+371-Re.Bb-2)%7&&dr++,dr)dr==53&&((Vr=(Re.ub+371-Re.Bb)%7)==4||Vr==3&&La(Re.Cb)||(dr=1));else{dr=52;var Vr=(Re.ub+7-Re.Bb-1)%7;(Vr==4||Vr==5&&La(Re.Cb%400-1))&&dr++}return ye(dr,2)},"%w":Re=>Re.ub,"%W":Re=>ye(Math.floor((Re.Bb+7-(Re.ub+6)%7)/7),2),"%y":Re=>(Re.Cb+1900).toString().substring(2),"%Y":Re=>Re.Cb+1900,"%z":Re=>{var dr=0<=(Re=Re.ic);return Re=Math.abs(Re)/60,(dr?"+":"-")+("0000"+(Re/60*100+Re%60)).slice(-4)},"%Z":Re=>Re.lc,"%%":()=>"%"},T=T.replace(/%%/g,"\0\0"),xt)T.includes(jt)&&(T=T.replace(new RegExp(jt,"g"),xt[jt](I)));return jt=function(Re){var dr=Array(Hp(Re)+1);return Wh(Re,dr,0,dr.length),dr}(T=T.replace(/\0\0/g,"%")),jt.length>m?0:(k_(jt,a),jt.length-1)}function A_(a,m,T,I){return $m(a>>>0,m>>>0,T>>>0,I>>>0)}X||function(){for(var a=l.numThreads-1;a--;)zh();Vo.unshift(()=>{Gs++,function(m){X?m():Promise.all(io.map(Lh)).then(m)}(()=>lp())})}();for(var km=Array(256),_p=0;256>_p;++_p)km[_p]=String.fromCharCode(_p);rm=km,ao=l.BindingError=class extends Error{constructor(a){super(a),this.name="BindingError"}},l.InternalError=class extends Error{constructor(a){super(a),this.name="InternalError"}},In.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>In.length/2-5-Xp.length;var I_=[Gp,Ih,Bh,Uh,Vh,Gh,Kh,Hh,qh,Qh,Xh,Yh,Jh,Zh,em,tm,fm,_m,bm,vm,Tm,xm,Em,Pm],Bt=function(){function a(T,I){return Bt=T.exports,Bt=function(){var W=Bt,ye={};for(let[Ge,rt]of Object.entries(W))ye[Ge]=typeof rt=="function"?(...yt)=>{pp.push(Ge);try{return rt(...yt)}finally{bs||(pp.pop(),wn&&uo===1&&pp.length===0&&(uo=0,Wo+=1,cp(Rm),typeof Fibers<"u"&&Fibers.sc()))}}:rt;return ye}(),Bt=function(){var W=Bt,ye=rt=>yt=>rt(yt)>>>0,Ge=rt=>()=>rt()>>>0;return(W=Object.assign({},W)).Ca=ye(W.Ca),W.fb=Ge(W.fb),W.gb=ye(W.gb),W.emscripten_main_runtime_thread_id=Ge(W.emscripten_main_runtime_thread_id),W.sb=ye(W.sb),W.tb=Ge(W.tb),W}(),Fh.push(Bt.ib),es.unshift(Bt.Ba),Er=I,lp(),Bt}var m=kh();if(Gs++,l.instantiateWasm)try{return l.instantiateWasm(m,a)}catch(T){zt(`Module.instantiateWasm callback failed with error: ${T}`),b(T)}return Np||(Np=l.locateFile?Ph("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",tt):tt+"ort-wasm-simd-threaded.jsep.wasm":new URL(c("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),c.b).href),function(T,I){var W=Np;return Mt||typeof WebAssembly.instantiateStreaming!="function"||Ph(W)||Ch(W)||typeof fetch!="function"?$h(W,T,I):fetch(W,{credentials:"same-origin"}).then(ye=>WebAssembly.instantiateStreaming(ye,T).then(I,function(Ge){return zt(`wasm streaming compile failed: ${Ge}`),zt("falling back to ArrayBuffer instantiation"),$h(W,T,I)}))}(m,function(T){a(T.instance,T.module)}).catch(b),{}}(),Am=a=>(Am=Bt.Ca)(a),Im=()=>(Im=Bt.Da)();l._OrtInit=(a,m)=>(l._OrtInit=Bt.Ea)(a,m),l._OrtGetLastError=(a,m)=>(l._OrtGetLastError=Bt.Fa)(a,m),l._OrtCreateSessionOptions=(a,m,T,I,W,ye,Ge,rt,yt,xt)=>(l._OrtCreateSessionOptions=Bt.Ga)(a,m,T,I,W,ye,Ge,rt,yt,xt),l._OrtAppendExecutionProvider=(a,m)=>(l._OrtAppendExecutionProvider=Bt.Ha)(a,m),l._OrtAddFreeDimensionOverride=(a,m,T)=>(l._OrtAddFreeDimensionOverride=Bt.Ia)(a,m,T),l._OrtAddSessionConfigEntry=(a,m,T)=>(l._OrtAddSessionConfigEntry=Bt.Ja)(a,m,T),l._OrtReleaseSessionOptions=a=>(l._OrtReleaseSessionOptions=Bt.Ka)(a),l._OrtCreateSession=(a,m,T)=>(l._OrtCreateSession=Bt.La)(a,m,T),l._OrtReleaseSession=a=>(l._OrtReleaseSession=Bt.Ma)(a),l._OrtGetInputOutputCount=(a,m,T)=>(l._OrtGetInputOutputCount=Bt.Na)(a,m,T),l._OrtGetInputName=(a,m)=>(l._OrtGetInputName=Bt.Oa)(a,m),l._OrtGetOutputName=(a,m)=>(l._OrtGetOutputName=Bt.Pa)(a,m),l._OrtFree=a=>(l._OrtFree=Bt.Qa)(a),l._OrtCreateTensor=(a,m,T,I,W,ye)=>(l._OrtCreateTensor=Bt.Ra)(a,m,T,I,W,ye),l._OrtGetTensorData=(a,m,T,I,W)=>(l._OrtGetTensorData=Bt.Sa)(a,m,T,I,W),l._OrtReleaseTensor=a=>(l._OrtReleaseTensor=Bt.Ta)(a),l._OrtCreateRunOptions=(a,m,T,I)=>(l._OrtCreateRunOptions=Bt.Ua)(a,m,T,I),l._OrtAddRunConfigEntry=(a,m,T)=>(l._OrtAddRunConfigEntry=Bt.Va)(a,m,T),l._OrtReleaseRunOptions=a=>(l._OrtReleaseRunOptions=Bt.Wa)(a),l._OrtCreateBinding=a=>(l._OrtCreateBinding=Bt.Xa)(a),l._OrtBindInput=(a,m,T)=>(l._OrtBindInput=Bt.Ya)(a,m,T),l._OrtBindOutput=(a,m,T,I)=>(l._OrtBindOutput=Bt.Za)(a,m,T,I),l._OrtClearBoundOutputs=a=>(l._OrtClearBoundOutputs=Bt._a)(a),l._OrtReleaseBinding=a=>(l._OrtReleaseBinding=Bt.$a)(a),l._OrtRunWithBinding=(a,m,T,I,W)=>(l._OrtRunWithBinding=Bt.ab)(a,m,T,I,W),l._OrtRun=(a,m,T,I,W,ye,Ge,rt)=>(l._OrtRun=Bt.bb)(a,m,T,I,W,ye,Ge,rt),l._OrtEndProfiling=a=>(l._OrtEndProfiling=Bt.cb)(a),l._JsepOutput=(a,m,T)=>(l._JsepOutput=Bt.db)(a,m,T),l._JsepGetNodeName=a=>(l._JsepGetNodeName=Bt.eb)(a);var gp,za=()=>(za=Bt.fb)(),wp=l._malloc=a=>(wp=l._malloc=Bt.gb)(a),yn=l._free=a=>(yn=l._free=Bt.hb)(a),ih=(a,m,T,I,W,ye)=>(ih=Bt.kb)(a,m,T,I,W,ye),Fm=()=>(Fm=Bt.lb)(),Om=(a,m,T,I,W)=>(Om=Bt.mb)(a,m,T,I,W),ah=a=>(ah=Bt.nb)(a),yp=a=>(yp=Bt.ob)(a),Dm=()=>(Dm=Bt.pb)(),Lm=(a,m)=>(Lm=Bt.qb)(a,m),Mp=a=>(Mp=Bt.rb)(a),lh=a=>(lh=Bt.sb)(a),uh=()=>(uh=Bt.tb)(),zm=l.dynCall_ii=(a,m)=>(zm=l.dynCall_ii=Bt.vb)(a,m),Bm=a=>(Bm=Bt.wb)(a),Rm=()=>(Rm=Bt.xb)(),jm=a=>(jm=Bt.yb)(a),Nm=()=>(Nm=Bt.zb)();function Um(){0uh(),l.stackRestore=a=>Mp(a),l.stackAlloc=a=>lh(a),l.UTF8ToString=is,l.stringToUTF8=Da,l.lengthBytesUTF8=Hp,oo=function a(){gp||Um(),gp||(oo=a)},Um(),F}),Is=zs,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&zs()}),Ts,Bs,Ys,un,gs,dn,Js,Zs,Rs=g(()=>{var e,t;Pt(),Ts=self.location.href??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),Bs=typeof location>"u"?void 0:location.origin,Ys=(r,s)=>{try{let n=s??Ts;return(n?new URL(r,n):new URL(r)).origin===Bs}catch{return!1}},un=async r=>{let s=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(s)},gs=(os(),$(ar)).default,dn=async()=>{if(!Ts)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ys(Ts))return[void 0,gs()];let r=await un(Ts);return[r,gs(r)]},Js=(Nt(),$(Qs)).default,Zs=async(r,s,n)=>[void 0,Js]}),ds,et,vt,It,Wr,en,js,xr,cs=g(()=>{Rs(),et=!1,vt=!1,It=!1,Wr=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},en=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},js=async e=>{if(et)return Promise.resolve();if(vt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(It)throw new Error("previous call to 'initializeWebAssembly()' failed.");vt=!0;let t=e.initTimeout,r=e.numThreads;if(!en())throw new Error("WebAssembly SIMD is not supported in the current environment.");let s=Wr();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let n=e.wasmPaths,i=typeof n=="string"?n:void 0,o=n==null?void 0:n.mjs,u=(o==null?void 0:o.href)??o,p=n==null?void 0:n.wasm,h=(p==null?void 0:p.href)??p,v=e.wasmBinary,[b,l]=await Zs(u,i,r>1),F=!1,D=[];if(t>0&&D.push(new Promise(z=>{setTimeout(()=>{F=!0,z()},t)})),D.push(new Promise((z,X)=>{let te={numThreads:r};v?te.wasmBinary=v:(h||i)&&(te.locateFile=(K,ce)=>h??(i??ce)+K),l(te).then(K=>{vt=!1,et=!0,ds=K,z(),b&&URL.revokeObjectURL(b)},K=>{vt=!1,It=!0,X(K)})})),await Promise.race(D),F)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},xr=()=>{if(et&&ds)return ds;throw new Error("WebAssembly is not initialized yet.")}}),Lr,Fs,br,Ns=g(()=>{cs(),Lr=(e,t)=>{let r=xr(),s=r.lengthBytesUTF8(e)+1,n=r._malloc(s);return r.stringToUTF8(e,n,s),t.push(n),n},Fs=(e,t,r,s)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,i])=>{let o=t?t+n:n;if(typeof i=="object")Fs(i,o+".",r,s);else if(typeof i=="string"||typeof i=="number")s(o,i.toString());else if(typeof i=="boolean")s(o,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},br=e=>{let t=xr(),r=t.stackSave();try{let s=t.stackAlloc(8);t._OrtGetLastError(s,s+4);let n=t.HEAP32[s/4],i=t.HEAPU32[s/4+1],o=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(r)}}}),Fn,po=g(()=>{cs(),Ns(),Fn=e=>{let t=xr(),r=0,s=[],n=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(n.terminate=!1);let i=0;return(e==null?void 0:e.tag)!==void 0&&(i=Lr(e.tag,s)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,i),r===0&&br("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Fs(e.extra,"",new WeakSet,(o,u)=>{let p=Lr(o,s),h=Lr(u,s);t._OrtAddRunConfigEntry(r,p,h)!==0&&br(`Can't set a run config entry: ${o} - ${u}.`)}),[r,s]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),s.forEach(o=>t._free(o)),i}}}),On,Dn,Us,Ln,zn,ho=g(()=>{cs(),Ns(),On=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}`)}},Dn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Us=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Ln=(e,t,r)=>{for(let s of t){let n=typeof s=="string"?s:s.name;switch(n){case"webnn":if(n="WEBNN",typeof s!="string"){let o=s==null?void 0:s.deviceType;if(o){let u=Lr("deviceType",r),p=Lr(o,r);xr()._OrtAddSessionConfigEntry(e,u,p)!==0&&br(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(n="JS",typeof s!="string"){let o=s;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let u=Lr("preferredLayout",r),p=Lr(o.preferredLayout,r);xr()._OrtAddSessionConfigEntry(e,u,p)!==0&&br(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let i=Lr(n,r);xr()._OrtAppendExecutionProvider(e,i)!==0&&br(`Can't append execution provider: ${n}.`)}},zn=e=>{let t=xr(),r=0,s=[],n=e||{};Us(n);try{let i=On(n.graphOptimizationLevel??"all"),o=Dn(n.executionMode??"sequential"),u=typeof n.logId=="string"?Lr(n.logId,s):0,p=n.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=n.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let v=typeof n.optimizedModelFilePath=="string"?Lr(n.optimizedModelFilePath,s):0;if(r=t._OrtCreateSessionOptions(i,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,u,p,h,v),r===0&&br("Can't create session options."),n.executionProviders&&Ln(r,n.executionProviders,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);let b=Lr("enableGraphCapture",s),l=Lr(n.enableGraphCapture.toString(),s);t._OrtAddSessionConfigEntry(r,b,l)!==0&&br(`Can't set a session config entry: 'enableGraphCapture' - ${n.enableGraphCapture}.`)}if(n.freeDimensionOverrides)for(let[b,l]of Object.entries(n.freeDimensionOverrides)){if(typeof b!="string")throw new Error(`free dimension override name must be a string: ${b}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let F=Lr(b,s);t._OrtAddFreeDimensionOverride(r,F,l)!==0&&br(`Can't set a free dimension override: ${b} - ${l}.`)}return n.extra!==void 0&&Fs(n.extra,"",new WeakSet,(b,l)=>{let F=Lr(b,s),D=Lr(l,s);t._OrtAddSessionConfigEntry(r,F,D)!==0&&br(`Can't set a session config entry: ${b} - ${l}.`)}),[r,s]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r),s.forEach(o=>t._free(o)),i}}}),tn,xs,ws,bn,cn,vn,Tn,Vs,Rt=g(()=>{tn=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}`)}},xs=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}`)}},ws=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof t=="number"?t:t.reduce((n,i)=>n*i,1);return r>0?Math.ceil(s*r):void 0},bn=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}`)}},cn=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}`)}},vn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Tn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool",Vs=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,Bn=g(()=>{Pt(),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 r=t.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(s)}catch(u){if(u instanceof RangeError){let p=Math.ceil(s/65536);i=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw u}let o=0;for(;;){let{done:u,value:p}=await n.read();if(u)break;let h=p.byteLength;new Uint8Array(i,o,h).set(p),o+=h}return new Uint8Array(i,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Rn,En,jn,Nn,pn,Un,_r,xe=g(()=>{Rt(),Rn=["V","I","W","E","F"],En=(e,t)=>{console.log(`[${Rn[e]},${new Date().toISOString()}]${t}`)},pn=(e,t)=>{jn=e,Nn=t},Un=(e,t)=>{let r=cn(e),s=cn(jn);r>=s&&En(r,typeof t=="function"?t():t)},_r=(...e)=>{Nn&&Un(...e)}}),M,G=g(()=>{Rt(),M=(e,t)=>new(bn(t))(e)}),oe=g(()=>{}),Me,Ee,Ve,at,_t,pt,bt,Kt,mr,rr=g(()=>{xe(),oe(),Me=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Ee=[],Ve=e=>Math.ceil(e/16)*16,at=e=>{for(let t=0;t_t++,bt=async(e,t,r,s)=>{let n=Ve(r),i=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,i,0,n),e.flush(),await i.mapAsync(GPUMapMode.READ);let u=i.getMappedRange();if(s){let p=s();return p.set(new Uint8Array(u,0,r)),p}else return new Uint8Array(u.slice(0,r))}finally{i.destroy()}},Kt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of Me)Ee.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,s=t.byteOffset,n=t.byteLength,i=Ve(n),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(o.originalSize!==n)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${n}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:i,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=u.getMappedRange();new Uint8Array(p).set(new Uint8Array(r,s,n)),u.unmap();let h=this.backend.getCommandEncoder();this.backend.endComputePass(),h.copyBufferToBuffer(u,0,o.gpuData.buffer,0,i),_r("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(u)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(t);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let n=Ve(r.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(r.gpuData.buffer,0,s.gpuData.buffer,0,n)}registerExternalBuffer(e,t,r){let s;if(r){if(s=r[0],e===r[1])return _r("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else s=pt();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:t}),_r("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),_r("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=at(e),s,n=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,i=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(n||i){let u=(n?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?s=u.pop():s=this.backend.device.createBuffer({size:r,usage:t}):s=this.backend.device.createBuffer({size:r,usage:t})}else s=this.backend.device.createBuffer({size:r,usage:t});let o={id:pt(),type:0,buffer:s};return this.storageCache.set(o.id,{gpuData:o,originalSize:e}),_r("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return _r("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("data does not exist");await bt(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Me.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e))}},mr=(...e)=>new Kt(...e)}),Cr,qt,cr=g(()=>{Cr=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},qt=e=>new Cr(e)}),ps,zr,De,gr,Hr,hs,Es,Dt=g(()=>{ps=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},zr=class{static calcShape(e,t,r=!1){let s=e.length,n=t.length;if(s===0)return t;if(n===0)return e;let i=Math.max(e.length,t.length),o=new Array(i);if(r){if(s<2||n<2)return;let u=ps.calcMatMulShape([e[s-2],e[s-1]],[t[n-2],t[n-1]]);if(u===void 0)return;[o[i-2],o[i-1]]=u}for(let u=r?3:1;u<=i;u++){let p=s-u<0?1:e[s-u],h=n-u<0?1:t[n-u];if(p!==h&&p>1&&h>1)return;let v=Math.max(p,h);if(p&&h)o[i-u]=Math.max(p,h);else{if(v>1)return;o[i-u]=0}}return o}static isValidBroadcast(e,t){let r=e.length,s=t.length;if(r>s)return!1;for(let n=1;n<=r;n++)if(e[r-n]!==1&&e[r-n]!==t[s-n])return!1;return!0}},De=class bp{static size(t){return bp.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let s=t.length;if(s===0)return[];let n=new Array(s),i=s-1;for(;i>=0;){if(t[i]%r===0){n[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error("cannot convert shape");n[i]=1,r/=t[i],i--}for(i--;i>=0;i--)n[i]=t[i];return n}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return bp.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return bp.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,s){let n=1;for(let i=r;i=0;--n)s[n]=s[n+1]*t[n+1];return s}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(s=>this.normalizeAxis(s,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(s=>t[s]):t.slice().reverse()}static padShape(t,r){let s=t.length;return t.map((n,i)=>n+r[i]+r[i+s])}static areEqual(t,r){return t.length!==r.length?!1:t.every((s,n)=>s===r[n])}},gr=class mc{static adjustPoolAttributes(t,r,s,n,i,o){if(!t&&s.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=s.length?s.push(r[u+2]):s[u]=r[u+2];for(let u=0;u=s[u]||o[u+s.length]>=s[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,s,n,i,o,u){if(u){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{Rt(),Dt(),qr=64,as=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},ir=(e,t=1)=>{let r=as(e,t);return typeof r=="string"?r:r[0]},wr=(e,t=1)=>{let r=as(e,t);return typeof r=="string"?r:r[1]},gt=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:De.computeStrides(r)})}),t},Qt=e=>e%4===0?4:e%2===0?2:1,Nr=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Os=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Ds=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,kt=(e,t,r,s)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?s==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:s==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,mo=(e,t,r,s,n)=>{let i=typeof r=="number",o=i?r:r.length,u=[...new Array(o).keys()],p=o<2?"u32":o<=4?`vec${o}`:`array`,h=as(t,n),v=typeof h=="string"?h:h[1],b=typeof h=="string"?h:h[0],l={indices:p,value:v,storage:b,tensor:t},F=We=>typeof We=="string"?We:`${We}u`,D={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},z=i?"uniforms.":"",X=`${z}${e}_shape`,te=`${z}${e}_strides`,K="";for(let We=0;We ${l.indices} { var indices: ${l.indices}; var current = offset; ${K} return indices; }`,ae=We=>(D.offsetToIndices=!0,o<2?We:`o2i_${e}(${We})`),fe=[];if(o>=2)for(let We=o-1;We>=0;We--)fe.push(`${kt(te,We,o)} * (indices[${We}])`);let Ue=o<2?"":` fn i2o_${e}(indices: ${l.indices}) -> u32 { return ${fe.join("+")}; }`,Ie=We=>(D.indicesToOffset=!0,o<2?We:`i2o_${e}(${We})`),tt=(...We)=>o===0?"0u":`${l.indices}(${We.map(F).join(",")})`,Mt=(We,ct)=>o<2?`${We}`:`${kt(We,ct,o)}`,St=(We,ct,Gt)=>o<2?`${We}=${Gt};`:`${kt(We,ct,o)}=${Gt};`,Zt={},tr=(We,ct)=>{D.broadcastedIndicesToOffset=!0;let Gt=`${ct.name}broadcastedIndicesTo${e}Offset`;if(Gt in Zt)return`${Gt}(${We})`;let Tr=[];for(let Kr=o-1;Kr>=0;Kr--){let Xr=ct.indicesGet("outputIndices",Kr+ct.rank-o);Tr.push(`${Mt(te,Kr)} * (${Xr} % ${Mt(X,Kr)})`)}return Zt[Gt]=`fn ${Gt}(outputIndices: ${ct.type.indices}) -> u32 { return ${Tr.length>0?Tr.join("+"):"0u"}; }`,`${Gt}(${We})`},zt=(We,ct)=>(()=>{if(l.storage===l.value)return`${e}[${We}]=${ct};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${We}]=vec2(u32(${ct}), select(0u, 0xFFFFFFFFu, ${ct} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${We}]=vec2(u32(${ct}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${We}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ct}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),vr=We=>(()=>{if(l.storage===l.value)return`${e}[${We}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${We}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${We}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${We}] & 0xFFu), bool(${e}[${We}] & 0xFF00u), bool(${e}[${We}] & 0xFF0000u), bool(${e}[${We}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Ar=o<2?"":` fn get_${e}ByIndices(indices: ${l.indices}) -> ${v} { return ${vr(`i2o_${e}(indices)`)}; }`,nr=o<2?"":(()=>{let We=u.map(Gt=>`d${Gt}: u32`).join(", "),ct=u.map(Gt=>`d${Gt}`).join(", ");return` fn get_${e}(${We}) -> ${v} { return get_${e}ByIndices(${tt(ct)}); }`})(),Er=(...We)=>{if(We.length!==o)throw new Error(`indices length must be ${o}`);let ct=We.map(F).join(",");return o===0?vr("0u"):o===1?vr(ct[0]):(D.get=!0,D.getByIndices=!0,D.indicesToOffset=!0,`get_${e}(${ct})`)},Ft=We=>o<2?vr(We):(D.getByIndices=!0,D.indicesToOffset=!0,`get_${e}ByIndices(${We})`),Vt=o<2?"":` fn set_${e}ByIndices(indices: ${l.indices}, value: ${v}) { ${zt(`i2o_${e}(indices)`,"value")} }`,pr=o<2?"":(()=>{let We=u.map(Gt=>`d${Gt}: u32`).join(", "),ct=u.map(Gt=>`d${Gt}`).join(", ");return` fn set_${e}(${We}, value: ${v}) { set_${e}ByIndices(${tt(ct)}, value); }`})();return{impl:()=>{let We=[],ct=!1;return D.offsetToIndices&&(We.push(ce),ct=!0),D.indicesToOffset&&(We.push(Ue),ct=!0),D.broadcastedIndicesToOffset&&(Object.values(Zt).forEach(Gt=>We.push(Gt)),ct=!0),D.set&&(We.push(pr),ct=!0),D.setByIndices&&(We.push(Vt),ct=!0),D.get&&(We.push(nr),ct=!0),D.getByIndices&&(We.push(Ar),ct=!0),!i&&ct&&We.unshift(`const ${X} = ${l.indices}(${r.join(",")});`,`const ${te} = ${l.indices}(${De.computeStrides(r).join(",")});`),We.join(` `)},type:l,offsetToIndices:ae,indicesToOffset:Ie,broadcastedIndicesToOffset:tr,indices:tt,indicesGet:Mt,indicesSet:St,set:(...We)=>{if(We.length!==o+1)throw new Error(`indices length must be ${o}`);let ct=We[o];if(typeof ct!="string")throw new Error("value must be string");let Gt=We.slice(0,o).map(F).join(",");return o===0?zt("0u",ct):o===1?zt(Gt[0],ct):(D.set=!0,D.setByIndices=!0,D.indicesToOffset=!0,`set_${e}(${Gt}, ${ct})`)},setByOffset:zt,setByIndices:(We,ct)=>o<2?zt(We,ct):(D.setByIndices=!0,D.indicesToOffset=!0,`set_${e}ByIndices(${We}, ${ct});`),get:Er,getByOffset:vr,getByIndices:Ft,usage:s,name:e,strides:te,shape:X,rank:o}},Xe=(e,t,r,s=1)=>mo(e,t,r,"input",s),At=(e,t,r,s=1)=>mo(e,t,r,"output",s),qo=(e,t,r,s=1)=>mo(e,t,r,"internal",s),Qo=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=qr){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let n=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,i=n?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,o=n?`let global_idx = global_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t*r*s}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${s}) fn main(${i}) { ${o} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",s=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:s}of this.uniforms)if(s&&s>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(s/8)}>`):e.push(`${t}:array, ${Math.ceil(s/4)}>`);else{let n=s==null||s===1?r:`vec${s}<${r}>`;e.push(`${t}:${n}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Ra=(e,t)=>new Qo(e,t),Vn=(e,t)=>{let r=e.length,s=[];for(let n=0;n1&&o===1&&s.unshift(i)}return s}}),ja,Wn,Na,Ua,Va,ms,hn,Wa,mn=g(()=>{Rt(),Dt(),cr(),Jt(),ja=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Wn=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Na=(e,t)=>De.sortBasedOnPerm(e,Wn(e.length,t)),Ua=(e,t,r,s)=>{let n=`fn perm(i: ${s.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`;for(let i=0;i{let r=[],s=[];for(let n=0;n{let r=e.dataType,s=e.dims.length,n=Wn(s,t),i=Na(e.dims,n),{newShape:o,newPerm:u}=Va(e.dims,n),p=De.areEqual(u,[2,3,1]),h=De.areEqual(u,[3,1,2]),v=o.length===2&&u[0]>u[1]||p||h,b=v?o:e.dims,l=i;v&&(b=p?[o[0],o[1]*o[2]]:h?[o[0]*o[1],o[2]]:o,l=[b[1],b[0]]);let F=Xe("a",r,b.length),D=At("output",r,l.length),z=16,X;return v?X=te=>` ${te.registerUniform("output_size","u32").declareVariables(F,D)} var tile : array, ${z}>; ${te.mainStart([z,z,1])} let stride = (uniforms.output_shape[1] - 1) / ${z} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${z}u + local_id.x; let input_row = workgroup_id_x * ${z}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${F.getByIndices(`${F.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${z}u + local_id.x; let output_row = workgroup_id_y * ${z}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${D.setByIndices(`${D.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`:X=te=>` ${te.registerUniform("output_size","u32").declareVariables(F,D)} ${Ua(n,s,F,D)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${D.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${D.setByOffset("global_idx",F.getByIndices("aIndices"))} }`,{name:v?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let te=De.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:v?{x:Math.ceil(l[1]/z),y:Math.ceil(l[0]/z)}:{x:Math.ceil(te/64)},programUniforms:[{type:12,data:te},...gt(b,l)]}},getShaderSource:X}},hn=(e,t)=>{ja(e.inputs),e.compute(ms(e.inputs[0],t.perm))},Wa=e=>qt({perm:e.perm})}),Ga,_c,Ka,Xo,Ha,qa,Qa,Xa,Ya,fo,Ps,Ja,Za,Yo,el,tl,Jo,rl,sl,Zo,nl,gc=g(()=>{Rt(),Dt(),Jt(),ii(),mn(),Ga={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"},_c={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},Ka={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Xo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ha=(e,t)=>{let r=[];for(let s=t-e;s{let r=[],s=e.length;for(let i=0;ie[i]);return[r,n]},Qa=(e,t)=>{let r=e.length+t.length,s=[],n=0;for(let i=0;i{for(let r=0;r{let r=[];if(!Xa(e,t)){for(let s=0;sr.push(s))}return r},fo=(e,t,r,s,n,i,o)=>{let u=r[0].dims,p=De.size(i),h=De.size(o),v=Xe("_A",r[0].dataType,u),b=At("output",n,i),l=32,F=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:D=>` ${D.registerUniform("reduceSize","u32").declareVariables(v,b)} ${F} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${D.mainStart(l)} let outputIndex = global_idx / ${l}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${Ka[s]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${l}) { let candidate = f32(${v.getByOffset("offset + k")}); bestValue = ${Ga[s]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${l}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${_c[s]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${b.setByOffset("outputIndex",`${s==="mean"?`${b.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${b.type.storage}(${Xo[s]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},Ps=(e,t,r,s)=>{let n=e.inputs.length===1?r:go(e.inputs,r),i=n.axes;i.length===0&&!n.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((F,D)=>D));let o=De.normalizeAxes(i,e.inputs[0].dims.length),u=o,p=e.inputs[0],h=Ya(u,e.inputs[0].dims.length);h.length>0&&(p=e.compute(ms(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],u=Ha(u.length,p.dims.length));let[v,b]=qa(p.dims,u),l=v;n.keepDims&&(l=Qa(v,o)),e.compute(fo(t,{hint:n.cacheKey,inputDependencies:["type"]},[p],s,e.inputs[0].dataType,l,b),{inputs:[p]})},Ja=(e,t)=>{Ps(e,"ReduceMeanShared",t,"mean")},Za=(e,t)=>{Ps(e,"ReduceL1Shared",t,"l1")},Yo=(e,t)=>{Ps(e,"ReduceL2Shared",t,"l2")},el=(e,t)=>{Ps(e,"ReduceLogSumExpShared",t,"logSumExp")},tl=(e,t)=>{Ps(e,"ReduceMaxShared",t,"max")},Jo=(e,t)=>{Ps(e,"ReduceMinShared",t,"min")},rl=(e,t)=>{Ps(e,"ReduceProdShared",t,"prod")},sl=(e,t)=>{Ps(e,"ReduceSumShared",t,"sum")},Zo=(e,t)=>{Ps(e,"ReduceSumSquareShared",t,"sumSquare")},nl=(e,t)=>{Ps(e,"ReduceLogSumShared",t,"logSum")}}),ys,ol,_o,go,Cs,il,ei,al,ll,ti,ul,dl,ri,cl,pl,Ms,hl,ml,si,fl,_l,ni,gl,wl,oi,yl,ii=g(()=>{Rt(),Dt(),cr(),Jt(),gc(),ys=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.")},ol=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],_o=(e,t,r,s,n,i,o=!1,u=!1)=>{let p=[],h=r[0].dims,v=h.length,b=De.normalizeAxes(n,v),l=!u&&b.length===0;h.forEach((z,X)=>{l||b.indexOf(X)>=0?o&&p.push(1):p.push(z)});let F=p.length,D=De.size(p);return{name:e,shaderCache:t,getShaderSource:z=>{let X=[],te=Xe("_A",r[0].dataType,v),K=At("output",i,F),ce=s(te,K,b),ae=ce[2];for(let fe=0,Ue=0;fe=0?(o&&Ue++,ae=`for(var j${fe}: u32 = 0; j${fe} < ${h[fe]}; j${fe}++) { ${ce[2].includes("last_index")?`let last_index = j${fe};`:""} ${te.indicesSet("input_indices",fe,`j${fe}`)} ${ae} }`):(X.push(`${te.indicesSet("input_indices",fe,K.indicesGet("output_indices",Ue))};`),Ue++);return` ${z.registerUniform("output_size","u32").declareVariables(te,K)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${te.type.indices}; let output_indices = ${K.offsetToIndices("global_idx")}; ${X.join(` `)} ${ce[0]} // init ops for reduce max/min ${ce[1]} ${ae} ${ce[3]} ${ce.length===4?K.setByOffset("global_idx","value"):ce.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:[{type:12,data:D},...gt(h,p)]})}},go=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),qt({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Cs=(e,t,r,s)=>{let n=e.inputs,i=n.length===1?r:go(n,r);e.compute(_o(t,{hint:i.cacheKey,inputDependencies:["rank"]},[n[0]],i.noopWithEmptyAxes&&i.axes.length===0?ol:s,i.axes,n[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},il=(e,t)=>{ys(e.inputs),Cs(e,"ReduceLogSum",t,(r,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},ei=(e,t)=>{ys(e.inputs),Cs(e,"ReduceL1",t,(r,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},al=(e,t)=>{ys(e.inputs),Cs(e,"ReduceL2",t,(r,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},ll=(e,t)=>{ys(e.inputs),Cs(e,"ReduceLogSumExp",t,(r,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},ti=(e,t)=>{ys(e.inputs),Cs(e,"ReduceMax",t,(r,s,n)=>{let i=[];for(let o=0;o=0||n.length===0)&&i.push(r.indicesSet("input_indices",o,0));return[`${i.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},ul=(e,t)=>{ys(e.inputs),Cs(e,"ReduceMean",t,(r,s,n)=>{let i=1;for(let o=0;o=0||n.length===0)&&(i*=e.inputs[0].dims[o]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${i});`]})},dl=(e,t)=>{ys(e.inputs),Cs(e,"ReduceMin",t,(r,s,n)=>{let i=[];for(let o=0;o=0||n.length===0)&&i.push(`input_indices[${o}] = 0;`);return[`${i.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},ri=(e,t)=>{ys(e.inputs),Cs(e,"ReduceProd",t,(r,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},cl=(e,t)=>{ys(e.inputs),Cs(e,"ReduceSum",t,(r,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},pl=(e,t)=>{ys(e.inputs),Cs(e,"ReduceSumSquare",t,(r,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},Ms=(e,t,r)=>{if(t.length===0)return r;let s=1,n=1;for(let i=0;i1024},hl=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ul(e,t):Ja(e,t)},ml=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ei(e,t):Za(e,t)},si=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?al(e,t):Yo(e,t)},fl=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ll(e,t):el(e,t)},_l=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ti(e,t):tl(e,t)},ni=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?dl(e,t):Jo(e,t)},gl=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ri(e,t):rl(e,t)},wl=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?cl(e,t):sl(e,t)},oi=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?pl(e,t):Zo(e,t)},yl=(e,t)=>{Ms(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?il(e,t):nl(e,t)}}),wo,Ml,bl,yo,wc=g(()=>{Rt(),cr(),ii(),wo=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)=>{wo(e.inputs);let r=(s,n,i)=>{let o=[];for(let u=0;u=0||i.length===0)&&o.push(`input_indices[${u}] = 0;`);return[`${o.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",n.setByOffset("global_idx","best_index")]};e.compute(_o("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},bl=(e,t)=>{wo(e.inputs);let r=(s,n,i)=>{let o=[];for(let u=0;u=0||i.length===0)&&o.push(`input_indices[${u}] = 0;`);return[`${o.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",n.setByOffset("global_idx","best_index")]};e.compute(_o("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},yo=e=>qt(e)}),vl,ai,Tl,xl,Pn,El,Pl,Mo=g(()=>{Rt(),Dt(),oe(),Jt(),vl=(e,t)=>{let r=e[0],s=e[1],n=e[2],i=e[3],o=e[4],u=e[5];if(o&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=r.dims[0],h=r.dims[1],v=r.dims[2];if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==v)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let b=n.dims[0]/3,l=b,F=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ce of t.qkvHiddenSizes)if(ce%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");b=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],F=t.qkvHiddenSizes[2]}let D=h;if(b!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==b+l+F)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let z=0;if(o){if(l!==F)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(z=o.dims[3])}let X=D+z,te=-1,K=0;if(i)throw new Error("Mask not supported");if(o)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]!==X)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:z,kvSequenceLength:D,totalSequenceLength:X,maxSequenceLength:te,inputHiddenSize:v,hiddenSize:b,vHiddenSize:F,headSize:Math.floor(b/t.numHeads),vHeadSize:Math.floor(F/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:K,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ai=(e,t,r)=>{let s=Qt(r),n=64,i=r/s;i{let F=At("x",e.dataType,e.dims,s),D=wr(e.dataType),z=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${l.registerUniforms(z).declareVariables(F)} ${l.mainStart([n,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${n}) * uniforms.d_comp + local_offset; var thread_max_vector = ${h}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${h}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(s){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${s}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${n}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${h}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${h}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(s){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${s}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${n}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${F.type.value}(${D}(uniforms.d_inv)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${h}(x[offset + i]); x[offset + i] = ${F.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${n};${p};${s}`,inputDependencies:v},getShaderSource:b,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:u})}},Tl=(e,t,r,s,n,i,o,u)=>{let p=u+i.kvSequenceLength,h=[i.batchSize,i.numHeads,i.sequenceLength,p],v=i.kvNumHeads===void 0&&e>1&&s,b=v?[i.batchSize,i.numHeads,p,i.headSize]:void 0,l=o.scale===0?1/Math.sqrt(i.headSize):o.scale,F=Qt(i.headSize),D=i.headSize/F,z=12,X={x:Math.ceil(p/z),y:Math.ceil(i.sequenceLength/z),z:i.batchSize*i.numHeads},te=[{type:12,data:i.sequenceLength},{type:12,data:D},{type:12,data:p},{type:12,data:i.numHeads},{type:1,data:l},{type:12,data:u},{type:12,data:i.kvSequenceLength}],K=v&&s&&De.size(s.dims)>0,ce=["type","type"];K&&ce.push("type"),n&&ce.push("type");let ae=[{dims:h,dataType:t.dataType,gpuDataType:0}];v&&ae.push({dims:b,dataType:t.dataType,gpuDataType:0});let fe=Ue=>{let Ie=Xe("q",t.dataType,t.dims,F),tt=Xe("key",r.dataType,r.dims,F),Mt=[Ie,tt];if(K){let vr=Xe("past_key",s.dataType,s.dims,F);Mt.push(vr)}n&&Mt.push(Xe("attention_bias",n.dataType,n.dims));let St=At("output",t.dataType,h),Zt=[St];v&&Zt.push(At("present_key",t.dataType,b,F));let tr=wr(1,F),zt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${z}u; var tileQ: array<${Ie.type.storage}, ${z*z}>; var tileK: array<${Ie.type.storage}, ${z*z}>; ${Ue.registerUniforms(zt).declareVariables(...Mt,...Zt)} ${Ue.mainStart([z,z,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; ${K&&v?` let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} ${v?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} var value = ${tr}(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; ${K&&v?` if (n + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else { tileK[idx] = key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} ${v?"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 += ${tr}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(F){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${F}`)}})()}; output[outputIdx] = ${St.type.value} (sum * uniforms.alpha) + ${n?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${F};${n!==void 0};${s!==void 0};${e}`,inputDependencies:ce},getRunData:()=>({outputs:ae,dispatchGroup:X,programUniforms:te}),getShaderSource:fe}},xl=(e,t,r,s,n,i)=>{let o=i+n.kvSequenceLength,u=n.nReps?n.nReps:1,p=n.vHiddenSize*u,h=n.kvNumHeads==null&&e>1&&s,v=h?[n.batchSize,n.numHeads,o,n.headSize]:void 0,b=[n.batchSize,n.sequenceLength,p],l=12,F={x:Math.ceil(n.vHeadSize/l),y:Math.ceil(n.sequenceLength/l),z:n.batchSize*n.numHeads},D=[{type:12,data:n.sequenceLength},{type:12,data:o},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:p},{type:12,data:i},{type:12,data:n.kvSequenceLength}],z=h&&s&&De.size(s.dims)>0,X=["type","type"];z&&X.push("type");let te=[{dims:b,dataType:t.dataType,gpuDataType:0}];h&&te.push({dims:v,dataType:t.dataType,gpuDataType:0});let K=ce=>{let ae=Xe("probs",t.dataType,t.dims),fe=Xe("v",r.dataType,r.dims),Ue=[ae,fe];z&&Ue.push(Xe("past_value",s.dataType,s.dims));let Ie=[At("output",t.dataType,b)];h&&Ie.push(At("present_value",t.dataType,v));let tt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${l}u; var tileQ: array<${ae.type.value}, ${l*l}>; var tileK: array<${ae.type.value}, ${l*l}>; ${ce.registerUniforms(tt).declareVariables(...Ue,...Ie)} ${ce.mainStart([l,l,1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; ${z&&h?` let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; `:` let offsetB = headIdx * uniforms.N * uniforms.K + n; `} ${h?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} var value = ${ae.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${z&&h?` if (w + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else { tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; } `:` tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; `} ${h?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:X},getRunData:()=>({outputs:te,dispatchGroup:F,programUniforms:D}),getShaderSource:K}},Pn=(e,t,r,s,n,i,o,u,p,h,v)=>{let b=Math.min(e.outputCount,1+(o?1:0)+(u?1:0)),l=h.kvNumHeads!==void 0||b>1?h.pastSequenceLength:0,F=l+h.kvSequenceLength,D=p&&De.size(p.dims)>0?p:void 0,z=[t,r];h.kvNumHeads===void 0&&b>1&&o&&De.size(o.dims)>0&&z.push(o),D&&z.push(D);let X=e.compute(Tl(b,t,r,o,D,h,v,l),{inputs:z,outputs:h.kvNumHeads===void 0&&b>1?[-1,1]:[-1]})[0];e.compute(ai(X,h.batchSize*h.numHeads*h.sequenceLength,F),{inputs:[X],outputs:[]});let te=[X,s];h.kvNumHeads===void 0&&b>1&&u&&De.size(u.dims)>0&&te.push(u),e.compute(xl(b,X,s,u,h,l),{inputs:te,outputs:h.kvNumHeads===void 0&&b>1?[0,2]:[0]})},El=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],s=t.sequenceLength,n=t.inputHiddenSize,i=t.headSize,o=12,u={x:Math.ceil(t.headSize/o),y:Math.ceil(t.sequenceLength/o),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:s},{type:12,data:n},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],v=b=>{let l=At("output_q",p[0].dataType,r),F=At("output_k",p[0].dataType,r),D=At("output_v",p[0].dataType,r),z=Xe("input",p[0].dataType,p[0].dims),X=Xe("weight",p[1].dataType,p[1].dims),te=Xe("bias",p[2].dataType,p[2].dims),K=z.type.storage,ce=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${o}u; var tileInput: array<${K}, ${o*o}>; var tileWeightQ: array<${K}, ${o*o}>; var tileWeightK: array<${K}, ${o*o}>; var tileWeightV: array<${K}, ${o*o}>; ${b.registerUniforms(ce).declareVariables(z,X,te,l,F,D)} ${b.mainStart([o,o,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${K}(0); var valueK = ${K}(0); var valueV = ${K}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:h}),getShaderSource:v},{inputs:p,outputs:[-1,-1,-1]})},Pl=(e,t)=>{let r=vl(e.inputs,t),[s,n,i]=El(e,r);return Pn(e,s,n,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),Cl,Sl,$l,kl,Al=g(()=>{Tt(),Rt(),Dt(),cr(),Jt(),Cl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(s,n,i)=>{let o=n.length;if(o!==s.length)throw new Error(`${i}: num dimensions != ${o}`);n.forEach((u,p)=>{if(u!==s[p])throw new Error(`${i}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let s=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,s,"Invalid input scale"),r(e[2].dims,s,"Invalid input B"),r(e[3].dims,s,"Invalid input mean"),r(e[4].dims,s,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Sl=(e,t)=>{let{epsilon:r,spatial:s,format:n}=t,i=e[0].dims,o=s?Qt(i[i.length-1]):1,u=n==="NHWC"&&i.length>1?o:1,p=De.size(i)/o,h=s,v=h?i.length:i,b=Xe("x",e[0].dataType,e[0].dims,o),l=Xe("scale",e[1].dataType,e[1].dims,u),F=Xe("bias",e[2].dataType,e[2].dims,u),D=Xe("inputMean",e[3].dataType,e[3].dims,u),z=Xe("inputVar",e[4].dataType,e[4].dims,u),X=At("y",e[0].dataType,v,o),te=()=>{let ce="";if(s)ce=`let cOffset = ${i.length===1?"0u":n==="NHWC"?`outputIndices[${i.length-1}] / ${o}`:"outputIndices[1]"};`;else if(n==="NCHW")ce=` ${X.indicesSet("outputIndices","0","0")} let cOffset = ${X.indicesToOffset("outputIndices")};`;else{ce=`var cIndices = ${l.type.indices}(0); cIndices[0] = outputIndices[${i.length-1}];`;for(let ae=1;ae` const epsilon = ${r}; ${ce.registerUniform("outputSize","u32").declareVariables(b,l,F,D,z,X)} ${ce.mainStart()} ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${X.offsetToIndices(`global_idx * ${o}`)}; ${te()} let scale = ${l.getByOffset("cOffset")}; let bias = ${F.getByOffset("cOffset")}; let inputMean = ${D.getByOffset("cOffset")}; let inputVar = ${z.getByOffset("cOffset")}; let x = ${b.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${X.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${s}_${o}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:K,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...gt(i)]:[{type:12,data:p}]})}},$l=e=>qt(e),kl=(e,t)=>{let{inputs:r,outputCount:s}=e,n=$l({...t,outputCount:s});if(C.webgpu.validateInputContent&&Cl(r,n),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Sl(r,n))}}),Il,Fl,li,yc=g(()=>{Dt(),Jt(),Il=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")},Fl=e=>{let t=e[0].dims,r=e[0].dims[2],s=De.size(t)/4,n=e[0].dataType,i=Xe("input",n,t,4),o=Xe("bias",n,[r],4),u=Xe("residual",n,t,4),p=At("output",n,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:h=>` const channels = ${r}u / 4; ${h.declareVariables(i,o,u,p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(s)} let value = ${i.getByOffset("global_idx")} + ${o.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; ${p.setByOffset("global_idx","value")} }`}},li=e=>{Il(e.inputs),e.compute(Fl(e.inputs))}}),Ol,lr,Dl,Ll,ui,zl,Bl,di,Rl,jl,ci,Nl,Ul,Vl,Wl,pi,Gn,Gl,bo,Kl,hi,Hl,ql,Ql,Xl,mi,Yl,Jl,Zl,eu,fi,tu,ru,_i,su,gi,wi,yi,Mi,bi,nu,ou,vi,iu,au,Kn=g(()=>{Rt(),Dt(),cr(),Jt(),Ol=(e,t,r,s,n,i,o)=>{let u=Math.ceil(t/4),p="";typeof n=="string"?p=`${n}(a)`:p=n("a");let h=Xe("inputData",r,[u],4),v=At("outputData",s,[u],4),b=[{name:"vec_size",type:"u32"}];return o&&b.push(...o),` ${e.registerUniforms(b).declareVariables(h,v)} ${i??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${v.setByOffset("global_idx",p)} }`},lr=(e,t,r,s,n,i=e.dataType,o,u)=>{let p=[{type:12,data:Math.ceil(De.size(e.dims)/4)}];return o&&p.push(...o),{name:t,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:h=>Ol(h,De.size(e.dims),e.dataType,i,r,s,u),getRunData:h=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(De.size(h[0].dims)/64/4)},programUniforms:p})}},Dl=e=>{e.compute(lr(e.inputs[0],"Abs","abs"))},Ll=e=>{e.compute(lr(e.inputs[0],"Acos","acos"))},ui=e=>{e.compute(lr(e.inputs[0],"Acosh","acosh"))},zl=e=>{e.compute(lr(e.inputs[0],"Asin","asin"))},Bl=e=>{e.compute(lr(e.inputs[0],"Asinh","asinh"))},di=e=>{e.compute(lr(e.inputs[0],"Atan","atan"))},Rl=e=>{e.compute(lr(e.inputs[0],"Atanh","atanh"))},jl=e=>qt(e),ci=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(lr(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Nl=e=>{let t,r,s=e.length>=2&&e[1].data!==0,n=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=s?e[1].getFloat32Array()[0]:-34028234663852886e22,r=n?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=s?e[1].getUint16Array()[0]:64511,r=n?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return qt({min:t,max:r})},Ul=(e,t)=>{let r=t||Nl(e.inputs),s=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"Clip",n=>`clamp(${n}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},Vl=e=>{e.compute(lr(e.inputs[0],"Ceil","ceil"))},Wl=e=>{e.compute(lr(e.inputs[0],"Cos","cos"))},pi=e=>{e.compute(lr(e.inputs[0],"Cosh","cosh"))},Gn=e=>qt(e),Gl=(e,t)=>{let r=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` const elu_alpha_ = ${r}(${t.alpha}); fn elu_f32(a: ${r}) -> ${r} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,t.cacheKey))},bo=(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)); }`,Kl=e=>{let t=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,bo(t)))},hi=e=>{e.compute(lr(e.inputs[0],"Exp","exp"))},Hl=e=>{e.compute(lr(e.inputs[0],"Floor","floor"))},ql=e=>{let t=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,bo(t)))},Ql=(e,t)=>{let r=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Xl=e=>{e.compute(lr(e.inputs[0],"Not",t=>`!${t}`))},mi=e=>{e.compute(lr(e.inputs[0],"Neg",t=>`-${t}`))},Yl=e=>{e.compute(lr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Jl=e=>{let t=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Zl=e=>{e.compute(lr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},eu=e=>qt(e),fi=(e,t)=>{let r=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"HardSigmoid",s=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${s} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},tu=e=>{e.compute(lr(e.inputs[0],"Sin","sin"))},ru=e=>{e.compute(lr(e.inputs[0],"Sinh","sinh"))},_i=e=>{e.compute(lr(e.inputs[0],"Sqrt","sqrt"))},su=e=>{e.compute(lr(e.inputs[0],"Tan","tan"))},gi=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,wi=e=>{e.compute(lr(e.inputs[0],"Tanh",gi))},yi=(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 ${gi("v")}; } `,Mi=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,bi=e=>{let t=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"FastGelu",Mi,yi(t),void 0,e.inputs[0].dataType))},nu=(e,t)=>{let r=wr(e.inputs[0].dataType);return e.compute(lr(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${r}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},ou=e=>{e.compute(lr(e.inputs[0],"Log","log"))},vi=(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; } `,iu=e=>`quick_gelu_impl(${e})`,au=(e,t)=>{let r=wr(e.inputs[0].dataType);e.compute(lr(e.inputs[0],"QuickGelu",iu,vi(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),lu,uu,Ti,du=g(()=>{Dt(),Jt(),Kn(),lu=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")},uu=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Xe("input",e[0].dataType,e[0].dims,4),s=Xe("bias",e[0].dataType,[e[0].dims[2]],4),n=At("output",e[0].dataType,t,4),i=De.size(t)/4,o=ir(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:u=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${u.declareVariables(r,s,n)} ${bo(o)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes(i)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${n.setByOffset("global_idx","valueLeft * geluRight")} }`}},Ti=e=>{lu(e.inputs),e.compute(uu(e.inputs))}}),cu,xi,Ss,pu,hu,Ei,mu,fu,_u,Pi,gu,wu,Ci,Mc=g(()=>{Rt(),Dt(),Jt(),cu=(e,t,r,s,n,i,o,u,p,h,v,b)=>{let l,F;typeof u=="string"?l=F=(K,ce)=>`${u}((${K}),(${ce}))`:typeof u=="function"?l=F=u:(l=u.scalar,F=u.vector);let D=At("outputData",v,s.length,4),z=Xe("aData",p,t.length,4),X=Xe("bData",h,r.length,4),te;if(n)if(i){let K=De.size(t)===1,ce=De.size(r)===1,ae=t.length>0&&t[t.length-1]%4===0,fe=r.length>0&&r[r.length-1]%4===0;K||ce?te=D.setByOffset("global_idx",F(K?`${z.type.value}(${z.getByOffset("0")}.x)`:z.getByOffset("global_idx"),ce?`${X.type.value}(${X.getByOffset("0")}.x)`:X.getByOffset("global_idx"))):te=` let outputIndices = ${D.offsetToIndices("global_idx * 4u")}; let offsetA = ${z.broadcastedIndicesToOffset("outputIndices",D)}; let offsetB = ${X.broadcastedIndicesToOffset("outputIndices",D)}; ${D.setByOffset("global_idx",F(o||ae?z.getByOffset("offsetA / 4u"):`${z.type.value}(${z.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||fe?X.getByOffset("offsetB / 4u"):`${X.type.value}(${X.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else te=D.setByOffset("global_idx",F(z.getByOffset("global_idx"),X.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let K=(ce,ae,fe="")=>{let Ue=`aData[indexA${ae}][componentA${ae}]`,Ie=`bData[indexB${ae}][componentB${ae}]`;return` let outputIndices${ae} = ${D.offsetToIndices(`global_idx * 4u + ${ae}u`)}; let offsetA${ae} = ${z.broadcastedIndicesToOffset(`outputIndices${ae}`,D)}; let offsetB${ae} = ${X.broadcastedIndicesToOffset(`outputIndices${ae}`,D)}; let indexA${ae} = offsetA${ae} / 4u; let indexB${ae} = offsetB${ae} / 4u; let componentA${ae} = offsetA${ae} % 4u; let componentB${ae} = offsetB${ae} % 4u; ${ce}[${ae}] = ${fe}(${l(Ue,Ie)}); `};v===9?te=` var data = vec4(0); ${K("data",0,"u32")} ${K("data",1,"u32")} ${K("data",2,"u32")} ${K("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:te=` ${K("outputData[global_idx]",0)} ${K("outputData[global_idx]",1)} ${K("outputData[global_idx]",2)} ${K("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(z,X,D)} ${b??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${te} }`},xi=(e,t,r,s,n,i,o=r.dataType)=>{let u=!De.areEqual(r.dims,s.dims),p=r.dims,h=De.size(r.dims),v=!1,b=!1,l=[u];if(u){let F=zr.calcShape(r.dims,s.dims,!1);if(!F)throw new Error("Can't perform binary op on the given tensors");p=F,h=De.size(p);let D=De.size(r.dims)===1,z=De.size(s.dims)===1,X=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,te=s.dims.length>0&&s.dims[s.dims.length-1]%4===0;l.push(D),l.push(z),l.push(X),l.push(te);let K=1;for(let ce=1;ceF.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:F=>cu(F,r.dims,s.dims,p,v,u,b,n,r.dataType,s.dataType,o,i),getRunData:()=>({outputs:[{dims:p,dataType:o}],dispatchGroup:{x:Math.ceil(h/64/4)},programUniforms:[{type:12,data:Math.ceil(De.size(p)/4)},...gt(r.dims,s.dims,p)]})}},Ss=(e,t,r,s,n,i)=>{e.compute(xi(t,n??"",e.inputs[0],e.inputs[1],r,s,i))},pu=e=>{Ss(e,"Add",(t,r)=>`${t}+${r}`)},hu=e=>{Ss(e,"Div",(t,r)=>`${t}/${r}`)},Ei=e=>{Ss(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},mu=e=>{Ss(e,"Mul",(t,r)=>`${t}*${r}`)},fu=e=>{let t=Xe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Ss(e,"Pow",{scalar:(r,s)=>`pow_custom(${r},${s})`,vector:(r,s)=>`pow_vector_custom(${r},${s})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { return ${t}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},_u=e=>{Ss(e,"Sub",(t,r)=>`${t}-${r}`)},Pi=e=>{Ss(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},gu=e=>{Ss(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},wu=e=>{Ss(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Ci=e=>{Ss(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),yu,Si,Mu,bu,$i,vu,bc=g(()=>{Rt(),Dt(),cr(),Jt(),yu=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,s=e[r],n=s.dataType,i=s.dims.length;e.forEach((o,u)=>{if(u!==r){if(o.dataType!==n)throw new Error("input tensors should be one type");if(o.dims.length!==i)throw new Error("input tensors should have the same shape");o.dims.forEach((p,h)=>{if(h!==t&&p!==s.dims[h])throw new Error("non concat dimensions must match")})}})},Si=(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; }`,Mu=(e,t)=>{let r=e.length,s=[];for(let n=0;n{let n=De.size(r),i=new Array(e.length),o=new Array(e.length),u=0,p=[],h=[],v=[{type:12,data:n}];for(let z=0;z`uniforms.sizeInConcatAxis${z}`).join(","),D=z=>` ${(()=>{z.registerUniform("outputSize","u32");for(let X=0;X(${F}); ${l} -= sizeInConcatAxis[inputIndex - 1u]; } ${Mu(o,b)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:r,dataType:s}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:v}),getShaderSource:D}},$i=(e,t)=>{let r=e.inputs,s=r[0].dims,n=De.normalizeAxis(t.axis,s.length);yu(r,n);let i=s.slice();i[n]=r.reduce((u,p)=>u+(p.dims.length>n?p.dims[n]:0),0);let o=r.filter(u=>De.size(u.dims)>0);e.compute(bu(o,n,i,r[0].dataType),{inputs:o})},vu=e=>qt({axis:e.axis})}),Ws,rn,sn,vo,nn=g(()=>{Rt(),Dt(),Ws=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},rn=(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})},sn=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},vo=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[r,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:r,beta:s}}else if(t==="Clip"){let[r,s]=(e==null?void 0:e.activation_params)||[hs,Es];return{activation:t,clipMax:s,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),ts,ki,To=g(()=>{ts=(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.`)}},ki=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),Hn,Tu=g(()=>{Hn=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)); } `}),xu,Eu,xo,Ai,Ii,Eo,Pu,Po,Co=g(()=>{Rt(),Dt(),Jt(),nn(),To(),xu=(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":""}); `,Eu=(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];"} }`,xo=(e,t,r="f32",s,n=!1,i=32,o=!1,u=32)=>{let p=t[1]*e[1],h=t[0]*e[0],v=n?p:i,b=n?i:p,l=v/t[0],F=i/t[1];if(!((n&&l===4&&e[1]===4||!n&&(l===3||l===4))&&v%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${l} must be 3 or 4. tileAWidth ${v} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${v/l}>, ${b}>; var mm_Bsub: array, ${h/e[0]}>, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${l}; const tileInner = ${i}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${o?"0":"i32(globalId.z)"}; ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${p}; let num_tiles = ${o?`${Math.ceil(u/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${o?`i32(globalId.z) * ${u}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${F}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${xu(n,s)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${F}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${l===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Eu(n,l)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Ai=(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":""}); `,Ii=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Eo=(e,t,r="f32",s,n=!1,i=32,o=!1,u=32,p=!1)=>{let h=e[1]*t[1],v=e[0]*t[0],b=n?h:i,l=n?i:h;if(!(l%t[1]===0&&b%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${b} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let F=l/t[1],D=b/t[0],z=i/t[1],X=p?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${h}; let globalColStart = i32(workgroupId.x) * ${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 inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${b}; inputCol = inputCol + ${t[0]}) { ${Ai(n,s)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${v}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${s?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${n?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${h}; let tileRowA = i32(localId.y) * ${F}; let tileColA = i32(localId.x) * ${D}; let tileRowB = i32(localId.y) * ${z}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${F}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${D}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Ai(n,s)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${z}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${s?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Ii(n)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${l}>; var mm_Bsub : array, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${i}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${o?"0":"i32(globalId.z)"}; ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${o?`${Math.ceil(u/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${o?`i32(globalId.z) * ${u}`:"0"}; var acc : array, rowPerThread>; ${X} } `},Pu=(e,t,r,s,n,i=!1)=>{let[o,u,p]=n,[h,v,b,l]=s,F=Vn(o,p),D=Vn(u,p),z=ir(s[0].type.tensor),X=()=>{let K=v.rank,ce=h.rank,ae=`var aIndices: ${v.type.indices};`;for(let fe=K-2-1,Ue=ce-1;fe>=0;fe--,Ue--)ae+=` aIndices[${fe}] = ${ce>1?`batchIndices[${Ue}]`:"batchIndices"};`;return F.forEach(fe=>{ae+=` aIndices[${fe}] = 0;`}),ae+=` aIndices[${K-2}] = u32(row); aIndices[${K-1}] = u32(colIn);`,ae},te=()=>{let K=b.rank,ce=h.rank,ae=`var bIndices: ${b.type.indices};`;for(let fe=K-2-1,Ue=ce-1;fe>=0;fe--,Ue--)ae+=` bIndices[${fe}] = ${ce>1?`batchIndices[${Ue}]`:"batchIndices"};`;return D.forEach(fe=>{ae+=` bIndices[${fe}] = 0;`}),ae+=` bIndices[${K-2}] = u32(row); bIndices[${K-1}] = u32(colIn);`,ae};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${ts(e,z)} { var value = ${ts(e,z)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${X()} value = ${v.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${ts(e,z)} { var value = ${ts(e,z)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${te()} value = ${b.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${ts(e,z)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${i?"bias[colIn]":`${ts(e,z)}(bias[row])`};`:""} ${r} ${l.setByIndices("vec3(coords)","value")} } } `},Po=(e,t,r,s,n=!1,i)=>{let o=e[0].dims,u=e[1].dims,p=o.slice(0,-2),h=u.slice(0,-2),v=s?s.slice(0,-2):r.slice(0,-2),b=De.size(v),l=o[o.length-2],F=o[o.length-1],D=u[u.length-1],z=F%4===0&&D%4===0,X=l<=8?[4,1,1]:[4,4,1],te=[8,8,1],K=[Math.ceil(D/te[0]/X[0]),Math.ceil(l/te[1]/X[1]),Math.ceil(b/te[2]/X[2])],ce=z?4:1,ae=[...p,l,F/ce],fe=ae.length,Ue=[...h,F,D/ce],Ie=Ue.length,tt=[b,l,D/ce],Mt=[{type:6,data:l},{type:6,data:D},{type:6,data:F}];rn(t,Mt),Mt.push(...gt(v,ae,Ue));let St=["rank","rank"],Zt=e.length>2;Zt&&(Mt.push(...gt(e[2].dims)),St.push("rank")),Mt.push(...gt(tt));let tr=zt=>{let vr=v.length,Ar=qo("batchDims",e[0].dataType,vr,1),nr=ir(e[0].dataType),Er=Xe("a",e[0].dataType,fe,ce),Ft=Xe("b",e[1].dataType,Ie,ce),Vt=At("result",e[0].dataType,tt.length,ce),pr=[Er,Ft];if(Zt){let Kr=n?ce:1;pr.push(Xe("bias",e[2].dataType,e[2].dims.length,Kr))}let We=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];sn(t,We);let ct=ir(Vt.type.tensor),Gt=Ws(t,Vt.type.value,ct),Tr=Pu(ce,Zt,Gt,[Ar,Er,Ft,Vt],[p,h,v],n);return` ${zt.registerUniforms(We).registerInternalVariables(Ar).declareVariables(...pr,Vt)} ${Tr} ${z?xo(X,te,nr,Ar):Eo(X,te,nr,Ar)} `};return{name:"MatMul",shaderCache:{hint:`${X};${t.activation};${z};${n}`,inputDependencies:St},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:K[0],y:K[1],z:K[2]},programUniforms:Mt}),getShaderSource:tr}}}),Cu,Su,vc=g(()=>{Rt(),xe(),Jt(),nn(),To(),Tu(),Co(),Cu=(e,t,r,s,n=!1,i,o=4,u=4,p=4,h="f32")=>{let v=Mt=>{switch(Mt){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 ${Mt} is not supported.`)}},b=Mt=>{switch(Mt){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 ${Mt} is not supported.`)}},l=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,F=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,D=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",z=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",X=e?"row":"col",te=e?"col":"row",K=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${X} / outWidth; let outCol = ${X} % outWidth; let WRow = ${te} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${te} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${te} % inChannels; var resData = ${ts(o,h)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${D} && xCol >= 0 && xCol < ${z}) { ${l} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${v(o)} } return resData;`,ce=e?t&&s?` let col = colIn * ${o}; ${K}`:` let col = colIn * ${o}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${K} } return ${ts(o,h)}(0.0);`:s&&r?` let col = colIn * ${o}; ${K}`:` let col = colIn * ${o}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${K} } return ${ts(o,h)}(0.0);`,ae=`${b(u)}`,fe=ts(p,h),Ue=ts(e?o:u,h),Ie=ts(e?u:o,h),tt=Ws(i,fe,h);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ue} { ${e?ce:ae} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ie} { ${e?ae:ce} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${fe}) { 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])"}; ${F} ${ki(n)} ${tt} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Su=(e,t,r,s,n,i,o,u,p)=>{let h=t.format==="NHWC",v=h?e[0].dims[3]:e[0].dims[1],b=r[0],l=h?r[2]:r[3],F=h?r[1]:r[2],D=h?r[3]:r[1],z=h&&(v%4===0||v%3===0)&&D%4===0,X=h?D:l*F,te=h?l*F:D,K=[8,8,1],ce=s<=8?[4,1,1]:[4,4,1],ae=[Math.ceil(X/K[0]/ce[0]),Math.ceil(te/K[1]/ce[1]),Math.ceil(b/K[2]/ce[2])];_r("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${ae}`);let fe=z?h&&v%4!==0?3:4:1,Ue=K[1]*ce[1],Ie=K[0]*ce[0],tt=Math.max(K[0]*fe,K[1]),Mt=s%Ue===0,St=n%Ie===0,Zt=i%tt===0,tr=z?[fe,4,4]:[1,1,1],zt=[{type:6,data:s},{type:6,data:n},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];rn(t,zt),zt.push(...gt(e[0].dims,e[1].dims));let vr=["rank","rank"];o&&(zt.push(...gt(e[2].dims)),vr.push("rank")),zt.push(...gt(r));let Ar=nr=>{let Er=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];sn(t,Er);let Ft=z?4:1,Vt=ir(e[0].dataType),pr=` fn setOutputAtIndex(flatIndex : i32, value : ${z?`vec4<${Vt}>`:Vt}) { result[flatIndex] = ${z?`vec4<${Vt}>`:Vt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${z?`vec4<${Vt}>`:Vt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${z?"/ 4":""}, value); }`,We=Xe("x",e[0].dataType,e[0].dims.length,fe===3?1:fe),ct=Xe("w",e[1].dataType,e[1].dims.length,Ft),Gt=[We,ct],Tr=At("result",e[0].dataType,r.length,Ft);if(o){let Kr=Xe("bias",e[2].dataType,e[2].dims.length,Ft);Gt.push(Kr),pr+=` fn getBiasByOutputCoords(coords : vec4) -> ${z?`vec4<${Vt}>`:Vt} { return bias[coords.${h?"w":"y"}${z?"/ 4":""}]; }`}return` ${Hn("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${nr.registerUniforms(Er).declareVariables(...Gt,Tr)} ${pr} ${Cu(h,Mt,St,Zt,o,t,tr[0],tr[1],tr[2],Vt)} ${z?xo(ce,K,Vt,void 0,!h,tt):Eo(ce,K,Vt,void 0,!h,tt,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${fe};${z};${Mt};${St};${Zt};${Ue};${Ie};${tt}`,inputDependencies:vr},getRunData:()=>({outputs:[{dims:p?p(r):r,dataType:e[0].dataType}],dispatchGroup:{x:ae[0],y:ae[1],z:ae[2]},programUniforms:zt}),getShaderSource:Ar}}}),Fi,Oi,qn,Di,Li,$u,zi,ku,Tc=g(()=>{Rt(),xe(),Dt(),Jt(),nn(),To(),Fi=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,qn=(e,t)=>t<=1?e:e+(e-1)*(t-1),Di=(e,t,r,s=1)=>{let n=qn(t,s);return Math.floor((e[0]*(r-1)-r+n)/2)},Li=(e,t,r,s,n)=>{n==null&&(n=Di(e,t[0],s[0]));let i=[0,0,0,r];for(let o=0;o<3;o++)e[o]+2*n>=t[o]&&(i[o]=Math.trunc((e[o]-t[o]+2*n)/s[o]+1));return i},$u=(e,t,r,s,n,i,o,u,p,h)=>{let v,b,l,F;if(e==="VALID"&&(e=0),typeof e=="number"){v={top:e,bottom:e,left:e,right:e,front:e,back:e};let D=Li([t,r,s,1],[u,p,h],1,[n,i,o],e);b=D[0],l=D[1],F=D[2]}else if(Array.isArray(e)){if(!e.every((z,X,te)=>z===te[0]))throw Error(`Unsupported padding parameter: ${e}`);v={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let D=Li([t,r,s,1],[u,p,h],1,[n,i,o],e[0]);b=D[0],l=D[1],F=D[2]}else if(e==="SAME_UPPER"){b=Math.ceil(t/n),l=Math.ceil(r/i),F=Math.ceil(s/o);let D=(b-1)*n+u-t,z=(l-1)*i+p-r,X=(F-1)*o+h-s,te=Math.floor(D/2),K=D-te,ce=Math.floor(z/2),ae=z-ce,fe=Math.floor(X/2),Ue=X-fe;v={top:ce,bottom:ae,left:fe,right:Ue,front:te,back:K}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:v,outDepth:b,outHeight:l,outWidth:F}},zi=(e,t,r,s,n,i=!1,o="channelsLast")=>{let u,p,h,v,b;if(o==="channelsLast")[u,p,h,v,b]=e;else if(o==="channelsFirst")[u,b,p,h,v]=e;else throw new Error(`Unknown dataFormat ${o}`);let[l,,F,D,z]=t,[X,te,K]=Oi(r),[ce,ae,fe]=Oi(s),Ue=qn(F,ce),Ie=qn(D,ae),tt=qn(z,fe),{padInfo:Mt,outDepth:St,outHeight:Zt,outWidth:tr}=$u(n,p,h,v,X,te,K,Ue,Ie,tt),zt=i?l*b:l,vr=[0,0,0,0,0];return o==="channelsFirst"?vr=[u,zt,St,Zt,tr]:o==="channelsLast"&&(vr=[u,St,Zt,tr,zt]),{batchSize:u,dataFormat:o,inDepth:p,inHeight:h,inWidth:v,inChannels:b,outDepth:St,outHeight:Zt,outWidth:tr,outChannels:zt,padInfo:Mt,strideDepth:X,strideHeight:te,strideWidth:K,filterDepth:F,filterHeight:D,filterWidth:z,effectiveFilterDepth:Ue,effectiveFilterHeight:Ie,effectiveFilterWidth:tt,dilationDepth:ce,dilationHeight:ae,dilationWidth:fe,inShape:e,outShape:vr,filterShape:t}},ku=(e,t,r,s,n,i)=>{let o=i==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],p={x:r.map((X,te)=>te)},h=[Math.ceil(Fi(p.x.map(X=>r[X]))/u[0]),1,1];_r("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let v=1,b=De.size(r),l=[{type:12,data:b},{type:12,data:s},{type:12,data:n},{type:12,data:t.strides},{type:12,data:t.dilations}];rn(t,l),l.push(...gt(e[0].dims,e[1].dims));let F=["rank","rank"],D=e.length===3;D&&(l.push(...gt(e[2].dims)),F.push("rank")),l.push(...gt(r));let z=X=>{let te=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:n.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];sn(t,te);let K=1,ce=ir(e[0].dataType),ae=Xe("x",e[0].dataType,e[0].dims.length,v),fe=Xe("W",e[1].dataType,e[1].dims.length,K),Ue=[ae,fe],Ie=At("result",e[0].dataType,r.length,K),tt="";if(D){let Zt=Xe("bias",e[2].dataType,e[2].dims.length,K);Ue.push(Zt),tt+=` fn getBiasByOutputCoords(coords : array) -> ${ce} { return bias[${o?kt("coords",4,5):kt("coords",1,5)}]; }`}let Mt=ts(v,ce),St=Ws(t,Mt,ce);return` ${tt} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${ae.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${fe.getByIndices("aIndices")}; } ${X.registerUniforms(te).declareVariables(...Ue,Ie)} ${X.mainStart()} ${X.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Ie.offsetToIndices("global_idx")}; let batch = ${kt("coords",0,ae.rank)}; let d2 = ${o?kt("coords",ae.rank-1,ae.rank):kt("coords",1,ae.rank)}; let xFRCCorner = vec3(${o?kt("coords",1,ae.rank):kt("coords",2,ae.rank)}, ${o?kt("coords",2,ae.rank):kt("coords",3,ae.rank)}, ${o?kt("coords",3,ae.rank):kt("coords",4,ae.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${o?kt("uniforms.x_shape",1,ae.rank):kt("uniforms.x_shape",2,ae.rank)}; let xShapeZ = ${o?kt("uniforms.x_shape",2,ae.rank):kt("uniforms.x_shape",3,ae.rank)}; let xShapeW = ${o?kt("uniforms.x_shape",3,ae.rank):kt("uniforms.x_shape",4,ae.rank)}; let xShapeU = ${o?kt("uniforms.x_shape",4,ae.rank):kt("uniforms.x_shape",1,ae.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${o?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${o?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${o?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${o?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${D?"value = value + getBiasByOutputCoords(coords)":""}; ${St} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${o};${v};${D}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:l}),getShaderSource:z}}}),Bi,Au,xc=g(()=>{Rt(),Dt(),Jt(),nn(),Bi=(e,t,r,s)=>{let n=e.length>2,i=n?"value += b[output_channel];":"",o=e[0].dims,u=e[1].dims,p=t.format==="NHWC",h=p?r[3]:r[1],v=h/t.group,b=p&&v>=4?Qt(h):1,l=De.size(r)/b,F=[{type:12,data:l},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:v}];rn(t,F),F.push(...gt(o,[u[0],u[1],u[2],u[3]/b]));let D=n?["rank","rank","rank"]:["rank","rank"];F.push(...gt([r[0],r[1],r[2],r[3]/b]));let z=X=>{let te=At("output",e[0].dataType,r.length,b),K=ir(te.type.tensor),ce=Ws(t,te.type.value,K),ae=Xe("x",e[0].dataType,o.length),fe=Xe("w",e[1].dataType,u.length,b),Ue=[ae,fe];n&&Ue.push(Xe("b",e[2].dataType,e[2].dims,b));let Ie=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];sn(t,Ie);let tt=p?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { continue; } for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; let xVal = ${ae.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${fe.get("wHeight","wWidth","wInChannel","output_channel")}; value += xVal * wVal; } } } `:` for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { continue; } let xVal = ${ae.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${fe.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${X.registerUniforms(Ie).declareVariables(...Ue,te)} ${X.mainStart()} ${X.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${te.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${p?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${b} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; var value: ${te.type.value} = ${te.type.value}(0); ${tt} ${i} ${ce} ${te.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${b}`,inputDependencies:D},getRunData:()=>({outputs:[{dims:s?s(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:F}),getShaderSource:z}},Au=(e,t,r,s)=>{let n=e.length>2,i=Qt(r[3]),o=Qt(r[2]),u=De.size(r)/i/o,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],v=[r[0],r[1],r[2],r[3]/i],b=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];rn(t,b),b.push(...gt(p,h,v));let l=(o-1)*t.strides[1]+h[1],F=D=>{let z=At("output",e[0].dataType,v.length,i),X=ir(z.type.tensor),te=Ws(t,z.type.value,X),K=Xe("x",e[0].dataType,p.length,i),ce=Xe("w",e[1].dataType,h.length,i),ae=[K,ce];n&&ae.push(Xe("b",e[2].dataType,e[2].dims,i));let fe=n?"value += b[output_channel];":"",Ue=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return sn(t,Ue),` ${D.registerUniforms(Ue).declareVariables(...ae,z)} ${D.mainStart()} ${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${o}u; let col = (index1 % width1) * ${o}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${K.type.value}, ${l}>; var values: array<${z.type.value}, ${o}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${l}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${K.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${K.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${ce.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${o}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${o}u; i++) { var value = values[i]; ${fe} ${te} ${z.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${o};${l};${h[0]};${h[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:b}),getShaderSource:F}}}),Ri,Iu,Fu,Ou=g(()=>{Rt(),Dt(),Co(),Jt(),nn(),Ri=(e,t,r,s,n=!1,i)=>{let o=e[0].dims,u=e[1].dims,p=o[o.length-2],h=u[u.length-1],v=o[o.length-1],b=Qt(h),l=Qt(v),F=Qt(p),D=De.size(r)/b/F,z=e.length>2,X=s?s.slice(0,-2):r.slice(0,-2),te=[De.size(X),p,h],K=[{type:12,data:D},{type:12,data:p},{type:12,data:h},{type:12,data:v}];rn(t,K),K.push(...gt(X,o,u)),z&&K.push(...gt(e[2].dims)),K.push(...gt(te));let ce=ae=>{let fe=qo("batch_dims",e[0].dataType,X.length),Ue=Xe("a",e[0].dataType,o.length,l),Ie=Xe("b",e[1].dataType,u.length,b),tt=At("output",e[0].dataType,te.length,b),Mt=ir(tt.type.tensor),St=Ws(t,tt.type.value,Mt),Zt=[Ue,Ie],tr="";if(z){let pr=n?b:1;Zt.push(Xe("bias",e[2].dataType,e[2].dims.length,pr)),tr=`${n?`value += bias[col / ${pr}];`:`value += ${tt.type.value}(bias[row + i]);`}`}let zt=o.slice(0,-2),vr=u.slice(0,-2),Ar=Vn(zt,X),nr=Vn(vr,X),Er=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];sn(t,Er);let Ft=(pr,We)=>{let ct=pr.rank,Gt=pr.name;if(ct===2)return`var ${Gt}_indices = ${pr.type.indices}(0u, 0u);`;let Tr=fe.rank,Kr=`var ${Gt}_indices: ${pr.type.indices};`;for(let Xr=ct-2-1,no=Tr-1;Xr>=0;Xr--,no--)Kr+=` ${Gt}_indices[${Xr}] = ${Tr>1?`batch_indices[${no}]`:"batch_indices"};`;return We.forEach(Xr=>{Kr+=` ${Gt}_indices[${Xr}] = 0;`}),Kr+=`${Gt}_indices[${ct-2}] = 0u; ${Gt}_indices[${ct-1}] = 0u;`,Kr},Vt=()=>{let pr=`var a_data: ${Ue.type.value};`;for(let We=0;We; for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { ${Vt()} } for (var i = 0u; i < ${F}u; i++) { var value = values[i]; ${tr} ${St} let cur_indices = ${tt.type.indices}(batch, row + i, col); let offset = ${tt.indicesToOffset("cur_indices")}; ${tt.setByOffset(`offset / ${b}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${b};${l};${F};${n}`,inputDependencies:z?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:K}),getShaderSource:ce}},Iu=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.")},Fu=e=>{Iu(e.inputs);let t=zr.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&s<8?e.compute(Ri(e.inputs,{activation:""},t)):e.compute(Po(e.inputs,{activation:""},t))}}),ji,So,Du,Qn,Ni,Ui,on,Lu,Vi,Ec=g(()=>{Dt(),vc(),Tc(),Co(),xc(),nn(),Ou(),mn(),ji=(e,t,r,s,n,i)=>{let o=e[0],u=e.slice(i?1:2,i?3:4),p=u.length,h=t[0],v=t.slice(2).map((l,F)=>l+(l-1)*(r[F]-1)),b=u.map((l,F)=>l+s[F]+s[F+p]).map((l,F)=>Math.floor((l-v[F]+n[F])/n[F]));return b.splice(0,0,o),b.splice(i?3:1,0,h),b},So=[2,3,1,0],Du=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*t.group;if(r!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Qn=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=vo(e),r=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,i=e.group,o=e.kernel_shape,u=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:s,format:r,dilations:n,group:i,kernelShape:o,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Ui=(e,t,r,s)=>{let n=r.format==="NHWC",i=ji(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,n);if(r.group!==1){let Ue=[t[0]];if(n){let Ie=e.kernelCustomData.wT??e.compute(ms(t[1],So),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ie),Ue.push(Ie)}else Ue.push(t[1]);t.length===3&&Ue.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&n&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(Au(Ue,r,i,s),{inputs:Ue}):e.compute(Bi(Ue,r,i,s),{inputs:Ue});return}let o=t.length===3,u=t[0].dims[n?1:2],p=t[0].dims[n?2:3],h=t[0].dims[n?3:1],v=t[1].dims[2],b=t[1].dims[3],l=i[n?1:2],F=i[n?2:3],D=i[n?3:1],z=n&&v===u&&b===p&&r.pads[0]===0&&r.pads[1]===0;if(z||v===1&&b===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let Ue=i[0],Ie,tt,Mt,St=[];if(n){let zt=e.kernelCustomData.wT??e.compute(ms(t[1],So),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=zt),z){let vr=u*p*h;Ie=t[0].reshape([1,Ue,vr]),tt=zt.reshape([1,vr,D]),Mt=[1,Ue,D]}else Ie=t[0].reshape([Ue,u*p,h]),tt=zt.reshape([1,h,D]),Mt=[Ue,l*F,D];St.push(Ie),St.push(tt)}else Ie=t[0].reshape([Ue,h,u*p]),tt=t[1].reshape([1,D,h]),Mt=[Ue,D,l*F],St.push(tt),St.push(Ie);o&&St.push(t[2]);let Zt=Mt[2],tr=St[0].dims[St[0].dims.length-1];Zt<8&&tr<8?e.compute(Ri(St,r,i,Mt,n,s),{inputs:St}):e.compute(Po(St,r,i,Mt,n,s),{inputs:St});return}let X=!0,te=e.kernelCustomData.wT??e.compute(ms(t[1],So),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=te);let K=[t[0],te];o&&K.push(t[2]);let ce=n?l*F:D,ae=n?D:l*F,fe=v*b*h;e.compute(Su(K,r,i,ce,ae,fe,o,X,s),{inputs:K})},on=(e,t)=>{let r=t.format==="NHWC",s=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let n=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),o=[1].concat(t.dilations),u=[1].concat(t.kernelShape),p=Qn({...t,pads:n,strides:i,dilations:o,kernelShape:u},s);Ui(e,s,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Lu=(e,t,r)=>{let s=r.format==="NHWC"?"channelsLast":"channelsFirst",n=Qn(r,t),i=r.autoPad==="NOTSET"?r.pads:r.autoPad,o=zi(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,s);e.compute(ku(t,n,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],s))},Vi=(e,t)=>{if(Du(e.inputs,t),e.inputs[0].dims.length===3)on(e,t);else if(e.inputs[0].dims.length===5)Lu(e,e.inputs,t);else{let r=Qn(t,e.inputs);Ui(e,e.inputs,r)}}}),zu,Wi,Pc=g(()=>{Rt(),xe(),Jt(),nn(),To(),Tu(),Co(),zu=(e,t=!1,r,s,n=4)=>{let i=X=>{switch(X){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${s}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${X} is not supported.`)}},o=e?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,u=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",v=e?"row":"col",b=e?"col":"row",l=` let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${v} / outWidth; let outCol = ${v} % outWidth; let WRow = ${b} / (uniforms.filter_dims[1] * inChannels); let WCol = ${b} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${p}) || fract(xR) > 0.0) { return ${s}(0.0); } if (xC < 0.0 || xC >= f32(${h}) || fract(xC) > 0.0) { return ${s}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${b} % inChannels; ${o} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${n}];`,F=e?` let col = colIn * ${n}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${l} } return ${s}(0.0);`:` let col = colIn * ${n}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${l} } return ${s}(0.0);`,D=` let col = colIn * ${n}; let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${i(n)} } return ${s}(0.0); `,z=Ws(r,s);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${s} { ${e?F:D} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${s} { ${e?D:F} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${s}) { let col = colIn * ${n}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${u} ${ki(t)} ${z} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${n}] = value; } }`},Wi=(e,t,r,s,n,i,o,u)=>{let p=t.format==="NHWC",h=p?e[0].dims[3]:e[0].dims[1],v=r[0],b=p?r[2]:r[3],l=p?r[1]:r[2],F=p?r[3]:r[1],D=p&&h%4===0&&h%3&&F%4===0,z=p?F:b*l,X=p?b*l:F,te=[8,8,1],K=s<=8?[4,1,1]:[4,4,1],ce=[Math.ceil(z/te[0]/K[0]),Math.ceil(X/te[1]/K[1]),Math.ceil(v/te[2]/K[2])];_r("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ce}`);let ae=D?4:1,fe=Math.max(te[0]*ae,te[1]),Ue=D?4:1,Ie=[t.kernelShape[p?1:2],t.kernelShape[p?2:3]],tt=[Ie[0]+(t.dilations[0]<=1?0:(Ie[0]-1)*(t.dilations[0]-1)),Ie[1]+(t.dilations[1]<=1?0:(Ie[1]-1)*(t.dilations[1]-1))],Mt=[tt[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),tt[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],St=[{type:6,data:s},{type:6,data:n},{type:6,data:i},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Ie},{type:6,data:Mt}];rn(t,St),St.push(...gt(e[0].dims,e[1].dims));let Zt=["rank","rank"];o&&(St.push(...gt(e[2].dims)),Zt.push("rank")),St.push(...gt(r));let tr=zt=>{let vr=Xe("x",e[0].dataType,e[0].dims.length,Ue),Ar=Xe("w",e[1].dataType,e[1].dims.length,1),nr=At("result",e[0].dataType,r.length,Ue),Er=[vr,Ar],Ft="";if(o){let We=Xe("bias",e[2].dataType,e[2].dims.length,Ue);Er.push(We),Ft+=` fn getBiasByOutputCoords(coords : vec4) -> ${We.type.value} { return bias[coords.${p?"w":"y"}${D?"/ 4":""}]; }`}let Vt=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:Ie.length},{name:"pads",type:"i32",length:Mt.length}];sn(t,Vt);let pr=ir(e[0].dataType,1);if(pr!=="f16"&&pr!=="f32")throw new Error(`elemType ${pr} is not supported.`);return` ${Hn("uniforms.result_strides")} ${zt.registerUniforms(Vt).declareVariables(...Er,nr)}; ${Ft} ${zu(p,o,t,vr.type.value,ae)} ${D?xo(K,te,pr,void 0,!p,fe):Eo(K,te,pr,void 0,!p,fe,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${K};${te};${D}`,inputDependencies:Zt},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ce[0],y:ce[1],z:ce[2]},programUniforms:St}),getShaderSource:tr}}}),Bu,Gi,Cc=g(()=>{Rt(),xe(),Dt(),Jt(),Bu=(e,t,r,s,n,i=!1,o,u,p=!1)=>{let h=p?1:2,v=p?2:3,b=p?3:1,l=i?2:1,F=` fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${o}>`:o}) { result[flatIndex] = ${i?`vec4<${o}>`:o}(value); }`;s&&(F+=` fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${o}>`:o} { return bias[coords.${p?"w":"y"}${i?"/ 4":""}]; }`);let D=i?4:1,z=Xe("W",t[1].dataType,t[1].dims.length,D),X=Xe("Dy",t[0].dataType,t[0].dims.length,D),te=[X,z];s&&te.push(Xe("bias",t[2].dataType,[r[b]].length,D));let K=At("result",t[0].dataType,r.length,D),ce=`{ let batch: u32 = ${n?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${n?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${n?"global_id.y":"workgroup_id.y"} * ${l}; let d1: u32 = ${n?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${l}>; for (var i = 0; i < ${l}; i++) { dotProd[i] = vec4<${o}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${o}(dyCorner.x) + ${o}(wR)) / ${o}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${o}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${o}(dyCorner.y) + ${o}(wC)) / ${o}(uniforms.strides.y); let dyC2 = (${o}(dyCorner.y) + 1.0 + ${o}(wC)) / ${o}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${o}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${o}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${X.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${X.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${b}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${X.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${z.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${X.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${l}; i = i + 1) { let value = dotProd[i] + ${s?"bias[c+i]":`vec4<${o}>(0.0)`}; ${K.set("batch","r","c + i","d1","value")}; } }`,ae=` let outputIndices = ${K.offsetToIndices("global_idx")}; let batch = ${K.indicesGet("outputIndices",0)}; let d1 = ${K.indicesGet("outputIndices",b)}; let r = ${K.indicesGet("outputIndices",h)}; let c = ${K.indicesGet("outputIndices",v)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${o}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${o}(dyRCorner) + ${o}(wR)) / ${o}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${o}(uniforms.Dy_shape[${h}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${o}(dyCCorner) + ${o}(wC)) / ${o}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${o}(uniforms.Dy_shape[${v}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${p?X.get("batch","idyR","idyC","inputChannel"):X.get("batch","inputChannel","idyR","idyC")}; let wValue = ${z.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${s?"bias[d1]":`${o}(0.0)`}; ${K.setByOffset("global_idx","value")}; `;return` ${e.registerUniforms(u).declareVariables(...te,K)} ${F} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${i?ce:ae}}`},Gi=(e,t,r)=>{let s=e.length>2,n=t.outputShape,i=De.size(n),o=[Math.ceil(i/64),1,1];_r("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${o}`);let u=t.format==="NHWC",p=["rank","rank"],h=[t.strides[0],t.strides[1]],v=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],b=[t.dilations[0],t.dilations[1]],l=[v[0]+(t.dilations[0]<=1?0:(t.kernelShape[u?1:2]-1)*(t.dilations[0]-1)),v[1]+(t.dilations[1]<=1?0:(t.kernelShape[u?2:3]-1)*(t.dilations[1]-1))],F=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],D=!1,z=t.group,X=e[1].dims,te=X[0]/z,K=X[1],ce=[{type:12,data:i},{type:12,data:h},{type:12,data:v},{type:12,data:b},{type:12,data:l},{type:6,data:F},{type:12,data:te},{type:12,data:K},...gt(e[0].dims,e[1].dims)];s&&(ce.push(...gt(e[2].dims)),p.push("rank")),ce.push(...gt(n));let ae=o[1]===1&&o[2]===1,fe=Ue=>{let Ie=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:h.length},{name:"filter_dims",type:"u32",length:v.length},{name:"dilations",type:"u32",length:v.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:F.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],tt=ir(e[0].dataType);return`${Bu(Ue,e,n,s,ae,D,tt,Ie,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:p},getRunData:()=>({dispatchGroup:{x:o[0],y:o[1],z:o[2]},outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],programUniforms:ce}),getShaderSource:fe}}}),$o,Ru,ju,Ki,Xn,Nu,Uu,Vu,Wu,ko,Sc=g(()=>{Pc(),Cc(),nn(),mn(),$o=(e,t,r,s,n,i)=>(e-1)*t+r+(s-1)*n+1-i,Ru=(e,t,r,s,n)=>{let i=Math.floor(e/2);t==="SAME_UPPER"?(r[s]=i,r[n]=e-i):t==="SAME_LOWER"&&(r[s]=e-i,r[n]=i)},ju=(e,t,r,s,n,i,o,u,p,h)=>{let v=e.length-2,b=h.length===0;p.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((b,l)=>b*l,1)===0){r.length=0;for(let b=2;bb+l,0)===0){let b=t[0].dims.length-2;p=new Array(b).fill(1)}let h=e.strides.slice();if(h.reduce((b,l)=>b+l,0)===0){let b=t[0].dims.length-2;h=new Array(b).fill(1)}ju(u,r,p,e.autoPad,e.group,n,h,s,o,i);let v=Object.assign({},e);return Object.assign(v,{kernelShape:r,pads:n,outputPadding:o,outputShape:i,dilations:p,strides:h}),v},Xn=e=>{let t=vo(e),r=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,i=e.group,o=e.kernelShape,u=e.pads,p=e.strides,h=e.wIsConst(),v=e.outputPadding,b=e.outputShape;return{autoPad:s,format:r,dilations:n,group:i,kernelShape:o,outputPadding:v,outputShape:b,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Nu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(r!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((o,u)=>o+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((o,u)=>o+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((o,u)=>o+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((o,u)=>o+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")},Uu=[2,3,1,0],Vu=(e,t,r)=>{let s=Ki(r,t),n=r.format==="NHWC",i=s.outputShape,o=i[n?3:1],u=t[0].dims[n?3:1];if(s.group!==1||o===1&&u===1){e.compute(Gi(t,s));return}let p=i[n?1:2],h=i[n?2:3],v=t[1].dims[2],b=t[1].dims[3],l=n?p*h:o,F=n?o:p*h,D=v*b*u,z=!0,X=e.kernelCustomData.wT??e.compute(ms(t[1],Uu),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=X);let te=[t[0],X],K=t.length===3;K&&(!n&&t[2].dims.length===1?te.push(t[2].reshape([t[2].dims[0],1,1])):te.push(t[2])),e.compute(Wi(te,s,i,l,F,D,K,z),{inputs:te})},Wu=(e,t)=>{let r=t.format==="NHWC",s=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let n=t.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let o=t.strides;(o.length===0||o[0]===0)&&(o=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],o=[1].concat(o),i=[1].concat(i),n=[1].concat(n);let p=Ki({...t,pads:u,strides:o,dilations:i,kernelShape:n},s);e.compute(Gi(s,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]]))},ko=(e,t)=>{Nu(e.inputs,t),e.inputs[0].dims.length===3?Wu(e,t):Vu(e,e.inputs,t)}}),Gu,Ku,$c,kc=g(()=>{Rt(),Dt(),cr(),Jt(),Gu=(e,t,r,s)=>{let n=De.size(t),i=t.length,o=Xe("input",e,i),u=At("output",e,i),p=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=De.normalizeAxis(p,i),v=b=>{let l=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,F=kt("uniforms.input_shape","uniforms.axis",i),D=s.reverse?l+(s.exclusive?" + 1":""):"0",z=s.reverse?F:l+(s.exclusive?"":" + 1");return` ${b.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,u)} ${b.mainStart()} ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${u.offsetToIndices("global_idx")}; var sum = ${u.type.value}(0); let first : i32 = ${D}; let last : i32 = ${z}; for (var i : i32 = first; i < last; i++) { ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${o.getByIndices("inputIndices")}; } ${u.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},{type:12,data:h},...gt(t,t)]}),getShaderSource:v}},Ku=(e,t)=>{let r=e.inputs[0].dims,s=e.inputs[0].dataType,n=e.inputs[1];e.compute(Gu(s,r,n,t),{inputs:[0]})},$c=e=>{let t=e.exclusive===1,r=e.reverse===1;return qt({exclusive:t,reverse:r})}}),Hu,qu,Cn,Qu,Xu,Ac=g(()=>{Rt(),Dt(),cr(),Jt(),Hu=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.")},qu=(e,t,r,s)=>{let n=[];n.push(`fn perm(i: ${s.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let i=0;i{let r,s,n,i,o,u,p=t.format==="NHWC",h=t.blocksize,v=t.mode==="DCR";p?([r,s,n,i]=e.dims,o=v?[r,s,n,h,h,i/h**2]:[r,s,n,i/h**2,h,h],u=v?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,s,n,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=v?[r,h,h,i/h**2,s,n]:[r,i/h**2,h,h,s,n],u=v?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let b=e.reshape(o),l=b.dims.length,F=e.dataType,D=Xe("a",F,l),z=At("output",F,l),X=te=>` ${te.registerUniform("output_size","u32").declareVariables(D,z)} ${qu(u,l,D,z)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${z.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${z.setByOffset("global_idx",D.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:te=>{let K=p?[r,s*h,n*h,i/h**2]:[r,i/h**2,s*h,n*h],ce=De.size(K),ae=b.dims,fe=De.sortBasedOnPerm(ae,u);return{outputs:[{dims:K,dataType:te[0].dataType}],dispatchGroup:{x:Math.ceil(ce/64)},programUniforms:[{type:12,data:ce},...gt(ae,fe)]}},getShaderSource:X}},Qu=(e,t)=>{Hu(e.inputs),e.compute(Cn(e.inputs[0],t))},Xu=e=>qt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ao,Yn,Jn,Ic,Yu,Ju,Zu,Hi,ed,qi,td,Fc=g(()=>{Rt(),Dt(),cr(),Jt(),Ao="[a-zA-Z]|\\.\\.\\.",Yn="("+Ao+")+",Jn="^"+Yn+"$",Ic="("+Yn+",)*"+Yn,Yu="^"+Ic+"$",Ju=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},Zu=class{constructor(e,t){var n;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,s]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(Yu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((i,o)=>{let u=e[o].dims.slice();if(!i.match(RegExp(Jn)))throw new Error("Invalid LHS term");let p=this.processTerm(i,!0,u,o);this.lhs.push(p)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([i,o])=>o.count===1||i==="...").map(([i])=>i).join("");else if(!s.match(RegExp(Yn)))throw new Error("Invalid RHS");(n=s.match(RegExp(Ao,"g")))==null||n.forEach(i=>{if(i==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(i);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,t,r){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==t&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(r)}else s={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,s)}processTerm(e,t,r,s=-1){let n=r.length,i=!1,o=[],u=0;if(!e.match(RegExp(Jn))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(Ao,"g")),h=new Ju(s);return p==null||p.forEach((v,b)=>{if(v==="..."){if(i)throw new Error("Only one ellipsis is allowed per input term");i=!0;let l=n-p.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(o=r.slice(u,u+l),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let F=0;Fe+"_max",ed=(e,t,r,s)=>{let n=e.map(h=>h.length).map((h,v)=>Xe(`input${v}`,t,h)),i=De.size(s),o=At("output",t,s.length),u=[...r.symbolToInfo.keys()].filter(h=>!r.rhs.symbolToIndices.has(h)),p=h=>{let v=[],b="var prod = 1.0;",l="var sum = 0.0;",F="sum += prod;",D=[],z=[],X=[],te=[],K=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((ae,fe)=>{var Ue;if(r.rhs.symbolToIndices.has(fe)){let Ie=(Ue=r.rhs.symbolToIndices.get(fe))==null?void 0:Ue[0];Ie!==void 0&&r.lhs.forEach((tt,Mt)=>{if(ae.inputIndices.includes(Mt)){let St=tt.symbolToIndices.get(fe);if(St===void 0)throw new Error("Invalid symbol error");St.forEach(Zt=>{v.push(`${n[Mt].indicesSet(`input${Mt}Indices`,Zt,o.indicesGet("outputIndices",Ie))}`)})}})}else r.lhs.forEach((Ie,tt)=>{if(ae.inputIndices.includes(tt)){let Mt=Ie.symbolToIndices.get(fe);if(Mt===void 0)throw new Error("Invalid symbol error");Mt.forEach(St=>{D.push(`${n[tt].indicesSet(`input${tt}Indices`,St,`${fe}`)}`)}),te.push(`prod *= ${n[tt].getByIndices(`input${tt}Indices`)};`)}}),z.push(`for(var ${fe}: u32 = 0; ${fe} < uniforms.${Hi(fe)}; ${fe}++) {`),X.push("}")});let ce=K?[...v,`let sum = ${n.map((ae,fe)=>ae.getByIndices(`input${fe}Indices`)).join(" * ")};`]:[...v,l,...z,...D,b,...te,F,...X];return` ${h.registerUniforms(u.map(ae=>({name:`${Hi(ae)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...n,o)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${o.offsetToIndices("global_idx")}; ${n.map((ae,fe)=>`var input${fe}Indices: ${n[fe].type.indices};`).join(` `)} ${ce.join(` `)}; ${o.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=u.filter(b=>r.symbolToInfo.has(b)).map(b=>{var l;return{type:12,data:((l=r.symbolToInfo.get(b))==null?void 0:l.dimValue)||0}});h.push({type:12,data:i});let v=e.map((b,l)=>[...gt(b)]).reduce((b,l)=>b.concat(l),h);return v.push(...gt(s)),{outputs:[{dims:s,dataType:t}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:v}},getShaderSource:p}},qi=(e,t)=>{let r=new Zu(e.inputs,t.equation),s=r.outputDims,n=e.inputs.map((i,o)=>i.dims);e.compute(ed(n,e.inputs[0].dataType,r,s))},td=e=>{let t=e.equation.replace(/\s+/g,"");return qt({equation:t})}}),Qi,Xi,rd,Yi,sd,Oc=g(()=>{Rt(),Dt(),Jt(),Qi=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),s=r.length{let r=e.length-t.length,s=[];for(let n=0;ne.length>t.length?Xi(e,t):Xi(t,e),Yi=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),s=rd(t,r),n=e[0].dataType,i=n===9?4:1,o=Math.ceil(De.size(s)/i),u=h=>{let v=Xe("input",n,t.length,i),b=At("output",n,s.length,i),l;if(n===9){let F=(D,z,X="")=>` let outputIndices${z} = ${b.offsetToIndices(`outputOffset + ${z}u`)}; let offset${z} = ${v.broadcastedIndicesToOffset(`outputIndices${z}`,b)}; let index${z} = offset${z} / 4u; let component${z} = offset${z} % 4u; ${D}[${z}] = ${X}(${v.getByOffset(`index${z}`)}[component${z}]); `;l=` let outputOffset = global_idx * ${i}; var data = vec4(0); ${F("data",0,"u32")} ${F("data",1,"u32")} ${F("data",2,"u32")} ${F("data",3,"u32")} ${b.setByOffset("global_idx","data")} }`}else l=` let outputIndices = ${b.offsetToIndices("global_idx")}; let inputOffset = ${v.broadcastedIndicesToOffset("outputIndices",b)}; ${b.setByOffset("global_idx",v.getByOffset("inputOffset"))} }`;return` ${h.registerUniform("vec_size","u32").declareVariables(v,b)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${l}`},p=[{type:12,data:o},...gt(t,s)];return{name:"Expand",shaderCache:{hint:`${s.length}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p})}},sd=e=>{Qi(e.inputs),e.compute(Yi(e.inputs),{inputs:[0]})}}),Io,nd,Dc=g(()=>{Rt(),Dt(),Jt(),Kn(),Io=e=>{let t=e[0].dataType,r=De.size(e[0].dims),s=De.size(e[1].dims),n=s%4===0,i=o=>{let u=Xe("x",t,[1],4),p=Xe("bias",t,[1],4),h=At("y",t,[1],4),v=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],b=F=>` let bias${F}_offset: u32 = (global_idx * 4 + ${F}) % uniforms.bias_size; let bias${F} = ${p.getByOffset(`bias${F}_offset / 4`)}[bias${F}_offset % 4];`,l=n?` let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${b(0)}${b(1)}${b(2)}${b(3)} let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(v).declareVariables(u,p,h)} ${yi(wr(t))} ${o.mainStart(qr)} ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${u.getByOffset("global_idx")}; ${l} let x_in = x + bias; ${h.setByOffset("global_idx",Mi("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:o=>({outputs:[{dims:o[0].dims,dataType:o[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(r/qr/4)}})}},nd=e=>{e.inputs.length<2||De.size(e.inputs[1].dims)===0?bi(e):e.compute(Io(e.inputs))}}),od,id,Ji,Fo,Pp=g(()=>{Rt(),Dt(),cr(),Jt(),od=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},id=(e,t)=>{let r=e[0].dims,s=e[1].dims,n=r.length,i=De.normalizeAxis(t.axis,n),o=r.slice(0);o.splice(i,1,...s);let u=r[i],p=e[0].dataType===9?4:1,h=Math.ceil(De.size(o)/p),v=[{type:12,data:h},{type:6,data:u},{type:12,data:i},...gt(e[0].dims,e[1].dims,o)],b=l=>{let F=Xe("data",e[0].dataType,e[0].dims.length,p),D=Xe("inputIndices",e[1].dataType,e[1].dims.length),z=At("output",e[0].dataType,o.length,p),X=K=>{let ce=s.length,ae=`var indicesIndices${K} = ${D.type.indices}(0);`;for(let fe=0;fe1?`indicesIndices${K}[${fe}]`:`indicesIndices${K}`} = ${o.length>1?`outputIndices${K}[uniforms.axis + ${fe}]`:`outputIndices${K}`};`;ae+=` var idx${K} = ${D.getByIndices(`indicesIndices${K}`)}; if (idx${K} < 0) { idx${K} = idx${K} + uniforms.axisDimLimit; } var dataIndices${K} : ${F.type.indices}; `;for(let fe=0,Ue=0;fe1?`dataIndices${K}[${fe}]`:`dataIndices${K}`} = u32(idx${K});`,Ue+=ce):(ae+=`${n>1?`dataIndices${K}[${fe}]`:`dataIndices${K}`} = ${o.length>1?`outputIndices${K}[${Ue}]`:`outputIndices${K}`};`,Ue++);return ae},te;if(e[0].dataType===9){let K=(ce,ae,fe="")=>` let outputIndices${ae} = ${z.offsetToIndices(`outputOffset + ${ae}u`)}; ${X(ae)}; let offset${ae} = ${F.indicesToOffset(`dataIndices${ae}`)}; let index${ae} = offset${ae} / 4u; let component${ae} = offset${ae} % 4u; ${ce}[${ae}] = ${fe}(${F.getByOffset(`index${ae}`)}[component${ae}]); `;te=` let outputOffset = global_idx * ${p}; var value = vec4(0); ${K("value",0,"u32")} ${K("value",1,"u32")} ${K("value",2,"u32")} ${K("value",3,"u32")} ${z.setByOffset("global_idx","value")} `}else te=` let outputIndices = ${z.offsetToIndices("global_idx")}; ${X("")}; let value = ${F.getByIndices("dataIndices")}; ${z.setByOffset("global_idx","value")}; `;return` ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(F,D,z)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${te} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:v}),getShaderSource:b}},Ji=e=>qt({axis:e.axis}),Fo=(e,t)=>{let r=e.inputs;od(r),e.compute(id(e.inputs,t))}}),ad,ld,Zi,ud,Lc=g(()=>{Rt(),Dt(),cr(),Jt(),ad=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=De.normalizeAxis(t.quantizeAxis,e[0].dims.length),s=t.blockSize,n=e[0],i=e[2],o=e.length===4?e[3]:void 0;if(i.dims.length!==n.dims.length||!n.dims.map((u,p)=>p===r?Math.ceil(u/s)===i.dims[p]:u===i.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(o){if(o.dataType!==n.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==i.dims.length||!o.dims.map((u,p)=>u===i.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.")}},ld=(e,t)=>{let r=e[0].dims,s=e[1].dims,n=r.length,i=De.normalizeAxis(t.gatherAxis,n),o=De.normalizeAxis(t.quantizeAxis,n),u=r.slice(0);u.splice(i,1,...s);let p=De.size(u),h=e[2].dataType,v=e[0].dataType===22,b=[{type:12,data:p},{type:12,data:o},{type:12,data:i},{type:12,data:t.blockSize},...gt(...e.map((F,D)=>F.dims),u)],l=F=>{let D=Xe("data",e[0].dataType,e[0].dims.length),z=Xe("inputIndices",e[1].dataType,e[1].dims.length),X=Xe("scales",e[2].dataType,e[2].dims.length),te=e.length>3?Xe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,K=At("output",h,u.length),ce=[D,z,X];te&&ce.push(te);let ae=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${F.registerUniforms(ae).declareVariables(...ce,K)} ${F.mainStart()} let output_indices = ${K.offsetToIndices("global_idx")}; var indices_indices = ${z.type.indices}(0); ${s.length>1?` for (var i: u32 = 0; i < ${s.length}; i++) { let index = ${K.indicesGet("output_indices","uniforms.gather_axis + i")}; ${z.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${K.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${D.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${K.indicesGet("output_indices","i")}; ${D.indicesSet("data_indices","i","index")}; } var index_from_indices = ${z.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${r[i]}; } ${D.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { let index = ${K.indicesGet("output_indices",`i + ${s.length} - 1`)}; ${D.indicesSet("data_indices","i","index")}; } let data_offset = ${D.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${D.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${v?"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 = ${X.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${X.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${X.getByIndices("scale_indices")}; ${te?` let zero_point_indices = scale_indices; let zero_point_offset = ${te.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${te.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${v?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${wr(h)}(quantized_data - zero_point) * scale; ${K.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((F,D)=>D!==1).map(F=>F.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(F,D)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:b}),getShaderSource:l}},Zi=(e,t)=>{let r=e.inputs;ad(r,t),e.compute(ld(e.inputs,t))},ud=e=>qt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),ea,dd,cd,ta,Cp=g(()=>{Rt(),Dt(),cr(),Jt(),ea=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.`)},dd=(e,t)=>{let r=e[0].dims,s=e[0].dataType,n=r.length,i=e[1].dims,o=e[1].dataType,u=De.normalizeAxis(t.axis,n),p=r[u],h=i.slice(0),v=De.size(h),b=Xe("input",s,n),l=Xe("indicesInput",o,i.length),F=At("output",s,h.length),D=[{type:12,data:v},{type:6,data:p},{type:12,data:u}];return D.push(...gt(r,i,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:D}),getShaderSource:z=>` ${z.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(b,l,F)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${F.offsetToIndices("global_idx")}; var idx = ${l.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${b.type.indices}(outputIndices); ${b.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${b.getByIndices("inputIndices")}; ${F.setByOffset("global_idx","value")}; }`}},cd=e=>qt({axis:e.axis}),ta=(e,t)=>{let r=e.inputs;ea(r),e.compute(dd(e.inputs,t))}}),zc,ra,sa,pd,Bc=g(()=>{Rt(),Dt(),Jt(),zc=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")},ra=(e,t)=>{let r=e[0].dims.slice(),s=e[1].dims.slice(),[n,i,o]=Hr.getShapeOfGemmResult(r,t.transA,s,t.transB,e.length===3?e[2].dims:void 0),u=[n,i];if(!u)throw new Error("Can't use gemm on the given tensors");let p=De.size(u),h=[{type:12,data:p},{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],v=["type","type"];e.length===3&&(h.push(...gt(e[2].dims)),v.push("rank")),h.push(...gt(u));let b=l=>{let F="";t.transA&&t.transB?F="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?F="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?F="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(F="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let D=t.alpha===1?"":"value *= uniforms.alpha;",z=Xe("a",e[0].dataType,e[0].dims),X=Xe("b",e[1].dataType,e[1].dims),te=z.type.value,K=null,ce=[z,X];e.length===3&&(K=Xe("c",e[2].dataType,e[2].dims.length),ce.push(K));let ae=At("output",e[0].dataType,u.length);ce.push(ae);let fe=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${l.registerUniforms(fe).declareVariables(...ce)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${te}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${F} } ${D} ${K!=null?`let cOffset = ${K.broadcastedIndicesToOffset("vec2(m, n)",ae)}; value += ${te}(uniforms.beta) * ${K.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:b}},sa=e=>{let t=e.transA,r=e.transB,s=e.alpha,n=e.beta;return{transA:t,transB:r,alpha:s,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},pd=(e,t)=>{zc(e.inputs),e.compute(ra(e.inputs,t))}}),rs,hd,md,Oo,fd,Zn,na,_d=g(()=>{Rt(),Dt(),cr(),oe(),Mo(),Jt(),mn(),rs=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,hd=(e,t)=>{let r=e[0],s=rs(e,1),n=rs(e,2),i=rs(e,3),o=rs(e,4),u=rs(e,5),p=rs(e,6),h=rs(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let v=r.dims[0],b=r.dims[1],l=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],F=b,D=0,z=0,X=Math.floor(l/t.numHeads);if(p&&h&&De.size(p.dims)&&De.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==v||p.dims[1]!==t.numHeads||p.dims[3]!==X)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==v||h.dims[1]!==t.numHeads||h.dims[3]!==X)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');D=p.dims[2],z=p.dims[2]}else if(p&&De.size(p.dims)||h&&De.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te;if(s&&De.size(s.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');te=2,F=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==t.numHeads||s.dims[3]!==2||s.dims[4]!==X)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');te=5,F=s.dims[1]}else{if(s.dims[1]!==t.numHeads||s.dims[3]!==X)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');te=0,F=s.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}if(i&&De.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let K=D+F,ce=0;if(o&&De.size(o.dims)>0){ce=8;let Ie=o.dims;throw Ie.length===1?Ie[0]===v?ce=1:Ie[0]===3*v+2&&(ce=3):Ie.length===2&&Ie[0]===v&&Ie[1]===K&&(ce=5),ce===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let ae=!1,fe=l;if(n&&De.size(n.dims)>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(F!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');fe=n.dims[2]}else{if(F!==n.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');fe=n.dims[1]*n.dims[3],ae=!0}}let Ue=!1;if(o&&De.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(u&&De.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]!==v||u.dims[1]!==t.numHeads||u.dims[2]!==b||u.dims[3]!==K)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:v,sequenceLength:b,pastSequenceLength:D,kvSequenceLength:F,totalSequenceLength:K,maxSequenceLength:z,inputHiddenSize:0,hiddenSize:l,vHiddenSize:fe,headSize:X,vHeadSize:Math.floor(fe/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ce,scale:t.scale,broadcastResPosBias:Ue,passPastInKv:ae,qkvFormat:te}},md=e=>qt({...e}),Oo=qt({perm:[0,2,1,3]}),fd=(e,t,r,s,n,i,o)=>{let u=[s,n,i],p=De.size(u),h=[{type:12,data:p},{type:12,data:o},{type:12,data:i}],v=b=>{let l=At("qkv_with_bias",t.dataType,u),F=Xe("qkv",t.dataType,u),D=Xe("bias",r.dataType,u),z=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${b.registerUniforms(z).declareVariables(F,D,l)} ${b.mainStart()} ${b.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:v},{inputs:[t,r],outputs:[-1]})[0]},Zn=(e,t,r,s,n,i,o,u)=>{let p=i;if(o&&De.size(o.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=fd(e,i,o,t,s,r*n,u),p=p.reshape([t,s,r,n]),r===1||s===1?p:e.compute(ms(p,Oo.perm),{inputs:[p],outputs:[-1]})[0]}else return i.dims.length===3&&(p=i.reshape([t,s,r,n])),r===1||s===1?p:e.compute(ms(p,Oo.perm),{inputs:[p],outputs:[-1]})[0]},na=(e,t)=>{let r=hd(e.inputs,t),s=e.inputs[0],n=rs(e.inputs,1),i=rs(e.inputs,2),o=rs(e.inputs,3),u=rs(e.inputs,4),p=rs(e.inputs,5),h=rs(e.inputs,6),v=rs(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((n==null?void 0:n.dims.length)===5)throw new Error("Packed KV is not implemented");let b=n&&i&&n.dims.length===4&&i.dims.length===4,l=Zn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,s,o,0);if(b)return Pn(e,l,n,i,u,void 0,h,v,p,r,t);if(!n||!i)throw new Error("key and value must be provided");let F=Zn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,n,o,r.hiddenSize),D=Zn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,o,2*r.hiddenSize);Pn(e,l,F,D,u,void 0,h,v,p,r,t)}}),oa,gd,wd,ia,yd,Md=g(()=>{Rt(),Dt(),Jt(),oa=e=>Array.from(e.getBigInt64Array(),Number),gd=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(oa(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")},wd=(e,t)=>{let r=[];for(let s=0;s{let r=e[0].dims,s=t??oa(e[1]),n=wd(r,s),i=De.size(n),o=e[0].dataType,u=Xe("input",o,r.length),p=At("output",o,n.length),h=v=>` const inputShape = ${u.indices(...r)}; ${v.registerUniform("output_size","u32").declareVariables(u,p)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${p.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; for (var i = 0; i < ${r.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:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...gt(e[0].dims,n)]}),getShaderSource:h}},yd=e=>{gd(e.inputs),e.compute(ia(e.inputs),{inputs:[0]})}}),bd,aa,la,vd,ua,da,Rc=g(()=>{Rt(),Dt(),cr(),Mo(),Jt(),_d(),Md(),mn(),bd=(e,t)=>{let r=e[0],s=e[1],n=e[2],i=e[3],o=e[4];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,p=r.dims[0],h=r.dims[1],v=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],b=h,l=0,F=0,D=Math.floor(v/t.numHeads),z=i&&i.dims.length!==0,X=o&&o.dims.length!==0,te=!0;if(z&&X){if(i.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=i.dims[1],F=i.dims[1]}else if(z||X)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let K;if(s){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(r.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');K=2,b=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==t.numHeads||s.dims[3]!==2||s.dims[4]!==D)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');K=5,b=s.dims[1]}else{if(s.dims[1]!==t.numHeads||s.dims[3]!==D)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');K=0,b=s.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');K=3}let ce=0,ae=!1,fe=v;if(n){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(b!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');fe=n.dims[2]}else{if(b!==n.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');fe=n.dims[1]*n.dims[3],ae=!0}}let Ue=l+b;return{batchSize:p,sequenceLength:h,pastSequenceLength:l,kvSequenceLength:b,totalSequenceLength:Ue,maxSequenceLength:F,inputHiddenSize:0,hiddenSize:v,vHiddenSize:fe,headSize:D,vHeadSize:Math.floor(fe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:ce,scale:t.scale,broadcastResPosBias:!1,passPastInKv:ae,qkvFormat:K,isPastkvBSNH:te}},aa=(e,t,r,s)=>{let n=[s.batchSize,s.totalSequenceLength,s.kvNumHeads,s.headSize],i=4,o=De.size(n)/i,u=s.totalSequenceLength,p=At("present_kv",r,n.length,i),h=Xe("new_kv",e.dataType,e.dims.length,i),v=t?Xe("past_kv",t.dataType,t.dims.length,i):void 0,b=Math.ceil(s.headSize/i),l={x:u,y:e.dims[0],z:1},F=t?["rank","rank"]:["rank"],D=[{type:12,data:o},{type:12,data:s.pastSequenceLength},{type:12,data:s.kvSequenceLength},{type:12,data:s.totalSequenceLength}],z=[h];v?(D.push(...gt(e.dims),...gt(t.dims),...gt(n)),z.push(v)):D.push(...gt(e.dims),...gt(n));let X=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],te=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; var past_head_stride = uniforms.past_seqlen * H; if (is_bsnh) { past_head_stride = H; } let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; present_kv[out_offset] = past_kv[in_offset];`,K=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; let new_row_stride = num_heads * H; let new_head_stride = H; let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; present_kv[out_offset] = new_kv[in_offset];`,ce=t?`if (s < past_seqlen) { ${te} } else if (s < past_seqlen + uniforms.new_seqlen) { ${K} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${K} }`,ae=fe=>` ${fe.registerUniforms(X).declareVariables(...z,p)} ${fe.mainStart([b,s.kvNumHeads,1])} ${fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${p.offsetToIndices("global_idx")}; let h = local_id.x; let n = local_id.y; let s = workgroup_id.x; let b = workgroup_id.y; let num_heads = ${s.kvNumHeads}u; let H = ${b}u; let present_seqlen = uniforms.present_seqlen; let present_batch_stride = present_seqlen * num_heads * H; var row_stride = H; let is_bsnh = ${s.isPastkvBSNH}; if (is_bsnh) { row_stride = num_heads * H; } var present_head_stride = present_seqlen * H; if (is_bsnh) { present_head_stride = H; } let past_seqlen = uniforms.past_seqlen; let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; ${ce} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${s.kvNumHeads}${b}${!!t}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:l,programUniforms:D}),getShaderSource:ae}},la=e=>qt({...e}),vd=qt({perm:[0,2,1,3]}),ua=(e,t,r,s,n)=>{let i=t,o=s.kvNumHeads,u=s.nReps;return t.dims.length===3&&s.kvSequenceLength!==0&&(i=t.reshape([s.batchSize,s.kvSequenceLength,o,s.headSize])),r?i=e.compute(aa(i,r,i.dataType,s),{inputs:[i,r],outputs:[s.isPastkvBSNH?n:-1]})[0]:i=e.compute(aa(i,void 0,i.dataType,s),{inputs:[i],outputs:[s.isPastkvBSNH?n:-1]})[0],u!==1&&(i=e.compute(ia([i],[1,1,1,u]),{inputs:[i],outputs:[-1]})[0],i=i.reshape([s.batchSize,s.totalSequenceLength,o*u,s.headSize])),e.compute(ms(i,vd.perm),{inputs:[i],outputs:[-1]})[0]},da=(e,t)=>{var p;let r=bd(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((p=e.inputs[1])==null?void 0:p.dims.length)===5)throw new Error("Packed KV is not implemented");let s=Zn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],void 0,0),n=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,i=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,o=ua(e,e.inputs[1],n,r,1),u=ua(e,e.inputs[2],i,r,2);Pn(e,s,o,u,void 0,void 0,void 0,void 0,void 0,r,t)}}),ca,yr,jc,Nc,Sp=g(()=>{Rt(),Dt(),mn(),Jt(),ca=(e,t,r,s,n,i,o,u)=>{let p=Qt(i),h=p===1?"f32":`vec${p}f`,v=p===1?"vec2f":`mat2x${p}f`,b=n*o,l=[n,o,i/p],F=[n,o,2],D=["rank","type","type"],z=[];z.push(...gt(l,F));let X=te=>{let K=Xe("x",t.dataType,3,p),ce=Xe("scale",r.dataType,r.dims),ae=Xe("bias",s.dataType,s.dims),fe=At("output",1,3,2),Ue=[K,ce,ae,fe],Ie=64;return` var workgroup_shared : array<${v}, ${Ie}>; const workgroup_size = ${Ie}u; ${te.declareVariables(...Ue)} ${te.mainStart(Ie)} 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}(${K.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${v}(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 = ${Ds("workgroup_shared[0][0]",p)} / f32(hight * ${p}); let squared_sum_final = ${Ds("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}`,inputDependencies:D},getRunData:()=>({outputs:[{dims:F,dataType:1}],dispatchGroup:{x:b},programUniforms:z}),getShaderSource:X},{inputs:[t,r,s],outputs:[-1]})[0]},yr=(e,t,r)=>{let s=t[0].dims,n=s,i=2,o=s[0],u=s[1],p=De.sizeFromDimension(s,i),h=Qt(p),v=De.size(n)/h,b=ca(e,t[0],t[1],t[2],o,p,u,r.epsilon),l=[o,u,p/h],F=[o,u],D=["type","none"],z=X=>{let te=Xe("x",t[0].dataType,l.length,h),K=Xe("scale_shift",1,F.length,2),ce=At("output",t[0].dataType,l.length,h),ae=[te,K,ce];return` ${X.registerUniform("output_size","u32").declareVariables(...ae)} ${X.mainStart()} ${X.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${ce.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${K.getByIndices("vec2(batch, channel)")}; let value = ${te.getByOffset("global_idx")} * ${ce.type.value}(scale_shift.x) + ${ce.type.value}(scale_shift.y); ${ce.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:D},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},...gt(l,F,l)]}),getShaderSource:z},{inputs:[t[0],b]})},jc=(e,t,r)=>{let s=t[0].dims,n=s,i=s[0],o=s[s.length-1],u=De.sizeFromDimension(s,1)/o,p=Qt(o),h=De.size(n)/p,v=[{type:12,data:u},{type:12,data:Math.floor(o/p)}],b=["type","type"],l=[0,s.length-1];for(let X=0;X{let te=ir(t[0].dataType),K=p===1?"vec2f":`mat${p}x2f`,ce=Ue=>{let Ie=Ue===0?"x":"y",tt=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${te}(${tt}(scale.${Ie}))`;case 2:return`vec2<${te}>(${tt}(scale[0].${Ie}, scale[1].${Ie}))`;case 4:return`vec4<${te}>(${tt}(scale[0].${Ie}, scale[1].${Ie}, scale[2].${Ie}, scale[3].${Ie}))`;default:throw new Error(`Not supported compoents ${p}`)}},ae=Xe("input",t[0].dataType,t[0].dims,p),fe=At("output",t[0].dataType,n,p);return` @group(0) @binding(0) var input : array<${ae.type.storage}>; @group(0) @binding(1) var scale_input : array<${K}>; @group(0) @binding(2) var output : array<${fe.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${X.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], ${ce(0)}, ${ce(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:v}),getShaderSource:z},{inputs:[t[0],D]})},Nc=(e,t)=>{t.format==="NHWC"?jc(e,e.inputs,t):yr(e,e.inputs,t)}}),pa,Td,xd,Uc=g(()=>{Rt(),Dt(),Jt(),pa=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Td=(e,t,r)=>{let s=t.simplified,n=e[0].dims,i=e[1],o=!s&&e[2],u=n,p=De.normalizeAxis(t.axis,n.length),h=De.sizeToDimension(n,p),v=De.sizeFromDimension(n,p),b=De.size(i.dims),l=o?De.size(o.dims):0;if(b!==v||o&&l!==v)throw new Error(`Size of X.shape()[axis:] == ${v}. Size of scale and bias (if provided) must match this. Got scale size of ${b} and bias size of ${l}`);let F=[];for(let fe=0;fe1,K=r>2,ce=fe=>{let Ue=ir(e[0].dataType),Ie=[Xe("x",e[0].dataType,e[0].dims,D),Xe("scale",i.dataType,i.dims,D)];o&&Ie.push(Xe("bias",o.dataType,o.dims,D)),Ie.push(At("output",e[0].dataType,u,D)),te&&Ie.push(At("mean_data_output",1,F)),K&&Ie.push(At("inv_std_output",1,F));let tt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${fe.registerUniforms(tt).declareVariables(...Ie)} ${fe.mainStart()} ${fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Nr("f32",D)}; var mean_square_vector = ${Nr("f32",D)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Os(Ue,D,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Ds("mean_vector",D)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Ds("mean_square_vector",D)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Os(Ue,D,"x[j + offset]")}; let f32scale = ${Os(Ue,D,"scale[j]")}; output[j + offset] = ${Ie[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale ${o?`+ ${Os(Ue,D,"bias[j]")}`:""} ); } ${te?"mean_data_output[global_idx] = mean":""}; ${K?"inv_std_output[global_idx] = inv_std_dev":""}; }`},ae=[{dims:u,dataType:e[0].dataType}];return te&&ae.push({dims:F,dataType:1}),K&&ae.push({dims:F,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${D};${r};${s}`,inputDependencies:z},getRunData:()=>({outputs:ae,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:X}),getShaderSource:ce}},xd=(e,t)=>{pa(e.inputs),e.compute(Td(e.inputs,t,e.outputCount))}}),Ed,ha,ma,Vc,Pd,Wc=g(()=>{Rt(),Dt(),cr(),Jt(),Ed=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],s=r.dims.length;if(r.dims[s-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let n=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,o=e[1];if(!De.areEqual(o.dims,[t.n,n,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(De.size(u)!==t.n*n)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*n:t.n*Math.floor((n+1)/2);if(De.size(p)!==h)throw new Error("zeroPoints input size error.")}},ha=(e,t)=>{let r=e[0].dims,s=r.length,n=r[s-2],i=t.k,o=t.n,u=r.slice(0,s-2),p=De.size(u),h=e[1].dims[2]/4,v=e[0].dataType,b=Qt(t.k),l=Qt(h),F=Qt(o),D=u.concat([n,o]),z=n>1&&o/F%2===0?2:1,X=De.size(D)/F/z,te=64,K=[],ce=[p,n,i/b],ae=De.convertShape(e[1].dims).slice();ae.splice(-1,1,h/l),K.push(...gt(ce)),K.push(...gt(ae)),K.push(...gt(e[2].dims)),e.length===4&&K.push(...gt(De.convertShape(e[3].dims)));let fe=[p,n,o/F];K.push(...gt(fe));let Ue=Ie=>{let tt=ce.length,Mt=Xe("a",e[0].dataType,tt,b),St=Xe("b",12,ae.length,l),Zt=Xe("scales",e[2].dataType,e[2].dims.length),tr=[Mt,St,Zt],zt=e.length===4?Xe("zero_points",12,e[3].dims.length):void 0;zt&&tr.push(zt);let vr=fe.length,Ar=At("output",e[0].dataType,vr,F),nr=ir(e[0].dataType),Er=(()=>{switch(b){case 1:return`array<${nr}, 8>`;case 2:return`mat4x2<${nr}>`;case 4:return`mat2x4<${nr}>`;default:throw new Error(`${b}-component is not supported.`)}})(),Ft=()=>{let We=` // reuse a data var input_offset = ${Mt.indicesToOffset(`${Mt.type.indices}(batch, row, word_offset)`)}; var a_data: ${Er}; for (var j: u32 = 0; j < ${8/b}; j++) { a_data[j] = ${Mt.getByOffset("input_offset")}; input_offset++; } `;for(let ct=0;ct> 4) & b_mask); b_quantized_values = ${Er}(${Array.from({length:4},(Gt,Tr)=>`${nr}(b_value_lower[${Tr}]), ${nr}(b_value_upper[${Tr}])`).join(", ")}); b_dequantized_values = ${b===1?`${Er}(${Array.from({length:8},(Gt,Tr)=>`(b_quantized_values[${Tr}] - ${zt?`zero_point${ct}`:"zero_point"}) * scale${ct}`).join(", ")});`:`(b_quantized_values - ${Er}(${Array(8).fill(`${zt?`zero_point${ct}`:"zero_point"}`).join(",")})) * scale${ct};`}; workgroup_shared[local_id.x * ${z} + ${Math.floor(ct/F)}]${F>1?`[${ct%F}]`:""} += ${Array.from({length:8/b},(Gt,Tr)=>`${b===1?`a_data[${Tr}] * b_dequantized_values[${Tr}]`:`dot(a_data[${Tr}], b_dequantized_values[${Tr}])`}`).join(" + ")}; `;return We},Vt=()=>{let We=` var col_index = col * ${F}; ${zt?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${nr}(8);`} `;for(let ct=0;ct> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${zt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${ct} = ${nr}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return We},pr=()=>{let We=`col_index = col * ${F};`;for(let ct=0;ct; var b_value_upper: vec4; var b_quantized_values: ${Er}; var b_dequantized_values: ${Er};`,We};return` var workgroup_shared: array<${Ar.type.value}, ${z*te}>; ${Ie.declareVariables(...tr,Ar)} ${Ie.mainStart([te,1,1])} let output_indices = ${Ar.offsetToIndices(`(global_idx / ${te}) * ${z}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${te}) { //process one block var word_offset: u32 = block * ${t.blockSize/b}; ${Vt()} for (var word: u32 = 0; word < ${h}; word += ${l}) { ${pr()} for (var i: u32 = 0; i < ${l}; i++) { ${Ft()} word_offset += ${8/b}; } } } workgroupBarrier(); if (local_id.x < ${z}) { var output_value: ${Ar.type.value} = ${Ar.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${te}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${z}; } ${Ar.setByIndices(`${Ar.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${b};${l};${F};${z};${te}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:D,dataType:v}],dispatchGroup:{x:X},programUniforms:K}),getShaderSource:Ue}},ma=(e,t)=>{let r=e[0].dims,s=r.length,n=r[s-2],i=t.k,o=t.n,u=r.slice(0,s-2),p=De.size(u),h=e[1].dims[2]/4,v=e[0].dataType,b=Qt(t.k),l=Qt(h),F=u.concat([n,o]),D=128,z=o%8===0?8:o%4===0?4:1,X=D/z,te=X*l*8,K=te/b,ce=te/t.blockSize,ae=De.size(F)/z,fe=[],Ue=[p,n,i/b],Ie=De.convertShape(e[1].dims).slice();Ie.splice(-1,1,h/l),fe.push(...gt(Ue)),fe.push(...gt(Ie)),fe.push(...gt(e[2].dims)),e.length===4&&fe.push(...gt(De.convertShape(e[3].dims)));let tt=[p,n,o];fe.push(...gt(tt));let Mt=St=>{let Zt=Ue.length,tr=Xe("a",e[0].dataType,Zt,b),zt=Xe("b",12,Ie.length,l),vr=Xe("scales",e[2].dataType,e[2].dims.length),Ar=[tr,zt,vr],nr=e.length===4?Xe("zero_points",12,e[3].dims.length):void 0;nr&&Ar.push(nr);let Er=tt.length,Ft=At("output",e[0].dataType,Er),Vt=ir(e[0].dataType),pr=()=>{switch(b){case 1:return` let a_data0 = vec4<${Vt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Vt}>(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<${Vt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Vt}>(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(`${b}-component is not supported.`)}};return` var sub_a: array<${tr.type.value}, ${K}>; var inter_results: array, ${z}>; ${St.declareVariables(...Ar,Ft)} ${St.mainStart([X,z,1])} let output_indices = ${Ft.offsetToIndices(`workgroup_index * ${z}`)}; 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) / ${ce} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${K}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${K}; a_offset += ${D}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${tr.getByIndices(`${tr.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${tr.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${ce} + local_id.x; ${nr?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${nr.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Vt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Vt}(8);`} let scale = ${vr.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${zt.getByIndices(`${zt.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/b}; for (var i: u32 = 0; i < ${l}; i++) { ${pr()} let b_value = ${l===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${Vt}>(${Array.from({length:4},(We,ct)=>`${Vt}(b_value_lower[${ct}]), ${Vt}(b_value_upper[${ct}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Vt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(We,ct)=>`${`dot(a_data${ct}, b_dequantized_values[${ct}])`}`).join(" + ")}; word_offset += ${8/b}; } workgroupBarrier(); } if (local_idx < ${z}) { var output_value: ${Ft.type.value} = ${Ft.type.value}(0); for (var b = 0u; b < ${X}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${Ft.setByIndices(`${Ft.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${b};${l};${X};${z}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:F,dataType:v}],dispatchGroup:{x:ae},programUniforms:fe}),getShaderSource:Mt}},Vc=(e,t)=>{Ed(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(ma(e.inputs,t)):e.compute(ha(e.inputs,t))},Pd=e=>qt(e)}),fa,Gc,Kc,Cd,Sd,$d,kd,Ad,Id,Hc=g(()=>{Rt(),Dt(),Jt(),fa=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].")}},Gc=(e,t,r)=>{let s="";for(let n=t-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${kt("uniforms.pads",n,r)}; if (k < 0) { break; } if (k >= i32(${kt("uniforms.x_shape",n,t)})) { break; } offset += k * i32(${kt("uniforms.x_strides",n,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${s} value = x[offset]; } `},Kc=(e,t,r)=>{let s="";for(let n=t-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${kt("uniforms.pads",n,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${kt("uniforms.x_shape",n,t)}) - 1); k = k % _2n_1; if(k >= i32(${kt("uniforms.x_shape",n,t)})) { k = _2n_1 - k; } } offset += k * i32(${kt("uniforms.x_strides",n,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},Cd=(e,t,r)=>{let s="";for(let n=t-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${kt("uniforms.pads",n,r)}; if (k < 0) { k = 0; } if (k >= i32(${kt("uniforms.x_shape",n,t)})) { k = i32(${kt("uniforms.x_shape",n,t)}) - 1; } offset += k * i32(${kt("uniforms.x_strides",n,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},Sd=(e,t,r)=>{let s="";for(let n=t-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${kt("uniforms.pads",n,r)}; if (k < 0) { k += i32(${kt("uniforms.x_shape",n,t)}]); } if (k >= i32(${kt("uniforms.x_shape",n,t)})) { k -= i32(${kt("uniforms.x_shape",n,t)}); } offset += k * i32(${kt("uniforms.x_strides",n,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},$d=(e,t,r)=>{switch(r.mode){case 0:return Gc(e,t,r.pads.length);case 1:return Kc(e,t,r.pads.length);case 2:return Cd(e,t,r.pads.length);case 3:return Sd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},kd=(e,t)=>{let r=De.padShape(e[0].dims.slice(),t.pads),s=e[0].dims,n=De.size(r),i=[{type:12,data:n},{type:6,data:t.pads}],o=e.length>=3&&e[2].data;t.mode===0&&i.push({type:o?e[2].dataType:1,data:t.value}),i.push(...gt(e[0].dims,r));let u=["rank"],p=h=>{let v=At("output",e[0].dataType,r.length),b=Xe("x",e[0].dataType,s.length),l=b.type.value,F=$d(v,s.length,t),D=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&D.push({name:"constant_value",type:o?l:"f32"}),` ${h.registerUniforms(D).declareVariables(b,v)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${v.offsetToIndices("global_idx")}; var value = ${l}(0); ${F} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${o}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(De.size(r)/64)},programUniforms:i}),getShaderSource:p}},Ad=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,n=e[0].dims.length,i=new Int32Array(2*n).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let p=0;pi[Number(p)]=Number(u));let o=[];return i.forEach(u=>o.push(u)),{mode:t.mode,value:s,pads:o}}else return t},Id=(e,t)=>{fa(e.inputs);let r=Ad(e.inputs,t);e.compute(kd(e.inputs,r),{inputs:[0]})}}),eo,_a,ga,wa,ya,qc,Fd,Ma,ba,Od,Dd,va,Qc,Ta,xa,Ld,zd,Bd,Rd,Xc=g(()=>{Tt(),Rt(),Dt(),Jt(),eo=e=>{if(C.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},_a=(e,t,r)=>{let s=t.format==="NHWC",n=e.dims.slice();s&&n.splice(1,0,n.pop());let i=Object.hasOwnProperty.call(t,"dilations"),o=t.kernelShape.slice(),u=t.strides.slice(),p=i?t.dilations.slice():[],h=t.pads.slice();gr.adjustPoolAttributes(r,n,o,u,p,h);let v=gr.computePoolOutputShape(r,n,u,p,o,h,t.autoPad),b=Object.assign({},t);i?Object.assign(b,{kernelShape:o,strides:u,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(b,{kernelShape:o,strides:u,pads:h,cacheKey:t.cacheKey});let l=v.slice();return l.push(l.splice(1,1)[0]),[b,s?l:v]},ga=(e,t)=>{let r=t.format==="NHWC",s=De.size(e),n=De.size(t.kernelShape),i=[{type:12,data:s},{type:12,data:n}],o=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],v=t.pads[t.pads.length-1],b=!!(h+v);i.push({type:12,data:u},{type:12,data:p},{type:12,data:h},{type:12,data:v}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(t.kernelShape.length===2){let F=t.kernelShape[t.kernelShape.length-2],D=t.strides[t.strides.length-2],z=t.pads[t.pads.length/2-2],X=t.pads[t.pads.length-2];l=!!(z+X),i.push({type:12,data:F},{type:12,data:D},{type:12,data:z},{type:12,data:X}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,o,!0,b,l]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=De.computeStrides(t.kernelShape);i.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),o.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,v)=>h+v);return[i,o,!!p,!1,!1]}},wa=(e,t,r,s,n,i,o,u,p,h,v,b)=>{let l=n.format==="NHWC",F=t.type.value,D=At("output",t.type.tensor,s);if(n.kernelShape.length<=2){let z="",X="",te="",K=r-(l?2:1);if(v?z=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${K}] = indices[${K}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${K}] < 0 || xIndices[${K}] >= uniforms.x_shape[${K}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`:z=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${K}] = indices[${K}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`,n.kernelShape.length===2){let ce=r-(l?3:2);b?X=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ce}] = indices[${ce}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${ce}] < 0 || xIndices[${ce}] >= uniforms.x_shape[${ce}]) { pad += i32(uniforms.kw); continue; } `:X=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ce}] = indices[${ce}] * uniforms.sh - uniforms.phStart + j; `,te=` } `}return` ${e.registerUniforms(p).declareVariables(t,D)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${D.offsetToIndices("global_idx")}; var xIndices = ${D.offsetToIndices("global_idx")}; var value = ${F}(${u}); var pad = 0; ${X} ${z} ${te} ${o} output[global_idx] = value; }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let z=n.kernelShape.length,X=n.pads.length,te="";return h?te=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`:te=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} `,` ${e.registerUniforms(p).declareVariables(t,D)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${D.offsetToIndices("global_idx")}; var xIndices = ${D.offsetToIndices("global_idx")}; var offsets: array; var value = ${F}(${u}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${z-1}u; j++) { offsets[j] = offset / ${kt("uniforms.kernelStrides","j",z)}; offset -= offsets[j] * ${kt("uniforms.kernelStrides","j",z)}; } offsets[${z-1}] = offset; isPad = false; for (var j = ${r-z}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${kt("uniforms.strides",`j - ${r-z}u`,z)} + offsets[j - ${r-z}u] - ${kt("uniforms.pads","j - 2u",X)}; ${te} } ${o} output[global_idx] = value; }`}},ya=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,qc=e=>`${ya(e)};${e.countIncludePad}`,Fd=e=>`${ya(e)};${e.storageOrder};${e.dilations}`,Ma=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}),ba=(e,t,r,s)=>{let[n,i]=_a(t,s,r),o=Xe("x",t.dataType,t.dims.length),u=o.type.value,p="value += x_val;",h="";n.countIncludePad?h+=`value /= ${u}(uniforms.kernelSize);`:h+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[v,b,l,F,D]=ga(i,n);v.push(...gt(t.dims,i));let z=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${l};${F};${D}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(De.size(i)/64)},programUniforms:v}),getShaderSource:X=>wa(X,o,t.dims.length,i.length,n,p,h,0,b,l,F,D)}},Od=e=>{let t=e.count_include_pad!==0,r=Ma(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:t,...r,cacheKey:""};return{...s,cacheKey:qc(s)}},Dd=(e,t)=>{eo(e.inputs),e.compute(ba("AveragePool",e.inputs[0],!1,t))},va={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Qc=e=>{let t=e.format;return{format:t,...va,cacheKey:t}},Ta=(e,t)=>{eo(e.inputs),e.compute(ba("GlobalAveragePool",e.inputs[0],!0,t))},xa=(e,t,r,s)=>{let[n,i]=_a(t,s,r),o=` value = max(x_val, value); `,u="",p=Xe("x",t.dataType,t.dims.length),h=["rank"],[v,b,l,F,D]=ga(i,n);return v.push(...gt(t.dims,i)),{name:e,shaderCache:{hint:`${s.cacheKey};${l};${F};${D}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(De.size(i)/64)},programUniforms:v}),getShaderSource:z=>wa(z,p,t.dims.length,i.length,n,o,u,t.dataType===10?-65504:-1e5,b,l,F,D)}},Ld=(e,t)=>{eo(e.inputs),e.compute(xa("MaxPool",e.inputs[0],!1,t))},zd=e=>{let t=e.storage_order,r=e.dilations,s=Ma(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:t,dilations:r,...s,cacheKey:""};return{...n,cacheKey:Fd(n)}},Bd=e=>{let t=e.format;return{format:t,...va,cacheKey:t}},Rd=(e,t)=>{eo(e.inputs),e.compute(xa("GlobalMaxPool",e.inputs[0],!0,t))}}),jd,Nd,Ud,Vd,Yc=g(()=>{Rt(),Dt(),cr(),Jt(),jd=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,s)=>r===e[2].dims[s]).reduce((r,s)=>r&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((n,i)=>i===t.axis||n===e[0].dims[i]).reduce((n,i)=>n&&i,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],s=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Nd=(e,t)=>{let r=De.normalizeAxis(t.axis,e[0].dims.length),s=e[0].dataType,n=s===3,i=e[0].dims,o=e[1].dataType,u=De.size(i),p=s===3||s===2,h=p?[Math.ceil(De.size(e[0].dims)/4)]:e[0].dims,v=e[1].dims,b=e.length>2?e[2]:void 0,l=b?p?[Math.ceil(De.size(b.dims)/4)]:b.dims:void 0,F=v.length===0||v.length===1&&v[0]===1,D=F===!1&&v.length===1,z=Qt(u),X=F&&(!p||z===4),te=X?z:1,K=X&&!p?z:1,ce=Xe("input",p?12:s,h.length,K),ae=Xe("scale",o,v.length),fe=b?Xe("zero_point",p?12:s,l.length):void 0,Ue=At("output",o,i.length,te),Ie=[ce,ae];fe&&Ie.push(fe);let tt=[h,v];b&&tt.push(l);let Mt=[{type:12,data:u/te},{type:12,data:r},{type:12,data:t.blockSize},...gt(...tt,i)],St=Zt=>{let tr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${Zt.registerUniforms(tr).declareVariables(...Ie,Ue)} ${Zt.mainStart()} ${Zt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${Ue.offsetToIndices("global_idx")}; // Set input x ${p?` let input = ${ce.getByOffset("global_idx / 4")}; let x_vec = ${n?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${te===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ce.getByOffset("global_idx")};`}; // Set scale input ${F?`let scale_value= ${ae.getByOffset("0")}`:D?` let scale_index = ${Ue.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${ae.getByOffset("scale_index")};`:` var scale_indices: ${ae.type.indices} = output_indices; let index = ${ae.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${ae.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${ae.getByIndices("scale_indices")};`}; // Set zero-point input ${fe?F?p?` let zero_point_input = ${fe.getByOffset("0")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${fe.getByOffset("0")}`:D?p?` let zero_point_index = ${Ue.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${fe.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${Ue.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${fe.getByOffset("zero_point_index")};`:p?` let zero_point_offset = ${ae.indicesToOffset("scale_indices")}; let zero_point_input = ${fe.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${fe.getByIndices("scale_indices")};`:`let zero_point_value = ${p?n?"i32":"u32":ce.type.value}(0);`}; // Compute and write output ${Ue.setByOffset("global_idx",`${Ue.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:fe?["rank","rank","rank"]:["rank","rank"]},getShaderSource:St,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(u/te/64),y:1,z:1},programUniforms:Mt})}},Ud=(e,t)=>{jd(e.inputs,t),e.compute(Nd(e.inputs,t))},Vd=e=>qt({axis:e.axis,blockSize:e.blockSize})}),Wd,Gd,Kd,Jc=g(()=>{Tt(),Rt(),Jt(),Wd=(e,t,r)=>{let s=e===t,n=et&&r>0;if(s||n||i)throw new Error("Range these inputs' contents are invalid.")},Gd=(e,t,r,s)=>{let n=Math.abs(Math.ceil((t-e)/r)),i=[n],o=n,u=[{type:12,data:o},{type:s,data:e},{type:s,data:r},...gt(i)],p=h=>{let v=At("output",s,i.length),b=v.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:b},{name:"delta",type:b}];return` ${h.registerUniforms(l).declareVariables(v)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${b}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:u})}},Kd=e=>{let t=0,r=0,s=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),C.webgpu.validateInputContent&&Wd(t,r,s),e.compute(Gd(t,r,s,e.inputs[0].dataType),{inputs:[]})}}),Hd,qd,Qd,Xd,Yd,Jd,Zd,ec,tc,rc,sc,Ea,nc,Zc,er,oc,Qr,Jr,ss,Sn=g(()=>{Rt(),Dt(),cr(),Jt(),Hd=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},qd=(e,t,r)=>{t.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(r).fill(1);return t.forEach((n,i)=>s[n]=e[i]),s},Qd=(e,t,r,s,n,i)=>{let[o,u,p]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(v=>i.push(v));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(v=>s.push(v)),s.length!==0&&s.length!==h&&r>=18&&s.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Hd(s,t),t.axes.length>0&&qd(s,t.axes,h).forEach((v,b)=>s[b]=v)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(v=>n.push(Number(v))),n.length!==0&&n.length!==h&&r>=18&&n.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(s.length!==0&&s.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof n<"u"&&s.length>0&&n.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},Xd=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${t}(roiStart) * ${t}(lengthOriginal - 1) + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / ${t}(lengthResized - 1); } else { return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Yd=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Jd=(e,t,r)=>{let s=new Array(r).fill(0).concat(new Array(r).fill(1)),n=e.length===0?s:e.slice();return t.length>0?(t.forEach((i,o)=>{s[i]=n[o],s[o+r]=n[t.length+o]}),s):n},Zd=(e,t,r,s)=>{let n=[];if(r.length>0)if(s.length>0){if(e.forEach(i=>n.push(i)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((i,o)=>n[i]=r[o])}else r.forEach(i=>n.push(i));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((i,o)=>Math.round(i*t[o]))}return n},ec=(e,t,r)=>{let s=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let n=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=s),r.axes.forEach(i=>n[i]=Math.round(e[i]*t[i]))):(t.fill(s,0,t.length),n.forEach((i,o)=>n[o]=Math.round(i*t[o]))),n},tc=(e,t,r,s,n)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${kt("uniforms.scales","i",s)}; var roi_low = ${kt("uniforms.roi","i",n)}; var roi_hi = ${kt("uniforms.roi",`i + ${t.length}`,n)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${kt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${kt("uniforms.output_shape","i",r.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,rc=(e,t,r,s,n,i,o)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${kt("uniforms.scales","i",n)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${kt("uniforms.roi","i",i)}; var roi_hi = ${kt("uniforms.roi",`i + ${r.length}`,i)}; var input_shape_i = ${kt("uniforms.input_shape","i",r.length)}; var output_shape_i = ${kt("uniforms.output_shape","i",s.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${o} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,sc=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${kt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,Ea=(e,t,r,s)=>e.rank>s?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",nc=(e,t,r,s,n)=>{let[i,o,u,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(row, ${r[o]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; ${Ea(e,p,i,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${h} = originalIndices[${o}]; var col:${h} = originalIndices[${u}]; ${s?`if (row < 0 || row > (${r[o]} - 1) || col < 0 || col > (${r[u]} - 1)) { return ${n}; }`:""}; row = max(0, min(row, ${r[o]} - 1)); col = max(0, min(col, ${r[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 = ${r.length>2?`u32(originalIndices[${p}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${i}])`:"0"}; var x11: ${h} = getInputValue(batch, channel, row1, col1); var x12: ${h} = getInputValue(batch, channel, row1, col2); var x21: ${h} = getInputValue(batch, channel, row2, col1); var x22: ${h} = getInputValue(batch, channel, row2, col2); var dx1: ${h} = abs(row - ${h}(row1)); var dx2: ${h} = abs(${h}(row2) - row); var dy1: ${h} = abs(col - ${h}(col1)); var dy2: ${h} = abs(${h}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},Zc=(e,t,r,s,n,i,o,u,p,h)=>{let v=r.length===2,[b,l]=v?[0,1]:[2,3],F=e.type.value,D=z=>{let X=z===b?"row":"col";return` fn ${X}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${F} { var output_index = ${t.indicesGet("output_indices",z)}; var originalIdx: ${F} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[z]}, ${s[z]}, ${r[z]}, ${i[z]}, ${i[z]} + ${r.length}); var fractOriginalIdx: ${F} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${u} && (originalIdx < 0 || originalIdx > (${r[z]} - 1))) { return ${p}; } var data: array<${F}, 4> = array<${F}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${X}: ${F} = originalIdx + ${F}(i); if (${X} < 0 || ${X} >= ${r[z]}) { ${h?`coefs[i + 1] = 0.0; continue;`:u?`return ${p};`:`${X} = max(0, min(${X}, ${r[z]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",z,`u32(${X})`)}; data[i + 1] = ${z===b?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${D(b)}; ${D(l)}; fn getCubicInterpolationCoefs(s: ${F}) -> array<${F}, 4> { var absS = abs(s); var coeffs: array<${F}, 4> = array<${F}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${F} = 1.0 - absS; var twoMinusAbsS: ${F} = 2.0 - absS; var onePlusAbsS: ${F} = 1.0 + absS; coeffs[0] = ((${o} * onePlusAbsS - 5 * ${o}) * onePlusAbsS + 8 * ${o}) * onePlusAbsS - 4 * ${o}; coeffs[1] = ((${o} + 2) * absS - (${o} + 3)) * absS * absS + 1; coeffs[2] = ((${o} + 2) * oneMinusAbsS - (${o} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${o} * twoMinusAbsS - 5 * ${o}) * twoMinusAbsS + 8 * ${o}) * twoMinusAbsS - 4 * ${o}; return coeffs; } fn cubicInterpolation1D(x: array<${F}, 4>, coefs: array<${F}, 4>) -> ${F} { var coefsSum: ${F} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${F} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},er=(e,t,r,s,n)=>{let[i,o,u,p,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],v=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${v} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(depth, ${r[o]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; ${e.indicesSet("input_indices",p,`max(0, min(width, ${r[p]} - 1))`)}; ${Ea(e,h,i,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${v} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${v} = originalIndices[${o}]; var height:${v} = originalIndices[${u}]; var width:${v} = originalIndices[${p}]; ${s?`if (depth < 0 || depth > (${r[o]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[p]} - 1)) { return ${n}; }`:""}; depth = max(0, min(depth, ${r[o]} - 1)); height = max(0, min(height, ${r[u]} - 1)); width = max(0, min(width, ${r[p]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${r.length>3?`u32(originalIndices[${h}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${i}])`:"0"}; var x111: ${v} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${v} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${v} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${v} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${v} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${v} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${v} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${v} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${v} = abs(depth - ${v}(depth1)); var dx2: ${v} = abs(${v}(depth2) - depth); var dy1: ${v} = abs(height - ${v}(height1)); var dy2: ${v} = abs(${v}(height2) - height); var dz1: ${v} = abs(width - ${v}(width1)); var dz2: ${v} = abs(${v}(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); }`},oc=(e,t,r,s,n,i)=>{let o=e.dims,u=Jd(i,t.axes,o.length),p=Zd(o,s,n,t.axes),h=s.slice();s.length===0&&(h=o.map((K,ce)=>K===0?1:p[ce]/K),t.keepAspectRatioPolicy!=="stretch"&&(p=ec(o,h,t)));let v=At("output",e.dataType,p.length),b=Xe("input",e.dataType,o.length),l=De.size(p),F=o.length===p.length&&o.every((K,ce)=>K===p[ce]),D=t.coordinateTransformMode==="tf_crop_and_resize",z=t.extrapolationValue,X=b.type.value,te=K=>` ${F?"":` ${Xd(t.coordinateTransformMode,X)}; ${(()=>{switch(t.mode){case"nearest":return` ${sc(b,o)}; ${Yd(t.nearestMode,r,X)}; ${rc(b,v,o,p,h.length,u.length,D)}; `;case"linear":return` ${tc(v,o,p,h.length,u.length)}; ${(()=>{if(o.length===2||o.length===4)return`${nc(b,v,o,D,z)}`;if(o.length===3||o.length===5)return`${er(b,v,o,D,z)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(o.length===2||o.length===4)return`${Zc(b,v,o,p,h,u,t.cubicCoeffA,D,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")}})()}; `} ${K.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",u.length).declareVariables(b,v)} ${K.mainStart()} ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${F?"output[global_idx] = input[global_idx];":` let output_indices = ${v.offsetToIndices("global_idx")}; var input_indices: ${b.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${b.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${o.length===2||o.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${h.length>0?h:""}|${n.length>0?n:""}|${u.length>0?u:""}|${F}|${o}`,inputDependencies:["rank"]},getShaderSource:te,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:h},{type:1,data:u},...gt(o,p)]})}},Qr=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Jr=(e,t)=>{let r=[],s=[],n=[],i=Qr(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Qd(e.inputs,t,i,r,s,n),e.compute(oc(e.inputs[0],t,i,r,s,n),{inputs:[0]})},ss=e=>{let t=e.antialias,r=e.axes,s=e.coordinateTransformMode,n=e.cubicCoeffA,i=e.excludeOutside!==0,o=e.extrapolationValue,u=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return qt({antialias:t,axes:r,coordinateTransformMode:s,cubicCoeffA:n,excludeOutside:i,extrapolationValue:o,keepAspectRatioPolicy:u,mode:p,nearestMode:h})}}),ep,ic,ac,f=g(()=>{Rt(),Dt(),cr(),Jt(),ep=(e,t)=>{let[r,s,n,i]=e,{numHeads:o,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!De.areEqual(s.dims,[])&&!De.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!De.areEqual(n.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&o===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=r.dims[0],h=r.dims[r.dims.length-2],v=n.dims[0],b=De.sizeFromDimension(r.dims,1)/h,l=u===0?n.dims[1]*2:b/o;if(u>l)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(p!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(h!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(l/2!==n.dims[1]&&u/2!==n.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${n.dims[1]}`);if(h>v)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},ic=(e,t)=>{let{interleaved:r,numHeads:s,rotaryEmbeddingDim:n,scale:i}=t,o=e[0].dims[0],u=De.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=u/p,v=e[2].dims[1],b=n===0?v*2:h/s,l=new Array(o,p,h/b,b-v),F=De.computeStrides(l),D=[{type:1,data:i},{type:12,data:l},{type:12,data:F},...e[0].dims.length===3?new Array({type:12,data:[u,h,b,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,b,p*b,1]}):[],...gt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],z=X=>{let te=Xe("input",e[0].dataType,e[0].dims.length),K=Xe("position_ids",e[1].dataType,e[1].dims.length),ce=Xe("cos_cache",e[2].dataType,e[2].dims.length),ae=Xe("sin_cache",e[3].dataType,e[3].dims.length),fe=At("output",e[0].dataType,e[0].dims.length);return X.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:F.length},{name:"input_output_strides",type:"u32",length:F.length}]),` ${X.declareVariables(te,K,ce,ae,fe)} ${X.mainStart(qr)} let half_rotary_emb_dim = uniforms.${ce.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${X.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${K.broadcastedIndicesToOffset("bsnh.xy",At("",K.type.tensor,2))}; let position_id = u32(${K.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); let j = i + select(half_rotary_emb_dim, 1, ${r}); let re = ${te.getByOffset("i")} * ${ce.get("position_id","bsnh[3]")} - ${te.getByOffset("j")} * ${ae.get("position_id","bsnh[3]")}; ${fe.setByOffset("i","re")} let im = ${te.getByOffset("i")} * ${ae.get("position_id","bsnh[3]")} + ${te.getByOffset("j")} * ${ce.get("position_id","bsnh[3]")}; ${fe.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${fe.setByOffset("k",te.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:qt({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:z,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(De.size(l)/qr)},programUniforms:D})}},ac=(e,t)=>{ep(e.inputs,t),e.compute(ic(e.inputs,t))}}),S,L,ve,Fe=g(()=>{Rt(),Dt(),Jt(),S=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],s=e[2];if(t.dataType!==r.dataType||t.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let n=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==i)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let o=e[3];if(o.dims.length!==1)throw new Error("Beta must be 1D");if(o.dims[o.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let o=e[4];if(o.dims.length!==1)throw new Error("Bias must be 1D");if(o.dims[o.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},L=(e,t,r,s)=>{let n=t.simplified,i=e[0].dims,o=De.size(i),u=i,p=o,h=i.slice(-1)[0],v=s?i.slice(0,-1).concat(1):[],b=!n&&e.length>3,l=e.length>4,F=s&&r>1,D=s&&r>2,z=r>3,X=64,te=Qt(h),K=[{type:12,data:p},{type:12,data:te},{type:12,data:h},{type:1,data:t.epsilon}],ce=fe=>{let Ue=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ie=[Xe("x",e[0].dataType,e[0].dims,te),Xe("skip",e[1].dataType,e[1].dims,te),Xe("gamma",e[2].dataType,e[2].dims,te)];b&&Ie.push(Xe("beta",e[3].dataType,e[3].dims,te)),l&&Ie.push(Xe("bias",e[4].dataType,e[4].dims,te)),Ie.push(At("output",e[0].dataType,u,te)),F&&Ie.push(At("mean_output",1,v)),D&&Ie.push(At("inv_std_output",1,v)),z&&Ie.push(At("input_skip_bias_sum",e[0].dataType,u,te));let tt=ir(e[0].dataType),Mt=ir(1,te);return` ${fe.registerUniforms(Ue).declareVariables(...Ie)} var sum_shared : array<${Mt}, ${X}>; var sum_squared_shared : array<${Mt}, ${X}>; ${fe.mainStart([X,1,1])} let ix = local_id.x; let iy = global_id.x / ${X}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${X}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${X-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${l?"bias[offset1d + i]":tt+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${z?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Os(tt,te,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${X}; 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 = ${Ds("sum",te)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Ds("square_sum",te)} / f32(uniforms.hidden_size) ${n?"":"- mean * mean"} + uniforms.epsilon); ${F?"mean_output[global_idx] = mean;":""} ${D?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${n?"":`- ${tt}(mean)`}) * ${tt}(inv_std_dev) * gamma[offset1d + i] ${b?"+ beta[offset1d + i]":""}; } }`},ae=[{dims:u,dataType:e[0].dataType}];return r>1&&ae.push({dims:v,dataType:1}),r>2&&ae.push({dims:v,dataType:1}),r>3&&ae.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${te};${F};${D};${z}`,inputDependencies:e.map((fe,Ue)=>"type")},getShaderSource:ce,getRunData:()=>({outputs:ae,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:K})}},ve=(e,t)=>{S(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute(L(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Ae,qe,it,mt,Ct,Ut,Ot,Wt,Lt=g(()=>{Rt(),Dt(),cr(),Jt(),Ae=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},qe=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(s=>r.push(Number(s)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(s=>r.push(Number(s)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},it=(e,t)=>{if(e.length>1){let r=qe(e,1),s=qe(e,2),n=qe(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),qt({starts:r,ends:s,axes:n})}else return t},mt=(e,t,r,s,n)=>{let i=e;return e<0&&(i+=r[s[t]]),n[t]<0?Math.max(0,Math.min(i,r[s[t]]-1)):Math.max(0,Math.min(i,r[s[t]]))},Ct=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${kt("uniforms.input_shape","i",r.length)}; let steps_i = ${kt("uniforms.steps","i",r.length)}; let signs_i = ${kt("uniforms.signs","i",r.length)}; let starts_i = ${kt("uniforms.starts","i",r.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,Ut=(e,t)=>{let r=e[0].dims,s=De.size(r),n=t.axes.length>0?De.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=qe(e,4);i.forEach(te=>te!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(n.length).fill(1));let o=t.starts.map((te,K)=>mt(te,K,r,n,i)),u=t.ends.map((te,K)=>mt(te,K,r,n,i));if(n.length!==o.length||n.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==r.length)for(let te=0;teMath.sign(te));i.forEach((te,K,ce)=>{if(te<0){let ae=(u[K]-o[K])/te,fe=o[K],Ue=fe+ae*i[K];o[K]=Ue,u[K]=fe,ce[K]=-te}});let h=r.slice(0);n.forEach((te,K)=>{h[te]=Math.ceil((u[te]-o[te])/i[te])});let v={dims:h,dataType:e[0].dataType},b=At("output",e[0].dataType,h.length),l=Xe("input",e[0].dataType,e[0].dims.length),F=De.size(h),D=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:i.length}],z=[{type:12,data:F},{type:12,data:o},{type:6,data:p},{type:12,data:i},...gt(e[0].dims,h)],X=te=>` ${te.registerUniforms(D).declareVariables(l,b)} ${Ct(l,b,r)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${b.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${b.setByOffset("global_idx",l.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${o.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:X,getRunData:()=>({outputs:[v],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:z})}},Ot=(e,t)=>{Ae(e.inputs,t);let r=it(e.inputs,t);e.compute(Ut(e.inputs,r),{inputs:[0]})},Wt=e=>{let t=e.starts,r=e.ends,s=e.axes;return qt({starts:t,ends:r,axes:s})}}),sr,or,Yt,ur,Rr=g(()=>{Rt(),Dt(),cr(),mn(),Jt(),sr=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},or=(e,t)=>{let r=e.inputs[0],s=r.dims,n=De.size(s),i=64,o=s.length,u=De.normalizeAxis(t.axis,o),p=utt),v[u]=o-1,v[o-1]=u,h=e.compute(ms(r,v),{inputs:[r],outputs:[-1]})[0]):h=r;let b=h.dims,l=b[o-1],F=n/l,D=Qt(l),z=l/D,X=(Ie,tt)=>tt===4?`max(max(${Ie}.x, ${Ie}.y), max(${Ie}.z, ${Ie}.w))`:tt===2?`max(${Ie}.x, ${Ie}.y)`:tt===3?`max(max(${Ie}.x, ${Ie}.y), ${Ie}.z)`:Ie,te=Xe("x",h.dataType,h.dims,D),K=At("result",h.dataType,h.dims,D),ce=te.type.value,ae=ir(h.dataType)==="f32"?`var threadMax = ${ce}(-3.402823e+38f);`:`var threadMax = ${ce}(-65504.0h);`,fe=Ie=>` var rowMaxShared : ${ce}; var rowSumShared : ${ce}; var threadShared : array<${ce}, ${i}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${ce} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${ce}) { let index = row * row_stride + col; result[index] = value; } ${Ie.registerUniform("packedCols","i32").declareVariables(te,K)} ${Ie.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${i}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${ae} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${ce}(${X("threadShared[0]",D)}); } workgroupBarrier(); // find the rows sum var threadSum = ${ce}(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 = ${ce}(${Ds("threadShared[0]",D)}); } 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); } }`,Ue=e.compute({name:"Softmax",shaderCache:{hint:`${D}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:b,dataType:h.dataType}],dispatchGroup:{x:F},programUniforms:[{type:6,data:z}]}),getShaderSource:fe},{inputs:[h],outputs:[p?-1:0]})[0];p&&e.compute(ms(Ue,v),{inputs:[Ue]})},Yt=(e,t)=>{sr(e.inputs),or(e,t)},ur=e=>qt({axis:e.axis})}),Sr,$r,kr,Or,Zr,Gr,$s,to=g(()=>{Rt(),Dt(),cr(),Jt(),Sr=e=>{if(!e||e.length<1)throw new Error("too few inputs")},$r=(e,t)=>{let r=[],s=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),s=r.length),qt({numOutputs:s,axis:t.axis,splitSizes:r})},kr=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${kt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Or=e=>{let t=e.length,r=[];for(let s=0;s{let r=e[0].dims,s=De.size(r),n=e[0].dataType,i=De.normalizeAxis(t.axis,r.length),o=new Array(t.numOutputs),u=Xe("input",n,r.length),p=new Array(t.numOutputs),h=[],v=[],b=0,l=[{type:12,data:s}];for(let D=0;D` ${D.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(u,...o)} ${kr(p.length)} ${Or(o)} ${D.mainStart()} ${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${u.offsetToIndices("global_idx")}; var index = ${u.indicesGet("indices",i)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${kt("uniforms.size_in_split_axis","output_number - 1u",p.length)}; ${u.indicesSet("indices",i,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:F,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:l})}},Gr=(e,t)=>{Sr(e.inputs);let r=e.inputs.length===1?t:$r(e.inputs,t);e.compute(Zr(e.inputs,r),{inputs:[0]})},$s=e=>{let t=e.axis,r=e.splitSizes,s=e.numOutputs<0?r.length:e.numOutputs;if(s!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qt({axis:t,numOutputs:s,splitSizes:r})}}),Pa,fs,Ls,lc=g(()=>{Rt(),Dt(),Jt(),Pa=(e,t,r,s,n)=>{let i=At("output_data",n,r.length,4),o=Xe("a_data",t[1].dataType,t[1].dims.length,4),u=Xe("b_data",t[2].dataType,t[2].dims.length,4),p=Xe("c_data",t[0].dataType,t[0].dims.length,4),h,v=(b,l,F)=>`select(${l}, ${b}, ${F})`;if(!s)h=i.setByOffset("global_idx",v(o.getByOffset("global_idx"),u.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let b=(l,F,D="")=>{let z=`a_data[index_a${F}][component_a${F}]`,X=`b_data[index_b${F}][component_b${F}]`,te=`bool(c_data[index_c${F}] & (0xffu << (component_c${F} * 8)))`;return` let output_indices${F} = ${i.offsetToIndices(`global_idx * 4u + ${F}u`)}; let offset_a${F} = ${o.broadcastedIndicesToOffset(`output_indices${F}`,i)}; let offset_b${F} = ${u.broadcastedIndicesToOffset(`output_indices${F}`,i)}; let offset_c${F} = ${p.broadcastedIndicesToOffset(`output_indices${F}`,i)}; let index_a${F} = offset_a${F} / 4u; let index_b${F} = offset_b${F} / 4u; let index_c${F} = offset_c${F} / 4u; let component_a${F} = offset_a${F} % 4u; let component_b${F} = offset_b${F} % 4u; let component_c${F} = offset_c${F} % 4u; ${l}[${F}] = ${D}(${v(z,X,te)}); `};n===9?h=` var data = vec4(0); ${b("data",0,"u32")} ${b("data",1,"u32")} ${b("data",2,"u32")} ${b("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` ${b("output_data[global_idx]",0)} ${b("output_data[global_idx]",1)} ${b("output_data[global_idx]",2)} ${b("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(p,o,u,i)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${h} }`},fs=e=>{let t=e[1].dims,r=e[2].dims,s=e[0].dims,n=e[1].dataType,i=!(De.areEqual(t,r)&&De.areEqual(r,s)),o=t,u=De.size(t);if(i){let h=zr.calcShape(zr.calcShape(t,r,!1),s,!1);if(!h)throw new Error("Can't perform where op on the given tensors");o=h,u=De.size(o)}let p=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Pa(h,e,o,i,n),getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:p},...gt(s,t,r,o)]})}},Ls=e=>{e.compute(fs(e.inputs))}}),Do,Ca=g(()=>{wc(),Mo(),Al(),yc(),du(),Mc(),bc(),Ec(),Sc(),kc(),Ac(),Fc(),Oc(),Dc(),Pp(),Lc(),Cp(),Bc(),Rc(),Sp(),Uc(),Ou(),Wc(),_d(),Hc(),Xc(),Yc(),Jc(),ii(),Sn(),f(),Fe(),Lt(),Rr(),to(),Md(),mn(),Kn(),lc(),Do=new Map([["Abs",[Dl]],["Acos",[Ll]],["Acosh",[ui]],["Add",[pu]],["ArgMax",[bl,yo]],["ArgMin",[Ml,yo]],["Asin",[zl]],["Asinh",[Bl]],["Atan",[di]],["Atanh",[Rl]],["Attention",[Pl]],["AveragePool",[Dd,Od]],["BatchNormalization",[kl]],["BiasAdd",[li]],["BiasSplitGelu",[Ti]],["Cast",[ci,jl]],["Ceil",[Vl]],["Clip",[Ul]],["Concat",[$i,vu]],["Conv",[Vi,Ni]],["ConvTranspose",[ko,Xn]],["Cos",[Wl]],["Cosh",[pi]],["CumSum",[Ku,$c]],["DepthToSpace",[Qu,Xu]],["DequantizeLinear",[Ud,Vd]],["Div",[hu]],["Einsum",[qi,td]],["Elu",[Gl,Gn]],["Equal",[Ei]],["Erf",[Kl]],["Exp",[hi]],["Expand",[sd]],["FastGelu",[nd]],["Floor",[Hl]],["FusedConv",[Vi,Ni]],["Gather",[Fo,Ji]],["GatherElements",[ta,cd]],["GatherBlockQuantized",[Zi,ud]],["Gelu",[ql]],["Gemm",[pd,sa]],["GlobalAveragePool",[Ta,Qc]],["GlobalMaxPool",[Rd,Bd]],["Greater",[Pi]],["GreaterOrEqual",[wu]],["GroupQueryAttention",[da,la]],["HardSigmoid",[fi,eu]],["InstanceNormalization",[Nc]],["LayerNormalization",[xd]],["LeakyRelu",[Ql,Gn]],["Less",[gu]],["LessOrEqual",[Ci]],["Log",[ou]],["MatMul",[Fu]],["MatMulNBits",[Vc,Pd]],["MaxPool",[Ld,zd]],["Mul",[mu]],["MultiHeadAttention",[na,md]],["Neg",[mi]],["Not",[Xl]],["Pad",[Id]],["Pow",[fu]],["QuickGelu",[au,Gn]],["Range",[Kd]],["Reciprocal",[Yl]],["ReduceMin",[ni]],["ReduceMean",[hl]],["ReduceMax",[_l]],["ReduceSum",[wl]],["ReduceProd",[gl]],["ReduceL1",[ml]],["ReduceL2",[si]],["ReduceLogSum",[yl]],["ReduceLogSumExp",[fl]],["ReduceSumSquare",[oi]],["Relu",[Jl]],["Resize",[Jr,ss]],["RotaryEmbedding",[ac]],["Sigmoid",[Zl]],["Sin",[tu]],["Sinh",[ru]],["Slice",[Ot,Wt]],["SkipLayerNormalization",[ve]],["Split",[Gr,$s]],["Sqrt",[_i]],["Softmax",[Yt,ur]],["Sub",[_u]],["Tan",[su]],["Tanh",[wi]],["ThresholdedRelu",[nu,Gn]],["Tile",[yd]],["Transpose",[hn,Wa]],["Where",[Ls]]])}),Lo,Ir=g(()=>{Tt(),xe(),Jt(),Lo=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,s,n){He(e.programInfo.name);let i=this.backend.device,o=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 r)u.push({binding:u.length,resource:{buffer:h.buffer}});n&&u.push({binding:u.length,resource:n});let p=i.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:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}o.setPipeline(e.computePipeline),o.setBindGroup(0,p),o.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Be(e.programInfo.name)}dispose(){}build(e,t){He(e.name);let r=this.backend.device,s=[];r.features.has("shader-f16")&&s.push("enable f16;");let n=Ra(t,this.backend.device.limits),i=e.getShaderSource(n),o=`${s.join(` `)} ${n.additionalImplementations} ${i}`,u=r.createShaderModule({code:o,label:e.name});_r("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let p=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Be(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:n.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,n=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=n&&r<=n&&s<=n)return[t,r,s];let i=t*r*s,o=Math.ceil(Math.sqrt(i));if(o>n){if(o=Math.ceil(Math.cbrt(i)),o>n)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),Ur,an,fn,$n,Sa=g(()=>{Tt(),Rt(),xe(),G(),rr(),Ca(),Ir(),Ur=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let s=0;s{var n,i;let s=e.name;return(n=e.shaderCache)!=null&&n.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+r+`:${Ur(t,((i=e.shaderCache)==null?void 0:i.inputDependencies)??new Array(t.length).fill("dims"))}`,s},fn=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},$n=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};t.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&r.push("timestamp-query"),t.features.has("shader-f16")&&r.push("shader-f16"),this.device=await t.requestDevice(s),this.adapterInfo=new fn(t.info||await t.requestAdapterInfo()),this.gpuDataManager=mr(this),this.programManager=new Lo(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,pn(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;He(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let n=0;n"u"&&(this.queryTimeBase=F);let z=Number(F-this.queryTimeBase),X=Number(D-this.queryTimeBase);if(!Number.isSafeInteger(z)||!Number.isSafeInteger(X))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:b.map(te=>({dims:te.dims,dataType:xs(te.dataType)})),outputsMetadata:l.map(te=>({dims:te.dims,dataType:xs(te.dataType)})),kernelId:o,kernelType:p,kernelName:h,programName:v,startTime:z,endTime:X});else{let te="";b.forEach((ce,ae)=>{te+=`input[${ae}]: [${ce.dims}] | ${xs(ce.dataType)}, `});let K="";l.forEach((ce,ae)=>{K+=`output[${ae}]: [${ce.dims}] | ${xs(ce.dataType)}, `}),console.log(`[profiling] kernel "${o}|${p}|${h}|${v}" ${te}${K}execution time: ${X-z} ns`)}Ze("GPU",`${v}::${F}::${D}`)}e.unmap(),this.pendingQueries.delete(e)}),Be()}run(e,t,r,s,n,i){He(e.name);let o=[];for(let K=0;Kce):r;if(v.length!==u.length)throw new Error(`Output size ${v.length} must be equal to ${u.length}.`);let b=[],l=[];for(let K=0;K=i)throw new Error(`Invalid output index: ${v[K]}`);if(v[K]===-3)continue;let ce=v[K]===-1,ae=v[K]===-2,fe=ce||ae?n(u[K].dataType,u[K].dims):s(v[K],u[K].dataType,u[K].dims);if(b.push(fe),fe.data===0)continue;let Ue=this.gpuDataManager.get(fe.data);if(!Ue)throw new Error(`no GPU data for output: ${fe.data}`);if(ce&&this.temporaryData.push(Ue),ae){let Ie=this.kernelPersistentData.get(this.currentKernelId);Ie||(Ie=[],this.kernelPersistentData.set(this.currentKernelId,Ie)),Ie.push(Ue)}l.push(Ue)}if(o.length!==t.length||l.length!==b.length){if(l.length===0)return Be(e.name),b;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let F;if(h){let K=0,ce=[];h.forEach(Ie=>{let tt=typeof Ie.data=="number"?[Ie.data]:Ie.data;if(tt.length===0)return;let Mt=Ie.type===10?2:4,St,Zt;Ie.type===10?(Zt=tt.length>4?16:tt.length>2?8:tt.length*Mt,St=tt.length>4?16:Mt*tt.length):(Zt=tt.length<=2?tt.length*Mt:16,St=16),K=Math.ceil(K/Zt)*Zt,ce.push(K);let tr=Ie.type===10?8:4;K+=tt.length>4?Math.ceil(tt.length/tr)*St:tt.length*Mt});let ae=16;K=Math.ceil(K/ae)*ae;let fe=new ArrayBuffer(K);h.forEach((Ie,tt)=>{let Mt=ce[tt],St=typeof Ie.data=="number"?[Ie.data]:Ie.data;if(Ie.type===6)new Int32Array(fe,Mt,St.length).set(St);else if(Ie.type===12)new Uint32Array(fe,Mt,St.length).set(St);else if(Ie.type===10)new Uint16Array(fe,Mt,St.length).set(St);else if(Ie.type===1)new Float32Array(fe,Mt,St.length).set(St);else throw new Error(`Unsupported uniform type: ${xs(Ie.type)}`)});let Ue=this.gpuDataManager.create(K,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ue.buffer,0,fe,0,K),this.gpuDataManager.release(Ue.id),F={offset:0,size:K,buffer:Ue.buffer}}let D=this.programManager.normalizeDispatchGroupSize(p),z=D[1]===1&&D[2]===1,X=an(e,t,z),te=this.programManager.getArtifact(X);if(te||(te=this.programManager.build(e,D),this.programManager.setArtifact(X,te),_r("info",()=>`[artifact] key: ${X}, programName: ${e.name}`)),h&&te.uniformVariablesInfo){if(h.length!==te.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${te.uniformVariablesInfo.length}, got ${h.length} in program "${te.programInfo.name}".`);for(let K=0;K`[ProgramManager] run "${e.name}" (key=${X}) with ${D[0]}x${D[1]}x${D[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let K={kernelId:this.currentKernelId,programName:te.programInfo.name,inputTensorViews:t,outputTensorViews:b};this.pendingKernels.push(K),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(K)}return this.programManager.run(te,o,l,D,F),Be(e.name),b}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,s){let n=Do.get(e);if(!n)throw new Error(`kernel not implemented: ${e}`);let i={kernelType:e,kernelName:s,kernelEntry:n[0],attributes:[n[1],r]};this.kernels.set(t,i)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let n=s.kernelType,i=s.kernelName,o=s.kernelEntry,u=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${n}] ${i}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),_r("info",()=>`[WebGPU] Start to run kernel "[${n}] ${i}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),o(t,u[1]),0}catch(h){return r.push(Promise.resolve(`[WebGPU] Kernel "[${n}] ${i}" failed. ${h}`)),1}finally{p&&r.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${n}] ${i}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,s){let n=this.sessionExternalDataMapping.get(e);n||(n=new Map,this.sessionExternalDataMapping.set(e,n));let i=n.get(t),o=this.gpuDataManager.registerExternalBuffer(r,s,i);return n.set(t,[o,r]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let s=await bt(this,e,t);return M(s.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){_r("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){_r("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){_r("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),$a,zo,Bo,tp,ka,Aa=g(()=>{xe(),$a=1,zo=()=>$a++,Bo=class{constructor(e,t){this.mlContext=e,this.tensorEntry=t,this.tensorCache=t?[t]:[]}get tensor(){var e;return(e=this.tensorEntry)==null?void 0:e[0]}get context(){if(!this.mlContext)throw new Error("MLContext has not been set.");return this.mlContext}set context(e){if(this.mlContext&&this.mlContext!==e)throw new Error("MLTensor in use in a different MLContext.");this.mlContext=e}destroy(){for(let[e]of this.tensorCache)e.destroy();this.tensorCache=[],this.tensorEntry=void 0}trySelectTensor(e,t){for(let[r,s,n]of this.tensorCache)if(t===r){if(this.context!==e)throw new Error("MLTensor cannot be registered with a different MLContext.");return this.tensorEntry=[r,s,n],!0}return!1}async ensureTensor(e,t,r){var i;if(this.tensorEntry){let[o,u,p]=this.tensorEntry;if(u===e&&p.every((h,v)=>h===t[v]))return o}for(let[o,u,p]of this.tensorCache)if(u===e&&p.every((h,v)=>h===t[v])){if(r&&this.tensorEntry){_r("verbose",()=>`[WebNN] Slowdown may occur, having to copy existing tensor {dataType: ${e}, shape: ${t}}`);let h=await this.context.readTensor(this.tensorEntry[0]);this.context.writeTensor(o,h)}return this.tensorEntry=[o,u,p],o}_r("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let s=MLTensorUsage.READ|MLTensorUsage.WRITE,n=await this.context.createTensor({dataType:e,shape:t,dimensions:t,usage:s});return this.tensorEntry=[n,e,t],this.tensorCache.push(this.tensorEntry),this.activeUpload&&((i=this.mlContext)==null||i.writeTensor(n,this.activeUpload),this.activeUpload=void 0),n}upload(e){var t;if(!this.tensorEntry){this.activeUpload=new Uint8Array(e);return}(t=this.mlContext)==null||t.writeTensor(this.tensorEntry[0],e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.tensorEntry)throw new Error("Tensor has not been created.");return e?this.context.readTensor(this.tensorEntry[0],e):this.context.readTensor(this.tensorEntry[0])}},tp=class{constructor(e){this.backend=e,this.tensorsById=new Map,this.tensorIdsByContext=new Map}reserveTensorId(){let e=zo();return this.tensorsById.set(e,new Bo),e}releaseTensorId(e){let t=this.tensorsById.get(e);if(t){t.destroy(),this.tensorsById.delete(e);for(let[r,s]of this.tensorIdsByContext)if(s.has(e)){s.delete(e),s.size===0&&this.tensorIdsByContext.delete(r);break}}}async ensureTensor(e,t,r,s){var i;_r("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${s}}`);let n=this.tensorsById.get(e);if(!n)throw new Error("Tensor not found.");return n.context=this.backend.currentContext,this.tensorIdsByContext.has(this.backend.currentContext)||this.tensorIdsByContext.set(this.backend.currentContext,new Set),(i=this.tensorIdsByContext.get(this.backend.currentContext))==null||i.add(e),n.ensureTensor(t,r,s)}upload(e,t){this.tensorsById.get(e).upload(t)}async download(e,t){return _r("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`),this.tensorsById.get(e).download(t)}releaseTensorsForContext(e){let t=this.tensorIdsByContext.get(e);if(t){for(let r of t)this.tensorsById.get(r).destroy(),this.tensorsById.delete(r);this.tensorIdsByContext.delete(e)}}registerTensor(e,t,r,s){for(let[o,u]of this.tensorsById)if(u.trySelectTensor(e,t))return o;let n=zo();this.tensorsById.set(n,new Bo(e,[t,r,s]));let i=this.tensorIdsByContext.get(e);return i||(i=new Set,this.tensorIdsByContext.set(e,i)),i.add(n),n}},ka=(...e)=>new tp(...e)}),Ro,uc,dc=g(()=>{Rt(),cs(),G(),Aa(),xe(),Ro=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),uc=class{constructor(e){this.tensorManager=ka(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,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}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);r.delete(e),r.size===0&&(this.sessionIdsByMLContext.delete(t),this.tensorManager.releaseTensorsForContext(t))}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){_r("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,s){let n=Ro.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,n,r,s)}uploadTensor(e,t){if(!xr().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");_r("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return M(r,t)}}registerMLTensor(e,t,r){let s=Ro.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(this.currentContext,e,s,r);return _r("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${s}, dimensions: ${r}} -> {tensorId: ${n}}`),n}flush(){}}}),jo={};x(jo,{init:()=>sp});var Ia,rp,sp,kn=g(()=>{Rt(),Sa(),xe(),Dt(),dc(),Ia=class Km{constructor(t,r,s,n){this.module=t,this.dataType=r,this.data=s,this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=De.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=De.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=De.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=De.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(De.size(t)!==De.size(this.dims))throw new Error("Invalid new shape");return new Km(this.module,this.dataType,this.data,t)}},rp=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let s=e.HEAPU32,n=r>>>2;this.opKernelContext=s[n++];let i=s[n++];this.outputCount=s[n++],this.customDataOffset=s[n++],this.customDataSize=s[n++];let o=[];for(let u=0;utypeof u=="number"?this.inputs[u]:u))??this.inputs,s=(t==null?void 0:t.outputs)??[],n=(u,p,h)=>new Ia(this.module,p,this.output(u,h),h),i=(u,p)=>{let h=ws(u,p);if(!h)throw new Error(`Unsupported data type: ${u}`);let v=h>0?this.backend.gpuDataManager.create(h).id:0;return new Ia(this.module,u,v,p)};return this.backend.run(e,r,s,n,i,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let s=this.module.stackAlloc((1+t.length)*4),n=s>>2;this.module.HEAPU32[n++]=t.length;for(let i=0;i{let n=t.jsepInit;if(!n)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let i=new $n;await i.initialize(r,s),n("webgpu",[i,o=>i.alloc(o),o=>i.free(o),(o,u,p,h=!1)=>{if(h)_r("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${o}, dst=${u}, size=${p}`),i.memcpy(o,u);else{_r("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${o}, gpuDataId=${u}, size=${p}`);let v=t.HEAPU8.subarray(o>>>0,(o>>>0)+p);i.upload(u,v)}},async(o,u,p)=>{_r("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${u}, size=${p}`),await i.download(o,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+p))},(o,u,p)=>i.createKernel(o,u,p,t.UTF8ToString(t._JsepGetNodeName(u))),o=>i.releaseKernel(o),(o,u,p,h)=>{_r("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${o}, contextDataOffset=${u}`);let v=new rp(t,i,u);return i.computeKernel(o,v,h)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new uc(r);n("webnn",[i,()=>i.reserveTensorId(),o=>i.releaseTensorId(o),async(o,u,p,h)=>i.ensureTensor(o,u,p,h),(o,u)=>{i.uploadTensor(o,u)},async(o,u)=>i.downloadTensor(o,u)])}}}),ks,$p,kp,ro,ch,np,Ap,Ip,Fp,Op,Dp,Lp,ph=g(()=>{po(),ho(),Rt(),cs(),Ns(),Bn(),ks=(e,t)=>{xr()._OrtInit(e,t)!==0&&br("Can't initialize onnxruntime.")},$p=async e=>{ks(e.wasm.numThreads,cn(e.logLevel))},kp=async(e,t)=>{{let r=(kn(),$(jo)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:i}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",xr(),e,s)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",xr(),e)}}},ro=new Map,ch=e=>{let t=xr(),r=t.stackSave();try{let s=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,s,s+4)!==0&&br("Can't get session input/output count."),[t.HEAP32[s/4],t.HEAP32[s/4+1]]}finally{t.stackRestore(r)}},np=e=>{let t=xr(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Ap=async(e,t)=>{var b,l;let r,s,n=xr();Array.isArray(e)?[r,s]=e:e.buffer===n.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=np(e);let i=0,o=0,u=0,p=[],h=[],v=[];try{if([o,p]=zn(t),(t==null?void 0:t.externalData)&&n.mountExternalData){let ae=[];for(let fe of t.externalData){let Ue=typeof fe=="string"?fe:fe.path;ae.push(xn(typeof fe=="string"?fe:fe.data).then(Ie=>{n.mountExternalData(Ue,Ie)}))}await Promise.all(ae)}for(let ae of(t==null?void 0:t.executionProviders)??[])if((typeof ae=="string"?ae:ae.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,n.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof ae!="string"){let fe=ae,Ue=fe==null?void 0:fe.context,Ie=fe==null?void 0:fe.gpuDevice,tt=fe==null?void 0:fe.deviceType,Mt=fe==null?void 0:fe.numThreads,St=fe==null?void 0:fe.powerPreference;Ue?n.currentContext=Ue:Ie?n.currentContext=await navigator.ml.createContext(Ie):n.currentContext=await navigator.ml.createContext({deviceType:tt,numThreads:Mt,powerPreference:St})}else n.currentContext=await navigator.ml.createContext();break}i=await n._OrtCreateSession(r,s,o),i===0&&br("Can't create a session."),n.currentContext&&(n.jsepRegisterMLContext(i,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[F,D]=ch(i),z=!!(t!=null&&t.enableGraphCapture),X=[],te=[],K=[];for(let ae=0;aeae==="gpu-buffer"||ae==="ml-tensor")&&(u=n._OrtCreateBinding(i),u===0&&br("Can't create IO binding."),ce={handle:u,outputPreferredLocations:K,outputPreferredLocationsEncoded:K.map(ae=>Vs(ae))}),ro.set(i,[i,h,v,ce,z,!1]),[i,X,te]}catch(F){throw h.forEach(D=>n._OrtFree(D)),v.forEach(D=>n._OrtFree(D)),u!==0&&n._OrtReleaseBinding(u),i!==0&&n._OrtReleaseSession(i),F}finally{n._free(r),o!==0&&n._OrtReleaseSessionOptions(o),p.forEach(F=>n._free(F)),(l=n.unmountExternalData)==null||l.call(n)}},Ip=e=>{var p;let t=xr(),r=ro.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,i,o,u]=r;o&&(u&&t._OrtClearBoundOutputs(o.handle),t._OrtReleaseBinding(o.handle)),(p=t.jsepOnReleaseSession)==null||p.call(t,e),n.forEach(h=>t._OrtFree(h)),i.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(s),ro.delete(e)},Fp=(e,t,r,s,n,i=!1)=>{if(!e){t.push(0);return}let o=xr(),u=e[0],p=e[1],h=e[3],v,b;if(u==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let D=e[2].gpuBuffer;b=ws(tn(u),p);let z=o.jsepRegisterBuffer;if(!z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');v=z(s,n,D,b)}else if(h==="ml-tensor"){let D=e[2].mlTensor;b=ws(tn(u),p);let z=o.jsepRegisterMLTensor;if(!z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');v=z(D,tn(u),p)}else{let D=e[2];if(Array.isArray(D)){b=4*D.length,v=o._malloc(b),r.push(v);let z=v/4;for(let X=0;Xo.HEAP32[D++]=X);let z=o._OrtCreateTensor(tn(u),v,b,F,p.length,Vs(h));z===0&&br(`Can't create tensor for input/output. session=${s}, index=${n}.`),t.push(z)}finally{o.stackRestore(l)}},Op=async(e,t,r,s,n,i)=>{var St,Zt;let o=xr(),u=ro.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=u[0],h=u[1],v=u[2],b=u[3],l=u[4],F=u[5],D=t.length,z=s.length,X=0,te=[],K=[],ce=[],ae=[],fe=o.stackSave(),Ue=o.stackAlloc(D*4),Ie=o.stackAlloc(D*4),tt=o.stackAlloc(z*4),Mt=o.stackAlloc(z*4);try{(St=o.jsepOnRunStart)==null||St.call(o,p),[X,te]=Fn(i);for(let Ft=0;Ftes*ls,1);Gt=xs(Xr);let Vo=b==null?void 0:b.outputPreferredLocations[s[Ft]];if(Gt==="string"){if(Vo==="gpu-buffer"||Vo==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let es=[],ls=Tr/4;for(let Gs=0;Gs0){let es=o.jsepGetBuffer;if(!es)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ls=es(Tr),Gs=ws(Xr,ns);if(Gs===void 0||!vn(Gt))throw new Error(`Unsupported data type: ${Gt}`);ct=!0,Er.push([Gt,bs,{gpuBuffer:ls,download:o.jsepCreateDownloader(ls,Gs,Gt),dispose:()=>{o._OrtReleaseTensor(Vt)}},"gpu-buffer"])}else if(Vo==="ml-tensor"&&ns>0){let es=o.jsepEnsureTensor;if(!es)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ws(Xr,ns)===void 0||!Tn(Gt))throw new Error(`Unsupported data type: ${Gt}`);let ls=await es(Tr,Xr,bs,!1);ct=!0,Er.push([Gt,bs,{mlTensor:ls,download:o.jsepCreateMLTensorDownloader(Tr,Gt),dispose:()=>{o.jsepReleaseTensorId(Tr),o._OrtReleaseTensor(Vt)}},"ml-tensor"])}else{let es=bn(Gt),ls=new es(ns);new Uint8Array(ls.buffer,ls.byteOffset,ls.byteLength).set(o.HEAPU8.subarray(Tr,Tr+ls.byteLength)),Er.push([Gt,bs,ls,"cpu"])}}finally{o.stackRestore(pr),Gt==="string"&&Tr&&o._free(Tr),ct||o._OrtReleaseTensor(Vt)}}return b&&!l&&(o._OrtClearBoundOutputs(b.handle),ro.set(e,[p,h,v,b,l,!1])),Er}finally{o.stackRestore(fe),K.forEach(tr=>o._OrtReleaseTensor(tr)),ce.forEach(tr=>o._OrtReleaseTensor(tr)),ae.forEach(tr=>o._free(tr)),X!==0&&o._OrtReleaseRunOptions(X),te.forEach(tr=>o._free(tr))}},Dp=e=>{let t=xr(),r=ro.get(e);if(!r)throw new Error("invalid session id");let s=r[0],n=t._OrtEndProfiling(s);n===0&&br("Can't get an profile file name."),t._OrtFree(n)},Lp=e=>{let t=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&t.push(s.buffer)}return t}}),so,As,Fa,cc,pc,op,zp,ip,No,Uo,hh,mh,fh,_h,gh,wh,yh,Mh,bh=g(()=>{Tt(),ph(),cs(),Rs(),so=()=>!!C.wasm.proxy&&typeof document<"u",Fa=!1,cc=!1,pc=!1,ip=new Map,No=(e,t)=>{let r=ip.get(e);r?r.push(t):ip.set(e,[t])},Uo=()=>{if(Fa||!cc||pc||!As)throw new Error("worker not ready")},hh=e=>{switch(e.data.type){case"init-wasm":Fa=!1,e.data.err?(pc=!0,zp[1](e.data.err)):(cc=!0,zp[0]()),op&&(URL.revokeObjectURL(op),op=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=ip.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},mh=async()=>{if(!cc){if(Fa)throw new Error("multiple calls to 'initWasm()' detected.");if(pc)throw new Error("previous call to 'initWasm()' failed.");if(Fa=!0,so())return new Promise((e,t)=>{As==null||As.terminate(),dn().then(([r,s])=>{try{As=s,As.onerror=i=>t(i),As.onmessage=hh,zp=[e,t];let n={type:"init-wasm",in:C};As.postMessage(n),op=r}catch(n){t(n)}},t)});try{await js(C.wasm),await $p(C),cc=!0}catch(e){throw pc=!0,e}finally{Fa=!1}}},fh=async e=>{if(so())return Uo(),new Promise((t,r)=>{No("init-ep",[t,r]);let s={type:"init-ep",in:{epName:e,env:C}};As.postMessage(s)});await kp(C,e)},_h=async e=>so()?(Uo(),new Promise((t,r)=>{No("copy-from",[t,r]);let s={type:"copy-from",in:{buffer:e}};As.postMessage(s,[e.buffer])})):np(e),gh=async(e,t)=>{if(so()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Uo(),new Promise((r,s)=>{No("create",[r,s]);let n={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),As.postMessage(n,i)})}else return Ap(e,t)},wh=async e=>{if(so())return Uo(),new Promise((t,r)=>{No("release",[t,r]);let s={type:"release",in:e};As.postMessage(s)});Ip(e)},yh=async(e,t,r,s,n,i)=>{if(so()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Uo(),new Promise((o,u)=>{No("run",[o,u]);let p=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:s,options:i}};As.postMessage(h,Lp(p))})}else return Op(e,t,r,s,n,i)},Mh=async e=>{if(so())return Uo(),new Promise((t,r)=>{No("end-profiling",[t,r]);let s={type:"end-profiling",in:e};As.postMessage(s)});Dp(e)}}),Bp,vh,Th,pf=g(()=>{Tt(),bh(),Rt(),Pt(),Bn(),Bp=(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()}`)}},vh=e=>{switch(e[3]){case"cpu":return new we(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!vn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=e[2];return we.fromGpuBuffer(r,{dataType:t,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let t=e[0];if(!Tn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=e[2];return we.fromMLTensor(r,{dataType:t,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},Th=class{async fetchModelAndCopyToWasmMemory(e){return _h(await xn(e))}async loadModel(e,t){He();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await gh(r,t),Be()}async dispose(){return wh(this.sessionId)}async run(e,t,r){He();let s=[],n=[];Object.entries(e).forEach(b=>{let l=b[0],F=b[1],D=this.inputNames.indexOf(l);if(D===-1)throw new Error(`invalid input '${l}'`);s.push(F),n.push(D)});let i=[],o=[];Object.entries(t).forEach(b=>{let l=b[0],F=b[1],D=this.outputNames.indexOf(l);if(D===-1)throw new Error(`invalid output '${l}'`);i.push(F),o.push(D)});let u=s.map((b,l)=>Bp(b,()=>`input "${this.inputNames[n[l]]}"`)),p=i.map((b,l)=>b?Bp(b,()=>`output "${this.outputNames[o[l]]}"`):null),h=await yh(this.sessionId,n,u,o,p,r),v={};for(let b=0;bjp,initializeFlags:()=>Rp,wasmBackend:()=>Eh});var Rp,jp,Eh,hf=g(()=>{Tt(),bh(),pf(),Rs(),Rp=()=>{if((typeof C.wasm.initTimeout!="number"||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0),C.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 C.wasm.proxy!="boolean"&&(C.wasm.proxy=!1),typeof C.wasm.trace!="boolean"&&(C.wasm.trace=!1),typeof C.wasm.numThreads!="number"||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let e=typeof navigator>"u"?q("node:os").cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},jp=class{async init(e){Rp(),await mh(),await fh(e)}async createInferenceSessionHandler(e,t){let r=new Th;return await r.loadModel(e,t),Promise.resolve(r)}},Eh=new jp});Tt(),Tt(),Tt();var mf="1.20.1",ff=Et;{let e=(hf(),$(xh)).wasmBackend;se("webgpu",e,5),se("webnn",e,5),se("cpu",e,10),se("wasm",e,10)}Object.defineProperty(C.versions,"web",{value:mf,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */},"./src/backends/onnx.js":(Oe,B,c)=>{var w;c.r(B),c.d(B,{Tensor:()=>q.Tensor,createInferenceSession:()=>le,deviceToExecutionProviders:()=>se,isONNXProxy:()=>ne,isONNXTensor:()=>U});var R=c("./src/env.js"),H=c("?2ce3"),J=c("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),q=c("./node_modules/onnxruntime-common/dist/esm/index.js");const g=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),x=[];let E,$;const P=Symbol.for("onnxruntime");if(P in globalThis)$=globalThis[P];else if(R.apis.IS_NODE_ENV){switch($=H??(w||(w=c.t(H,2))),process.platform){case"win32":x.push("dml");break;case"linux":process.arch==="x64"&&x.push("cuda");break}x.push("cpu"),E=["cpu"]}else $=J,R.apis.IS_WEBNN_AVAILABLE&&x.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),R.apis.IS_WEBGPU_AVAILABLE&&x.push("webgpu"),x.push("wasm"),E=["wasm"];const Y=$.InferenceSession;function se(N=null){if(!N)return E;switch(N){case"auto":return x;case"gpu":return x.filter(O=>["webgpu","cuda","dml","webnn-gpu"].includes(O))}if(x.includes(N))return[g[N]??N];throw new Error(`Unsupported device: "${N}". Should be one of: ${x.join(", ")}.`)}let ue=null;async function le(N,O,_){ue&&await ue;const k=Y.create(N,O);ue??(ue=k);const C=await k;return C.config=_,C}function U(N){return N instanceof $.Tensor}const Q=$==null?void 0:$.env;Q!=null&&Q.wasm&&(Q.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${R.env.version}/dist/`,Q.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(Q.wasm.numThreads=1)),Q!=null&&Q.webgpu&&(Q.webgpu.powerPreference="high-performance");function ne(){var N;return(N=Q==null?void 0:Q.wasm)==null?void 0:N.proxy}R.env.backends.onnx=Q},"./src/base/feature_extraction_utils.js":(Oe,B,c)=>{c.r(B),c.d(B,{FeatureExtractor:()=>J,validate_audio_inputs:()=>q});var w=c("./src/utils/constants.js"),R=c("./src/utils/generic.js"),H=c("./src/utils/hub.js");class J extends R.Callable{constructor(x){super(),this.config=x}static async from_pretrained(x,E){const $=await(0,H.getModelJSON)(x,w.FEATURE_EXTRACTOR_NAME,!0,E);return new this($)}}function q(g,x){var E;if(!(g instanceof Float32Array||g instanceof Float64Array))throw new Error(`${x} expects input to be a Float32Array or a Float64Array, but got ${((E=g==null?void 0:g.constructor)==null?void 0:E.name)??typeof g} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(Oe,B,c)=>{c.r(B),c.d(B,{ImageProcessor:()=>N,post_process_instance_segmentation:()=>ne,post_process_object_detection:()=>P,post_process_panoptic_segmentation:()=>Q,post_process_semantic_segmentation:()=>Y});var w=c("./src/utils/generic.js"),R=c("./src/utils/tensor.js"),H=c("./src/utils/maths.js");c("./src/utils/image.js");var J=c("./src/utils/core.js"),q=c("./src/utils/hub.js"),g=c("./src/utils/constants.js");function x(O,_,k=0,C=null){const Z=O/_;let ee=(0,H.bankers_round)(Z)*_;return C!==null&&ee>C&&(ee=Math.floor(Z)*_),ee_&&Ne.push(Je)}else{let Je=(0,H.max)($e.data)[1];if(Je===be-1||(Ke=(0,H.softmax)($e.data),Ke[Je]<_))continue;Ne.push(Je)}for(const Je of Ne){let lt=he[pe].data;lt=$(lt),Le!==null&&(lt=lt.map((ie,je)=>ie*Le[(je+1)%2])),me.boxes.push(lt),me.classes.push(Je),me.scores.push(Ke[Je])}}Se.push(me)}return Se}function Y(O,_=null){const k=O.logits,C=k.dims[0];if(_!==null&&_.length!==C)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Z=[];for(let ee=0;eeLe[Ne]&&(Le[Ne]=$e[Ne],me[Ne]=pe)}const j=new Array(ge.dims[0]);for(let pe=0;pepe!==void 0);Z.push({segmentation:Pe,labels:he})}return Z}function se(O,_,k,C){const Z=[],ee=[],_e=[];for(let ge=0;gek&&(Z.push(Se),ee.push(me),_e.push(Pe))}return[Z,ee,_e]}function ue(O,_,k,C=.5,Z=.8){const ee=[];let _e=0,ge=0;const be=_[k].data;for(let Pe=0;Pe=C&&++ge;let Se=_e>0&&ge>0;return Se&&(Se=_e/ge>Z),[Se,ee]}function le(O,_,k,C,Z,ee=null,_e=null){const[ge,be]=_e??O[0].dims,Se=new R.Tensor("int32",new Int32Array(ge*be),[ge,be]),Pe=[];if(_e!==null)for(let pe=0;peme[Ke]&&(Le[Ke]=pe,me[Ke]=Ne[Ke])}let j=0;const he=Se.data;for(let pe=0;pe200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(O,_)/Math.min(O,_)}`);let ee=Math.round(O/k)*k,_e=Math.round(_/k)*k;if(ee*_e>Z){const ge=Math.sqrt(O*_/Z);ee=Math.floor(O/ge/k)*k,_e=Math.floor(_/ge/k)*k}else if(ee*_eee?Se=Math.floor(ee*be/Z):ee>Z&&(be=Math.floor(Z*Se/ee)),await _.resize(Se,be,{resample:C}))}async crop_margin(_,k=200){const C=_.clone().grayscale(),Z=(0,H.min)(C.data)[0],_e=(0,H.max)(C.data)[0]-Z;if(_e===0)return _;const ge=k/255;let be=C.width,Se=C.height,Pe=0,Le=0;const me=C.data;for(let j=0;jthis.preprocess(ee)));return{pixel_values:(0,R.stack)(C.map(ee=>ee.pixel_values),0),original_sizes:C.map(ee=>ee.original_size),reshaped_input_sizes:C.map(ee=>ee.reshaped_input_size)}}static async from_pretrained(_,k){const C=await(0,q.getModelJSON)(_,g.IMAGE_PROCESSOR_NAME,!0,k);return new this(C)}}},"./src/base/processing_utils.js":(Oe,B,c)=>{c.r(B),c.d(B,{Processor:()=>J});var w=c("./src/utils/constants.js"),R=c("./src/utils/generic.js"),H=c("./src/utils/hub.js");class J extends R.Callable{constructor(g,x){super(),this.config=g,this.components=x}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,x={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(g,{tokenize:!1,...x})}batch_decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...g)}async _call(g,...x){for(const E of[this.image_processor,this.feature_extractor,this.tokenizer])if(E)return E(g,...x);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(g,x){const[E,$]=await Promise.all([this.uses_processor_config?(0,H.getModelJSON)(g,w.PROCESSOR_NAME,!0,x):{},Promise.all(this.classes.filter(P=>P in this).map(async P=>{const Y=await this[P].from_pretrained(g,x);return[P.replace(/_class$/,""),Y]})).then(Object.fromEntries)]);return new this(E,$)}}Te(J,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),Te(J,"uses_processor_config",!1)},"./src/configs.js":(Oe,B,c)=>{c.r(B),c.d(B,{AutoConfig:()=>x,PretrainedConfig:()=>g,getKeyValueShapes:()=>q});var w=c("./src/utils/core.js"),R=c("./src/utils/hub.js");async function H(E,$){return await(0,R.getModelJSON)(E,"config.json",!0,$)}function J(E){const $={};let P={};switch(E.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":P=J(E.text_config);break;case"moondream1":P=J(E.phi_config);break;case"musicgen":P=J(E.decoder);break;case"multi_modality":P=J(E.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":$.num_heads="n_head",$.num_layers="n_layer",$.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":$.num_heads="num_attention_heads",$.num_layers="num_hidden_layers",$.hidden_size="hidden_size";break;case"llama":case"olmo":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":$.num_heads="num_key_value_heads",$.num_layers="num_hidden_layers",$.hidden_size="hidden_size",$.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":$.num_heads="num_key_value_heads",$.num_layers="num_hidden_layers",$.dim_kv="head_dim";break;case"openelm":$.num_heads="num_kv_heads",$.num_layers="num_transformer_layers",$.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":$.num_heads="num_heads",$.num_layers="num_layers",$.hidden_size="hidden_size";break;case"bloom":$.num_heads="n_head",$.num_layers="n_layer",$.hidden_size="hidden_size";break;case"mpt":$.num_heads="n_heads",$.num_layers="n_layers",$.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":$.num_decoder_layers="num_decoder_layers",$.num_decoder_heads="num_heads",$.decoder_dim_kv="d_kv",$.num_encoder_layers="num_layers",$.num_encoder_heads="num_heads",$.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":$.num_decoder_layers="decoder_layers",$.num_decoder_heads="decoder_attention_heads",$.decoder_hidden_size="d_model",$.num_encoder_layers="encoder_layers",$.num_encoder_heads="encoder_attention_heads",$.encoder_hidden_size="d_model";break;case"speecht5":$.num_decoder_layers="decoder_layers",$.num_decoder_heads="decoder_attention_heads",$.decoder_hidden_size="hidden_size",$.num_encoder_layers="encoder_layers",$.num_encoder_heads="encoder_attention_heads",$.encoder_hidden_size="hidden_size";break;case"trocr":$.num_encoder_layers=$.num_decoder_layers="decoder_layers",$.num_encoder_heads=$.num_decoder_heads="decoder_attention_heads",$.encoder_hidden_size=$.decoder_hidden_size="d_model";break;case"musicgen_decoder":$.num_encoder_layers=$.num_decoder_layers="num_hidden_layers",$.num_encoder_heads=$.num_decoder_heads="num_attention_heads",$.encoder_hidden_size=$.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const se=J(E.decoder),ue="num_decoder_layers"in se,le=(0,w.pick)(E,["model_type","is_encoder_decoder"]);return ue?(le.num_decoder_layers=se.num_decoder_layers,le.num_decoder_heads=se.num_decoder_heads,le.decoder_hidden_size=se.decoder_hidden_size,le.num_encoder_layers=se.num_encoder_layers,le.num_encoder_heads=se.num_encoder_heads,le.encoder_hidden_size=se.encoder_hidden_size):(le.num_layers=se.num_layers,le.num_heads=se.num_heads,le.hidden_size=se.hidden_size),le}const Y={...P,...(0,w.pick)(E,["model_type","multi_query","is_encoder_decoder"])};for(const se in $)Y[se]=E[$[se]];return Y}function q(E,{prefix:$="past_key_values",batch_size:P=1}={}){const Y={},se=E.normalized_config;if(se.is_encoder_decoder&&"num_encoder_heads"in se&&"num_decoder_heads"in se){const ue=se.encoder_dim_kv??se.encoder_hidden_size/se.num_encoder_heads,le=se.decoder_dim_kv??se.decoder_hidden_size/se.num_decoder_heads,U=[P,se.num_encoder_heads,0,ue],Q=[P,se.num_decoder_heads,0,le];for(let ne=0;ne{var C;c.r(B),c.d(B,{apis:()=>le,env:()=>_});var w=c("?569f"),R=c("?3f59"),H=c("?154a");const J="3.1.0",q=typeof self<"u",g=q&&self.constructor.name==="DedicatedWorkerGlobalScope",x=q&&"caches"in self,E=typeof navigator<"u"&&"gpu"in navigator,$=typeof navigator<"u"&&"ml"in navigator,P=typeof process<"u",Y=P&&((C=process==null?void 0:process.release)==null?void 0:C.name)==="node",se=!k(w),ue=!k(R),le=Object.freeze({IS_BROWSER_ENV:q,IS_WEBWORKER_ENV:g,IS_WEB_CACHE_AVAILABLE:x,IS_WEBGPU_AVAILABLE:E,IS_WEBNN_AVAILABLE:$,IS_PROCESS_AVAILABLE:P,IS_NODE_ENV:Y,IS_FS_AVAILABLE:se,IS_PATH_AVAILABLE:ue}),U=se&&ue;let Q="./";if(U){const Z=Object({url:self.location.href}).url;Z?Q=R.dirname(R.dirname(H.fileURLToPath(Z))):typeof __dirname<"u"&&(Q=R.dirname(__dirname))}const ne=U?R.join(Q,"/.cache/"):null,N="/models/",O=U?R.join(Q,N):N,_={version:J,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!q,localModelPath:O,useFS:se,useBrowserCache:x,useFSCache:se,cacheDir:ne,useCustomCache:!1,customCache:null};function k(Z){return Object.keys(Z).length===0}},"./src/generation/configuration_utils.js":(Oe,B,c)=>{c.r(B),c.d(B,{GenerationConfig:()=>R});var w=c("./src/utils/core.js");class R{constructor(J){Te(this,"max_length",20);Te(this,"max_new_tokens",null);Te(this,"min_length",0);Te(this,"min_new_tokens",null);Te(this,"early_stopping",!1);Te(this,"max_time",null);Te(this,"do_sample",!1);Te(this,"num_beams",1);Te(this,"num_beam_groups",1);Te(this,"penalty_alpha",null);Te(this,"use_cache",!0);Te(this,"temperature",1);Te(this,"top_k",50);Te(this,"top_p",1);Te(this,"typical_p",1);Te(this,"epsilon_cutoff",0);Te(this,"eta_cutoff",0);Te(this,"diversity_penalty",0);Te(this,"repetition_penalty",1);Te(this,"encoder_repetition_penalty",1);Te(this,"length_penalty",1);Te(this,"no_repeat_ngram_size",0);Te(this,"bad_words_ids",null);Te(this,"force_words_ids",null);Te(this,"renormalize_logits",!1);Te(this,"constraints",null);Te(this,"forced_bos_token_id",null);Te(this,"forced_eos_token_id",null);Te(this,"remove_invalid_values",!1);Te(this,"exponential_decay_length_penalty",null);Te(this,"suppress_tokens",null);Te(this,"begin_suppress_tokens",null);Te(this,"forced_decoder_ids",null);Te(this,"guidance_scale",null);Te(this,"num_return_sequences",1);Te(this,"output_attentions",!1);Te(this,"output_hidden_states",!1);Te(this,"output_scores",!1);Te(this,"return_dict_in_generate",!1);Te(this,"pad_token_id",null);Te(this,"bos_token_id",null);Te(this,"eos_token_id",null);Te(this,"encoder_no_repeat_ngram_size",0);Te(this,"decoder_start_token_id",null);Te(this,"generation_kwargs",{});Object.assign(this,(0,w.pick)(J,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Oe,B,c)=>{c.r(B),c.d(B,{ClassifierFreeGuidanceLogitsProcessor:()=>U,ForcedBOSTokenLogitsProcessor:()=>g,ForcedEOSTokenLogitsProcessor:()=>x,LogitsProcessor:()=>H,LogitsProcessorList:()=>q,LogitsWarper:()=>J,MinLengthLogitsProcessor:()=>se,MinNewTokensLengthLogitsProcessor:()=>ue,NoBadWordsLogitsProcessor:()=>le,NoRepeatNGramLogitsProcessor:()=>P,RepetitionPenaltyLogitsProcessor:()=>Y,SuppressTokensAtBeginLogitsProcessor:()=>E,TemperatureLogitsWarper:()=>Q,TopKLogitsWarper:()=>N,TopPLogitsWarper:()=>ne,WhisperTimeStampLogitsProcessor:()=>$});var w=c("./src/utils/generic.js");c("./src/utils/tensor.js");var R=c("./src/utils/maths.js");class H extends w.Callable{_call(_,k){throw Error("`_call` should be implemented in a subclass")}}class J extends w.Callable{_call(_,k){throw Error("`_call` should be implemented in a subclass")}}class q extends w.Callable{constructor(){super(),this.processors=[]}push(_){this.processors.push(_)}extend(_){this.processors.push(..._)}_call(_,k){let C=k;for(const Z of this.processors)C=Z(_,C);return C}[Symbol.iterator](){return this.processors.values()}}class g extends H{constructor(_){super(),this.bos_token_id=_}_call(_,k){for(let C=0;C<_.length;++C)if(_[C].length===1){const Z=k[C].data;Z.fill(-1/0),Z[this.bos_token_id]=0}return k}}class x extends H{constructor(_,k){super(),this.max_length=_,this.eos_token_id=Array.isArray(k)?k:[k]}_call(_,k){for(let C=0;C<_.length;++C)if(_[C].length===this.max_length-1){const Z=k[C].data;Z.fill(-1/0);for(const ee of this.eos_token_id)Z[ee]=0}return k}}class E extends H{constructor(_,k){super(),this.begin_suppress_tokens=_,this.begin_index=k}_call(_,k){for(let C=0;C<_.length;++C)if(_[C].length===this.begin_index){const Z=k[C].data;for(const ee of this.begin_suppress_tokens)Z[ee]=-1/0}return k}}class $ extends H{constructor(_,k){super(),this.eos_token_id=Array.isArray(_.eos_token_id)?_.eos_token_id[0]:_.eos_token_id,this.no_timestamps_token_id=_.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=k.length,k.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=_.max_initial_timestamp_index}_call(_,k){for(let C=0;C<_.length;++C){const Z=k[C].data;if(Z[this.no_timestamps_token_id]=-1/0,_[C].length===this.begin_index-1){Z.fill(-1/0),Z[this.timestamp_begin]=0;continue}const ee=_[C].slice(this.begin_index),_e=ee.length>=1&&ee[ee.length-1]>=this.timestamp_begin,ge=ee.length<2||ee[ee.length-2]>=this.timestamp_begin;if(_e&&(ge?Z.subarray(this.timestamp_begin).fill(-1/0):Z.subarray(0,this.eos_token_id).fill(-1/0)),_[C].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Le=this.timestamp_begin+this.max_initial_timestamp_index;Z.subarray(Le+1).fill(-1/0)}const be=(0,R.log_softmax)(Z),Se=Math.log(be.subarray(this.timestamp_begin).map(Math.exp).reduce((Le,me)=>Le+me)),Pe=(0,R.max)(be.subarray(0,this.timestamp_begin))[0];Se>Pe&&Z.subarray(0,this.timestamp_begin).fill(-1/0)}return k}}class P extends H{constructor(_){super(),this.no_repeat_ngram_size=_}getNgrams(_){const k=_.length,C=[];for(let ee=0;ee1 to use the classifier free guidance processor, got guidance scale ${_}.`);this.guidance_scale=_}_call(_,k){if(k.dims[0]!==2*_.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${k.dims[0]} for the logits and ${_.length} for the input ids.`);const C=_.length,Z=k.slice([0,C],null),ee=k.slice([C,k.dims[0]],null);for(let _e=0;_e1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${_}`);if(!Number.isInteger(C)||C<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${C}`);this.top_p=_,this.filter_value=k,this.min_tokens_to_keep=C}}class N extends J{constructor(_,{filter_value:k=-1/0,min_tokens_to_keep:C=1}={}){if(super(),!Number.isInteger(_)||_<0)throw new Error(`\`top_k\` must be a positive integer, but is ${_}`);this.top_k=Math.max(_,C),this.filter_value=k}}},"./src/generation/logits_sampler.js":(Oe,B,c)=>{c.r(B),c.d(B,{LogitsSampler:()=>J});var w=c("./src/utils/generic.js"),R=c("./src/utils/tensor.js"),H=c("./src/utils/maths.js");c("./src/generation/configuration_utils.js");class J extends w.Callable{constructor($){super(),this.generation_config=$}async _call($){return this.sample($)}async sample($){throw Error("sample should be implemented in subclasses.")}getLogits($,P){let Y=$.dims.at(-1),se=$.data;if(P===-1)se=se.slice(-Y);else{let ue=P*Y;se=se.slice(ue,ue+Y)}return se}randomSelect($){let P=0;for(let se=0;se<$.length;++se)P+=$[se];let Y=Math.random()*P;for(let se=0;se<$.length;++se)if(Y-=$[se],Y<=0)return se;return 0}static getSampler($){if($.do_sample)return new g($);if($.num_beams>1)return new x($);if($.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${$.num_return_sequences}.`);return new q($)}}class q extends J{async sample($){const P=(0,H.max)($.data)[1];return[[BigInt(P),0]]}}class g extends J{async sample($){let P=$.dims.at(-1);this.generation_config.top_k>0&&(P=Math.min(this.generation_config.top_k,P));const[Y,se]=await(0,R.topk)($,P),ue=(0,H.softmax)(Y.data);return Array.from({length:this.generation_config.num_beams},()=>{const le=this.randomSelect(ue);return[se.data[le],Math.log(ue[le])]})}}class x extends J{async sample($){let P=$.dims.at(-1);this.generation_config.top_k>0&&(P=Math.min(this.generation_config.top_k,P));const[Y,se]=await(0,R.topk)($,P),ue=(0,H.softmax)(Y.data);return Array.from({length:this.generation_config.num_beams},(le,U)=>[se.data[U],Math.log(ue[U])])}}},"./src/generation/stopping_criteria.js":(Oe,B,c)=>{c.r(B),c.d(B,{EosTokenCriteria:()=>q,InterruptableStoppingCriteria:()=>g,MaxLengthCriteria:()=>J,StoppingCriteria:()=>R,StoppingCriteriaList:()=>H});var w=c("./src/utils/generic.js");class R extends w.Callable{_call(E,$){throw Error("StoppingCriteria needs to be subclassed")}}class H extends w.Callable{constructor(){super(),this.criteria=[]}push(E){this.criteria.push(E)}extend(E){E instanceof H?E=E.criteria:E instanceof R&&(E=[E]),this.criteria.push(...E)}_call(E,$){const P=new Array(E.length).fill(!1);for(const Y of this.criteria){const se=Y(E,$);for(let ue=0;ue$.length>=this.max_length)}}class q extends R{constructor(E){super(),Array.isArray(E)||(E=[E]),this.eos_token_id=E}_call(E,$){return E.map(P=>{const Y=P.at(-1);return this.eos_token_id.some(se=>Y==se)})}}class g extends R{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(E,$){return new Array(E.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Oe,B,c)=>{c.r(B),c.d(B,{BaseStreamer:()=>J,TextStreamer:()=>g,WhisperTextStreamer:()=>x});var w=c("./src/utils/core.js"),R=c("./src/tokenizers.js"),H=c("./src/env.js");class J{put($){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const q=H.apis.IS_PROCESS_AVAILABLE?E=>process.stdout.write(E):E=>console.log(E);class g extends J{constructor($,{skip_prompt:P=!1,callback_function:Y=null,token_callback_function:se=null,decode_kwargs:ue={},...le}={}){super(),this.tokenizer=$,this.skip_prompt=P,this.callback_function=Y??q,this.token_callback_function=se,this.decode_kwargs={...ue,...le},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put($){var ue;if($.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 P=$[0];(ue=this.token_callback_function)==null||ue.call(this,P),this.token_cache=(0,w.mergeArrays)(this.token_cache,P);const Y=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let se;Y.endsWith(` `)?(se=Y.slice(this.print_len),this.token_cache=[],this.print_len=0):Y.length>0&&(0,R.is_chinese_char)(Y.charCodeAt(Y.length-1))?(se=Y.slice(this.print_len),this.print_len+=se.length):(se=Y.slice(this.print_len,Y.lastIndexOf(" ")+1),this.print_len+=se.length),this.on_finalized_text(se,!1)}end(){let $;this.token_cache.length>0?($=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):$="",this.next_tokens_are_prompt=!0,this.on_finalized_text($,!0)}on_finalized_text($,P){var Y,se;$.length>0&&((Y=this.callback_function)==null||Y.call(this,$)),P&&this.callback_function===q&&H.apis.IS_PROCESS_AVAILABLE&&((se=this.callback_function)==null||se.call(this,` `))}}class x extends g{constructor($,{skip_prompt:P=!1,callback_function:Y=null,token_callback_function:se=null,on_chunk_start:ue=null,on_chunk_end:le=null,on_finalize:U=null,time_precision:Q=.02,skip_special_tokens:ne=!0,decode_kwargs:N={}}={}){super($,{skip_prompt:P,callback_function:Y,token_callback_function:se,decode_kwargs:{skip_special_tokens:ne,...N}}),this.timestamp_begin=$.timestamp_begin,this.on_chunk_start=ue,this.on_chunk_end=le,this.on_finalize=U,this.time_precision=Q,this.waiting_for_timestamp=!1}put($){var Y,se;if($.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const P=$[0];if(P.length===1){const ue=Number(P[0])-this.timestamp_begin;if(ue>=0){const le=ue*this.time_precision;this.waiting_for_timestamp?(Y=this.on_chunk_end)==null||Y.call(this,le):(se=this.on_chunk_start)==null||se.call(this,le),this.waiting_for_timestamp=!this.waiting_for_timestamp,$=[[]]}}return super.put($)}end(){var $;super.end(),($=this.on_finalize)==null||$.call(this)}}},"./src/models.js":(Oe,B,c)=>{c.r(B),c.d(B,{ASTForAudioClassification:()=>qo,ASTModel:()=>At,ASTPreTrainedModel:()=>Xe,AlbertForMaskedLM:()=>Rn,AlbertForQuestionAnswering:()=>Bn,AlbertForSequenceClassification:()=>xn,AlbertModel:()=>Rt,AlbertPreTrainedModel:()=>Vs,AutoModel:()=>Ta,AutoModelForAudioClassification:()=>Xd,AutoModelForAudioFrameClassification:()=>Jd,AutoModelForCTC:()=>Qd,AutoModelForCausalLM:()=>jd,AutoModelForDepthEstimation:()=>rc,AutoModelForDocumentQuestionAnswering:()=>Zd,AutoModelForImageClassification:()=>Yc,AutoModelForImageFeatureExtraction:()=>nc,AutoModelForImageMatting:()=>ec,AutoModelForImageSegmentation:()=>Wd,AutoModelForImageToImage:()=>tc,AutoModelForMaskGeneration:()=>qd,AutoModelForMaskedLM:()=>Nd,AutoModelForNormalEstimation:()=>sc,AutoModelForObjectDetection:()=>Jc,AutoModelForPoseEstimation:()=>Ea,AutoModelForQuestionAnswering:()=>Ud,AutoModelForSemanticSegmentation:()=>Gd,AutoModelForSeq2SeqLM:()=>zd,AutoModelForSequenceClassification:()=>xa,AutoModelForSpeechSeq2Seq:()=>Bd,AutoModelForTextToSpectrogram:()=>Rd,AutoModelForTextToWaveform:()=>Xc,AutoModelForTokenClassification:()=>Ld,AutoModelForUniversalSegmentation:()=>Kd,AutoModelForVision2Seq:()=>Vd,AutoModelForXVector:()=>Yd,AutoModelForZeroShotObjectDetection:()=>Hd,BartForConditionalGeneration:()=>Ee,BartForSequenceClassification:()=>Ve,BartModel:()=>Me,BartPretrainedModel:()=>oe,BaseModelOutput:()=>st,BeitForImageClassification:()=>au,BeitModel:()=>iu,BeitPreTrainedModel:()=>vi,BertForMaskedLM:()=>Ce,BertForQuestionAnswering:()=>He,BertForSequenceClassification:()=>Ze,BertForTokenClassification:()=>Qe,BertModel:()=>we,BertPreTrainedModel:()=>ze,BlenderbotForConditionalGeneration:()=>Cr,BlenderbotModel:()=>rr,BlenderbotPreTrainedModel:()=>mr,BlenderbotSmallForConditionalGeneration:()=>ps,BlenderbotSmallModel:()=>cr,BlenderbotSmallPreTrainedModel:()=>qt,BloomForCausalLM:()=>Ll,BloomModel:()=>Dl,BloomPreTrainedModel:()=>lr,CLIPModel:()=>Wa,CLIPPreTrainedModel:()=>hn,CLIPSegForImageSegmentation:()=>tl,CLIPSegModel:()=>el,CLIPSegPreTrainedModel:()=>Yo,CLIPTextModel:()=>mn,CLIPTextModelWithProjection:()=>Ga,CLIPVisionModel:()=>_c,CLIPVisionModelWithProjection:()=>Ka,CamembertForMaskedLM:()=>os,CamembertForQuestionAnswering:()=>zs,CamembertForSequenceClassification:()=>Qs,CamembertForTokenClassification:()=>Xs,CamembertModel:()=>Br,CamembertPreTrainedModel:()=>Fr,CausalLMOutput:()=>Sn,CausalLMOutputWithPast:()=>ep,ChineseCLIPModel:()=>Ya,ChineseCLIPPreTrainedModel:()=>Xa,ClapAudioModelWithProjection:()=>od,ClapModel:()=>nd,ClapPreTrainedModel:()=>Io,ClapTextModelWithProjection:()=>Dc,CodeGenForCausalLM:()=>pl,CodeGenModel:()=>cl,CodeGenPreTrainedModel:()=>ri,CohereForCausalLM:()=>bl,CohereModel:()=>Ml,CoherePreTrainedModel:()=>wo,ConvBertForMaskedLM:()=>ke,ConvBertForQuestionAnswering:()=>dt,ConvBertForSequenceClassification:()=>Ye,ConvBertForTokenClassification:()=>ot,ConvBertModel:()=>de,ConvBertPreTrainedModel:()=>V,ConvNextForImageClassification:()=>qn,ConvNextModel:()=>Oi,ConvNextPreTrainedModel:()=>Fi,ConvNextV2ForImageClassification:()=>$u,ConvNextV2Model:()=>Li,ConvNextV2PreTrainedModel:()=>Di,DPTForDepthEstimation:()=>ts,DPTModel:()=>nn,DPTPreTrainedModel:()=>vo,DebertaForMaskedLM:()=>Ts,DebertaForQuestionAnswering:()=>un,DebertaForSequenceClassification:()=>Bs,DebertaForTokenClassification:()=>Ys,DebertaModel:()=>Nt,DebertaPreTrainedModel:()=>Is,DebertaV2ForMaskedLM:()=>Js,DebertaV2ForQuestionAnswering:()=>ds,DebertaV2ForSequenceClassification:()=>Zs,DebertaV2ForTokenClassification:()=>Rs,DebertaV2Model:()=>dn,DebertaV2PreTrainedModel:()=>gs,DecisionTransformerModel:()=>wd,DecisionTransformerPreTrainedModel:()=>gd,DeiTForImageClassification:()=>wu,DeiTModel:()=>gu,DeiTPreTrainedModel:()=>Pi,DepthAnythingForDepthEstimation:()=>To,DepthAnythingPreTrainedModel:()=>ki,DepthProForDepthEstimation:()=>Ai,DepthProPreTrainedModel:()=>xo,DetrForObjectDetection:()=>uu,DetrForSegmentation:()=>Ti,DetrModel:()=>lu,DetrObjectDetectionOutput:()=>du,DetrPreTrainedModel:()=>Kn,DetrSegmentationOutput:()=>cu,Dinov2ForImageClassification:()=>Tc,Dinov2Model:()=>ku,Dinov2PreTrainedModel:()=>zi,DistilBertForMaskedLM:()=>js,DistilBertForQuestionAnswering:()=>en,DistilBertForSequenceClassification:()=>It,DistilBertForTokenClassification:()=>Wr,DistilBertModel:()=>vt,DistilBertPreTrainedModel:()=>et,DonutSwinModel:()=>vc,DonutSwinPreTrainedModel:()=>Su,EfficientNetForImageClassification:()=>cd,EfficientNetModel:()=>dd,EfficientNetPreTrainedModel:()=>ea,ElectraForMaskedLM:()=>Tt,ElectraForQuestionAnswering:()=>Mr,ElectraForSequenceClassification:()=>Pt,ElectraForTokenClassification:()=>ar,ElectraModel:()=>Et,ElectraPreTrainedModel:()=>$t,EsmForMaskedLM:()=>Lr,EsmForSequenceClassification:()=>Fs,EsmForTokenClassification:()=>br,EsmModel:()=>cs,EsmPreTrainedModel:()=>xr,FalconForCausalLM:()=>Oc,FalconModel:()=>sd,FalconPreTrainedModel:()=>Yi,FastViTForImageClassification:()=>Jl,FastViTModel:()=>Yl,FastViTPreTrainedModel:()=>mi,Florence2ForConditionalGeneration:()=>ms,Florence2PreTrainedModel:()=>Va,GLPNForDepthEstimation:()=>Cu,GLPNModel:()=>Co,GLPNPreTrainedModel:()=>Po,GPT2LMHeadModel:()=>sl,GPT2Model:()=>rl,GPT2PreTrainedModel:()=>Jo,GPTBigCodeForCausalLM:()=>dl,GPTBigCodeModel:()=>ul,GPTBigCodePreTrainedModel:()=>ti,GPTJForCausalLM:()=>ll,GPTJModel:()=>al,GPTJPreTrainedModel:()=>ei,GPTNeoForCausalLM:()=>_o,GPTNeoModel:()=>ol,GPTNeoPreTrainedModel:()=>ys,GPTNeoXForCausalLM:()=>il,GPTNeoXModel:()=>Cs,GPTNeoXPreTrainedModel:()=>go,Gemma2ForCausalLM:()=>xl,Gemma2Model:()=>Tl,Gemma2PreTrainedModel:()=>ai,GemmaForCausalLM:()=>vl,GemmaModel:()=>wc,GemmaPreTrainedModel:()=>yo,GraniteForCausalLM:()=>ii,GraniteModel:()=>yl,GranitePreTrainedModel:()=>oi,GroupViTModel:()=>Xl,GroupViTPreTrainedModel:()=>Ql,HieraForImageClassification:()=>yu,HieraModel:()=>Mc,HieraPreTrainedModel:()=>Ci,HubertForCTC:()=>Hu,HubertForSequenceClassification:()=>qu,HubertModel:()=>kc,HubertPreTrainedModel:()=>$c,ImageMattingOutput:()=>ic,JAISLMHeadModel:()=>gc,JAISModel:()=>nl,JAISPreTrainedModel:()=>Zo,JinaCLIPModel:()=>Ps,JinaCLIPPreTrainedModel:()=>fo,JinaCLIPTextModel:()=>Ja,JinaCLIPVisionModel:()=>Za,LlamaForCausalLM:()=>ml,LlamaModel:()=>hl,LlamaPreTrainedModel:()=>Ms,LlavaForConditionalGeneration:()=>Wn,LlavaOnevisionForConditionalGeneration:()=>Na,LlavaPreTrainedModel:()=>ja,LongT5ForConditionalGeneration:()=>_r,LongT5Model:()=>Un,LongT5PreTrainedModel:()=>pn,M2M100ForConditionalGeneration:()=>Ui,M2M100Model:()=>Ni,M2M100PreTrainedModel:()=>Qn,MBartForCausalLM:()=>Kt,MBartForConditionalGeneration:()=>pt,MBartForSequenceClassification:()=>bt,MBartModel:()=>_t,MBartPreTrainedModel:()=>at,MPNetForMaskedLM:()=>zn,MPNetForQuestionAnswering:()=>xs,MPNetForSequenceClassification:()=>ho,MPNetForTokenClassification:()=>tn,MPNetModel:()=>Ln,MPNetPreTrainedModel:()=>Us,MT5ForConditionalGeneration:()=>G,MT5Model:()=>M,MT5PreTrainedModel:()=>xe,MarianMTModel:()=>Du,MarianModel:()=>So,MarianPreTrainedModel:()=>ji,MaskFormerForInstanceSegmentation:()=>Pu,MaskFormerModel:()=>Eo,MaskFormerPreTrainedModel:()=>Ii,MaskedLMOutput:()=>Jr,MgpstrForSceneTextRecognition:()=>aa,MgpstrModelOutput:()=>Md,MgpstrPreTrainedModel:()=>bd,MistralForCausalLM:()=>Fc,MistralModel:()=>td,MistralPreTrainedModel:()=>qi,MobileBertForMaskedLM:()=>po,MobileBertForQuestionAnswering:()=>Dn,MobileBertForSequenceClassification:()=>On,MobileBertModel:()=>Fn,MobileBertPreTrainedModel:()=>Ns,MobileLLMForCausalLM:()=>_l,MobileLLMModel:()=>fl,MobileLLMPreTrainedModel:()=>si,MobileNetV1ForImageClassification:()=>Bc,MobileNetV1Model:()=>pd,MobileNetV1PreTrainedModel:()=>sa,MobileNetV2ForImageClassification:()=>md,MobileNetV2Model:()=>hd,MobileNetV2PreTrainedModel:()=>rs,MobileNetV3ForImageClassification:()=>Zn,MobileNetV3Model:()=>fd,MobileNetV3PreTrainedModel:()=>Oo,MobileNetV4ForImageClassification:()=>oa,MobileNetV4Model:()=>_d,MobileNetV4PreTrainedModel:()=>na,MobileViTForImageClassification:()=>ru,MobileViTModel:()=>tu,MobileViTPreTrainedModel:()=>fi,MobileViTV2ForImageClassification:()=>gi,MobileViTV2Model:()=>su,MobileViTV2PreTrainedModel:()=>_i,ModelOutput:()=>je,Moondream1ForConditionalGeneration:()=>Ua,MptForCausalLM:()=>Bl,MptModel:()=>zl,MptPreTrainedModel:()=>ui,MultiModalityCausalLM:()=>yd,MultiModalityPreTrainedModel:()=>ia,MusicgenForCausalLM:()=>zc,MusicgenForConditionalGeneration:()=>ra,MusicgenModel:()=>Cp,MusicgenPreTrainedModel:()=>ta,NomicBertModel:()=>nt,NomicBertPreTrainedModel:()=>Be,OPTForCausalLM:()=>jl,OPTModel:()=>Rl,OPTPreTrainedModel:()=>di,OlmoForCausalLM:()=>wl,OlmoModel:()=>gl,OlmoPreTrainedModel:()=>ni,OpenELMForCausalLM:()=>Pl,OpenELMModel:()=>El,OpenELMPreTrainedModel:()=>Pn,OwlViTForObjectDetection:()=>Mi,OwlViTModel:()=>yi,OwlViTPreTrainedModel:()=>wi,Owlv2ForObjectDetection:()=>ou,Owlv2Model:()=>nu,Owlv2PreTrainedModel:()=>bi,PatchTSMixerForPrediction:()=>ca,PatchTSMixerModel:()=>Rc,PatchTSMixerPreTrainedModel:()=>da,PatchTSTForPrediction:()=>ua,PatchTSTModel:()=>vd,PatchTSTPreTrainedModel:()=>la,Phi3ForCausalLM:()=>Ol,Phi3Model:()=>yc,Phi3PreTrainedModel:()=>li,PhiForCausalLM:()=>Fl,PhiModel:()=>Il,PhiPreTrainedModel:()=>Al,PreTrainedModel:()=>ie,PretrainedMixin:()=>yr,PvtForImageClassification:()=>Gl,PvtModel:()=>Gn,PvtPreTrainedModel:()=>pi,PyAnnoteForAudioFrameClassification:()=>Bu,PyAnnoteModel:()=>Pc,PyAnnotePreTrainedModel:()=>Wi,QuestionAnsweringModelOutput:()=>ss,Qwen2ForCausalLM:()=>Sl,Qwen2Model:()=>Cl,Qwen2PreTrainedModel:()=>Mo,Qwen2VLForConditionalGeneration:()=>kl,Qwen2VLPreTrainedModel:()=>$l,RTDetrForObjectDetection:()=>pu,RTDetrModel:()=>Ss,RTDetrObjectDetectionOutput:()=>hu,RTDetrPreTrainedModel:()=>xi,ResNetForImageClassification:()=>bu,ResNetModel:()=>Mu,ResNetPreTrainedModel:()=>Si,RoFormerForMaskedLM:()=>ht,RoFormerForQuestionAnswering:()=>re,RoFormerForSequenceClassification:()=>ft,RoFormerForTokenClassification:()=>A,RoFormerModel:()=>wt,RoFormerPreTrainedModel:()=>ut,RobertaForMaskedLM:()=>gr,RobertaForQuestionAnswering:()=>Es,RobertaForSequenceClassification:()=>Hr,RobertaForTokenClassification:()=>hs,RobertaModel:()=>De,RobertaPreTrainedModel:()=>zr,SamImageSegmentationOutput:()=>Ou,SamModel:()=>Fu,SamPreTrainedModel:()=>Iu,SapiensForDepthEstimation:()=>xu,SapiensForNormalEstimation:()=>Eu,SapiensForSemanticSegmentation:()=>Tu,SapiensPreTrainedModel:()=>Hn,SegformerForImageClassification:()=>ad,SegformerForSemanticSegmentation:()=>ld,SegformerModel:()=>Pp,SegformerPreTrainedModel:()=>Fo,Seq2SeqLMOutput:()=>Zc,SequenceClassifierOutput:()=>er,SiglipModel:()=>Ha,SiglipPreTrainedModel:()=>Xo,SiglipTextModel:()=>qa,SiglipVisionModel:()=>Qa,SpeechT5ForSpeechToText:()=>Yu,SpeechT5ForTextToSpeech:()=>Ju,SpeechT5HifiGan:()=>Zu,SpeechT5Model:()=>Ic,SpeechT5PreTrainedModel:()=>Jn,SqueezeBertForMaskedLM:()=>cn,SqueezeBertForQuestionAnswering:()=>Tn,SqueezeBertForSequenceClassification:()=>vn,SqueezeBertModel:()=>bn,SqueezeBertPreTrainedModel:()=>ws,StableLmForCausalLM:()=>Lc,StableLmModel:()=>ud,StableLmPreTrainedModel:()=>Zi,Starcoder2ForCausalLM:()=>rd,Starcoder2Model:()=>Xi,Starcoder2PreTrainedModel:()=>Qi,Swin2SRForImageSuperResolution:()=>sn,Swin2SRModel:()=>rn,Swin2SRPreTrainedModel:()=>Ws,SwinForImageClassification:()=>bc,SwinModel:()=>vu,SwinPreTrainedModel:()=>$i,T5ForConditionalGeneration:()=>Nn,T5Model:()=>jn,T5PreTrainedModel:()=>En,TableTransformerForObjectDetection:()=>fu,TableTransformerModel:()=>mu,TableTransformerObjectDetectionOutput:()=>_u,TableTransformerPreTrainedModel:()=>Ei,TokenClassifierOutput:()=>Qr,TrOCRForCausalLM:()=>ed,TrOCRPreTrainedModel:()=>Hi,UniSpeechForCTC:()=>ju,UniSpeechForSequenceClassification:()=>Ki,UniSpeechModel:()=>Ru,UniSpeechPreTrainedModel:()=>$o,UniSpeechSatForAudioFrameClassification:()=>Wu,UniSpeechSatForCTC:()=>Uu,UniSpeechSatForSequenceClassification:()=>Vu,UniSpeechSatModel:()=>Nu,UniSpeechSatPreTrainedModel:()=>Xn,ViTForImageClassification:()=>Ul,ViTMAEModel:()=>Kl,ViTMAEPreTrainedModel:()=>bo,ViTMSNForImageClassification:()=>ql,ViTMSNModel:()=>Hl,ViTMSNPreTrainedModel:()=>hi,ViTModel:()=>Nl,ViTPreTrainedModel:()=>ci,VisionEncoderDecoderModel:()=>Jt,VitMatteForImageMatting:()=>eu,VitMattePreTrainedModel:()=>Zl,VitPoseForPoseEstimation:()=>Wl,VitPosePreTrainedModel:()=>Vl,VitsModel:()=>Ji,VitsModelOutput:()=>ac,VitsPreTrainedModel:()=>id,Wav2Vec2BertForCTC:()=>Gu,Wav2Vec2BertForSequenceClassification:()=>Ku,Wav2Vec2BertModel:()=>Sc,Wav2Vec2BertPreTrainedModel:()=>ko,Wav2Vec2ForAudioFrameClassification:()=>zu,Wav2Vec2ForCTC:()=>Vi,Wav2Vec2ForSequenceClassification:()=>Ec,Wav2Vec2Model:()=>Lu,Wav2Vec2PreTrainedModel:()=>on,WavLMForAudioFrameClassification:()=>Yn,WavLMForCTC:()=>Xu,WavLMForSequenceClassification:()=>Ac,WavLMForXVector:()=>Ao,WavLMModel:()=>Qu,WavLMPreTrainedModel:()=>Cn,WeSpeakerResNetModel:()=>Cc,WeSpeakerResNetPreTrainedModel:()=>Gi,WhisperForConditionalGeneration:()=>Vn,WhisperModel:()=>Ra,WhisperPreTrainedModel:()=>Qo,XLMForQuestionAnswering:()=>gt,XLMForSequenceClassification:()=>ir,XLMForTokenClassification:()=>wr,XLMModel:()=>qr,XLMPreTrainedModel:()=>Dt,XLMRobertaForMaskedLM:()=>Os,XLMRobertaForQuestionAnswering:()=>mo,XLMRobertaForSequenceClassification:()=>Ds,XLMRobertaForTokenClassification:()=>kt,XLMRobertaModel:()=>Nr,XLMRobertaPreTrainedModel:()=>Qt,XLMWithLMHeadModel:()=>as,XVectorOutput:()=>oc,YolosForObjectDetection:()=>xc,YolosModel:()=>Au,YolosObjectDetectionOutput:()=>Ri,YolosPreTrainedModel:()=>Bi});var w=c("./src/configs.js"),R=c("./src/backends/onnx.js"),H=c("./src/utils/dtypes.js"),J=c("./src/utils/generic.js"),q=c("./src/utils/core.js"),g=c("./src/utils/hub.js"),x=c("./src/utils/constants.js"),E=c("./src/generation/logits_process.js"),$=c("./src/generation/configuration_utils.js"),P=c("./src/utils/tensor.js"),Y=c("./src/utils/image.js"),se=c("./src/utils/maths.js"),ue=c("./src/generation/stopping_criteria.js"),le=c("./src/generation/logits_sampler.js"),U=c("./src/env.js"),Q=c("./src/models/whisper/generation_whisper.js"),ne=c("./src/models/whisper/common_whisper.js");const N={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8},O=new Map,_=new Map,k=new Map;async function C(f,S,L){var Sr;const ve=((Sr=L.config)==null?void 0:Sr["transformers.js_config"])??{};let Fe=L.device??ve.device;Fe&&typeof Fe!="string"&&(Fe.hasOwnProperty(S)?Fe=Fe[S]:(console.warn(`device not specified for "${S}". Using the default device.`),Fe=null));const Ae=Fe??(U.apis.IS_NODE_ENV?"cpu":"wasm"),qe=(0,R.deviceToExecutionProviders)(Ae);let it=L.dtype??ve.dtype;typeof it!="string"&&(it&&it.hasOwnProperty(S)?it=it[S]:(it=H.DEFAULT_DEVICE_DTYPE_MAPPING[Ae]??H.DATA_TYPES.fp32,console.warn(`dtype not specified for "${S}". Using the default dtype (${it}) for this device (${Ae}).`)));const mt=it;if(H.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(mt)){if(mt===H.DATA_TYPES.fp16&&Ae==="webgpu"&&!await(0,H.isWebGpuFp16Supported)())throw new Error(`The device (${Ae}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${mt}. Should be one of: ${Object.keys(H.DATA_TYPES).join(", ")}`);const Ct=ve.kv_cache_dtype?typeof ve.kv_cache_dtype=="string"?ve.kv_cache_dtype:ve.kv_cache_dtype[mt]??"float32":void 0;if(Ct&&!["float32","float16"].includes(Ct))throw new Error(`Invalid kv_cache_dtype: ${Ct}. Should be one of: float32, float16`);const Ut={dtype:mt,kv_cache_dtype:Ct},Ot=H.DEFAULT_DTYPE_SUFFIX_MAPPING[mt],Wt=`${L.subfolder??""}/${S}${Ot}.onnx`,Lt={...L.session_options};Lt.executionProviders??(Lt.executionProviders=qe);const sr=ve.free_dimension_overrides;sr?Lt.freeDimensionOverrides??(Lt.freeDimensionOverrides=sr):Ae.startsWith("webnn")&&!Lt.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 or=(0,g.getModelFile)(f,Wt,!0,L),Yt=L.use_external_data_format??ve.use_external_data_format;let ur=[];if(Yt&&(Yt===!0||typeof Yt=="object"&&Yt.hasOwnProperty(S)&&Yt[S]===!0)){if(U.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const $r=`${S}${Ot}.onnx_data`,kr=`${L.subfolder??""}/${$r}`;ur.push(new Promise(async(Or,Zr)=>{const Gr=await(0,g.getModelFile)(f,kr,!0,L);Or({path:$r,data:Gr})}))}else Lt.externalData!==void 0&&(ur=Lt.externalData.map(async $r=>{if(typeof $r.data=="string"){const kr=await(0,g.getModelFile)(f,$r.data,!0,L);return{...$r,data:kr}}return $r}));if(ur.length>0&&(Lt.externalData=await Promise.all(ur)),Ae==="webgpu"){const $r=(0,w.getKeyValueShapes)(L.config,{prefix:"present"});if(Object.keys($r).length>0&&!(0,R.isONNXProxy)()){const kr={};for(const Or in $r)kr[Or]="gpu-buffer";Lt.preferredOutputLocation=kr}}return{buffer:await or,session_options:Lt,session_config:Ut}}async function Z(f,S,L){return Object.fromEntries(await Promise.all(Object.keys(S).map(async ve=>{const{buffer:Fe,session_options:Ae,session_config:qe}=await C(f,S[ve],L),it=await(0,R.createInferenceSession)(Fe,Ae,qe);return[ve,it]})))}async function ee(f,S,L){return Object.fromEntries(await Promise.all(Object.keys(S).map(async ve=>{const Fe=await(0,g.getModelJSON)(f,S[ve],!1,L);return[ve,Fe]})))}function _e(f,S){const L=Object.create(null),ve=[];for(const qe of f.inputNames){const it=S[qe];if(!(it instanceof P.Tensor)){ve.push(qe);continue}L[qe]=(0,R.isONNXProxy)()?it.clone():it}if(ve.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ve.join(", ")}.`);const Fe=Object.keys(S).length,Ae=f.inputNames.length;if(Fe>Ae){let qe=Object.keys(S).filter(it=>!f.inputNames.includes(it));console.warn(`WARNING: Too many inputs were provided (${Fe} > ${Ae}). The following inputs will be ignored: "${qe.join(", ")}".`)}return L}async function ge(f,S){const L=_e(f,S);try{const ve=Object.fromEntries(Object.entries(L).map(([Ae,qe])=>[Ae,qe.ort_tensor]));let Fe=await f.run(ve);return Fe=be(Fe),Fe}catch(ve){throw console.error(`An error occurred during model execution: "${ve}".`),console.error("Inputs given to model:",L),ve}}function be(f){for(let S in f)(0,R.isONNXTensor)(f[S])?f[S]=new P.Tensor(f[S]):typeof f[S]=="object"&&be(f[S]);return f}function Se(f){if(f instanceof P.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(S=>S.length!==f[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new P.Tensor("int64",BigInt64Array.from(f.flat().map(S=>BigInt(S))),[f.length,f[0].length])}else return new P.Tensor("int64",BigInt64Array.from(f.map(S=>BigInt(S))),[1,f.length])}function Pe(f){return new P.Tensor("bool",[f],[1])}async function Le(f,S){let{encoder_outputs:L,input_ids:ve,decoder_input_ids:Fe,...Ae}=S;if(!L){const it=(0,q.pick)(S,f.sessions.model.inputNames);L=(await me(f,it)).last_hidden_state}return Ae.input_ids=Fe,Ae.encoder_hidden_states=L,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Ae.encoder_attention_mask=S.attention_mask),await j(f,Ae,!0)}async function me(f,S){const L=f.sessions.model,ve=(0,q.pick)(S,L.inputNames);if(L.inputNames.includes("inputs_embeds")&&!ve.inputs_embeds){if(!S.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ve.inputs_embeds=await f.encode_text({input_ids:S.input_ids})}return L.inputNames.includes("token_type_ids")&&!ve.token_type_ids&&(ve.token_type_ids=new P.Tensor("int64",new BigInt64Array(ve.input_ids.data.length),ve.input_ids.dims)),await ge(L,ve)}async function j(f,S,L=!1){const ve=f.sessions[L?"decoder_model_merged":"model"],{past_key_values:Fe,...Ae}=S;ve.inputNames.includes("use_cache_branch")&&(Ae.use_cache_branch=Pe(!!Fe)),ve.inputNames.includes("position_ids")&&Ae.attention_mask&&!Ae.position_ids&&(Ae.position_ids=$e(Ae,Fe)),f.addPastKeyValues(Ae,Fe);const qe=(0,q.pick)(Ae,ve.inputNames);return await ge(ve,qe)}async function he(f,{input_ids:S=null,attention_mask:L=null,pixel_values:ve=null,position_ids:Fe=null,inputs_embeds:Ae=null,past_key_values:qe=null,generation_config:it=null,logits_processor:mt=null,...Ct}){if(!Ae){if(Ae=await f.encode_text({input_ids:S,...Ct}),ve&&S.dims[1]!==1){const Ot=await f.encode_image({pixel_values:ve,...Ct});({inputs_embeds:Ae,attention_mask:L}=f._merge_input_ids_with_image_features({image_features:Ot,inputs_embeds:Ae,input_ids:S,attention_mask:L}))}else if(qe&&ve&&S.dims[1]===1){const Ot=S.dims[1],Wt=Object.values(qe)[0].dims.at(-2);L=(0,P.cat)([(0,P.ones)([S.dims[0],Wt]),L.slice(null,[L.dims[1]-Ot,L.dims[1]])],1)}}if(!Fe&&f.config.model_type==="qwen2_vl"){const{image_grid_thw:Ot,video_grid_thw:Wt}=Ct;[Fe]=f.get_rope_index(S,Ot,Wt,L)}return await j(f,{inputs_embeds:Ae,past_key_values:qe,attention_mask:L,position_ids:Fe,generation_config:it,logits_processor:mt},!0)}function pe(f){const[S,L]=f.dims,ve=f.data,Fe=new BigInt64Array(ve.length);for(let Ae=0;AeAe.dims[1])){if(Feit==f.config.image_token_index)){const it=f.config.num_image_tokens;if(!it)throw new Error("`num_image_tokens` is missing in the model configuration.");const mt=Ae.dims[1]-(Fe-it);L.input_ids=Ae.slice(null,[-mt,null]),L.attention_mask=(0,P.ones)([1,Fe+mt])}}}return L}function Ke(f,S,L,ve){return L.past_key_values&&(S=S.map(Fe=>[Fe.at(-1)])),{...L,decoder_input_ids:Se(S)}}function Je(f,...S){return f.config.is_encoder_decoder?Ke(f,...S):Ne(f,...S)}function lt(f,S,L,ve){const Fe=!!L.past_key_values;return ve.guidance_scale!==null&&ve.guidance_scale>1&&(Fe?L.input_ids=(0,P.cat)([L.input_ids,L.input_ids],0):(L.input_ids=(0,P.cat)([L.input_ids,(0,P.full_like)(L.input_ids,BigInt(ve.pad_token_id))],0),L.attention_mask=(0,P.cat)([L.attention_mask,(0,P.full_like)(L.attention_mask,0n)],0))),(Fe||!L.pixel_values)&&(L.pixel_values=(0,P.full)([0,0,3,384,384],1)),Fe&&(L.images_seq_mask=new P.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),L.images_emb_mask=new P.Tensor("bool",new Array(0).fill(!1),[1,1,0])),L}class ie extends J.Callable{constructor(L,ve,Fe){super();Te(this,"main_input_name","input_ids");Te(this,"forward_params",["input_ids","attention_mask"]);this.config=L,this.sessions=ve,this.configs=Fe;const Ae=k.get(this.constructor),qe=O.get(Ae);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,qe){case N.DecoderOnly:this.can_generate=!0,this._forward=j,this._prepare_inputs_for_generation=Ne;break;case N.Seq2Seq:case N.Vision2Seq:case N.Musicgen:this.can_generate=!0,this._forward=Le,this._prepare_inputs_for_generation=Ke;break;case N.EncoderDecoder:this._forward=Le;break;case N.ImageTextToText:this.can_generate=!0,this._forward=he,this._prepare_inputs_for_generation=Je;break;case N.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=lt;break;default:this._forward=me;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ve;const L=[];for(const Fe of Object.values(this.sessions))(ve=Fe==null?void 0:Fe.handler)!=null&&ve.dispose&&L.push(Fe.handler.dispose());return await Promise.all(L)}static async from_pretrained(L,{progress_callback:ve=null,config:Fe=null,cache_dir:Ae=null,local_files_only:qe=!1,revision:it="main",model_file_name:mt=null,subfolder:Ct="onnx",device:Ut=null,dtype:Ot=null,use_external_data_format:Wt=null,session_options:Lt={}}={}){let sr={progress_callback:ve,config:Fe,cache_dir:Ae,local_files_only:qe,revision:it,model_file_name:mt,subfolder:Ct,device:Ut,dtype:Ot,use_external_data_format:Wt,session_options:Lt};const or=k.get(this),Yt=O.get(or);Fe=sr.config=await w.AutoConfig.from_pretrained(L,sr);let ur;if(Yt===N.DecoderOnly)ur=await Promise.all([Z(L,{model:sr.model_file_name??"model"},sr),ee(L,{generation_config:"generation_config.json"},sr)]);else if(Yt===N.Seq2Seq||Yt===N.Vision2Seq)ur=await Promise.all([Z(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},sr),ee(L,{generation_config:"generation_config.json"},sr)]);else if(Yt===N.MaskGeneration)ur=await Promise.all([Z(L,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},sr)]);else if(Yt===N.EncoderDecoder)ur=await Promise.all([Z(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},sr)]);else if(Yt===N.ImageTextToText){const Rr={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Fe.is_encoder_decoder&&(Rr.model="encoder_model"),ur=await Promise.all([Z(L,Rr,sr),ee(L,{generation_config:"generation_config.json"},sr)])}else Yt===N.Musicgen?ur=await Promise.all([Z(L,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},sr),ee(L,{generation_config:"generation_config.json"},sr)]):Yt===N.MultiModality?ur=await Promise.all([Z(L,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},sr),ee(L,{generation_config:"generation_config.json"},sr)]):(Yt!==N.EncoderOnly&&console.warn(`Model type for '${or??(Fe==null?void 0:Fe.model_type)}' not found, assuming encoder-only architecture. Please report this at ${x.GITHUB_ISSUE_URL}.`),ur=await Promise.all([Z(L,{model:sr.model_file_name??"model"},sr)]));return new this(Fe,...ur)}async _call(L){return await this.forward(L)}async forward(L){return await this._forward(this,L)}get generation_config(){var L;return((L=this.configs)==null?void 0:L.generation_config)??null}_get_logits_warper(L){const ve=new E.LogitsProcessorList;return L.temperature!==null&&L.temperature!==1&&ve.push(new E.TemperatureLogitsWarper(L.temperature)),L.top_k!==null&&L.top_k!==0&&ve.push(new E.TopKLogitsWarper(L.top_k)),L.top_p!==null&&L.top_p<1&&ve.push(new E.TopPLogitsWarper(L.top_p)),ve}_get_logits_processor(L,ve,Fe=null){const Ae=new E.LogitsProcessorList;if(L.repetition_penalty!==null&&L.repetition_penalty!==1&&Ae.push(new E.RepetitionPenaltyLogitsProcessor(L.repetition_penalty)),L.no_repeat_ngram_size!==null&&L.no_repeat_ngram_size>0&&Ae.push(new E.NoRepeatNGramLogitsProcessor(L.no_repeat_ngram_size)),L.bad_words_ids!==null&&Ae.push(new E.NoBadWordsLogitsProcessor(L.bad_words_ids,L.eos_token_id)),L.min_length!==null&&L.eos_token_id!==null&&L.min_length>0&&Ae.push(new E.MinLengthLogitsProcessor(L.min_length,L.eos_token_id)),L.min_new_tokens!==null&&L.eos_token_id!==null&&L.min_new_tokens>0&&Ae.push(new E.MinNewTokensLengthLogitsProcessor(ve,L.min_new_tokens,L.eos_token_id)),L.forced_bos_token_id!==null&&Ae.push(new E.ForcedBOSTokenLogitsProcessor(L.forced_bos_token_id)),L.forced_eos_token_id!==null&&Ae.push(new E.ForcedEOSTokenLogitsProcessor(L.max_length,L.forced_eos_token_id)),L.begin_suppress_tokens!==null){const qe=ve>1||L.forced_bos_token_id===null?ve:ve+1;Ae.push(new E.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,qe))}return L.guidance_scale!==null&&L.guidance_scale>1&&Ae.push(new E.ClassifierFreeGuidanceLogitsProcessor(L.guidance_scale)),Fe!==null&&Ae.extend(Fe),Ae}_prepare_generation_config(L,ve,Fe=$.GenerationConfig){const Ae={...this.config};for(const it of["decoder","generator","text_config"])it in Ae&&Object.assign(Ae,Ae[it]);const qe=new Fe(Ae);return Object.assign(qe,this.generation_config??{}),L&&Object.assign(qe,L),ve&&Object.assign(qe,(0,q.pick)(ve,Object.getOwnPropertyNames(qe))),qe}_get_stopping_criteria(L,ve=null){const Fe=new ue.StoppingCriteriaList;return L.max_length!==null&&Fe.push(new ue.MaxLengthCriteria(L.max_length,this.config.max_position_embeddings??null)),L.eos_token_id!==null&&Fe.push(new ue.EosTokenCriteria(L.eos_token_id)),ve&&Fe.extend(ve),Fe}_validate_model_class(){if(!this.can_generate){const L=[ma,fa,ha,pa],ve=k.get(this.constructor),Fe=new Set,Ae=this.config.model_type;for(const it of L){const mt=it.get(Ae);mt&&Fe.add(mt[0])}let qe=`The current model class (${ve}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Fe.size>0&&(qe+=` Please use the following class instead: ${[...Fe].join(", ")}`),Error(qe)}}prepare_inputs_for_generation(...L){return this._prepare_inputs_for_generation(this,...L)}_update_model_kwargs_for_generation({generated_input_ids:L,outputs:ve,model_inputs:Fe,is_encoder_decoder:Ae}){return Fe.past_key_values=this.getPastKeyValues(ve,Fe.past_key_values),Fe.input_ids=new P.Tensor("int64",L.flat(),[L.length,1]),Ae||(Fe.attention_mask=(0,P.cat)([Fe.attention_mask,(0,P.ones)([Fe.attention_mask.dims[0],1])],1)),Fe.position_ids=null,Fe}_prepare_model_inputs({inputs:L,bos_token_id:ve,model_kwargs:Fe}){const Ae=(0,q.pick)(Fe,this.forward_params),qe=this.main_input_name;if(qe in Ae){if(L)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Ae[qe]=L;return{inputs_tensor:Ae[qe],model_inputs:Ae,model_input_name:qe}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:L,model_inputs:ve,model_input_name:Fe,generation_config:Ae}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ve.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:it,pixel_values:mt,attention_mask:Ct,...Ut}=ve,Ot=await this._prepare_inputs_embeds(ve);ve={...Ut,...(0,q.pick)(Ot,["inputs_embeds","attention_mask"])}}let{last_hidden_state:qe}=await me(this,ve);if(Ae.guidance_scale!==null&&Ae.guidance_scale>1)qe=(0,P.cat)([qe,(0,P.full_like)(qe,0)],0),"attention_mask"in ve&&(ve.attention_mask=(0,P.cat)([ve.attention_mask,(0,P.zeros_like)(ve.attention_mask)],0));else if(ve.decoder_input_ids){const it=Se(ve.decoder_input_ids).dims[0];if(it!==qe.dims[0]){if(qe.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${qe.dims[0]}) than the decoder inputs (${it}).`);qe=(0,P.cat)(Array.from({length:it},()=>qe),0)}}return ve.encoder_outputs=qe,ve}_prepare_decoder_input_ids_for_generation({batch_size:L,model_input_name:ve,model_kwargs:Fe,decoder_start_token_id:Ae,bos_token_id:qe,generation_config:it}){let{decoder_input_ids:mt,...Ct}=Fe;if(!(mt instanceof P.Tensor)){if(mt)Array.isArray(mt[0])||(mt=Array.from({length:L},()=>mt));else if(Ae??(Ae=qe),this.config.model_type==="musicgen")mt=Array.from({length:L*this.config.decoder.num_codebooks},()=>[Ae]);else if(Array.isArray(Ae)){if(Ae.length!==L)throw new Error(`\`decoder_start_token_id\` expcted to have length ${L} but got ${Ae.length}`);mt=Ae}else mt=Array.from({length:L},()=>[Ae]);mt=Se(mt)}return Fe.decoder_attention_mask=(0,P.ones_like)(mt),{input_ids:mt,model_inputs:Ct}}async generate({inputs:L=null,generation_config:ve=null,logits_processor:Fe=null,stopping_criteria:Ae=null,streamer:qe=null,...it}){this._validate_model_class(),ve=this._prepare_generation_config(ve,it);let{inputs_tensor:mt,model_inputs:Ct,model_input_name:Ut}=this._prepare_model_inputs({inputs:L,model_kwargs:it});const Ot=this.config.is_encoder_decoder;Ot&&("encoder_outputs"in Ct||(Ct=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:mt,model_inputs:Ct,model_input_name:Ut,generation_config:ve})));let Wt;Ot?{input_ids:Wt,model_inputs:Ct}=this._prepare_decoder_input_ids_for_generation({batch_size:Ct[Ut].dims.at(0),model_input_name:Ut,model_kwargs:Ct,decoder_start_token_id:ve.decoder_start_token_id,bos_token_id:ve.bos_token_id,generation_config:ve}):Wt=Ct[Ut];let Lt=Wt.dims.at(-1);ve.max_new_tokens!==null&&(ve.max_length=Lt+ve.max_new_tokens);const sr=this._get_logits_processor(ve,Lt,Fe),or=this._get_stopping_criteria(ve,Ae),Yt=Ct[Ut].dims.at(0),ur=le.LogitsSampler.getSampler(ve),Rr=new Array(Yt).fill(0),Sr=Wt.tolist();qe&&qe.put(Sr);let $r,kr={};for(;;){if(Ct=this.prepare_inputs_for_generation(Sr,Ct,ve),$r=await this.forward(Ct),ve.output_attentions&&ve.return_dict_in_generate){const fs=this.getAttentions($r);for(const Ls in fs)Ls in kr||(kr[Ls]=[]),kr[Ls].push(fs[Ls])}const Gr=$r.logits.slice(null,-1,null),$s=sr(Sr,Gr),to=[];for(let fs=0;fs<$s.dims.at(0);++fs){const Ls=$s[fs],lc=await ur(Ls);for(const[Do,Ca]of lc){const Lo=BigInt(Do);Rr[fs]+=Ca,Sr[fs].push(Lo),to.push([Lo]);break}}if(qe&&qe.put(to),or(Sr).every(fs=>fs))break;Ct=this._update_model_kwargs_for_generation({generated_input_ids:to,outputs:$r,model_inputs:Ct,is_encoder_decoder:Ot})}qe&&qe.end();const Or=this.getPastKeyValues($r,Ct.past_key_values,!0),Zr=new P.Tensor("int64",Sr.flat(),[Sr.length,Sr[0].length]);if(ve.return_dict_in_generate)return{sequences:Zr,past_key_values:Or,...kr};for(const Gr of Object.values($r))Gr.location==="gpu-buffer"&&Gr.dispose();return Zr}getPastKeyValues(L,ve,Fe=!1){const Ae=Object.create(null);for(const qe in L)if(qe.startsWith("present")){const it=qe.replace("present","past_key_values"),mt=qe.includes("encoder");if(mt&&ve?Ae[it]=ve[it]:Ae[it]=L[qe],ve&&(!mt||Fe)){const Ct=ve[it];Ct.location==="gpu-buffer"&&Ct.dispose()}}return Ae}getAttentions(L){const ve={};for(const Fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Ae in L)Ae.startsWith(Fe)&&(Fe in ve||(ve[Fe]=[]),ve[Fe].push(L[Ae]));return ve}addPastKeyValues(L,ve){var Fe,Ae;if(ve)Object.assign(L,ve);else{const qe=this.sessions.decoder_model_merged??this.sessions.model,it=((Fe=qe==null?void 0:qe.config)==null?void 0:Fe.kv_cache_dtype)??"float32",mt=it==="float16"?new Uint16Array:[],Ct=((Ae=(L[this.main_input_name]??L.attention_mask).dims)==null?void 0:Ae[0])??1,Ut=(0,w.getKeyValueShapes)(this.config,{batch_size:Ct});for(const Ot in Ut)L[Ot]=new P.Tensor(it,mt,Ut[Ot])}}async encode_image({pixel_values:L}){const ve=(await ge(this.sessions.vision_encoder,{pixel_values:L})).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 (${ve.dims[1]}).`),this.config.num_image_tokens=ve.dims[1]),ve}async encode_text({input_ids:L}){return(await ge(this.sessions.embed_tokens,{input_ids:L})).inputs_embeds}}class je{}class st extends je{constructor({last_hidden_state:S,hidden_states:L=null,attentions:ve=null}){super(),this.last_hidden_state=S,this.hidden_states=L,this.attentions=ve}}class ze extends ie{}class we extends ze{}class Ce extends ze{async _call(S){return new Jr(await super._call(S))}}class Ze extends ze{async _call(S){return new er(await super._call(S))}}class Qe extends ze{async _call(S){return new Qr(await super._call(S))}}class He extends ze{async _call(S){return new ss(await super._call(S))}}class Be extends ie{}class nt extends Be{}class ut extends ie{}class wt extends ut{}class ht extends ut{async _call(S){return new Jr(await super._call(S))}}class ft extends ut{async _call(S){return new er(await super._call(S))}}class A extends ut{async _call(S){return new Qr(await super._call(S))}}class re extends ut{async _call(S){return new ss(await super._call(S))}}class V extends ie{}class de extends V{}class ke extends V{async _call(S){return new Jr(await super._call(S))}}class Ye extends V{async _call(S){return new er(await super._call(S))}}class ot extends V{async _call(S){return new Qr(await super._call(S))}}class dt extends V{async _call(S){return new ss(await super._call(S))}}class $t extends ie{}class Et extends $t{}class Tt extends $t{async _call(S){return new Jr(await super._call(S))}}class Pt extends $t{async _call(S){return new er(await super._call(S))}}class ar extends $t{async _call(S){return new Qr(await super._call(S))}}class Mr extends $t{async _call(S){return new ss(await super._call(S))}}class Fr extends ie{}class Br extends Fr{}class os extends Fr{async _call(S){return new Jr(await super._call(S))}}class Qs extends Fr{async _call(S){return new er(await super._call(S))}}class Xs extends Fr{async _call(S){return new Qr(await super._call(S))}}class zs extends Fr{async _call(S){return new ss(await super._call(S))}}class Is extends ie{}class Nt extends Is{}class Ts extends Is{async _call(S){return new Jr(await super._call(S))}}class Bs extends Is{async _call(S){return new er(await super._call(S))}}class Ys extends Is{async _call(S){return new Qr(await super._call(S))}}class un extends Is{async _call(S){return new ss(await super._call(S))}}class gs extends ie{}class dn extends gs{}class Js extends gs{async _call(S){return new Jr(await super._call(S))}}class Zs extends gs{async _call(S){return new er(await super._call(S))}}class Rs extends gs{async _call(S){return new Qr(await super._call(S))}}class ds extends gs{async _call(S){return new ss(await super._call(S))}}class et extends ie{}class vt extends et{}class It extends et{async _call(S){return new er(await super._call(S))}}class Wr extends et{async _call(S){return new Qr(await super._call(S))}}class en extends et{async _call(S){return new ss(await super._call(S))}}class js extends et{async _call(S){return new Jr(await super._call(S))}}class xr extends ie{}class cs extends xr{}class Lr extends xr{async _call(S){return new Jr(await super._call(S))}}class Fs extends xr{async _call(S){return new er(await super._call(S))}}class br extends xr{async _call(S){return new Qr(await super._call(S))}}class Ns extends ie{}class Fn extends Ns{}class po extends Ns{async _call(S){return new Jr(await super._call(S))}}class On extends Ns{async _call(S){return new er(await super._call(S))}}class Dn extends Ns{async _call(S){return new ss(await super._call(S))}}class Us extends ie{}class Ln extends Us{}class zn extends Us{async _call(S){return new Jr(await super._call(S))}}class ho extends Us{async _call(S){return new er(await super._call(S))}}class tn extends Us{async _call(S){return new Qr(await super._call(S))}}class xs extends Us{async _call(S){return new ss(await super._call(S))}}class ws extends ie{}class bn extends ws{}class cn extends ws{async _call(S){return new Jr(await super._call(S))}}class vn extends ws{async _call(S){return new er(await super._call(S))}}class Tn extends ws{async _call(S){return new ss(await super._call(S))}}class Vs extends ie{}class Rt extends Vs{}class xn extends Vs{async _call(S){return new er(await super._call(S))}}class Bn extends Vs{async _call(S){return new ss(await super._call(S))}}class Rn extends Vs{async _call(S){return new Jr(await super._call(S))}}class En extends ie{constructor(){super(...arguments);Te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class jn extends En{}class Nn extends En{}class pn extends ie{}class Un extends pn{}class _r extends pn{}class xe extends ie{}class M extends xe{}class G extends xe{}class oe extends ie{}class Me extends oe{}class Ee extends oe{}class Ve extends oe{async _call(S){return new er(await super._call(S))}}class at extends ie{}class _t extends at{}class pt extends at{}class bt extends at{async _call(S){return new er(await super._call(S))}}class Kt extends at{}class mr extends ie{}class rr extends mr{}class Cr extends mr{}class qt extends ie{}class cr extends qt{}class ps extends qt{}class zr extends ie{}class De extends zr{}class gr extends zr{async _call(S){return new Jr(await super._call(S))}}class Hr extends zr{async _call(S){return new er(await super._call(S))}}class hs extends zr{async _call(S){return new Qr(await super._call(S))}}class Es extends zr{async _call(S){return new ss(await super._call(S))}}class Dt extends ie{}class qr extends Dt{}class as extends Dt{async _call(S){return new Jr(await super._call(S))}}class ir extends Dt{async _call(S){return new er(await super._call(S))}}class wr extends Dt{async _call(S){return new Qr(await super._call(S))}}class gt extends Dt{async _call(S){return new ss(await super._call(S))}}class Qt extends ie{}class Nr extends Qt{}class Os extends Qt{async _call(S){return new Jr(await super._call(S))}}class Ds extends Qt{async _call(S){return new er(await super._call(S))}}class kt extends Qt{async _call(S){return new Qr(await super._call(S))}}class mo extends Qt{async _call(S){return new ss(await super._call(S))}}class Xe extends ie{}class At extends Xe{}class qo extends Xe{}class Qo extends ie{constructor(){super(...arguments);Te(this,"requires_attention_mask",!1);Te(this,"main_input_name","input_features");Te(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ra extends Qo{}class Vn extends Qo{_prepare_generation_config(S,L){return super._prepare_generation_config(S,L,Q.WhisperGenerationConfig)}_retrieve_init_tokens(S){const L=[S.decoder_start_token_id];let ve=S.language;const Fe=S.task;if(S.is_multilingual){ve||(console.warn("No language specified - defaulting to English (en)."),ve="en");const qe=`<|${(0,ne.whisper_language_to_code)(ve)}|>`;L.push(S.lang_to_id[qe]),L.push(S.task_to_id[Fe??"transcribe"])}else if(ve||Fe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!S.return_timestamps&&S.no_timestamps_token_id&&L.at(-1)!==S.no_timestamps_token_id?L.push(S.no_timestamps_token_id):S.return_timestamps&&L.at(-1)===S.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),L.pop()),L.filter(Ae=>Ae!=null)}async generate({inputs:S=null,generation_config:L=null,logits_processor:ve=null,stopping_criteria:Fe=null,...Ae}){L=this._prepare_generation_config(L,Ae);const qe=Ae.decoder_input_ids??this._retrieve_init_tokens(L);if(L.return_timestamps&&(ve??(ve=new E.LogitsProcessorList),ve.push(new E.WhisperTimeStampLogitsProcessor(L,qe))),L.begin_suppress_tokens&&(ve??(ve=new E.LogitsProcessorList),ve.push(new E.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,qe.length))),L.return_token_timestamps){if(!L.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.");L.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),L.output_attentions=!0,L.return_dict_in_generate=!0}const it=await super.generate({inputs:S,generation_config:L,logits_processor:ve,decoder_input_ids:qe,...Ae});return L.return_token_timestamps&&(it.token_timestamps=this._extract_token_timestamps(it,L.alignment_heads,L.num_frames)),it}_extract_token_timestamps(S,L,ve=null,Fe=.02){if(!S.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");ve==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 Ae=this.config.median_filter_width;Ae===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Ae=7);const qe=S.cross_attentions,it=Array.from({length:this.config.decoder_layers},(or,Yt)=>(0,P.cat)(qe.map(ur=>ur[Yt]),2)),mt=(0,P.stack)(L.map(([or,Yt])=>{if(or>=it.length)throw new Error(`Layer index ${or} is out of bounds for cross attentions (length ${it.length}).`);return ve?it[or].slice(null,Yt,null,[0,ve]):it[or].slice(null,Yt)})).transpose(1,0,2,3),[Ct,Ut]=(0,P.std_mean)(mt,-2,0,!0),Ot=mt.clone();for(let or=0;orur[Zr+1]-ur[Zr]),$r=(0,q.mergeArrays)([1],Sr).map(Or=>!!Or),kr=[];for(let Or=0;Or<$r.length;++Or)$r[Or]&&kr.push(Rr[Or]*Fe);sr[or].data.set(kr,1)}return sr}}class Jt extends ie{constructor(){super(...arguments);Te(this,"main_input_name","pixel_values");Te(this,"forward_params",["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"])}}class ja extends ie{constructor(){super(...arguments);Te(this,"forward_params",["input_ids","pixel_values","attention_mask","position_ids","past_key_values"])}}class Wn extends ja{_merge_input_ids_with_image_features({inputs_embeds:S,image_features:L,input_ids:ve,attention_mask:Fe}){const Ae=this.config.image_token_index,it=ve.tolist().map(Wt=>Wt.findIndex(Lt=>Lt==Ae)),mt=it.every(Wt=>Wt===-1),Ct=it.every(Wt=>Wt!==-1);if(!mt&&!Ct)throw new Error("Every input should contain either 0 or 1 image token.");if(mt)return{inputs_embeds:S,attention_mask:Fe};const Ut=[],Ot=[];for(let Wt=0;WtArray.from({length:S.dims[0]},Sr=>Array.from({length:S.dims[1]},$r=>1))),sr=L?L.tolist():[],or=ve?ve.tolist():[];let Yt=0,ur=0;for(let Rr=0;RrWt[Rr][Ur]==1),kr=Sr.reduce((Ir,Ur,an)=>(Ur==mt&&Ir.push(an),Ir),[]).map(Ir=>Sr[Ir+1]),Or=kr.filter(Ir=>Ir==qe).length,Zr=kr.filter(Ir=>Ir==it).length;let Gr=[],$s=0,to=Or,Pa=Zr;for(let Ir=0;Irks>$s&&kn==qe),an=Sr.findIndex((kn,ks)=>ks>$s&&kn==it),fn=to>0&&Ur!==-1?Ur:Sr.length+1,$n=Pa>0&&an!==-1?an:Sr.length+1;let Sa,$a,zo,Bo;fn<$n?([$a,zo,Bo]=sr[Yt],++Yt,--to,Sa=fn):([$a,zo,Bo]=or[ur],++ur,--Pa,Sa=$n);const[tp,ka,Aa]=[Number($a),Math.floor(Number(zo)/Ct),Math.floor(Number(Bo)/Ct)],Ro=Sa-$s,uc=Gr.length>0?(0,se.max)(Gr.at(-1))[0]+1:0;Gr.push(Array.from({length:3*Ro},(kn,ks)=>uc+ks%Ro));const dc=Ro+uc,jo=tp*ka*Aa,Ia=Array.from({length:jo},(kn,ks)=>dc+Math.floor(ks/(ka*Aa))),rp=Array.from({length:jo},(kn,ks)=>dc+Math.floor(ks/Aa)%ka),sp=Array.from({length:jo},(kn,ks)=>dc+ks%Aa);Gr.push([Ia,rp,sp].flat()),$s=Sa+jo}if($s0?(0,se.max)(Gr.at(-1))[0]+1:0,Ur=Sr.length-$s;Gr.push(Array.from({length:3*Ur},(an,fn)=>Ir+fn%Ur))}const fs=Gr.reduce((Ir,Ur)=>Ir+Ur.length,0),Ls=new Array(fs);let lc=0;for(let Ir=0;Ir<3;++Ir)for(let Ur=0;UrOt[Yt%Ot.length]),sr=Array.from({length:Wt[0]},(or,Yt)=>(0,se.max)(Ot.subarray(Wt[1]*Yt,Wt[1]*(Yt+1)))[0]+1+Wt[1]);return[new P.Tensor("int64",Lt,[3,...Wt]),new P.Tensor("int64",sr,[sr.length,1])]}else{const[Ot,Wt]=S.dims,Lt=BigInt64Array.from({length:3*Ot*Wt},(sr,or)=>BigInt(Math.floor(or%Wt/Ot)));return[new P.Tensor("int64",Lt,[3,...S.dims]),(0,P.zeros)([Ot,1])]}}async encode_image({pixel_values:S,image_grid_thw:L}){return(await ge(this.sessions.vision_encoder,{pixel_values:S,grid_thw:L})).image_features}_merge_input_ids_with_image_features({inputs_embeds:S,image_features:L,input_ids:ve,attention_mask:Fe}){const{image_token_id:Ae}=this.config,qe=ve.tolist().map(Ut=>Ut.reduce((Ot,Wt,Lt)=>(Wt==Ae&&Ot.push(Lt),Ot),[])),it=qe.reduce((Ut,Ot)=>Ut+Ot.length,0),mt=L.dims[0];if(it!==mt)throw new Error(`Image features and image tokens do not match: tokens: ${it}, features ${mt}`);let Ct=0;for(let Ut=0;UtFe+qe);L.position_ids=(0,P.stack)([Ae,Ae,Ae],0)}return L}}class Al extends ie{}class Il extends Al{}class Fl extends Al{}class li extends ie{}class yc extends li{}class Ol extends li{}class lr extends ie{}class Dl extends lr{}class Ll extends lr{}class ui extends ie{}class zl extends ui{}class Bl extends ui{}class di extends ie{}class Rl extends di{}class jl extends di{}class ci extends ie{}class Nl extends ci{}class Ul extends ci{async _call(S){return new er(await super._call(S))}}class Vl extends ie{}class Wl extends Vl{}class pi extends ie{}class Gn extends pi{}class Gl extends pi{async _call(S){return new er(await super._call(S))}}class bo extends ie{}class Kl extends bo{}class hi extends ie{}class Hl extends hi{}class ql extends hi{async _call(S){return new er(await super._call(S))}}class Ql extends ie{}class Xl extends Ql{}class mi extends ie{}class Yl extends mi{}class Jl extends mi{async _call(S){return new er(await super._call(S))}}class Zl extends ie{}class eu extends Zl{async _call(S){return new ic(await super._call(S))}}class fi extends ie{}class tu extends fi{}class ru extends fi{async _call(S){return new er(await super._call(S))}}class _i extends ie{}class su extends _i{}class gi extends _i{async _call(S){return new er(await super._call(S))}}class wi extends ie{}class yi extends wi{}class Mi extends wi{}class bi extends ie{}class nu extends bi{}class ou extends bi{}class vi extends ie{}class iu extends vi{}class au extends vi{async _call(S){return new er(await super._call(S))}}class Kn extends ie{}class lu extends Kn{}class uu extends Kn{async _call(S){return new du(await super._call(S))}}class Ti extends Kn{async _call(S){return new cu(await super._call(S))}}class du extends je{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class cu extends je{constructor({logits:S,pred_boxes:L,pred_masks:ve}){super(),this.logits=S,this.pred_boxes=L,this.pred_masks=ve}}class xi extends ie{}class Ss extends xi{}class pu extends xi{async _call(S){return new hu(await super._call(S))}}class hu extends je{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class Ei extends ie{}class mu extends Ei{}class fu extends Ei{async _call(S){return new _u(await super._call(S))}}class _u extends du{}class Pi extends ie{}class gu extends Pi{}class wu extends Pi{async _call(S){return new er(await super._call(S))}}class Ci extends ie{}class Mc extends Ci{}class yu extends Ci{async _call(S){return new er(await super._call(S))}}class Si extends ie{}class Mu extends Si{}class bu extends Si{async _call(S){return new er(await super._call(S))}}class $i extends ie{}class vu extends $i{}class bc extends $i{async _call(S){return new er(await super._call(S))}}class Ws extends ie{}class rn extends Ws{}class sn extends Ws{}class vo extends ie{}class nn extends vo{}class ts extends vo{}class ki extends ie{}class To extends ki{}class Hn extends ie{}class Tu extends Hn{}class xu extends Hn{}class Eu extends Hn{}class xo extends ie{}class Ai extends xo{}class Ii extends ie{}class Eo extends Ii{}class Pu extends Ii{}class Po extends ie{}class Co extends Po{}class Cu extends Po{}class Su extends ie{}class vc extends Su{}class Fi extends ie{}class Oi extends Fi{}class qn extends Fi{async _call(S){return new er(await super._call(S))}}class Di extends ie{}class Li extends Di{}class $u extends Di{async _call(S){return new er(await super._call(S))}}class zi extends ie{}class ku extends zi{}class Tc extends zi{async _call(S){return new er(await super._call(S))}}class Bi extends ie{}class Au extends Bi{}class xc extends Bi{async _call(S){return new Ri(await super._call(S))}}class Ri extends je{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class Iu extends ie{}class Fu extends Iu{async get_image_embeddings({pixel_values:S}){return await me(this,{pixel_values:S})}async forward(S){if((!S.image_embeddings||!S.image_positional_embeddings)&&(S={...S,...await this.get_image_embeddings(S)}),!S.input_labels&&S.input_points){const ve=S.input_points.dims.slice(0,-1),Fe=ve.reduce((Ae,qe)=>Ae*qe,1);S.input_labels=new P.Tensor("int64",new BigInt64Array(Fe).fill(1n),ve)}const L={image_embeddings:S.image_embeddings,image_positional_embeddings:S.image_positional_embeddings};return S.input_points&&(L.input_points=S.input_points),S.input_labels&&(L.input_labels=S.input_labels),S.input_boxes&&(L.input_boxes=S.input_boxes),await ge(this.sessions.prompt_encoder_mask_decoder,L)}async _call(S){return new Ou(await super._call(S))}}class Ou extends je{constructor({iou_scores:S,pred_masks:L}){super(),this.iou_scores=S,this.pred_masks=L}}class ji extends ie{}class So extends ji{}class Du extends ji{}class Qn extends ie{}class Ni extends Qn{}class Ui extends Qn{}class on extends ie{}class Lu extends on{}class Vi extends on{async _call(S){return new Sn(await super._call(S))}}class Ec extends on{async _call(S){return new er(await super._call(S))}}class zu extends on{async _call(S){return new Qr(await super._call(S))}}class Wi extends ie{}class Pc extends Wi{}class Bu extends Wi{async _call(S){return new Qr(await super._call(S))}}class Gi extends ie{}class Cc extends Gi{}class $o extends ie{}class Ru extends $o{}class ju extends $o{async _call(S){return new Sn(await super._call(S))}}class Ki extends $o{async _call(S){return new er(await super._call(S))}}class Xn extends ie{}class Nu extends Xn{}class Uu extends Xn{async _call(S){return new Sn(await super._call(S))}}class Vu extends Xn{async _call(S){return new er(await super._call(S))}}class Wu extends Xn{async _call(S){return new Qr(await super._call(S))}}class ko extends ie{}class Sc extends ko{}class Gu extends ko{async _call(S){return new Sn(await super._call(S))}}class Ku extends ko{async _call(S){return new er(await super._call(S))}}class $c extends ie{}class kc extends on{}class Hu extends on{async _call(S){return new Sn(await super._call(S))}}class qu extends on{async _call(S){return new er(await super._call(S))}}class Cn extends ie{}class Qu extends Cn{}class Xu extends Cn{async _call(S){return new Sn(await super._call(S))}}class Ac extends Cn{async _call(S){return new er(await super._call(S))}}class Ao extends Cn{async _call(S){return new oc(await super._call(S))}}class Yn extends Cn{async _call(S){return new Qr(await super._call(S))}}class Jn extends ie{}class Ic extends Jn{}class Yu extends Jn{}class Ju extends Jn{async generate_speech(S,L,{threshold:ve=.5,minlenratio:Fe=0,maxlenratio:Ae=20,vocoder:qe=null}={}){const it={input_ids:S},{encoder_outputs:mt,encoder_attention_mask:Ct}=await me(this,it),Ut=mt.dims[1]/this.config.reduction_factor,Ot=Math.floor(Ut*Ae),Wt=Math.floor(Ut*Fe),Lt=this.config.num_mel_bins;let sr=[],or=null,Yt=null,ur=0;for(;;){++ur;const $r=Pe(!!Yt);let kr;Yt?kr=Yt.output_sequence_out:kr=new P.Tensor("float32",new Float32Array(Lt),[1,1,Lt]);let Or={use_cache_branch:$r,output_sequence:kr,encoder_attention_mask:Ct,speaker_embeddings:L,encoder_hidden_states:mt};this.addPastKeyValues(Or,or),Yt=await ge(this.sessions.decoder_model_merged,Or),or=this.getPastKeyValues(Yt,or);const{prob:Zr,spectrum:Gr}=Yt;if(sr.push(Gr),ur>=Wt&&(Array.from(Zr.data).filter($s=>$s>=ve).length>0||ur>=Ot))break}const Rr=(0,P.cat)(sr),{waveform:Sr}=await ge(qe.sessions.model,{spectrogram:Rr});return{spectrogram:Rr,waveform:Sr}}}class Zu extends ie{constructor(){super(...arguments);Te(this,"main_input_name","spectrogram")}}class Hi extends ie{}class ed extends Hi{}class qi extends ie{}class td extends qi{}class Fc extends qi{}class Qi extends ie{}class Xi extends Qi{}class rd extends Qi{}class Yi extends ie{}class sd extends Yi{}class Oc extends Yi{}class Io extends ie{}class nd extends Io{}class Dc extends Io{static async from_pretrained(S,L={}){return L.model_file_name??(L.model_file_name="text_model"),super.from_pretrained(S,L)}}class od extends Io{static async from_pretrained(S,L={}){return L.model_file_name??(L.model_file_name="audio_model"),super.from_pretrained(S,L)}}class id extends ie{}class Ji extends id{async _call(S){return new ac(await super._call(S))}}class Fo extends ie{}class Pp extends Fo{}class ad extends Fo{}class ld extends Fo{}class Zi extends ie{}class ud extends Zi{}class Lc extends Zi{}class ea extends ie{}class dd extends ea{}class cd extends ea{async _call(S){return new er(await super._call(S))}}class ta extends ie{}class Cp extends ta{}class zc extends ta{}class ra extends ie{constructor(){super(...arguments);Te(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(L){const[ve,Fe]=L.dims,Ae=this.config.decoder.num_codebooks,qe=Fe-Ae;let it=0;for(let Ut=0;Ut0&&Lt<=qe&&(L.data[it++]=L.data[Ut])}const mt=Math.floor(ve/Ae),Ct=it/(mt*Ae);return new P.Tensor(L.type,L.data.slice(0,it),[mt,Ae,Ct])}prepare_inputs_for_generation(L,ve,Fe){let Ae=structuredClone(L);for(let it=0;it=mt&&(Ae[it][mt]=BigInt(this.config.decoder.pad_token_id));return Fe.guidance_scale!==null&&Fe.guidance_scale>1&&(Ae=Ae.concat(Ae)),super.prepare_inputs_for_generation(Ae,ve,Fe)}async generate(L){const ve=await super.generate(L),Fe=this._apply_and_filter_by_delay_pattern_mask(ve).unsqueeze_(0),{audio_values:Ae}=await ge(this.sessions.encodec_decode,{audio_codes:Fe});return Ae}}class sa extends ie{}class pd extends sa{}class Bc extends sa{async _call(S){return new er(await super._call(S))}}class rs extends ie{}class hd extends rs{}class md extends rs{async _call(S){return new er(await super._call(S))}}class Oo extends ie{}class fd extends Oo{}class Zn extends Oo{async _call(S){return new er(await super._call(S))}}class na extends ie{}class _d extends na{}class oa extends na{async _call(S){return new er(await super._call(S))}}class gd extends ie{}class wd extends gd{}class ia extends ie{}class yd extends ia{constructor(...L){super(...L);Te(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(L){const ve=this._generation_mode??"text";let Fe;if(ve==="text"||!L.past_key_values){const Ct=this.sessions.prepare_inputs_embeds,Ut=(0,q.pick)(L,Ct.inputNames);Fe=await ge(Ct,Ut)}else{const Ct=this.sessions.gen_img_embeds,Ut=(0,q.pick)({image_ids:L.input_ids},Ct.inputNames);Fe=await ge(Ct,Ut)}const Ae={...L,...Fe},qe=await j(this,Ae),it=this.sessions[ve==="text"?"lm_head":"gen_head"];if(!it)throw new Error(`Unable to find "${it}" generation head`);const mt=await ge(it,(0,q.pick)(qe,it.inputNames));return{...Fe,...qe,...mt}}async generate(L){return this._generation_mode="text",super.generate(L)}async generate_images(L){this._generation_mode="image";const ve=(L.inputs??L[this.main_input_name]).dims[1],Ae=(await super.generate(L)).slice(null,[ve,null]),qe=this.sessions.image_decode,{decoded_image:it}=await ge(qe,{generated_tokens:Ae}),mt=it.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Ct=[];for(const Ut of mt){const Ot=Y.RawImage.fromTensor(Ut);Ct.push(Ot)}return Ct}}class Md extends je{constructor({char_logits:S,bpe_logits:L,wp_logits:ve}){super(),this.char_logits=S,this.bpe_logits=L,this.wp_logits=ve}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class bd extends ie{}class aa extends bd{async _call(S){return new Md(await super._call(S))}}class la extends ie{}class vd extends la{}class ua extends la{}class da extends ie{}class Rc extends da{}class ca extends da{}class yr{static async from_pretrained(S,{progress_callback:L=null,config:ve=null,cache_dir:Fe=null,local_files_only:Ae=!1,revision:qe="main",model_file_name:it=null,subfolder:mt="onnx",device:Ct=null,dtype:Ut=null,use_external_data_format:Ot=null,session_options:Wt={}}={}){const Lt={progress_callback:L,config:ve,cache_dir:Fe,local_files_only:Ae,revision:qe,model_file_name:it,subfolder:mt,device:Ct,dtype:Ut,use_external_data_format:Ot,session_options:Wt};if(Lt.config=await w.AutoConfig.from_pretrained(S,Lt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const sr of this.MODEL_CLASS_MAPPINGS){const or=sr.get(Lt.config.model_type);if(or)return await or[1].from_pretrained(S,Lt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Lt.config.model_type}", attempting to construct from base class.`),await ie.from_pretrained(S,Lt);throw Error(`Unsupported model type: ${Lt.config.model_type}`)}}Te(yr,"MODEL_CLASS_MAPPINGS",null),Te(yr,"BASE_IF_FAIL",!1);const jc=new Map([["bert",["BertModel",we]],["nomic_bert",["NomicBertModel",nt]],["roformer",["RoFormerModel",wt]],["electra",["ElectraModel",Et]],["esm",["EsmModel",cs]],["convbert",["ConvBertModel",de]],["camembert",["CamembertModel",Br]],["deberta",["DebertaModel",Nt]],["deberta-v2",["DebertaV2Model",dn]],["mpnet",["MPNetModel",Ln]],["albert",["AlbertModel",Rt]],["distilbert",["DistilBertModel",vt]],["roberta",["RobertaModel",De]],["xlm",["XLMModel",qr]],["xlm-roberta",["XLMRobertaModel",Nr]],["clap",["ClapModel",nd]],["clip",["CLIPModel",Wa]],["clipseg",["CLIPSegModel",el]],["chinese_clip",["ChineseCLIPModel",Ya]],["siglip",["SiglipModel",Ha]],["jina_clip",["JinaCLIPModel",Ps]],["mobilebert",["MobileBertModel",Fn]],["squeezebert",["SqueezeBertModel",bn]],["wav2vec2",["Wav2Vec2Model",Lu]],["wav2vec2-bert",["Wav2Vec2BertModel",Sc]],["unispeech",["UniSpeechModel",Ru]],["unispeech-sat",["UniSpeechSatModel",Nu]],["hubert",["HubertModel",kc]],["wavlm",["WavLMModel",Qu]],["audio-spectrogram-transformer",["ASTModel",At]],["vits",["VitsModel",Ji]],["pyannote",["PyAnnoteModel",Pc]],["wespeaker-resnet",["WeSpeakerResNetModel",Cc]],["detr",["DetrModel",lu]],["rt_detr",["RTDetrModel",Ss]],["table-transformer",["TableTransformerModel",mu]],["vit",["ViTModel",Nl]],["pvt",["PvtModel",Gn]],["vit_msn",["ViTMSNModel",Hl]],["vit_mae",["ViTMAEModel",Kl]],["groupvit",["GroupViTModel",Xl]],["fastvit",["FastViTModel",Yl]],["mobilevit",["MobileViTModel",tu]],["mobilevitv2",["MobileViTV2Model",su]],["owlvit",["OwlViTModel",yi]],["owlv2",["Owlv2Model",nu]],["beit",["BeitModel",iu]],["deit",["DeiTModel",gu]],["hiera",["HieraModel",Mc]],["convnext",["ConvNextModel",Oi]],["convnextv2",["ConvNextV2Model",Li]],["dinov2",["Dinov2Model",ku]],["resnet",["ResNetModel",Mu]],["swin",["SwinModel",vu]],["swin2sr",["Swin2SRModel",rn]],["donut-swin",["DonutSwinModel",vc]],["yolos",["YolosModel",Au]],["dpt",["DPTModel",nn]],["glpn",["GLPNModel",Co]],["hifigan",["SpeechT5HifiGan",Zu]],["efficientnet",["EfficientNetModel",dd]],["decision_transformer",["DecisionTransformerModel",wd]],["patchtst",["PatchTSTForPrediction",vd]],["patchtsmixer",["PatchTSMixerForPrediction",Rc]],["mobilenet_v1",["MobileNetV1Model",pd]],["mobilenet_v2",["MobileNetV2Model",hd]],["mobilenet_v3",["MobileNetV3Model",fd]],["mobilenet_v4",["MobileNetV4Model",_d]],["maskformer",["MaskFormerModel",Eo]],["mgp-str",["MgpstrForSceneTextRecognition",aa]]]),Nc=new Map([["t5",["T5Model",jn]],["longt5",["LongT5Model",Un]],["mt5",["MT5Model",M]],["bart",["BartModel",Me]],["mbart",["MBartModel",_t]],["marian",["MarianModel",So]],["whisper",["WhisperModel",Ra]],["m2m_100",["M2M100Model",Ni]],["blenderbot",["BlenderbotModel",rr]],["blenderbot-small",["BlenderbotSmallModel",cr]]]),Sp=new Map([["bloom",["BloomModel",Dl]],["jais",["JAISModel",nl]],["gpt2",["GPT2Model",rl]],["gptj",["GPTJModel",al]],["gpt_bigcode",["GPTBigCodeModel",ul]],["gpt_neo",["GPTNeoModel",ol]],["gpt_neox",["GPTNeoXModel",Cs]],["codegen",["CodeGenModel",cl]],["llama",["LlamaModel",hl]],["olmo",["OlmoModel",gl]],["mobilellm",["MobileLLMModel",fl]],["granite",["GraniteModel",yl]],["cohere",["CohereModel",Ml]],["gemma",["GemmaModel",wc]],["gemma2",["Gemma2Model",Tl]],["openelm",["OpenELMModel",El]],["qwen2",["Qwen2Model",Cl]],["phi",["PhiModel",Il]],["phi3",["Phi3Model",yc]],["mpt",["MptModel",zl]],["opt",["OPTModel",Rl]],["mistral",["MistralModel",td]],["starcoder2",["Starcoder2Model",Xi]],["falcon",["FalconModel",sd]],["stablelm",["StableLmModel",ud]]]),pa=new Map([["speecht5",["SpeechT5ForSpeechToText",Yu]],["whisper",["WhisperForConditionalGeneration",Vn]]]),Td=new Map([["speecht5",["SpeechT5ForTextToSpeech",Ju]]]),xd=new Map([["vits",["VitsModel",Ji]],["musicgen",["MusicgenForConditionalGeneration",ra]]]),Uc=new Map([["bert",["BertForSequenceClassification",Ze]],["roformer",["RoFormerForSequenceClassification",ft]],["electra",["ElectraForSequenceClassification",Pt]],["esm",["EsmForSequenceClassification",Fs]],["convbert",["ConvBertForSequenceClassification",Ye]],["camembert",["CamembertForSequenceClassification",Qs]],["deberta",["DebertaForSequenceClassification",Bs]],["deberta-v2",["DebertaV2ForSequenceClassification",Zs]],["mpnet",["MPNetForSequenceClassification",ho]],["albert",["AlbertForSequenceClassification",xn]],["distilbert",["DistilBertForSequenceClassification",It]],["roberta",["RobertaForSequenceClassification",Hr]],["xlm",["XLMForSequenceClassification",ir]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ds]],["bart",["BartForSequenceClassification",Ve]],["mbart",["MBartForSequenceClassification",bt]],["mobilebert",["MobileBertForSequenceClassification",On]],["squeezebert",["SqueezeBertForSequenceClassification",vn]]]),Ed=new Map([["bert",["BertForTokenClassification",Qe]],["roformer",["RoFormerForTokenClassification",A]],["electra",["ElectraForTokenClassification",ar]],["esm",["EsmForTokenClassification",br]],["convbert",["ConvBertForTokenClassification",ot]],["camembert",["CamembertForTokenClassification",Xs]],["deberta",["DebertaForTokenClassification",Ys]],["deberta-v2",["DebertaV2ForTokenClassification",Rs]],["mpnet",["MPNetForTokenClassification",tn]],["distilbert",["DistilBertForTokenClassification",Wr]],["roberta",["RobertaForTokenClassification",hs]],["xlm",["XLMForTokenClassification",wr]],["xlm-roberta",["XLMRobertaForTokenClassification",kt]]]),ha=new Map([["t5",["T5ForConditionalGeneration",Nn]],["longt5",["LongT5ForConditionalGeneration",_r]],["mt5",["MT5ForConditionalGeneration",G]],["bart",["BartForConditionalGeneration",Ee]],["mbart",["MBartForConditionalGeneration",pt]],["marian",["MarianMTModel",Du]],["m2m_100",["M2M100ForConditionalGeneration",Ui]],["blenderbot",["BlenderbotForConditionalGeneration",Cr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ps]]]),ma=new Map([["bloom",["BloomForCausalLM",Ll]],["gpt2",["GPT2LMHeadModel",sl]],["jais",["JAISLMHeadModel",gc]],["gptj",["GPTJForCausalLM",ll]],["gpt_bigcode",["GPTBigCodeForCausalLM",dl]],["gpt_neo",["GPTNeoForCausalLM",_o]],["gpt_neox",["GPTNeoXForCausalLM",il]],["codegen",["CodeGenForCausalLM",pl]],["llama",["LlamaForCausalLM",ml]],["olmo",["OlmoForCausalLM",wl]],["mobilellm",["MobileLLMForCausalLM",_l]],["granite",["GraniteForCausalLM",ii]],["cohere",["CohereForCausalLM",bl]],["gemma",["GemmaForCausalLM",vl]],["gemma2",["Gemma2ForCausalLM",xl]],["openelm",["OpenELMForCausalLM",Pl]],["qwen2",["Qwen2ForCausalLM",Sl]],["phi",["PhiForCausalLM",Fl]],["phi3",["Phi3ForCausalLM",Ol]],["mpt",["MptForCausalLM",Bl]],["opt",["OPTForCausalLM",jl]],["mbart",["MBartForCausalLM",Kt]],["mistral",["MistralForCausalLM",Fc]],["starcoder2",["Starcoder2ForCausalLM",rd]],["falcon",["FalconForCausalLM",Oc]],["trocr",["TrOCRForCausalLM",ed]],["stablelm",["StableLmForCausalLM",Lc]]]),Vc=new Map([["multi_modality",["MultiModalityCausalLM",yd]]]),Pd=new Map([["bert",["BertForMaskedLM",Ce]],["roformer",["RoFormerForMaskedLM",ht]],["electra",["ElectraForMaskedLM",Tt]],["esm",["EsmForMaskedLM",Lr]],["convbert",["ConvBertForMaskedLM",ke]],["camembert",["CamembertForMaskedLM",os]],["deberta",["DebertaForMaskedLM",Ts]],["deberta-v2",["DebertaV2ForMaskedLM",Js]],["mpnet",["MPNetForMaskedLM",zn]],["albert",["AlbertForMaskedLM",Rn]],["distilbert",["DistilBertForMaskedLM",js]],["roberta",["RobertaForMaskedLM",gr]],["xlm",["XLMWithLMHeadModel",as]],["xlm-roberta",["XLMRobertaForMaskedLM",Os]],["mobilebert",["MobileBertForMaskedLM",po]],["squeezebert",["SqueezeBertForMaskedLM",cn]]]),Wc=new Map([["bert",["BertForQuestionAnswering",He]],["roformer",["RoFormerForQuestionAnswering",re]],["electra",["ElectraForQuestionAnswering",Mr]],["convbert",["ConvBertForQuestionAnswering",dt]],["camembert",["CamembertForQuestionAnswering",zs]],["deberta",["DebertaForQuestionAnswering",un]],["deberta-v2",["DebertaV2ForQuestionAnswering",ds]],["mpnet",["MPNetForQuestionAnswering",xs]],["albert",["AlbertForQuestionAnswering",Bn]],["distilbert",["DistilBertForQuestionAnswering",en]],["roberta",["RobertaForQuestionAnswering",Es]],["xlm",["XLMForQuestionAnswering",gt]],["xlm-roberta",["XLMRobertaForQuestionAnswering",mo]],["mobilebert",["MobileBertForQuestionAnswering",Dn]],["squeezebert",["SqueezeBertForQuestionAnswering",Tn]]]),fa=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Jt]]]),Gc=new Map([["llava",["LlavaForConditionalGeneration",Wn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Na]],["moondream1",["Moondream1ForConditionalGeneration",Ua]],["florence2",["Florence2ForConditionalGeneration",ms]],["qwen2-vl",["Qwen2VLForConditionalGeneration",kl]]]),Kc=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Jt]]]),Cd=new Map([["vit",["ViTForImageClassification",Ul]],["pvt",["PvtForImageClassification",Gl]],["vit_msn",["ViTMSNForImageClassification",ql]],["fastvit",["FastViTForImageClassification",Jl]],["mobilevit",["MobileViTForImageClassification",ru]],["mobilevitv2",["MobileViTV2ForImageClassification",gi]],["beit",["BeitForImageClassification",au]],["deit",["DeiTForImageClassification",wu]],["hiera",["HieraForImageClassification",yu]],["convnext",["ConvNextForImageClassification",qn]],["convnextv2",["ConvNextV2ForImageClassification",$u]],["dinov2",["Dinov2ForImageClassification",Tc]],["resnet",["ResNetForImageClassification",bu]],["swin",["SwinForImageClassification",bc]],["segformer",["SegformerForImageClassification",ad]],["efficientnet",["EfficientNetForImageClassification",cd]],["mobilenet_v1",["MobileNetV1ForImageClassification",Bc]],["mobilenet_v2",["MobileNetV2ForImageClassification",md]],["mobilenet_v3",["MobileNetV3ForImageClassification",Zn]],["mobilenet_v4",["MobileNetV4ForImageClassification",oa]]]),Sd=new Map([["detr",["DetrForObjectDetection",uu]],["rt_detr",["RTDetrForObjectDetection",pu]],["table-transformer",["TableTransformerForObjectDetection",fu]],["yolos",["YolosForObjectDetection",xc]]]),$d=new Map([["owlvit",["OwlViTForObjectDetection",Mi]],["owlv2",["Owlv2ForObjectDetection",ou]]]),kd=new Map([["detr",["DetrForSegmentation",Ti]],["clipseg",["CLIPSegForImageSegmentation",tl]]]),Ad=new Map([["segformer",["SegformerForSemanticSegmentation",ld]],["sapiens",["SapiensForSemanticSegmentation",Tu]]]),Id=new Map([["detr",["DetrForSegmentation",Ti]],["maskformer",["MaskFormerForInstanceSegmentation",Pu]]]),Hc=new Map([["sam",["SamModel",Fu]]]),eo=new Map([["wav2vec2",["Wav2Vec2ForCTC",Vi]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Gu]],["unispeech",["UniSpeechForCTC",ju]],["unispeech-sat",["UniSpeechSatForCTC",Uu]],["wavlm",["WavLMForCTC",Xu]],["hubert",["HubertForCTC",Hu]]]),_a=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Ec]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Ku]],["unispeech",["UniSpeechForSequenceClassification",Ki]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Vu]],["wavlm",["WavLMForSequenceClassification",Ac]],["hubert",["HubertForSequenceClassification",qu]],["audio-spectrogram-transformer",["ASTForAudioClassification",qo]]]),ga=new Map([["wavlm",["WavLMForXVector",Ao]]]),wa=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Wu]],["wavlm",["WavLMForAudioFrameClassification",Yn]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",zu]],["pyannote",["PyAnnoteForAudioFrameClassification",Bu]]]),ya=new Map([["vitmatte",["VitMatteForImageMatting",eu]]]),qc=new Map([["patchtst",["PatchTSTForPrediction",ua]],["patchtsmixer",["PatchTSMixerForPrediction",ca]]]),Fd=new Map([["swin2sr",["Swin2SRForImageSuperResolution",sn]]]),Ma=new Map([["dpt",["DPTForDepthEstimation",ts]],["depth_anything",["DepthAnythingForDepthEstimation",To]],["glpn",["GLPNForDepthEstimation",Cu]],["sapiens",["SapiensForDepthEstimation",xu]],["depth_pro",["DepthProForDepthEstimation",Ai]]]),ba=new Map([["sapiens",["SapiensForNormalEstimation",Eu]]]),Od=new Map([["vitpose",["VitPoseForPoseEstimation",Wl]]]),Dd=new Map([["clip",["CLIPVisionModelWithProjection",Ka]],["siglip",["SiglipVisionModel",Qa]],["jina_clip",["JinaCLIPVisionModel",Za]]]),va=[[jc,N.EncoderOnly],[Nc,N.EncoderDecoder],[Sp,N.DecoderOnly],[Uc,N.EncoderOnly],[Ed,N.EncoderOnly],[ha,N.Seq2Seq],[pa,N.Seq2Seq],[ma,N.DecoderOnly],[Vc,N.MultiModality],[Pd,N.EncoderOnly],[Wc,N.EncoderOnly],[fa,N.Vision2Seq],[Gc,N.ImageTextToText],[Cd,N.EncoderOnly],[kd,N.EncoderOnly],[Id,N.EncoderOnly],[Ad,N.EncoderOnly],[ya,N.EncoderOnly],[qc,N.EncoderOnly],[Fd,N.EncoderOnly],[Ma,N.EncoderOnly],[ba,N.EncoderOnly],[Od,N.EncoderOnly],[Sd,N.EncoderOnly],[$d,N.EncoderOnly],[Hc,N.MaskGeneration],[eo,N.EncoderOnly],[_a,N.EncoderOnly],[Td,N.Seq2Seq],[xd,N.EncoderOnly],[ga,N.EncoderOnly],[wa,N.EncoderOnly],[Dd,N.EncoderOnly]];for(const[f,S]of va)for(const[L,ve]of f.values())O.set(L,S),k.set(ve,L),_.set(L,ve);const Qc=[["MusicgenForConditionalGeneration",ra,N.Musicgen],["CLIPTextModelWithProjection",Ga,N.EncoderOnly],["SiglipTextModel",qa,N.EncoderOnly],["JinaCLIPTextModel",Ja,N.EncoderOnly],["ClapTextModelWithProjection",Dc,N.EncoderOnly],["ClapAudioModelWithProjection",od,N.EncoderOnly]];for(const[f,S,L]of Qc)O.set(f,L),k.set(S,f),_.set(f,S);class Ta extends yr{}Te(Ta,"MODEL_CLASS_MAPPINGS",va.map(S=>S[0])),Te(Ta,"BASE_IF_FAIL",!0);class xa extends yr{}Te(xa,"MODEL_CLASS_MAPPINGS",[Uc]);class Ld extends yr{}Te(Ld,"MODEL_CLASS_MAPPINGS",[Ed]);class zd extends yr{}Te(zd,"MODEL_CLASS_MAPPINGS",[ha]);class Bd extends yr{}Te(Bd,"MODEL_CLASS_MAPPINGS",[pa]);class Rd extends yr{}Te(Rd,"MODEL_CLASS_MAPPINGS",[Td]);class Xc extends yr{}Te(Xc,"MODEL_CLASS_MAPPINGS",[xd]);class jd extends yr{}Te(jd,"MODEL_CLASS_MAPPINGS",[ma]);class Nd extends yr{}Te(Nd,"MODEL_CLASS_MAPPINGS",[Pd]);class Ud extends yr{}Te(Ud,"MODEL_CLASS_MAPPINGS",[Wc]);class Vd extends yr{}Te(Vd,"MODEL_CLASS_MAPPINGS",[fa]);class Yc extends yr{}Te(Yc,"MODEL_CLASS_MAPPINGS",[Cd]);class Wd extends yr{}Te(Wd,"MODEL_CLASS_MAPPINGS",[kd]);class Gd extends yr{}Te(Gd,"MODEL_CLASS_MAPPINGS",[Ad]);class Kd extends yr{}Te(Kd,"MODEL_CLASS_MAPPINGS",[Id]);class Jc extends yr{}Te(Jc,"MODEL_CLASS_MAPPINGS",[Sd]);class Hd extends yr{}Te(Hd,"MODEL_CLASS_MAPPINGS",[$d]);class qd extends yr{}Te(qd,"MODEL_CLASS_MAPPINGS",[Hc]);class Qd extends yr{}Te(Qd,"MODEL_CLASS_MAPPINGS",[eo]);class Xd extends yr{}Te(Xd,"MODEL_CLASS_MAPPINGS",[_a]);class Yd extends yr{}Te(Yd,"MODEL_CLASS_MAPPINGS",[ga]);class Jd extends yr{}Te(Jd,"MODEL_CLASS_MAPPINGS",[wa]);class Zd extends yr{}Te(Zd,"MODEL_CLASS_MAPPINGS",[Kc]);class ec extends yr{}Te(ec,"MODEL_CLASS_MAPPINGS",[ya]);class tc extends yr{}Te(tc,"MODEL_CLASS_MAPPINGS",[Fd]);class rc extends yr{}Te(rc,"MODEL_CLASS_MAPPINGS",[Ma]);class sc extends yr{}Te(sc,"MODEL_CLASS_MAPPINGS",[ba]);class Ea extends yr{}Te(Ea,"MODEL_CLASS_MAPPINGS",[Od]);class nc extends yr{}Te(nc,"MODEL_CLASS_MAPPINGS",[Dd]);class Zc extends je{constructor({logits:S,past_key_values:L,encoder_outputs:ve,decoder_attentions:Fe=null,cross_attentions:Ae=null}){super(),this.logits=S,this.past_key_values=L,this.encoder_outputs=ve,this.decoder_attentions=Fe,this.cross_attentions=Ae}}class er extends je{constructor({logits:S}){super(),this.logits=S}}class oc extends je{constructor({logits:S,embeddings:L}){super(),this.logits=S,this.embeddings=L}}class Qr extends je{constructor({logits:S}){super(),this.logits=S}}class Jr extends je{constructor({logits:S}){super(),this.logits=S}}class ss extends je{constructor({start_logits:S,end_logits:L}){super(),this.start_logits=S,this.end_logits=L}}class Sn extends je{constructor({logits:S}){super(),this.logits=S}}class ep extends je{constructor({logits:S,past_key_values:L}){super(),this.logits=S,this.past_key_values=L}}class ic extends je{constructor({alphas:S}){super(),this.alphas=S}}class ac extends je{constructor({waveform:S,spectrogram:L}){super(),this.waveform=S,this.spectrogram=L}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(Oe,B,c)=>{c.r(B),c.d(B,{ASTFeatureExtractor:()=>H});var w=c("./src/base/feature_extraction_utils.js");c("./src/utils/tensor.js");var R=c("./src/utils/audio.js");class H extends w.FeatureExtractor{constructor(q){super(q);const g=this.config.sampling_rate,x=(0,R.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let E=0;E{c.r(B),c.d(B,{AutoFeatureExtractor:()=>J});var w=c("./src/utils/constants.js"),R=c("./src/utils/hub.js");c("./src/base/feature_extraction_utils.js");var H=c("./src/models/feature_extractors.js");class J{static async from_pretrained(g,x={}){const E=await(0,R.getModelJSON)(g,w.FEATURE_EXTRACTOR_NAME,!0,x),$=E.feature_extractor_type,P=H[$];if(!P)throw new Error(`Unknown feature_extractor_type: '${$}'. Please report this at ${w.GITHUB_ISSUE_URL}.`);return new P(E)}}},"./src/models/auto/image_processing_auto.js":(Oe,B,c)=>{c.r(B),c.d(B,{AutoImageProcessor:()=>q});var w=c("./src/utils/constants.js"),R=c("./src/utils/hub.js"),H=c("./src/base/image_processors_utils.js"),J=c("./src/models/image_processors.js");class q{static async from_pretrained(x,E={}){const $=await(0,R.getModelJSON)(x,w.IMAGE_PROCESSOR_NAME,!0,E),P=$.image_processor_type??$.feature_extractor_type;let Y=J[P];return Y||(P!==void 0&&console.warn(`Image processor type '${P}' not found, assuming base ImageProcessor. Please report this at ${w.GITHUB_ISSUE_URL}.`),Y=H.ImageProcessor),new Y($)}}},"./src/models/auto/processing_auto.js":(Oe,B,c)=>{c.r(B),c.d(B,{AutoProcessor:()=>x});var w=c("./src/utils/constants.js"),R=c("./src/utils/hub.js"),H=c("./src/base/processing_utils.js"),J=c("./src/models/processors.js"),q=c("./src/models/image_processors.js"),g=c("./src/models/feature_extractors.js");class x{static async from_pretrained($,P={}){const Y=await(0,R.getModelJSON)($,w.IMAGE_PROCESSOR_NAME,!0,P),{image_processor_type:se,feature_extractor_type:ue,processor_class:le}=Y;if(le&&J[le])return J[le].from_pretrained($,P);if(!se&&!ue)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const U={};if(se){const ne=q[se];if(!ne)throw new Error(`Unknown image_processor_type: '${se}'.`);U.image_processor=new ne(Y)}if(ue){const ne=q[ue];if(ne)U.image_processor=new ne(Y);else{const N=g[ue];if(!N)throw new Error(`Unknown feature_extractor_type: '${ue}'.`);U.feature_extractor=new N(Y)}}const Q={};return new H.Processor(Q,U)}}},"./src/models/beit/image_processing_beit.js":(Oe,B,c)=>{c.r(B),c.d(B,{BeitFeatureExtractor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(Oe,B,c)=>{c.r(B),c.d(B,{BitImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(Oe,B,c)=>{c.r(B),c.d(B,{ChineseCLIPFeatureExtractor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(Oe,B,c)=>{c.r(B),c.d(B,{ClapFeatureExtractor:()=>H});var w=c("./src/base/feature_extraction_utils.js");c("./src/utils/tensor.js");var R=c("./src/utils/audio.js");class H extends w.FeatureExtractor{constructor(q){super(q),this.mel_filters=(0,R.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,R.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,R.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(q,g,x,E){let $;const P=q.length-g;if(P>0)if(x==="rand_trunc"){const Y=Math.floor(Math.random()*(P+1));q=q.subarray(Y,Y+g),$=await this._extract_fbank_features(q,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${x}" not implemented`);else{if(P<0){let Y=new Float64Array(g);if(Y.set(q),E==="repeat")for(let se=q.length;se{c.r(B),c.d(B,{CLIPFeatureExtractor:()=>H,CLIPImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/convnext/image_processing_convnext.js":(Oe,B,c)=>{c.r(B),c.d(B,{ConvNextFeatureExtractor:()=>H,ConvNextImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{constructor(q){super(q),this.crop_pct=this.config.crop_pct??.875}async resize(q){var x;const g=(x=this.size)==null?void 0:x.shortest_edge;if(g===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(g<384){const E=Math.floor(g/this.crop_pct),[$,P]=this.get_resize_output_image_size(q,{shortest_edge:E});q=await q.resize($,P,{resample:this.resample}),q=await q.center_crop(g,g)}else q=await q.resize(g,g,{resample:this.resample});return q}}class H extends R{}},"./src/models/deit/image_processing_deit.js":(Oe,B,c)=>{c.r(B),c.d(B,{DeiTFeatureExtractor:()=>H,DeiTImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/detr/image_processing_detr.js":(Oe,B,c)=>{c.r(B),c.d(B,{DetrFeatureExtractor:()=>J,DetrImageProcessor:()=>H});var w=c("./src/base/image_processors_utils.js"),R=c("./src/utils/tensor.js");class H extends w.ImageProcessor{async _call(g){const x=await super._call(g),E=[x.pixel_values.dims[0],64,64],$=(0,R.full)(E,1n);return{...x,pixel_mask:$}}post_process_object_detection(...g){return(0,w.post_process_object_detection)(...g)}post_process_panoptic_segmentation(...g){return(0,w.post_process_panoptic_segmentation)(...g)}post_process_instance_segmentation(...g){return(0,w.post_process_instance_segmentation)(...g)}}class J extends H{}},"./src/models/donut/image_processing_donut.js":(Oe,B,c)=>{c.r(B),c.d(B,{DonutFeatureExtractor:()=>H,DonutImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{pad_image(q,g,x,E={}){const[$,P,Y]=g;let se=this.image_mean;Array.isArray(this.image_mean)||(se=new Array(Y).fill(se));let ue=this.image_std;Array.isArray(ue)||(ue=new Array(Y).fill(se));const le=se.map((U,Q)=>-U/ue[Q]);return super.pad_image(q,g,x,{center:!0,constant_values:le,...E})}}class H extends R{}},"./src/models/dpt/image_processing_dpt.js":(Oe,B,c)=>{c.r(B),c.d(B,{DPTFeatureExtractor:()=>H,DPTImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/efficientnet/image_processing_efficientnet.js":(Oe,B,c)=>{c.r(B),c.d(B,{EfficientNetImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{constructor(J){super(J),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(q=>q*q))}}},"./src/models/feature_extractors.js":(Oe,B,c)=>{c.r(B),c.d(B,{ASTFeatureExtractor:()=>w.ASTFeatureExtractor,ClapFeatureExtractor:()=>R.ClapFeatureExtractor,ImageFeatureExtractor:()=>$.ImageProcessor,PyAnnoteFeatureExtractor:()=>H.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>J.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>q.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>g.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>x.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>E.WhisperFeatureExtractor});var w=c("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),R=c("./src/models/clap/feature_extraction_clap.js"),H=c("./src/models/pyannote/feature_extraction_pyannote.js"),J=c("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),q=c("./src/models/speecht5/feature_extraction_speecht5.js"),g=c("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),x=c("./src/models/wespeaker/feature_extraction_wespeaker.js"),E=c("./src/models/whisper/feature_extraction_whisper.js"),$=c("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(Oe,B,c)=>{c.r(B),c.d(B,{Florence2Processor:()=>J});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/image_processing_auto.js"),H=c("./src/tokenizers.js");class J extends w.Processor{constructor(g,x){super(g,x);const{tasks_answer_post_processing_type:E,task_prompts_without_inputs:$,task_prompts_with_input:P}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(E??{})),this.task_prompts_without_inputs=new Map(Object.entries($??{})),this.task_prompts_with_input=new Map(Object.entries(P??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(g){typeof g=="string"&&(g=[g]);const x=[];for(const E of g)if(this.task_prompts_without_inputs.has(E))x.push(this.task_prompts_without_inputs.get(E));else{for(const[$,P]of this.task_prompts_with_input)if(E.includes($)){x.push(P.replaceAll("{input}",E).replaceAll($,""));break}x.length!==g.length&&x.push(E)}return x}post_process_generation(g,x,E){const $=this.tasks_answer_post_processing_type.get(x)??"pure_text";g=g.replaceAll("","").replaceAll("","");let P;switch($){case"pure_text":P=g;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Y=$==="ocr"?"quad_boxes":"bboxes",se=g.matchAll(this.regexes[Y]),ue=[],le=[];for(const[U,Q,...ne]of se)ue.push(Q?Q.trim():ue.at(-1)??""),le.push(ne.map((N,O)=>(Number(N)+.5)/this.size_per_bin*E[O%2]));P={labels:ue,[Y]:le};break;default:throw new Error(`Task "${x}" (of type "${$}") not yet implemented.`)}return{[x]:P}}async _call(g,x=null,E={}){if(!g&&!x)throw new Error("Either text or images must be provided");const $=await this.image_processor(g,E),P=x?this.tokenizer(x,E):{};return{...$,...P}}}Te(J,"tokenizer_class",H.AutoTokenizer),Te(J,"image_processor_class",R.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(Oe,B,c)=>{c.r(B),c.d(B,{GLPNFeatureExtractor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}},"./src/models/image_processors.js":(Oe,B,c)=>{c.r(B),c.d(B,{BeitFeatureExtractor:()=>w.BeitFeatureExtractor,BitImageProcessor:()=>R.BitImageProcessor,CLIPFeatureExtractor:()=>J.CLIPFeatureExtractor,CLIPImageProcessor:()=>J.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>H.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>q.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>q.ConvNextImageProcessor,DPTFeatureExtractor:()=>$.DPTFeatureExtractor,DPTImageProcessor:()=>$.DPTImageProcessor,DeiTFeatureExtractor:()=>g.DeiTFeatureExtractor,DeiTImageProcessor:()=>g.DeiTImageProcessor,DetrFeatureExtractor:()=>x.DetrFeatureExtractor,DetrImageProcessor:()=>x.DetrImageProcessor,DonutFeatureExtractor:()=>E.DonutFeatureExtractor,DonutImageProcessor:()=>E.DonutImageProcessor,EfficientNetImageProcessor:()=>P.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>Y.GLPNFeatureExtractor,JinaCLIPImageProcessor:()=>ue.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>le.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>U.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>Q.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>Q.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>ne.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>ne.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>N.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>N.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>O.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>O.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>k.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>k.MobileViTImageProcessor,NougatImageProcessor:()=>C.NougatImageProcessor,OwlViTFeatureExtractor:()=>ee.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>ee.OwlViTImageProcessor,Owlv2ImageProcessor:()=>Z.Owlv2ImageProcessor,PvtImageProcessor:()=>_e.PvtImageProcessor,Qwen2VLImageProcessor:()=>ge.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>be.RTDetrImageProcessor,SamImageProcessor:()=>Se.SamImageProcessor,SegformerFeatureExtractor:()=>Pe.SegformerFeatureExtractor,SegformerImageProcessor:()=>Pe.SegformerImageProcessor,SiglipImageProcessor:()=>Le.SiglipImageProcessor,Swin2SRImageProcessor:()=>me.Swin2SRImageProcessor,VLMImageProcessor:()=>se.VLMImageProcessor,ViTFeatureExtractor:()=>j.ViTFeatureExtractor,ViTImageProcessor:()=>j.ViTImageProcessor,VitMatteImageProcessor:()=>he.VitMatteImageProcessor,VitPoseImageProcessor:()=>pe.VitPoseImageProcessor,YolosFeatureExtractor:()=>$e.YolosFeatureExtractor,YolosImageProcessor:()=>$e.YolosImageProcessor});var w=c("./src/models/beit/image_processing_beit.js"),R=c("./src/models/bit/image_processing_bit.js"),H=c("./src/models/chinese_clip/image_processing_chinese_clip.js"),J=c("./src/models/clip/image_processing_clip.js"),q=c("./src/models/convnext/image_processing_convnext.js"),g=c("./src/models/deit/image_processing_deit.js"),x=c("./src/models/detr/image_processing_detr.js"),E=c("./src/models/donut/image_processing_donut.js"),$=c("./src/models/dpt/image_processing_dpt.js"),P=c("./src/models/efficientnet/image_processing_efficientnet.js"),Y=c("./src/models/glpn/image_processing_glpn.js"),se=c("./src/models/janus/image_processing_janus.js"),ue=c("./src/models/jina_clip/image_processing_jina_clip.js"),le=c("./src/models/llava_onevision/image_processing_llava_onevision.js"),U=c("./src/models/mask2former/image_processing_mask2former.js"),Q=c("./src/models/maskformer/image_processing_maskformer.js"),ne=c("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),N=c("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),O=c("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),_=c("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),k=c("./src/models/mobilevit/image_processing_mobilevit.js"),C=c("./src/models/nougat/image_processing_nougat.js"),Z=c("./src/models/owlv2/image_processing_owlv2.js"),ee=c("./src/models/owlvit/image_processing_owlvit.js"),_e=c("./src/models/pvt/image_processing_pvt.js"),ge=c("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),be=c("./src/models/rt_detr/image_processing_rt_detr.js"),Se=c("./src/models/sam/image_processing_sam.js"),Pe=c("./src/models/segformer/image_processing_segformer.js"),Le=c("./src/models/siglip/image_processing_siglip.js"),me=c("./src/models/swin2sr/image_processing_swin2sr.js"),j=c("./src/models/vit/image_processing_vit.js"),he=c("./src/models/vitmatte/image_processing_vitmatte.js"),pe=c("./src/models/vitpose/image_processing_vitpose.js"),$e=c("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(Oe,B,c)=>{c.r(B),c.d(B,{VLMImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{constructor(J){super({do_pad:!0,pad_size:{width:J.image_size,height:J.image_size},...J}),this.constant_values=this.config.background_color.map(q=>q*this.rescale_factor)}pad_image(J,q,g,x){return super.pad_image(J,q,g,{constant_values:this.constant_values,center:!0,...x})}}},"./src/models/janus/processing_janus.js":(Oe,B,c)=>{c.r(B),c.d(B,{VLChatProcessor:()=>x});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/image_processing_auto.js"),H=c("./src/tokenizers.js"),J=c("./src/utils/core.js"),q=c("./src/utils/tensor.js"),g=c("./src/utils/image.js");class x extends w.Processor{constructor($,P){super($,P),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($,{images:P=null,chat_template:Y="default"}={}){P?Array.isArray(P)||(P=[P]):P=await Promise.all($.filter(ee=>ee.images).flatMap(ee=>ee.images).map(ee=>g.RawImage.read(ee)));const se=this.tokenizer,ue=se.apply_chat_template($,{tokenize:!1,add_generation_prompt:!0,chat_template:Y}),le=ee=>se.encode(ee,{add_special_tokens:!1}),U=ue.split(this.image_tag),Q=U.length-1;if(P.length!==Q)throw new Error(`Number of images provided (${P.length}) does not match number of "${this.image_tag}" image tags (${Q})`);const[ne,N,O]=se.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let _=le(U[0]),k=new Array(_.length).fill(!1);for(let ee=1;ee0){const ee=await this.image_processor(P);return ee.pixel_values.unsqueeze_(0),{...Z,...ee}}return Z}}Te(x,"image_processor_class",R.AutoImageProcessor),Te(x,"tokenizer_class",H.AutoTokenizer),Te(x,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(Oe,B,c)=>{c.r(B),c.d(B,{JinaCLIPImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{constructor(J){const{resize_mode:q,fill_color:g,interpolation:x,size:E,...$}=J,P=q==="squash"?{width:E,height:E}:q==="shortest"?{shortest_edge:E}:{longest_edge:E},Y=x==="bicubic"?3:2;super({...$,size:P,resample:Y,do_center_crop:!0,crop_size:E,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(Oe,B,c)=>{c.r(B),c.d(B,{JinaCLIPProcessor:()=>J});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/image_processing_auto.js"),H=c("./src/tokenizers.js");class J extends w.Processor{async _call(g=null,x=null,E={}){if(!g&&!x)throw new Error("Either text or images must be provided");const $=g?this.tokenizer(g,E):{},P=x?await this.image_processor(x,E):{};return{...$,...P}}}Te(J,"tokenizer_class",H.AutoTokenizer),Te(J,"image_processor_class",R.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(Oe,B,c)=>{c.r(B),c.d(B,{LlavaOnevisionImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(Oe,B,c)=>{c.r(B),c.d(B,{Mask2FormerImageProcessor:()=>R});var w=c("./src/models/maskformer/image_processing_maskformer.js");class R extends w.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(Oe,B,c)=>{c.r(B),c.d(B,{MaskFormerFeatureExtractor:()=>H,MaskFormerImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{post_process_panoptic_segmentation(...q){return(0,w.post_process_panoptic_segmentation)(...q)}post_process_instance_segmentation(...q){return(0,w.post_process_instance_segmentation)(...q)}}class H extends R{}},"./src/models/mgp_str/processing_mgp_str.js":(Oe,B,c)=>{c.r(B),c.d(B,{MgpstrProcessor:()=>g});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/image_processing_auto.js"),H=c("./src/tokenizers.js"),J=c("./src/utils/maths.js");const q={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class g extends w.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(E,$){if(!q.hasOwnProperty($))throw new Error(`Format ${$} is not supported.`);const[P,Y]=q[$],se=this[P].bind(this),[ue,le]=E.dims,U=[],Q=[],ne=E.tolist();for(let O=0;O0?C.reduce((ee,_e)=>ee*_e,1):0;Q.push(k),U.push(Z)}return[se(Q),U]}char_decode(E){return this.char_tokenizer.batch_decode(E).map($=>$.replaceAll(" ",""))}bpe_decode(E){return this.bpe_tokenizer.batch_decode(E)}wp_decode(E){return this.wp_tokenizer.batch_decode(E).map($=>$.replaceAll(" ",""))}batch_decode([E,$,P]){const[Y,se]=this._decode_helper(E,"char"),[ue,le]=this._decode_helper($,"bpe"),[U,Q]=this._decode_helper(P,"wp"),ne=[],N=[];for(let O=0;O{c.r(B),c.d(B,{MobileNetV1FeatureExtractor:()=>H,MobileNetV1ImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(Oe,B,c)=>{c.r(B),c.d(B,{MobileNetV2FeatureExtractor:()=>H,MobileNetV2ImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(Oe,B,c)=>{c.r(B),c.d(B,{MobileNetV3FeatureExtractor:()=>H,MobileNetV3ImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(Oe,B,c)=>{c.r(B),c.d(B,{MobileNetV4FeatureExtractor:()=>H,MobileNetV4ImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/mobilevit/image_processing_mobilevit.js":(Oe,B,c)=>{c.r(B),c.d(B,{MobileViTFeatureExtractor:()=>H,MobileViTImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/nougat/image_processing_nougat.js":(Oe,B,c)=>{c.r(B),c.d(B,{NougatImageProcessor:()=>R});var w=c("./src/models/donut/image_processing_donut.js");class R extends w.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(Oe,B,c)=>{c.r(B),c.d(B,{Owlv2ImageProcessor:()=>R});var w=c("./src/models/owlvit/image_processing_owlvit.js");class R extends w.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(Oe,B,c)=>{c.r(B),c.d(B,{OwlViTFeatureExtractor:()=>H,OwlViTImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{post_process_object_detection(...q){return(0,w.post_process_object_detection)(...q)}}class H extends R{}},"./src/models/owlvit/processing_owlvit.js":(Oe,B,c)=>{c.r(B),c.d(B,{OwlViTProcessor:()=>J});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/image_processing_auto.js"),H=c("./src/tokenizers.js");class J extends w.Processor{}Te(J,"tokenizer_class",H.AutoTokenizer),Te(J,"image_processor_class",R.AutoImageProcessor)},"./src/models/processors.js":(Oe,B,c)=>{c.r(B),c.d(B,{Florence2Processor:()=>w.Florence2Processor,JinaCLIPProcessor:()=>J.JinaCLIPProcessor,MgpstrProcessor:()=>R.MgpstrProcessor,OwlViTProcessor:()=>q.OwlViTProcessor,PyAnnoteProcessor:()=>g.PyAnnoteProcessor,Qwen2VLProcessor:()=>x.Qwen2VLProcessor,SamProcessor:()=>E.SamProcessor,SpeechT5Processor:()=>$.SpeechT5Processor,VLChatProcessor:()=>H.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>P.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>Y.WhisperProcessor});var w=c("./src/models/florence2/processing_florence2.js"),R=c("./src/models/mgp_str/processing_mgp_str.js"),H=c("./src/models/janus/processing_janus.js"),J=c("./src/models/jina_clip/processing_jina_clip.js"),q=c("./src/models/owlvit/processing_owlvit.js"),g=c("./src/models/pyannote/processing_pyannote.js"),x=c("./src/models/qwen2_vl/processing_qwen2_vl.js"),E=c("./src/models/sam/processing_sam.js"),$=c("./src/models/speecht5/processing_speecht5.js"),P=c("./src/models/wav2vec2/processing_wav2vec2.js"),Y=c("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(Oe,B,c)=>{c.r(B),c.d(B,{PvtImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(Oe,B,c)=>{c.r(B),c.d(B,{PyAnnoteFeatureExtractor:()=>H});var w=c("./src/base/feature_extraction_utils.js"),R=c("./src/utils/tensor.js");class H extends w.FeatureExtractor{async _call(q){(0,w.validate_audio_inputs)(q,"PyAnnoteFeatureExtractor"),q instanceof Float64Array&&(q=new Float32Array(q));const g=[1,1,q.length];return{input_values:new R.Tensor("float32",q,g)}}}},"./src/models/pyannote/processing_pyannote.js":(Oe,B,c)=>{c.r(B),c.d(B,{PyAnnoteProcessor:()=>J});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/feature_extraction_auto.js"),H=c("./src/utils/maths.js");class J extends w.Processor{async _call(g){return await this.feature_extractor(g)}samples_to_frames(g){return(g-this.config.offset)/this.config.step}post_process_speaker_diarization(g,x){const E=x/this.samples_to_frames(x)/this.config.sampling_rate,$=[];for(const P of g.tolist()){const Y=[];let se=-1;for(let ue=0;ue({id:ue,start:le*E,end:U*E,confidence:Q/(U-le)})))}return $}}Te(J,"feature_extractor_class",R.AutoFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(Oe,B,c)=>{c.r(B),c.d(B,{Qwen2VLImageProcessor:()=>H});var w=c("./src/base/image_processors_utils.js"),R=c("./src/utils/tensor.js");class H extends w.ImageProcessor{async _call(q,...g){const{pixel_values:x,original_sizes:E,reshaped_input_sizes:$}=await super._call(q,...g);let P=x;const{temporal_patch_size:Y,merge_size:se,patch_size:ue}=this.config;P.dims[0]===1&&(P=(0,R.cat)(Array.from({length:Y},()=>P),0));const le=P.dims[0]/Y,U=P.dims[1],Q=Math.floor(P.dims[2]/ue),ne=Math.floor(P.dims[3]/ue),N=P.view(le,Y,U,Math.floor(Q/se),se,ue,Math.floor(ne/se),se,ue).permute(0,3,6,4,7,2,1,5,8).view(le*Q*ne,U*Y*ue*ue),O=new R.Tensor("int64",[le,Q,ne],[1,3]);return{pixel_values:N,image_grid_thw:O,original_sizes:E,reshaped_input_sizes:$}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(Oe,B,c)=>{c.r(B),c.d(B,{Qwen2VLProcessor:()=>J});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/image_processing_auto.js"),H=c("./src/tokenizers.js");c("./src/utils/image.js");class J extends w.Processor{async _call(g,x=null,...E){Array.isArray(g)||(g=[g]);let $,P;if(x&&($=await this.image_processor(x),P=$.image_grid_thw),P){let se=this.image_processor.config.merge_size**2,ue=0;const le=P.tolist();g=g.map(U=>{for(;U.includes("<|image_pad|>");){const Q=Number(le[ue++].reduce((ne,N)=>ne*N,1n));U=U.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(Q/se)))}return U.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(g),...$}}}Te(J,"image_processor_class",R.AutoImageProcessor),Te(J,"tokenizer_class",H.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(Oe,B,c)=>{c.r(B),c.d(B,{RTDetrImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{post_process_object_detection(...J){return(0,w.post_process_object_detection)(...J)}}},"./src/models/sam/image_processing_sam.js":(Oe,B,c)=>{c.r(B),c.d(B,{SamImageProcessor:()=>J});var w=c("./src/base/image_processors_utils.js"),R=c("./src/utils/core.js"),H=c("./src/utils/tensor.js");class J extends w.ImageProcessor{reshape_input_points(g,x,E,$=!1){g=structuredClone(g);let P=(0,R.calculateDimensions)(g);if(P.length===3)$||(P=[1,...P]),g=[g];else if(P.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 Y=0;Y$!==x.dims[P]))throw Error(`The first ${E.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new H.Tensor("int64",g.flat(1/0).map(BigInt),E)}async _call(g,{input_points:x=null,input_labels:E=null,input_boxes:$=null}={}){const P=await super._call(g);if(x&&(P.input_points=this.reshape_input_points(x,P.original_sizes,P.reshaped_input_sizes)),E){if(!P.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");P.input_labels=this.add_input_labels(E,P.input_points)}return $&&(P.input_boxes=this.reshape_input_points($,P.original_sizes,P.reshaped_input_sizes,!0)),P}async post_process_masks(g,x,E,{mask_threshold:$=0,binarize:P=!0,pad_size:Y=null}={}){const se=[];Y=Y??this.pad_size;const ue=[Y.height,Y.width];for(let le=0;le$&&(O[_]=1);ne=new H.Tensor("bool",O,ne.dims)}se.push(ne)}return se}generate_crop_boxes(g,x,{crop_n_layers:E=0,overlap_ratio:$=.3413333333333333,points_per_crop:P=32,crop_n_points_downscale_factor:Y=1}={}){}}},"./src/models/sam/processing_sam.js":(Oe,B,c)=>{c.r(B),c.d(B,{SamProcessor:()=>H});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/image_processing_auto.js");class H extends w.Processor{async _call(...q){return await this.image_processor(...q)}post_process_masks(...q){return this.image_processor.post_process_masks(...q)}reshape_input_points(...q){return this.image_processor.reshape_input_points(...q)}}Te(H,"image_processor_class",R.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(Oe,B,c)=>{c.r(B),c.d(B,{SeamlessM4TFeatureExtractor:()=>J});var w=c("./src/base/feature_extraction_utils.js"),R=c("./src/utils/tensor.js"),H=c("./src/utils/audio.js");class J extends w.FeatureExtractor{constructor(g){super(g);const x=this.config.sampling_rate,E=(0,H.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(x/2),x,null,"kaldi",!0);for(let $=0;$E*32768),(0,H.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:x,transpose:!0})}async _call(g,{padding:x=!0,pad_to_multiple_of:E=2,do_normalize_per_mel_bins:$=!0,return_attention_mask:P=!0}={}){(0,w.validate_audio_inputs)(g,"SeamlessM4TFeatureExtractor");let Y=await this._extract_fbank_features(g,this.config.max_length);if($){const[O,_]=Y.dims,k=Y.data;for(let C=0;C<_;++C){let Z=0;for(let be=0;be0){const Z=new Float32Array(_*(O+C));Z.set(k),Z.fill(this.config.padding_value,k.length);const ee=O+C;Y=new R.Tensor(Y.type,Z,[ee,_]),P&&(se=new R.Tensor("int64",new BigInt64Array(ee),[1,ee]),se.data.fill(1n,0,O))}}const[ue,le]=Y.dims,U=this.config.stride;if(ue%U!==0)throw new Error(`The number of frames (${ue}) must be a multiple of the stride (${U}).`);const ne=Y.view(1,Math.floor(ue/U),le*U),N={input_features:ne};if(P){const O=ne.dims[1],_=new BigInt64Array(O);if(se){const k=se.data;for(let C=1,Z=0;C{c.r(B),c.d(B,{SegformerFeatureExtractor:()=>H,SegformerImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{post_process_semantic_segmentation(...q){return(0,w.post_process_semantic_segmentation)(...q)}}class H extends R{}},"./src/models/siglip/image_processing_siglip.js":(Oe,B,c)=>{c.r(B),c.d(B,{SiglipImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(Oe,B,c)=>{c.r(B),c.d(B,{SpeechT5FeatureExtractor:()=>R});var w=c("./src/base/feature_extraction_utils.js");class R extends w.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(Oe,B,c)=>{c.r(B),c.d(B,{SpeechT5Processor:()=>J});var w=c("./src/base/processing_utils.js"),R=c("./src/tokenizers.js"),H=c("./src/models/auto/feature_extraction_auto.js");class J extends w.Processor{async _call(g){return await this.feature_extractor(g)}}Te(J,"tokenizer_class",R.AutoTokenizer),Te(J,"feature_extractor_class",H.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(Oe,B,c)=>{c.r(B),c.d(B,{Swin2SRImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{pad_image(J,q,g,x={}){const[E,$,P]=q;return super.pad_image(J,q,{width:$+(g-$%g)%g,height:E+(g-E%g)%g},{mode:"symmetric",center:!1,constant_values:-1,...x})}}},"./src/models/vit/image_processing_vit.js":(Oe,B,c)=>{c.r(B),c.d(B,{ViTFeatureExtractor:()=>H,ViTImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{}class H extends R{}},"./src/models/vitmatte/image_processing_vitmatte.js":(Oe,B,c)=>{c.r(B),c.d(B,{VitMatteImageProcessor:()=>H});var w=c("./src/base/image_processors_utils.js"),R=c("./src/utils/tensor.js");class H extends w.ImageProcessor{async _call(q,g){Array.isArray(q)||(q=[q]),Array.isArray(g)||(g=[g]);const x=await Promise.all(q.map(P=>this.preprocess(P))),E=await Promise.all(g.map(P=>this.preprocess(P,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,R.stack)(x.map((P,Y)=>(0,R.cat)([P.pixel_values,E[Y].pixel_values],0)),0),original_sizes:x.map(P=>P.original_size),reshaped_input_sizes:x.map(P=>P.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(Oe,B,c)=>{c.r(B),c.d(B,{VitPoseImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{post_process_pose_estimation(J,q,{threshold:g=null}={}){const x=J.tolist(),[E,$,P,Y]=J.dims,se=[];for(let ue=0;ue{c.r(B),c.d(B,{Wav2Vec2FeatureExtractor:()=>H});var w=c("./src/base/feature_extraction_utils.js"),R=c("./src/utils/tensor.js");class H extends w.FeatureExtractor{_zero_mean_unit_var_norm(q){const x=q.reduce(($,P)=>$+P,0)/q.length,E=q.reduce(($,P)=>$+(P-x)**2,0)/q.length;return q.map($=>($-x)/Math.sqrt(E+1e-7))}async _call(q){(0,w.validate_audio_inputs)(q,"Wav2Vec2FeatureExtractor"),q instanceof Float64Array&&(q=new Float32Array(q));let g=q;this.config.do_normalize&&(g=this._zero_mean_unit_var_norm(g));const x=[1,g.length];return{input_values:new R.Tensor("float32",g,x),attention_mask:new R.Tensor("int64",new BigInt64Array(g.length).fill(1n),x)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(Oe,B,c)=>{c.r(B),c.d(B,{Wav2Vec2ProcessorWithLM:()=>H});var w=c("./src/base/processing_utils.js"),R=c("./src/models/auto/feature_extraction_auto.js");class H extends w.Processor{async _call(q){return await this.feature_extractor(q)}}Te(H,"feature_extractor_class",R.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(Oe,B,c)=>{c.r(B),c.d(B,{WeSpeakerFeatureExtractor:()=>H});var w=c("./src/base/feature_extraction_utils.js");c("./src/utils/tensor.js");var R=c("./src/utils/audio.js");class H extends w.FeatureExtractor{constructor(q){super(q);const g=this.config.sampling_rate,x=(0,R.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let E=0;Eg*32768),(0,R.spectrogram)(q,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(q){(0,w.validate_audio_inputs)(q,"WeSpeakerFeatureExtractor");const g=(await this._extract_fbank_features(q)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const x=g.mean(1).data,E=g.data,[$,P,Y]=g.dims;for(let se=0;se<$;++se){const ue=se*P*Y,le=se*Y;for(let U=0;U{c.r(B),c.d(B,{WHISPER_LANGUAGE_MAPPING:()=>R,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>H,whisper_language_to_code:()=>J});const w=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],R=new Map(w),H=new Map([...w.map(([q,g])=>[g,q]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function J(q){q=q.toLowerCase();let g=H.get(q);if(g===void 0)if(R.has(q))g=q;else{const E=q.length===2?R.keys():R.values();throw new Error(`Language "${q}" is not supported. Must be one of: ${JSON.stringify(E)}`)}return g}},"./src/models/whisper/feature_extraction_whisper.js":(Oe,B,c)=>{c.r(B),c.d(B,{WhisperFeatureExtractor:()=>J});var w=c("./src/base/feature_extraction_utils.js");c("./src/utils/tensor.js");var R=c("./src/utils/audio.js"),H=c("./src/utils/maths.js");class J extends w.FeatureExtractor{constructor(g){var x;super(g),(x=this.config).mel_filters??(x.mel_filters=(0,R.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,R.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(g){const x=await(0,R.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}),E=x.data,$=(0,H.max)(E)[0];for(let P=0;Pthis.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`."),x=g.slice(0,this.config.n_samples)):(x=new Float32Array(this.config.n_samples),x.set(g)),{input_features:(await this._extract_fbank_features(x)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(Oe,B,c)=>{c.r(B),c.d(B,{WhisperGenerationConfig:()=>R});var w=c("./src/generation/configuration_utils.js");class R extends w.GenerationConfig{constructor(){super(...arguments);Te(this,"return_timestamps",null);Te(this,"return_token_timestamps",null);Te(this,"num_frames",null);Te(this,"alignment_heads",null);Te(this,"task",null);Te(this,"language",null);Te(this,"no_timestamps_token_id",null);Te(this,"prompt_ids",null);Te(this,"is_multilingual",null);Te(this,"lang_to_id",null);Te(this,"task_to_id",null);Te(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(Oe,B,c)=>{c.r(B),c.d(B,{WhisperProcessor:()=>J});var w=c("./src/models/auto/feature_extraction_auto.js"),R=c("./src/tokenizers.js"),H=c("./src/base/processing_utils.js");class J extends H.Processor{async _call(g){return await this.feature_extractor(g)}}Te(J,"tokenizer_class",R.AutoTokenizer),Te(J,"feature_extractor_class",w.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(Oe,B,c)=>{c.r(B),c.d(B,{YolosFeatureExtractor:()=>H,YolosImageProcessor:()=>R});var w=c("./src/base/image_processors_utils.js");class R extends w.ImageProcessor{post_process_object_detection(...q){return(0,w.post_process_object_detection)(...q)}}class H extends R{}},"./src/ops/registry.js":(Oe,B,c)=>{c.r(B),c.d(B,{TensorOpRegistry:()=>J});var w=c("./src/backends/onnx.js"),R=c("./src/utils/tensor.js");const H=async(q,g,x)=>{const E=await(0,w.createInferenceSession)(new Uint8Array(q),g);return async $=>{const P=Object.fromEntries(Object.entries($).map(([se,ue])=>[se,ue.ort_tensor])),Y=await E.run(P);return Array.isArray(x)?x.map(se=>new R.Tensor(Y[se])):new R.Tensor(Y[x])}};class J{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=H([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=H([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=H([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=H([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=H([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=H([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}}Te(J,"session_options",{})},"./src/pipelines.js":(Oe,B,c)=>{c.r(B),c.d(B,{AudioClassificationPipeline:()=>ge,AutomaticSpeechRecognitionPipeline:()=>Se,DepthEstimationPipeline:()=>Je,DocumentQuestionAnsweringPipeline:()=>$e,FeatureExtractionPipeline:()=>ee,FillMaskPipeline:()=>ne,ImageClassificationPipeline:()=>Le,ImageFeatureExtractionPipeline:()=>_e,ImageSegmentationPipeline:()=>me,ImageToImagePipeline:()=>Ke,ImageToTextPipeline:()=>Pe,ObjectDetectionPipeline:()=>he,Pipeline:()=>ue,QuestionAnsweringPipeline:()=>Q,SummarizationPipeline:()=>O,Text2TextGenerationPipeline:()=>N,TextClassificationPipeline:()=>le,TextGenerationPipeline:()=>C,TextToAudioPipeline:()=>Ne,TokenClassificationPipeline:()=>U,TranslationPipeline:()=>_,ZeroShotAudioClassificationPipeline:()=>be,ZeroShotClassificationPipeline:()=>Z,ZeroShotImageClassificationPipeline:()=>j,ZeroShotObjectDetectionPipeline:()=>pe,pipeline:()=>je});var w=c("./src/tokenizers.js"),R=c("./src/models.js"),H=c("./src/models/auto/processing_auto.js");c("./src/base/processing_utils.js");var J=c("./src/utils/generic.js"),q=c("./src/utils/core.js"),g=c("./src/utils/maths.js"),x=c("./src/utils/audio.js"),E=c("./src/utils/tensor.js"),$=c("./src/utils/image.js");async function P(ze){return Array.isArray(ze)||(ze=[ze]),await Promise.all(ze.map(we=>$.RawImage.read(we)))}async function Y(ze,we){return Array.isArray(ze)||(ze=[ze]),await Promise.all(ze.map(Ce=>typeof Ce=="string"||Ce instanceof URL?(0,x.read_audio)(Ce,we):Ce instanceof Float64Array?new Float32Array(Ce):Ce))}function se(ze,we){we&&(ze=ze.map(Be=>Be|0));const[Ce,Ze,Qe,He]=ze;return{xmin:Ce,ymin:Ze,xmax:Qe,ymax:He}}class ue extends J.Callable{constructor({task:we,model:Ce,tokenizer:Ze=null,processor:Qe=null}){super(),this.task=we,this.model=Ce,this.tokenizer=Ze,this.processor=Qe}async dispose(){await this.model.dispose()}}class le extends ue{constructor(we){super(we)}async _call(we,{top_k:Ce=1}={}){const Ze=this.tokenizer(we,{padding:!0,truncation:!0}),Qe=await this.model(Ze),He=this.model.config.problem_type==="multi_label_classification"?ut=>ut.sigmoid():ut=>new E.Tensor("float32",(0,g.softmax)(ut.data),ut.dims),Be=this.model.config.id2label,nt=[];for(const ut of Qe.logits){const wt=He(ut),ht=await(0,E.topk)(wt,Ce),ft=ht[0].tolist(),re=ht[1].tolist().map((V,de)=>({label:Be?Be[V]:`LABEL_${V}`,score:ft[de]}));Ce===1?nt.push(...re):nt.push(re)}return Array.isArray(we)||Ce===1?nt:nt[0]}}class U extends ue{constructor(we){super(we)}async _call(we,{ignore_labels:Ce=["O"]}={}){const Ze=Array.isArray(we),Qe=this.tokenizer(Ze?we:[we],{padding:!0,truncation:!0}),Be=(await this.model(Qe)).logits,nt=this.model.config.id2label,ut=[];for(let wt=0;wtdt==this.tokenizer.sep_token_id);ut[ft].map((dt,$t)=>dt==1&&($t===0||$t>re&&wt.findIndex(Et=>Et==A[$t])===-1));const V=He[ft].tolist(),de=Be[ft].tolist();for(let dt=1;dt$t==A[dt])!==-1)&&(V[dt]=-1/0,de[dt]=-1/0);const ke=(0,g.softmax)(V).map((dt,$t)=>[dt,$t]),Ye=(0,g.softmax)(de).map((dt,$t)=>[dt,$t]);ke[0][0]=0,Ye[0][0]=0;const ot=(0,q.product)(ke,Ye).filter(dt=>dt[0][1]<=dt[1][1]).map(dt=>[dt[0][1],dt[1][1],dt[0][0]*dt[1][0]]).sort((dt,$t)=>$t[2]-dt[2]);for(let dt=0;dtV==this.tokenizer.mask_token_id);if(wt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const ht=Qe[nt][wt],ft=await(0,E.topk)(new E.Tensor("float32",(0,g.softmax)(ht.data),ht.dims),Ce),A=ft[0].tolist(),re=ft[1].tolist();He.push(re.map((V,de)=>{const ke=ut.slice();return ke[wt]=V,{score:A[de],token:Number(V),token_str:this.tokenizer.model.vocab[V],sequence:this.tokenizer.decode(ke,{skip_special_tokens:!0})}}))}return Array.isArray(we)?He:He[0]}}class N extends ue{constructor(Ce){super(Ce);Te(this,"_key","generated_text")}async _call(Ce,Ze={}){Array.isArray(Ce)||(Ce=[Ce]),this.model.config.prefix&&(Ce=Ce.map(wt=>this.model.config.prefix+wt));const Qe=this.model.config.task_specific_params;Qe&&Qe[this.task]&&Qe[this.task].prefix&&(Ce=Ce.map(wt=>Qe[this.task].prefix+wt));const He=this.tokenizer,Be={padding:!0,truncation:!0};let nt;this instanceof _&&"_build_translation_inputs"in He?nt=He._build_translation_inputs(Ce,Be,Ze):nt=He(Ce,Be);const ut=await this.model.generate({...nt,...Ze});return He.batch_decode(ut,{skip_special_tokens:!0}).map(wt=>({[this._key]:wt}))}}class O extends N{constructor(Ce){super(Ce);Te(this,"_key","summary_text")}}class _ extends N{constructor(Ce){super(Ce);Te(this,"_key","translation_text")}}function k(ze){return Array.isArray(ze)&&ze.every(we=>"role"in we&&"content"in we)}class C extends ue{constructor(we){super(we)}async _call(we,Ce={}){let Ze=!1,Qe=!1,He;if(typeof we=="string")He=we=[we];else if(Array.isArray(we)&&we.every(re=>typeof re=="string"))Ze=!0,He=we;else{if(k(we))we=[we];else if(Array.isArray(we)&&we.every(k))Ze=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Qe=!0,He=we.map(re=>this.tokenizer.apply_chat_template(re,{tokenize:!1,add_generation_prompt:!0}))}const Be=Ce.add_special_tokens??!1,nt=Qe?!1:Ce.return_full_text??!0;this.tokenizer.padding_side="left";const ut=this.tokenizer(He,{add_special_tokens:Be,padding:!0,truncation:!0}),wt=await this.model.generate({...ut,...Ce}),ht=this.tokenizer.batch_decode(wt,{skip_special_tokens:!0});let ft;!nt&&ut.input_ids.dims.at(-1)>0&&(ft=this.tokenizer.batch_decode(ut.input_ids,{skip_special_tokens:!0}).map(re=>re.length));const A=Array.from({length:we.length},re=>[]);for(let re=0;re[Ce.toLowerCase(),Ze])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(we,Ce,{hypothesis_template:Ze="This example is {}.",multi_label:Qe=!1}={}){const He=Array.isArray(we);He||(we=[we]),Array.isArray(Ce)||(Ce=[Ce]);const Be=Ce.map(wt=>Ze.replace("{}",wt)),nt=Qe||Ce.length===1,ut=[];for(const wt of we){const ht=[];for(const re of Be){const V=this.tokenizer(wt,{text_pair:re,padding:!0,truncation:!0}),de=await this.model(V);nt?ht.push([de.logits.data[this.contradiction_id],de.logits.data[this.entailment_id]]):ht.push(de.logits.data[this.entailment_id])}const A=(nt?ht.map(re=>(0,g.softmax)(re)[1]):(0,g.softmax)(ht)).map((re,V)=>[re,V]).sort((re,V)=>V[0]-re[0]);ut.push({sequence:wt,labels:A.map(re=>Ce[re[1]]),scores:A.map(re=>re[0])})}return He?ut:ut[0]}}class ee extends ue{constructor(we){super(we)}async _call(we,{pooling:Ce="none",normalize:Ze=!1,quantize:Qe=!1,precision:He="binary"}={}){const Be=this.tokenizer(we,{padding:!0,truncation:!0}),nt=await this.model(Be);let ut=nt.last_hidden_state??nt.logits??nt.token_embeddings;if(Ce!=="none")if(Ce==="mean")ut=(0,E.mean_pooling)(ut,Be.attention_mask);else if(Ce==="cls")ut=ut.slice(null,0);else throw Error(`Pooling method '${Ce}' not supported.`);return Ze&&(ut=ut.normalize(2,-1)),Qe&&(ut=(0,E.quantize_embeddings)(ut,He)),ut}}class _e extends ue{constructor(we){super(we)}async _call(we,{pool:Ce=null}={}){const Ze=await P(we),{pixel_values:Qe}=await this.processor(Ze),He=await this.model({pixel_values:Qe});let Be;if(Ce){if(!("pooler_output"in He))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Be=He.pooler_output}else Be=He.last_hidden_state??He.logits??He.image_embeds;return Be}}class ge extends ue{constructor(we){super(we)}async _call(we,{top_k:Ce=5}={}){const Ze=this.processor.feature_extractor.config.sampling_rate,Qe=await Y(we,Ze),He=this.model.config.id2label,Be=[];for(const nt of Qe){const ut=await this.processor(nt),ht=(await this.model(ut)).logits[0],ft=await(0,E.topk)(new E.Tensor("float32",(0,g.softmax)(ht.data),ht.dims),Ce),A=ft[0].tolist(),V=ft[1].tolist().map((de,ke)=>({label:He?He[de]:`LABEL_${de}`,score:A[ke]}));Be.push(V)}return Array.isArray(we)?Be:Be[0]}}class be extends ue{constructor(we){super(we)}async _call(we,Ce,{hypothesis_template:Ze="This is a sound of {}."}={}){const Qe=!Array.isArray(we);Qe&&(we=[we]);const He=Ce.map(ht=>Ze.replace("{}",ht)),Be=this.tokenizer(He,{padding:!0,truncation:!0}),nt=this.processor.feature_extractor.config.sampling_rate,ut=await Y(we,nt),wt=[];for(const ht of ut){const ft=await this.processor(ht),A=await this.model({...Be,...ft}),re=(0,g.softmax)(A.logits_per_audio.data);wt.push([...re].map((V,de)=>({score:V,label:Ce[de]})))}return Qe?wt[0]:wt}}class Se extends ue{constructor(we){super(we)}async _call(we,Ce={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(we,Ce);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(we,Ce);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(we,Ce){Ce.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Ce.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ze=!Array.isArray(we);Ze&&(we=[we]);const Qe=this.processor.feature_extractor.config.sampling_rate,He=await Y(we,Qe),Be=[];for(const nt of He){const ut=await this.processor(nt),ht=(await this.model(ut)).logits[0],ft=[];for(const re of ht)ft.push((0,g.max)(re.data)[1]);const A=this.tokenizer.decode(ft);Be.push({text:A})}return Ze?Be[0]:Be}async _call_whisper(we,Ce){const Ze=Ce.return_timestamps??!1,Qe=Ce.chunk_length_s??0,He=Ce.force_full_sequences??!1;let Be=Ce.stride_length_s??null;const nt={...Ce};Ze==="word"&&(nt.return_token_timestamps=!0,nt.return_timestamps=!1);const ut=!Array.isArray(we);ut&&(we=[we]);const wt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,ht=this.processor.feature_extractor.config.hop_length,ft=this.processor.feature_extractor.config.sampling_rate,A=await Y(we,ft),re=[];for(const V of A){let de=[];if(Qe>0){if(Be===null)Be=Qe/6;else if(Qe<=Be)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ot=ft*Qe,dt=ft*Be,$t=ot-2*dt;let Et=0;for(;;){const Tt=Et+ot,Pt=V.subarray(Et,Tt),ar=await this.processor(Pt),Mr=Et===0,Fr=Tt>=V.length;if(de.push({stride:[Pt.length,Mr?0:dt,Fr?0:dt],input_features:ar.input_features,is_last:Fr}),Fr)break;Et+=$t}}else de=[{stride:[V.length,0,0],input_features:(await this.processor(V)).input_features,is_last:!0}];for(const ot of de){nt.num_frames=Math.floor(ot.stride[0]/ht);const dt=await this.model.generate({inputs:ot.input_features,...nt});Ze==="word"?(ot.tokens=dt.sequences.tolist()[0],ot.token_timestamps=dt.token_timestamps.tolist()[0].map($t=>(0,g.round)($t,2))):ot.tokens=dt[0].tolist(),ot.stride=ot.stride.map($t=>$t/ft)}const[ke,Ye]=this.tokenizer._decode_asr(de,{time_precision:wt,return_timestamps:Ze,force_full_sequences:He});re.push({text:ke,...Ye})}return ut?re[0]:re}}class Pe extends ue{constructor(we){super(we)}async _call(we,Ce={}){const Ze=Array.isArray(we),Qe=await P(we),{pixel_values:He}=await this.processor(Qe),Be=[];for(const nt of He){nt.dims=[1,...nt.dims];const ut=await this.model.generate({inputs:nt,...Ce}),wt=this.tokenizer.batch_decode(ut,{skip_special_tokens:!0}).map(ht=>({generated_text:ht.trim()}));Be.push(wt)}return Ze?Be:Be[0]}}class Le extends ue{constructor(we){super(we)}async _call(we,{top_k:Ce=5}={}){const Ze=await P(we),{pixel_values:Qe}=await this.processor(Ze),He=await this.model({pixel_values:Qe}),Be=this.model.config.id2label,nt=[];for(const ut of He.logits){const wt=await(0,E.topk)(new E.Tensor("float32",(0,g.softmax)(ut.data),ut.dims),Ce),ht=wt[0].tolist(),A=wt[1].tolist().map((re,V)=>({label:Be?Be[re]:`LABEL_${re}`,score:ht[V]}));nt.push(A)}return Array.isArray(we)?nt:nt[0]}}class me extends ue{constructor(we){super(we),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(we,{threshold:Ce=.5,mask_threshold:Ze=.5,overlap_mask_area_threshold:Qe=.8,label_ids_to_fuse:He=null,target_sizes:Be=null,subtask:nt=null}={}){if(Array.isArray(we)&&we.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const wt=await P(we),ht=wt.map(Ye=>[Ye.height,Ye.width]),{pixel_values:ft,pixel_mask:A}=await this.processor(wt),re=await this.model({pixel_values:ft,pixel_mask:A});let V=null;if(nt!==null)V=this.subtasks_mapping[nt];else for(let[Ye,ot]of Object.entries(this.subtasks_mapping))if(ot in this.processor.image_processor){V=this.processor.image_processor[ot].bind(this.processor.image_processor),nt=Ye;break}const de=this.model.config.id2label,ke=[];if(nt==="panoptic"||nt==="instance"){const Ye=V(re,Ce,Ze,Qe,He,Be??ht)[0],ot=Ye.segmentation;for(const dt of Ye.segments_info){const $t=new Uint8ClampedArray(ot.data.length);for(let Tt=0;TtZe.replace("{}",A)),nt=this.tokenizer(Be,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ut}=await this.processor(He),wt=await this.model({...nt,pixel_values:ut}),ht=this.model.config.model_type==="siglip"?A=>A.sigmoid().data:A=>(0,g.softmax)(A.data),ft=[];for(const A of wt.logits_per_image){const V=[...ht(A)].map((de,ke)=>({score:de,label:Ce[ke]}));V.sort((de,ke)=>ke.score-de.score),ft.push(V)}return Qe?ft:ft[0]}}class he extends ue{constructor(we){super(we)}async _call(we,{threshold:Ce=.9,percentage:Ze=!1}={}){const Qe=Array.isArray(we);if(Qe&&we.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const He=await P(we),Be=Ze?null:He.map(re=>[re.height,re.width]),{pixel_values:nt,pixel_mask:ut}=await this.processor(He),wt=await this.model({pixel_values:nt,pixel_mask:ut}),ht=this.processor.image_processor.post_process_object_detection(wt,Ce,Be),ft=this.model.config.id2label,A=ht.map(re=>re.boxes.map((V,de)=>({score:re.scores[de],label:ft[re.classes[de]],box:se(V,!Ze)})));return Qe?A:A[0]}}class pe extends ue{constructor(we){super(we)}async _call(we,Ce,{threshold:Ze=.1,top_k:Qe=null,percentage:He=!1}={}){const Be=Array.isArray(we),nt=await P(we),ut=this.tokenizer(Ce,{padding:!0,truncation:!0}),wt=await this.processor(nt),ht=[];for(let ft=0;ft({score:ke.scores[dt],label:Ce[ke.classes[dt]],box:se(ot,!He)})).sort((ot,dt)=>dt.score-ot.score);Qe!==null&&(Ye=Ye.slice(0,Qe)),ht.push(Ye)}return Be?ht:ht[0]}}class $e extends ue{constructor(we){super(we)}async _call(we,Ce,Ze={}){const Qe=(await P(we))[0],{pixel_values:He}=await this.processor(Qe),Be=`${Ce}`,nt=this.tokenizer(Be,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ut=await this.model.generate({inputs:He,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:nt,...Ze}),ht=this.tokenizer.batch_decode(ut)[0].match(/(.*?)<\/s_answer>/);let ft=null;return ht&&ht.length>=2&&(ft=ht[1].trim()),[{answer:ft}]}}class Ne extends ue{constructor(Ce){super(Ce);Te(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Ce.vocoder??null}async _call(Ce,{speaker_embeddings:Ze=null}={}){return this.processor?this._call_text_to_spectrogram(Ce,{speaker_embeddings:Ze}):this._call_text_to_waveform(Ce)}async _call_text_to_waveform(Ce){const Ze=this.tokenizer(Ce,{padding:!0,truncation:!0}),{waveform:Qe}=await this.model(Ze),He=this.model.config.sampling_rate;return{audio:Qe.data,sampling_rate:He}}async _call_text_to_spectrogram(Ce,{speaker_embeddings:Ze}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await R.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ze=="string"||Ze instanceof URL)&&(Ze=new Float32Array(await(await fetch(Ze)).arrayBuffer())),Ze instanceof Float32Array)Ze=new E.Tensor("float32",Ze,[1,Ze.length]);else if(!(Ze instanceof E.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Qe}=this.tokenizer(Ce,{padding:!0,truncation:!0}),{waveform:He}=await this.model.generate_speech(Qe,Ze,{vocoder:this.vocoder}),Be=this.processor.feature_extractor.config.sampling_rate;return{audio:He.data,sampling_rate:Be}}}class Ke extends ue{constructor(we){super(we)}async _call(we){const Ce=await P(we),Ze=await this.processor(Ce),Qe=await this.model(Ze),He=[];for(const Be of Qe.reconstruction){const nt=Be.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");He.push($.RawImage.fromTensor(nt))}return He.length>1?He:He[0]}}class Je extends ue{constructor(we){super(we)}async _call(we){const Ce=await P(we),Ze=await this.processor(Ce),{predicted_depth:Qe}=await this.model(Ze),He=[];for(let Be=0;Be1?He:He[0]}}const lt=Object.freeze({"text-classification":{tokenizer:w.AutoTokenizer,pipeline:le,model:R.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:w.AutoTokenizer,pipeline:U,model:R.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:w.AutoTokenizer,pipeline:Q,model:R.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:w.AutoTokenizer,pipeline:ne,model:R.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:w.AutoTokenizer,pipeline:O,model:R.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:w.AutoTokenizer,pipeline:_,model:R.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:w.AutoTokenizer,pipeline:N,model:R.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:w.AutoTokenizer,pipeline:C,model:R.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:w.AutoTokenizer,pipeline:Z,model:R.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ge,model:R.AutoModelForAudioClassification,processor:H.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:w.AutoTokenizer,pipeline:be,model:R.AutoModel,processor:H.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:w.AutoTokenizer,pipeline:Se,model:[R.AutoModelForSpeechSeq2Seq,R.AutoModelForCTC],processor:H.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:w.AutoTokenizer,pipeline:Ne,model:[R.AutoModelForTextToWaveform,R.AutoModelForTextToSpectrogram],processor:[H.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:w.AutoTokenizer,pipeline:Pe,model:R.AutoModelForVision2Seq,processor:H.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Le,model:R.AutoModelForImageClassification,processor:H.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:me,model:[R.AutoModelForImageSegmentation,R.AutoModelForSemanticSegmentation,R.AutoModelForUniversalSegmentation],processor:H.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:w.AutoTokenizer,pipeline:j,model:R.AutoModel,processor:H.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:he,model:R.AutoModelForObjectDetection,processor:H.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:w.AutoTokenizer,pipeline:pe,model:R.AutoModelForZeroShotObjectDetection,processor:H.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:w.AutoTokenizer,pipeline:$e,model:R.AutoModelForDocumentQuestionAnswering,processor:H.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Ke,model:R.AutoModelForImageToImage,processor:H.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Je,model:R.AutoModelForDepthEstimation,processor:H.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:w.AutoTokenizer,pipeline:ee,model:R.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:H.AutoProcessor,pipeline:_e,model:[R.AutoModelForImageFeatureExtraction,R.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ie=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function je(ze,we=null,{progress_callback:Ce=null,config:Ze=null,cache_dir:Qe=null,local_files_only:He=!1,revision:Be="main",device:nt=null,dtype:ut=null,model_file_name:wt=null,session_options:ht={}}={}){ze=ie[ze]??ze;const ft=lt[ze.split("_",1)[0]];if(!ft)throw Error(`Unsupported pipeline: ${ze}. Must be one of [${Object.keys(lt)}]`);we||(we=ft.default.model,console.log(`No model specified. Using default model: "${we}".`));const A={progress_callback:Ce,config:Ze,cache_dir:Qe,local_files_only:He,revision:Be,device:nt,dtype:ut,model_file_name:wt,session_options:ht},re=new Map([["tokenizer",ft.tokenizer],["model",ft.model],["processor",ft.processor]]),V=await st(re,we,A);V.task=ze,(0,q.dispatchCallback)(Ce,{status:"ready",task:ze,model:we});const de=ft.pipeline;return new de(V)}async function st(ze,we,Ce){const Ze=Object.create(null),Qe=[];for(const[He,Be]of ze.entries()){if(!Be)continue;let nt;Array.isArray(Be)?nt=new Promise(async(ut,wt)=>{var ft,A;let ht;for(const re of Be){if(re===null){ut(null);return}try{ut(await re.from_pretrained(we,Ce));return}catch(V){if((ft=V.message)!=null&&ft.includes("Unsupported model type"))ht=V;else if((A=V.message)!=null&&A.includes("Could not locate file"))ht=V;else{wt(V);return}}}wt(ht)}):nt=Be.from_pretrained(we,Ce),Ze[He]=nt,Qe.push(nt)}await Promise.all(Qe);for(const[He,Be]of Object.entries(Ze))Ze[He]=await Be;return Ze}},"./src/tokenizers.js":(Oe,B,c)=>{c.r(B),c.d(B,{AlbertTokenizer:()=>Bs,AutoTokenizer:()=>_r,BartTokenizer:()=>js,BertTokenizer:()=>Ts,BlenderbotSmallTokenizer:()=>Rn,BlenderbotTokenizer:()=>Bn,BloomTokenizer:()=>Fs,CLIPTokenizer:()=>Tn,CamembertTokenizer:()=>et,CodeGenTokenizer:()=>vn,CodeLlamaTokenizer:()=>Fn,CohereTokenizer:()=>pn,ConvBertTokenizer:()=>Zs,DebertaTokenizer:()=>gs,DebertaV2Tokenizer:()=>dn,DistilBertTokenizer:()=>ds,ElectraTokenizer:()=>It,EsmTokenizer:()=>Ln,FalconTokenizer:()=>Dn,GPT2Tokenizer:()=>en,GPTNeoXTokenizer:()=>Us,GemmaTokenizer:()=>ho,Grok1Tokenizer:()=>tn,HerbertTokenizer:()=>Js,LlamaTokenizer:()=>Ns,M2M100Tokenizer:()=>bn,MBart50Tokenizer:()=>cs,MBartTokenizer:()=>xr,MPNetTokenizer:()=>On,MarianTokenizer:()=>Rt,MgpstrTokenizer:()=>Un,MobileBertTokenizer:()=>Ys,NllbTokenizer:()=>ws,NougatTokenizer:()=>jn,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>zn,RoFormerTokenizer:()=>Rs,RobertaTokenizer:()=>Lr,SiglipTokenizer:()=>Vs,SpeechT5Tokenizer:()=>En,SqueezeBertTokenizer:()=>un,T5Tokenizer:()=>Wr,TokenizerModel:()=>_e,VitsTokenizer:()=>Nn,Wav2Vec2CTCTokenizer:()=>xn,WhisperTokenizer:()=>cn,XLMRobertaTokenizer:()=>po,XLMTokenizer:()=>vt,is_chinese_char:()=>ne});var w=c("./src/utils/generic.js"),R=c("./src/utils/core.js"),H=c("./src/utils/hub.js"),J=c("./src/utils/maths.js"),q=c("./src/utils/tensor.js"),g=c("./src/utils/data-structures.js"),x=c("./node_modules/@huggingface/jinja/dist/index.js"),E=c("./src/models/whisper/common_whisper.js");c("./src/utils/constants.js");async function $(xe,M){const G=await Promise.all([(0,H.getModelJSON)(xe,"tokenizer.json",!0,M),(0,H.getModelJSON)(xe,"tokenizer_config.json",!0,M)]);return M.legacy!==null&&(G[1].legacy=M.legacy),G}function P(xe,M){const G=[];let oe=0;for(const Me of xe.matchAll(M)){const Ee=Me[0];oe0&&G.push(Ee),oe=Me.index+Ee.length}return oe=19968&&xe<=40959||xe>=13312&&xe<=19903||xe>=131072&&xe<=173791||xe>=173824&&xe<=177983||xe>=177984&&xe<=178207||xe>=178208&&xe<=183983||xe>=63744&&xe<=64255||xe>=194560&&xe<=195103}function N(xe,M,G){const oe=[];let Me=0;for(;Methis.tokens_to_ids.get(G)??this.unk_token_id)}convert_ids_to_tokens(M){return M.map(G=>this.vocab[G]??this.unk_token)}}class ge extends _e{constructor(M){super(M),this.tokens_to_ids=se(M.vocab),this.unk_token_id=this.tokens_to_ids.get(M.unk_token),this.unk_token=M.unk_token,this.max_input_chars_per_word=M.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[G,oe]of this.tokens_to_ids)this.vocab[oe]=G}encode(M){const G=[];for(const oe of M){const Me=[...oe];if(Me.length>this.max_input_chars_per_word){G.push(this.unk_token);continue}let Ee=!1,Ve=0;const at=[];for(;Ve0&&(bt=this.config.continuing_subword_prefix+bt),this.tokens_to_ids.has(bt)){pt=bt;break}--_t}if(pt===null){Ee=!0;break}at.push(pt),Ve=_t}Ee?G.push(this.unk_token):G.push(...at)}return G}}class be extends _e{constructor(M,G){super(M);const oe=M.vocab.length;this.vocab=new Array(oe),this.scores=new Array(oe);for(let Me=0;Me[Me,Ee])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=G.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,J.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(M){const G=M.chars,oe=1;let Me=0;for(;Me{const xe=[...Array.from({length:94},(Me,Ee)=>Ee+33),...Array.from({length:12},(Me,Ee)=>Ee+161),...Array.from({length:82},(Me,Ee)=>Ee+174)],M=xe.slice();let G=0;for(let Me=0;Me<256;++Me)xe.includes(Me)||(xe.push(Me),M.push(256+G),G+=1);const oe=M.map(Me=>String.fromCharCode(Me));return Object.fromEntries(xe.map((Me,Ee)=>[Me,oe[Ee]]))})(),Pe=(0,R.reverseDictionary)(Se);class Le extends _e{constructor(M){super(M),this.tokens_to_ids=se(M.vocab),this.unk_token_id=this.tokens_to_ids.get(M.unk_token),this.unk_token=M.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[oe,Me]of this.tokens_to_ids)this.vocab[Me]=oe;const G=Array.isArray(M.merges[0]);this.merges=G?M.merges:M.merges.map(oe=>oe.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((oe,Me)=>[JSON.stringify(oe),Me])),this.end_of_word_suffix=M.end_of_word_suffix,this.continuing_subword_suffix=M.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(M){if(M.length===0)return[];const G=this.cache.get(M);if(G!==void 0)return G;const oe=Array.from(M);this.end_of_word_suffix&&(oe[oe.length-1]+=this.end_of_word_suffix);let Me=[];if(oe.length>1){const Ee=new g.PriorityQueue((_t,pt)=>_t.score`<0x${at.toString(16).toUpperCase().padStart(2,"0")}>`);Ve.every(at=>this.tokens_to_ids.has(at))?G.push(...Ve):G.push(this.unk_token)}else G.push(this.unk_token)}return G}}class me extends _e{constructor(M,G){super(M),this.tokens_to_ids=se(G.target_lang?M.vocab[G.target_lang]:M.vocab),this.bos_token=G.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=G.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=G.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=G.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[oe,Me]of this.tokens_to_ids)this.vocab[Me]=oe}encode(M){return M}}class j extends w.Callable{constructor(M){super(),this.config=M}static fromConfig(M){if(M===null)return null;switch(M.type){case"BertNormalizer":return new st(M);case"Precompiled":return new Mr(M);case"Sequence":return new je(M);case"Replace":return new he(M);case"NFC":return new pe(M);case"NFKC":return new $e(M);case"NFKD":return new Ne(M);case"Strip":return new Ke(M);case"StripAccents":return new Je(M);case"Lowercase":return new lt(M);case"Prepend":return new ie(M);default:throw new Error(`Unknown Normalizer type: ${M.type}`)}}normalize(M){throw Error("normalize should be implemented in subclass.")}_call(M){return this.normalize(M)}}class he extends j{normalize(M){const G=Y(this.config.pattern);return G===null?M:M.replaceAll(G,this.config.content)}}class pe extends j{normalize(M){return M=M.normalize("NFC"),M}}class $e extends j{normalize(M){return M=M.normalize("NFKC"),M}}class Ne extends j{normalize(M){return M=M.normalize("NFKD"),M}}class Ke extends j{normalize(M){return this.config.strip_left&&this.config.strip_right?M=M.trim():(this.config.strip_left&&(M=M.trimStart()),this.config.strip_right&&(M=M.trimEnd())),M}}class Je extends j{normalize(M){return M=U(M),M}}class lt extends j{normalize(M){return M=M.toLowerCase(),M}}class ie extends j{normalize(M){return M=this.config.prepend+M,M}}class je extends j{constructor(M){super(M),this.normalizers=M.normalizers.map(G=>j.fromConfig(G))}normalize(M){return this.normalizers.reduce((G,oe)=>oe.normalize(G),M)}}class st extends j{_tokenize_chinese_chars(M){const G=[];for(let oe=0;oethis.pre_tokenize_text(oe,G)):this.pre_tokenize_text(M,G)).flat()}_call(M,G){return this.pre_tokenize(M,G)}}class we extends ze{constructor(M){super(),this.pattern=new RegExp(`[^\\s${_}]+|[${_}]`,"gu")}pre_tokenize_text(M,G){return M.trim().match(this.pattern)||[]}}class Ce extends ze{constructor(M){super(),this.config=M,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=Se,this.text_encoder=new TextEncoder}pre_tokenize_text(M,G){return this.add_prefix_space&&!M.startsWith(" ")&&(M=" "+M),(this.use_regex?M.match(this.pattern)||[]:[M]).map(Me=>Array.from(this.text_encoder.encode(Me),Ee=>this.byte_encoder[Ee]).join(""))}}class Ze extends ze{constructor(M){super(),this.config=M,this.pattern=Y(this.config.pattern,this.config.invert)}pre_tokenize_text(M,G){var oe;return this.pattern===null?[]:this.config.invert?M.match(this.pattern)||[]:((oe=this.config.behavior)==null?void 0:oe.toLowerCase())==="removed"?M.split(this.pattern).filter(Me=>Me):P(M,this.pattern)}}class Qe extends ze{constructor(M){super(),this.config=M,this.pattern=new RegExp(`[^${_}]+|[${_}]+`,"gu")}pre_tokenize_text(M,G){return M.match(this.pattern)||[]}}class He extends ze{constructor(M){super(),this.config=M;const G=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(G,"gu")}pre_tokenize_text(M,G){return M.match(this.pattern)||[]}}class Be extends w.Callable{constructor(M){super(),this.config=M}static fromConfig(M){if(M===null)return null;switch(M.type){case"TemplateProcessing":return new wt(M);case"ByteLevel":return new ht(M);case"RobertaProcessing":return new ut(M);case"BertProcessing":return new nt(M);case"Sequence":return new ft(M);default:throw new Error(`Unknown PostProcessor type: ${M.type}`)}}post_process(M,...G){throw Error("post_process should be implemented in subclass.")}_call(M,...G){return this.post_process(M,...G)}}class nt extends Be{constructor(M){super(M),this.cls=M.cls[0],this.sep=M.sep[0]}post_process(M,G=null,{add_special_tokens:oe=!0}={}){oe&&(M=(0,R.mergeArrays)([this.cls],M,[this.sep]));let Me=new Array(M.length).fill(0);if(G!==null){const Ee=oe&&this instanceof ut?[this.sep]:[],Ve=oe?[this.sep]:[];M=(0,R.mergeArrays)(M,Ee,G,Ve),Me=(0,R.mergeArrays)(Me,new Array(G.length+Ee.length+Ve.length).fill(1))}return{tokens:M,token_type_ids:Me}}}class ut extends nt{}class wt extends Be{constructor(M){super(M),this.single=M.single,this.pair=M.pair}post_process(M,G=null,{add_special_tokens:oe=!0}={}){const Me=G===null?this.single:this.pair;let Ee=[],Ve=[];for(const at of Me)"SpecialToken"in at?oe&&(Ee.push(at.SpecialToken.id),Ve.push(at.SpecialToken.type_id)):"Sequence"in at&&(at.Sequence.id==="A"?(Ee=(0,R.mergeArrays)(Ee,M),Ve=(0,R.mergeArrays)(Ve,new Array(M.length).fill(at.Sequence.type_id))):at.Sequence.id==="B"&&(Ee=(0,R.mergeArrays)(Ee,G),Ve=(0,R.mergeArrays)(Ve,new Array(G.length).fill(at.Sequence.type_id))));return{tokens:Ee,token_type_ids:Ve}}}class ht extends Be{post_process(M,G=null){return G&&(M=(0,R.mergeArrays)(M,G)),{tokens:M}}}class ft extends Be{constructor(M){super(M),this.processors=M.processors.map(G=>Be.fromConfig(G))}post_process(M,G=null,oe={}){let Me;for(const Ee of this.processors)if(Ee instanceof ht)M=Ee.post_process(M).tokens,G&&(G=Ee.post_process(G).tokens);else{const Ve=Ee.post_process(M,G,oe);M=Ve.tokens,Me=Ve.token_type_ids}return{tokens:M,token_type_ids:Me}}}class A extends w.Callable{constructor(M){super(),this.config=M,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=M.trim_offsets}static fromConfig(M){if(M===null)return null;switch(M.type){case"WordPiece":return new Ye(M);case"Metaspace":return new ar(M);case"ByteLevel":return new ot(M);case"Replace":return new re(M);case"ByteFallback":return new V(M);case"Fuse":return new de(M);case"Strip":return new ke(M);case"Sequence":return new $t(M);case"CTC":return new dt(M);case"BPEDecoder":return new Et(M);default:throw new Error(`Unknown Decoder type: ${M.type}`)}}_call(M){return this.decode(M)}decode(M){return this.decode_chain(M).join("")}decode_chain(M){throw Error("`decode_chain` should be implemented in subclass.")}}class re extends A{decode_chain(M){const G=Y(this.config.pattern);return G===null?M:M.map(oe=>oe.replaceAll(G,this.config.content))}}class V extends A{constructor(M){super(M),this.text_decoder=new TextDecoder}decode_chain(M){const G=[];let oe=[];for(const Me of M){let Ee=null;if(Me.length===6&&Me.startsWith("<0x")&&Me.endsWith(">")){const Ve=parseInt(Me.slice(3,5),16);isNaN(Ve)||(Ee=Ve)}if(Ee!==null)oe.push(Ee);else{if(oe.length>0){const Ve=this.text_decoder.decode(Uint8Array.from(oe));G.push(Ve),oe=[]}G.push(Me)}}if(oe.length>0){const Me=this.text_decoder.decode(Uint8Array.from(oe));G.push(Me),oe=[]}return G}}class de extends A{decode_chain(M){return[M.join("")]}}class ke extends A{constructor(M){super(M),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(M){return M.map(G=>{let oe=0;for(let Ee=0;Ee(oe!==0&&(G.startsWith(this.config.prefix)?G=G.replace(this.config.prefix,""):G=" "+G),this.cleanup&&(G=le(G)),G))}}class ot extends A{constructor(M){super(M),this.byte_decoder=Pe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(M){const G=M.join(""),oe=new Uint8Array([...G].map(Ee=>this.byte_decoder[Ee]));return this.text_decoder.decode(oe)}decode_chain(M){const G=[];let oe=[];for(const Me of M)this.added_tokens.find(Ee=>Ee.content===Me)!==void 0?(oe.length>0&&(G.push(this.convert_tokens_to_string(oe)),oe=[]),G.push(Me)):oe.push(Me);return oe.length>0&&G.push(this.convert_tokens_to_string(oe)),G}}class dt extends A{constructor(M){super(M),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(M){if(M.length===0)return"";const G=[M[0]];for(let Ee=1;EeEe!==this.pad_token).join("");return this.cleanup&&(Me=le(Me).replaceAll(this.word_delimiter_token," ").trim()),Me}decode_chain(M){return[this.convert_tokens_to_string(M)]}}class $t extends A{constructor(M){super(M),this.decoders=M.decoders.map(G=>A.fromConfig(G))}decode_chain(M){return this.decoders.reduce((G,oe)=>oe.decode_chain(G),M)}}class Et extends A{constructor(M){super(M),this.suffix=this.config.suffix}decode_chain(M){return M.map((G,oe)=>G.replaceAll(this.suffix,oe===M.length-1?"":" "))}}class Tt extends A{decode_chain(M){let G="";for(let oe=1;oeoe.normalize("NFKC")).join("~"):M=M.normalize("NFKC"),M}}class Fr extends ze{constructor(M){super(),this.tokenizers=M.pretokenizers.map(G=>ze.fromConfig(G))}pre_tokenize_text(M,G){return this.tokenizers.reduce((oe,Me)=>Me.pre_tokenize(oe,G),[M])}}class Br extends ze{constructor(M){super()}pre_tokenize_text(M,G){return M.match(/\w+|[^\w\s]+/g)||[]}}class os extends ze{constructor(M){super()}pre_tokenize_text(M,G){return O(M)}}class Qs extends ze{constructor(M){super(),this.config=M,this.pattern=Y(this.config.pattern),this.content=this.config.content}pre_tokenize_text(M,G){return this.pattern===null?[M]:[M.replaceAll(this.pattern,this.config.content)]}}const Xs=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function zs(xe,M,G,oe){for(const Me of Object.keys(xe)){const Ee=M-xe[Me].length,Ve=G(Me),at=new Array(Ee).fill(Ve);xe[Me]=oe==="right"?(0,R.mergeArrays)(xe[Me],at):(0,R.mergeArrays)(at,xe[Me])}}function Is(xe,M){for(const G of Object.keys(xe))xe[G].length=M}class Nt extends w.Callable{constructor(G,oe){super();Te(this,"return_token_type_ids",!1);Te(this,"padding_side","right");this._tokenizer_config=oe,this.normalizer=j.fromConfig(G.normalizer),this.pre_tokenizer=ze.fromConfig(G.pre_tokenizer),this.model=_e.fromConfig(G.model,oe),this.post_processor=Be.fromConfig(G.post_processor),this.decoder=A.fromConfig(G.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Me of G.added_tokens){const Ee=new ee(Me);this.added_tokens.push(Ee),this.model.tokens_to_ids.set(Ee.content,Ee.id),this.model.vocab[Ee.id]=Ee.content,Ee.special&&(this.special_tokens.push(Ee.content),this.all_special_ids.push(Ee.id))}if(this.additional_special_tokens=oe.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((Me,Ee)=>Ee.content.length-Me.content.length).map(Me=>`${Me.lstrip?"\\s*":""}(${(0,R.escapeRegExp)(Me.content)})${Me.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=oe.model_max_length,this.remove_space=oe.remove_space,this.clean_up_tokenization_spaces=oe.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=oe.do_lowercase_and_remove_accent??!1,oe.padding_side&&(this.padding_side=oe.padding_side),this.legacy=!1,this.chat_template=oe.chat_template??null,Array.isArray(this.chat_template)){const Me=Object.create(null);for(const{name:Ee,template:Ve}of this.chat_template){if(typeof Ee!="string"||typeof Ve!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Me[Ee]=Ve}this.chat_template=Me}this._compiled_template_cache=new Map}getToken(...G){for(const oe of G){const Me=this._tokenizer_config[oe];if(Me)if(typeof Me=="object"){if(Me.__type==="AddedToken")return Me.content;throw Error(`Unknown token: ${Me}`)}else return Me}return null}static async from_pretrained(G,{progress_callback:oe=null,config:Me=null,cache_dir:Ee=null,local_files_only:Ve=!1,revision:at="main",legacy:_t=null}={}){const pt=await $(G,{progress_callback:oe,config:Me,cache_dir:Ee,local_files_only:Ve,revision:at,legacy:_t});return new this(...pt)}_call(G,{text_pair:oe=null,add_special_tokens:Me=!0,padding:Ee=!1,truncation:Ve=null,max_length:at=null,return_tensor:_t=!0,return_token_type_ids:pt=null}={}){const bt=Array.isArray(G);let Kt;if(bt){if(G.length===0)throw Error("text array must be non-empty");if(oe!==null){if(Array.isArray(oe)){if(G.length!==oe.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Kt=G.map((rr,Cr)=>this._encode_plus(rr,{text_pair:oe[Cr],add_special_tokens:Me,return_token_type_ids:pt}))}else Kt=G.map(rr=>this._encode_plus(rr,{add_special_tokens:Me,return_token_type_ids:pt}))}else{if(G==null)throw Error("text may not be null or undefined");if(Array.isArray(oe))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Kt=[this._encode_plus(G,{text_pair:oe,add_special_tokens:Me,return_token_type_ids:pt})]}if(at===null?Ee==="max_length"?at=this.model_max_length:at=(0,J.max)(Kt.map(rr=>rr.input_ids.length))[0]:Ve||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."),at=Math.min(at,this.model_max_length??1/0),Ee||Ve)for(let rr=0;rrat?Ve&&Is(Kt[rr],at):Ee&&zs(Kt[rr],at,Cr=>Cr==="input_ids"?this.pad_token_id:0,this.padding_side));const mr={};if(_t){if(!(Ee&&Ve)&&Kt.some(Cr=>{var qt;for(const cr of Object.keys(Cr))if(Cr[cr].length!==((qt=Kt[0][cr])==null?void 0:qt.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const rr=[Kt.length,Kt[0].input_ids.length];for(const Cr of Object.keys(Kt[0]))mr[Cr]=new q.Tensor("int64",BigInt64Array.from(Kt.flatMap(qt=>qt[Cr]).map(BigInt)),rr)}else{for(const rr of Object.keys(Kt[0]))mr[rr]=Kt.map(Cr=>Cr[rr]);if(!bt)for(const rr of Object.keys(mr))mr[rr]=mr[rr][0]}return mr}_encode_text(G){return G===null?null:(this.added_tokens_regex?G.split(this.added_tokens_regex).filter(Ee=>Ee):[G]).map((Ee,Ve)=>{if(this.added_tokens.find(_t=>_t.content===Ee)!==void 0)return Ee;{if(this.remove_space===!0&&(Ee=Ee.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Ee=Q(Ee)),this.normalizer!==null&&(Ee=this.normalizer(Ee)),Ee.length===0)return[];const _t=this.pre_tokenizer!==null?this.pre_tokenizer(Ee,{section_index:Ve}):[Ee];return this.model(_t)}}).flat()}_encode_plus(G,{text_pair:oe=null,add_special_tokens:Me=!0,return_token_type_ids:Ee=null}={}){const{tokens:Ve,token_type_ids:at}=this._tokenize_helper(G,{pair:oe,add_special_tokens:Me}),_t=this.model.convert_tokens_to_ids(Ve),pt={input_ids:_t,attention_mask:new Array(_t.length).fill(1)};return(Ee??this.return_token_type_ids)&&at&&(pt.token_type_ids=at),pt}_tokenize_helper(G,{pair:oe=null,add_special_tokens:Me=!1}={}){const Ee=this._encode_text(G),Ve=this._encode_text(oe);return this.post_processor?this.post_processor(Ee,Ve,{add_special_tokens:Me}):{tokens:(0,R.mergeArrays)(Ee??[],Ve??[])}}tokenize(G,{pair:oe=null,add_special_tokens:Me=!1}={}){return this._tokenize_helper(G,{pair:oe,add_special_tokens:Me}).tokens}encode(G,{text_pair:oe=null,add_special_tokens:Me=!0,return_token_type_ids:Ee=null}={}){return this._encode_plus(G,{text_pair:oe,add_special_tokens:Me,return_token_type_ids:Ee}).input_ids}batch_decode(G,oe={}){return G instanceof q.Tensor&&(G=G.tolist()),G.map(Me=>this.decode(Me,oe))}decode(G,oe={}){if(G instanceof q.Tensor&&(G=ue(G)),!Array.isArray(G)||G.length===0||!(0,R.isIntegralNumber)(G[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(G,oe)}decode_single(G,{skip_special_tokens:oe=!1,clean_up_tokenization_spaces:Me=null}){let Ee=this.model.convert_ids_to_tokens(G);oe&&(Ee=Ee.filter(at=>!this.special_tokens.includes(at)));let Ve=this.decoder?this.decoder(Ee):Ee.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ve=Ve.replaceAll(this.decoder.end_of_word_suffix," "),oe&&(Ve=Ve.trim())),(Me??this.clean_up_tokenization_spaces)&&(Ve=le(Ve)),Ve}get_chat_template({chat_template:G=null,tools:oe=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const Me=this.chat_template;if(G!==null&&Object.hasOwn(Me,G))G=Me[G];else if(G===null)if(oe!==null&&"tool_use"in Me)G=Me.tool_use;else if("default"in Me)G=Me.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(Me).sort()}.`)}else if(G===null)if(this.chat_template)G=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 G}apply_chat_template(G,{tools:oe=null,documents:Me=null,chat_template:Ee=null,add_generation_prompt:Ve=!1,tokenize:at=!0,padding:_t=!1,truncation:pt=!1,max_length:bt=null,return_tensor:Kt=!0,return_dict:mr=!1,tokenizer_kwargs:rr={},...Cr}={}){if(Ee=this.get_chat_template({chat_template:Ee,tools:oe}),typeof Ee!="string")throw Error(`chat_template must be a string, but got ${typeof Ee}`);let qt=this._compiled_template_cache.get(Ee);qt===void 0&&(qt=new x.Template(Ee),this._compiled_template_cache.set(Ee,qt));const cr=Object.create(null);for(const zr of Xs){const De=this.getToken(zr);De&&(cr[zr]=De)}const ps=qt.render({messages:G,add_generation_prompt:Ve,tools:oe,documents:Me,...cr,...Cr});if(at){const zr=this._call(ps,{add_special_tokens:!1,padding:_t,truncation:pt,max_length:bt,return_tensor:Kt,...rr});return mr?zr:zr.input_ids}return ps}}class Ts extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Bs extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Ys extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class un extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class gs extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class dn extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Js extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Zs extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Rs extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class ds extends Nt{}class et extends Nt{}class vt extends Nt{constructor(G,oe){super(G,oe);Te(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class It extends Nt{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Wr extends Nt{}class en extends Nt{}class js extends Nt{}class xr extends Nt{constructor(M,G){super(M,G),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(oe=>this.languageRegex.test(oe)),this.lang_to_token=oe=>oe}_build_translation_inputs(M,G,oe){return xs(this,M,G,oe)}}class cs extends xr{}class Lr extends Nt{}class Fs extends Nt{}const br="▁";class Ns extends Nt{constructor(G,oe){super(G,oe);Te(this,"padding_side","left");this.legacy=oe.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Pt({replacement:br,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(G){if(G===null)return null;if(this.legacy||G.length===0)return super._encode_text(G);let oe=super._encode_text(br+G.replaceAll(br," "));return oe.length>1&&oe[0]===br&&this.special_tokens.includes(oe[1])&&(oe=oe.slice(1)),oe}}class Fn extends Nt{}class po extends Nt{}class On extends Nt{}class Dn extends Nt{}class Us extends Nt{}class Ln extends Nt{}class zn extends Nt{}class ho extends Nt{}class tn extends Nt{}function xs(xe,M,G,oe){if(!("language_codes"in xe)||!Array.isArray(xe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in xe)||!(xe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in xe)||typeof xe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const Me=oe.src_lang,Ee=oe.tgt_lang;if(!xe.language_codes.includes(Ee))throw new Error(`Target language code "${Ee}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);if(Me!==void 0){if(!xe.language_codes.includes(Me))throw new Error(`Source language code "${Me}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);for(const Ve of xe.post_processor.config.single)if("SpecialToken"in Ve&&xe.languageRegex.test(Ve.SpecialToken.id)){Ve.SpecialToken.id=xe.lang_to_token(Me);break}}return oe.forced_bos_token_id=xe.model.convert_tokens_to_ids([xe.lang_to_token(Ee)])[0],xe._call(M,G)}class ws extends Nt{constructor(M,G){super(M,G),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(oe=>this.languageRegex.test(oe)),this.lang_to_token=oe=>oe}_build_translation_inputs(M,G,oe){return xs(this,M,G,oe)}}class bn extends Nt{constructor(M,G){super(M,G),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(oe=>this.languageRegex.test(oe)).map(oe=>oe.slice(2,-2)),this.lang_to_token=oe=>`__${oe}__`}_build_translation_inputs(M,G,oe){return xs(this,M,G,oe)}}class cn extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(M,{return_timestamps:G=!1,return_language:oe=!1,time_precision:Me=null,force_full_sequences:Ee=!0}={}){if(Me===null)throw Error("Must specify time_precision");let Ve=null;const at=G==="word";function _t(){return{language:Ve,timestamp:[null,null],text:""}}const pt=[];let bt=_t(),Kt=0;const mr=this.timestamp_begin;let rr=[],Cr=[],qt=!1,cr=null;const ps=new Set(this.all_special_ids);for(const gr of M){const Hr=gr.tokens,hs=at?gr.token_timestamps:null;let Es=null,Dt=mr;if("stride"in gr){const[ir,wr,gt]=gr.stride;if(Kt-=wr,cr=ir-gt,wr&&(Dt=wr/Me+mr),gt)for(let Qt=Hr.length-1;Qt>=0;--Qt){const Nr=Number(Hr[Qt]);if(Nr>=mr){if(Es!==null&&(Nr-mr)*Me=mr){const gt=(wr-mr)*Me+Kt,Qt=(0,J.round)(gt,2);if(Es!==null&&wr>=Es)qt=!0;else if(qt||rr.length>0&&wr0?(rr.push(qr),at&&Cr.push(as)):rr.every(ir=>ir.length===0)&&(bt=_t(),rr=[],qr=[],Cr=[],as=[])}if(rr.length>0){if(Ee&&G)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[gr,Hr]=this.findLongestCommonSequence(rr,Cr),hs=this.decode(gr);bt.text=hs,at&&(bt.words=this.collateWordTimestamps(gr,Hr,Ve)),pt.push(bt)}let zr=Object.create(null);const De=pt.map(gr=>gr.text).join("");if(G||oe){for(let gr=0;gr0;let at=Ve?[]:null,_t=Ve?G[0]:null;for(let pt=1;ptQt===as[Nr]&&_t[Hr+Nr]<=G[pt][Dt+Nr]).length:ir=Es.filter((Qt,Nr)=>Qt===as[Nr]).length;const wr=gr/1e4,gt=ir/gr+wr;ir>1&>>Kt&&(Kt=gt,mr=[Hr,hs,Dt,qr])}const[Cr,qt,cr,ps]=mr,zr=Math.floor((qt+Cr)/2),De=Math.floor((ps+cr)/2);Ee.push(...oe.slice(0,zr)),oe=bt.slice(De),Me=oe.length,Ve&&(at.push(..._t.slice(0,zr)),_t=G[pt].slice(De))}return Ee.push(...oe),Ve?(at.push(..._t),[Ee,at]):[Ee,[]]}collateWordTimestamps(M,G,oe){const[Me,Ee,Ve]=this.combineTokensIntoWords(M,oe),at=[];for(let _t=0;_t=Me){const at=((Ve-Me)*oe).toFixed(2);Ee.push(`<|${at}|>`),Ee.push([])}else Ee[Ee.length-1].push(Ve);return Ee=Ee.map(Ve=>typeof Ve=="string"?Ve:super.decode(Ve,G)),Ee.join("")}splitTokensOnUnicode(M){const G=this.decode(M,{decode_with_timestamps:!0}),oe="�",Me=[],Ee=[],Ve=[];let at=[],_t=[],pt=0;for(let bt=0;bt=this.model.tokens_to_ids.get("<|endoftext|>"),Cr=bt.startsWith(" "),qt=bt.trim(),cr=_t.test(qt);if(rr||Cr||cr||Ee.length===0)Ee.push(bt),Ve.push(Kt),at.push(mr);else{const ps=Ee.length-1;Ee[ps]+=bt,Ve[ps].push(...Kt),at[ps].push(...mr)}}return[Ee,Ve,at]}mergePunctuations(M,G,oe,Me,Ee){const Ve=structuredClone(M),at=structuredClone(G),_t=structuredClone(oe);let pt=Ve.length-2,bt=Ve.length-1;for(;pt>=0;)Ve[pt].startsWith(" ")&&Me.includes(Ve[pt].trim())?(Ve[bt]=Ve[pt]+Ve[bt],at[bt]=(0,R.mergeArrays)(at[pt],at[bt]),_t[bt]=(0,R.mergeArrays)(_t[pt],_t[bt]),Ve[pt]="",at[pt]=[],_t[pt]=[]):bt=pt,--pt;for(pt=0,bt=1;btKt),at.filter(Kt=>Kt.length>0),_t.filter(Kt=>Kt.length>0)]}}class vn extends Nt{}class Tn extends Nt{}class Vs extends Nt{}class Rt extends Nt{constructor(M,G){super(M,G),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(oe=>this.languageRegex.test(oe)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(M){if(M===null)return null;const[G,...oe]=M.trim().split(this.languageRegex);if(oe.length===0)return super._encode_text(G);if(oe.length===2){const[Me,Ee]=oe;return this.supported_language_codes.includes(Me)||console.warn(`Unsupported language code "${Me}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,R.mergeArrays)([Me],super._encode_text(Ee))}}}class xn extends Nt{}class Bn extends Nt{}class Rn extends Nt{}class En extends Nt{}class jn extends Nt{}class Nn extends Nt{constructor(M,G){super(M,G),this.decoder=new Tt({})}}class pn extends Nt{}class Un extends Nt{}class _r{static async from_pretrained(M,{progress_callback:G=null,config:oe=null,cache_dir:Me=null,local_files_only:Ee=!1,revision:Ve="main",legacy:at=null}={}){var mr;const[_t,pt]=await $(M,{progress_callback:G,config:oe,cache_dir:Me,local_files_only:Ee,revision:Ve,legacy:at}),bt=((mr=pt.tokenizer_class)==null?void 0:mr.replace(/Fast$/,""))??"PreTrainedTokenizer";let Kt=this.TOKENIZER_CLASS_MAPPING[bt];return Kt||(console.warn(`Unknown tokenizer class "${bt}", attempting to construct from base class.`),Kt=Nt),new Kt(_t,pt)}}Te(_r,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Wr,DistilBertTokenizer:ds,CamembertTokenizer:et,DebertaTokenizer:gs,DebertaV2Tokenizer:dn,BertTokenizer:Ts,HerbertTokenizer:Js,ConvBertTokenizer:Zs,RoFormerTokenizer:Rs,XLMTokenizer:vt,ElectraTokenizer:It,MobileBertTokenizer:Ys,SqueezeBertTokenizer:un,AlbertTokenizer:Bs,GPT2Tokenizer:en,BartTokenizer:js,MBartTokenizer:xr,MBart50Tokenizer:cs,RobertaTokenizer:Lr,WhisperTokenizer:cn,CodeGenTokenizer:vn,CLIPTokenizer:Tn,SiglipTokenizer:Vs,MarianTokenizer:Rt,BloomTokenizer:Fs,NllbTokenizer:ws,M2M100Tokenizer:bn,LlamaTokenizer:Ns,CodeLlamaTokenizer:Fn,XLMRobertaTokenizer:po,MPNetTokenizer:On,FalconTokenizer:Dn,GPTNeoXTokenizer:Us,EsmTokenizer:Ln,Wav2Vec2CTCTokenizer:xn,BlenderbotTokenizer:Bn,BlenderbotSmallTokenizer:Rn,SpeechT5Tokenizer:En,NougatTokenizer:jn,VitsTokenizer:Nn,Qwen2Tokenizer:zn,GemmaTokenizer:ho,Grok1Tokenizer:tn,CohereTokenizer:pn,MgpstrTokenizer:Un,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(Oe,B,c)=>{c.r(B),c.d(B,{hamming:()=>E,hanning:()=>x,mel_filter_bank:()=>U,read_audio:()=>q,spectrogram:()=>_,window_function:()=>k});var w=c("./src/utils/hub.js"),R=c("./src/utils/maths.js"),H=c("./src/utils/core.js"),J=c("./src/utils/tensor.js");async function q(C,Z){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 ee=await(await(0,w.getFile)(C)).arrayBuffer(),_e=new AudioContext({sampleRate:Z});typeof Z>"u"&&console.warn(`No sampling rate provided, using default of ${_e.sampleRate}Hz.`);const ge=await _e.decodeAudioData(ee);let be;if(ge.numberOfChannels===2){const Se=Math.sqrt(2),Pe=ge.getChannelData(0),Le=ge.getChannelData(1);be=new Float32Array(Pe.length);for(let me=0;me2595*Math.log10(1+C/700),kaldi:C=>1127*Math.log(1+C/700),slaney:(C,Z=1e3,ee=15,_e=27/Math.log(6.4))=>C>=Z?ee+Math.log(C/Z)*_e:3*C/200};function P(C,Z="htk"){const ee=$[Z];if(!ee)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof C=="number"?ee(C):C.map(_e=>ee(_e))}const Y={htk:C=>700*(10**(C/2595)-1),kaldi:C=>700*(Math.exp(C/1127)-1),slaney:(C,Z=1e3,ee=15,_e=Math.log(6.4)/27)=>C>=ee?Z*Math.exp(_e*(C-ee)):200*C/3};function se(C,Z="htk"){const ee=Y[Z];if(!ee)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof C=="number"?ee(C):C.map(_e=>ee(_e))}function ue(C,Z){const ee=Float64Array.from({length:Z.length-1},(Se,Pe)=>Z[Pe+1]-Z[Pe]),_e=Array.from({length:C.length},()=>new Array(Z.length));for(let Se=0;Senew Array(C.length));for(let Se=0;SeC+_e*be)}function U(C,Z,ee,_e,ge,be=null,Se="htk",Pe=!1){if(be!==null&&be!=="slaney")throw new Error('norm must be one of null or "slaney"');const Le=P(ee,Se),me=P(_e,Se),j=le(Le,me,Z+2);let he=se(j,Se),pe;if(Pe){const Ne=ge/(C*2);pe=P(Float64Array.from({length:C},(Ke,Je)=>Je*Ne),Se),he=j}else pe=le(0,Math.floor(ge/2),C);const $e=ue(pe,he);if(be!==null&&be==="slaney")for(let Ne=0;Nege)throw Error(`frame_length (${ee}) may not be larger than fft_length (${ge})`);if(ze!==ee)throw new Error(`Length of the window (${ze}) must equal frame_length (${ee})`);if(_e<=0)throw new Error("hop_length must be greater than zero");if(be===null&&j!==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(Se){if(Pe!=="reflect")throw new Error(`pad_mode="${Pe}" not implemented yet.`);const A=Math.floor((ge-1)/2)+1;C=Q(C,A,A)}let we=Math.floor(1+Math.floor((C.length-ee)/_e));lt!==null&&wewe?je&&(Qe=ie):Qe=Ze=ie);const He=new R.FFT(ge),Be=new Float64Array(ge),nt=new Float64Array(He.outputBufferSize),ut=new Float32Array(Ce*Qe);for(let A=0;A=1;--de)Be[de]-=me*Be[de-1];Be[0]*=1-me}for(let de=0;deMath.pow(Pe,.85));break;default:throw new Error(`Unknown window type ${Z}.`)}if(ee&&(Se=Se.subarray(0,C)),_e===null)return Se;if(C>_e)throw new Error(`Length of the window (${C}) may not be larger than frame_length (${_e})`);return Se}},"./src/utils/constants.js":(Oe,B,c)=>{c.r(B),c.d(B,{CHAT_TEMPLATE_NAME:()=>g,CONFIG_NAME:()=>R,FEATURE_EXTRACTOR_NAME:()=>H,GENERATION_CONFIG_NAME:()=>x,GITHUB_ISSUE_URL:()=>w,IMAGE_PROCESSOR_NAME:()=>J,PROCESSOR_NAME:()=>q});const w="https://github.com/huggingface/transformers.js/issues/new/choose",R="config.json",H="preprocessor_config.json",J=H,q="processor_config.json",g="chat_template.json",x="generation_config.json"},"./src/utils/core.js":(Oe,B,c)=>{c.r(B),c.d(B,{calculateDimensions:()=>x,calculateReflectOffset:()=>Y,dispatchCallback:()=>w,escapeRegExp:()=>H,isIntegralNumber:()=>q,isNullishDimension:()=>g,isTypedArray:()=>J,len:()=>ue,mergeArrays:()=>$,pick:()=>se,pop:()=>E,product:()=>P,reverseDictionary:()=>R});function w(le,U){le&&le(U)}function R(le){return Object.fromEntries(Object.entries(le).map(([U,Q])=>[Q,U]))}function H(le){return le.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(le){var U,Q,ne;return((ne=(Q=(U=le==null?void 0:le.prototype)==null?void 0:U.__proto__)==null?void 0:Q.constructor)==null?void 0:ne.name)==="TypedArray"}function q(le){return Number.isInteger(le)||typeof le=="bigint"}function g(le){return le==null||le===-1}function x(le){const U=[];let Q=le;for(;Array.isArray(Q);)U.push(Q.length),Q=Q[0];return U}function E(le,U,Q=void 0){const ne=le[U];if(ne!==void 0)return delete le[U],ne;if(Q===void 0)throw Error(`Key ${U} does not exist in object.`);return Q}function $(...le){return Array.prototype.concat.apply([],le)}function P(...le){return le.reduce((U,Q)=>U.flatMap(ne=>Q.map(N=>[ne,N])))}function Y(le,U){return Math.abs((le+U)%(2*U)-U)}function se(le,U){return Object.assign({},...U.map(Q=>{if(le[Q]!==void 0)return{[Q]:le[Q]}}))}function ue(le){let U=0;for(const Q of le)++U;return U}},"./src/utils/data-structures.js":(Oe,B,c)=>{c.r(B),c.d(B,{CharTrie:()=>R,PriorityQueue:()=>w,TokenLattice:()=>J});class w{constructor(x=($,P)=>$>P,E=1/0){this._heap=[],this._comparator=x,this._maxSize=E}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...x){return this.extend(x)}extend(x){for(const E of x)if(this.size0&&this._swap(0,E),this._heap.pop(),this._siftDown(),x}replace(x){const E=this.peek();return this._heap[0]=x,this._siftDown(),E}_parent(x){return(x+1>>>1)-1}_left(x){return(x<<1)+1}_right(x){return x+1<<1}_greater(x,E){return this._comparator(this._heap[x],this._heap[E])}_swap(x,E){const $=this._heap[x];this._heap[x]=this._heap[E],this._heap[E]=$}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(x){for(;x>0&&this._greater(x,this._parent(x));)this._swap(x,this._parent(x)),x=this._parent(x)}_siftDown(){let x=0;for(;this._left(x)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const P=new q(this.bosTokenId,0,0,0,0),Y=new q(this.eosTokenId,1,this.len,0,0);this.nodes.push(P.clone()),this.nodes.push(Y.clone()),this.beginNodes[this.len].push(Y),this.endNodes[0].push(P)}insert(x,E,$,P){const Y=this.nodes.length,se=new q(P,Y,x,E,$);this.beginNodes[x].push(se),this.endNodes[x+E].push(se),this.nodes.push(se)}viterbi(){const x=this.len;let E=0;for(;E<=x;){if(this.beginNodes[E].length==0)return[];for(let ue of this.beginNodes[E]){ue.prev=null;let le=0,U=null;for(let Q of this.endNodes[E]){const ne=Q.backtraceScore+ue.score;(U===null||ne>le)&&(U=Q.clone(),le=ne)}if(U!==null)ue.prev=U,ue.backtraceScore=le;else return[]}++E}const $=[],Y=this.beginNodes[x][0].prev;if(Y===null)return[];let se=Y.clone();for(;se.prev!==null;)$.push(se.clone()),se=se.clone().prev.clone();return $.reverse(),$}piece(x){return this.chars.slice(x.pos,x.pos+x.length).join("")}tokens(){return this.viterbi().map(E=>this.piece(E))}tokenIds(){return this.viterbi().map(E=>E.tokenId)}}class q{constructor(x,E,$,P,Y){this.tokenId=x,this.nodeId=E,this.pos=$,this.length=P,this.score=Y,this.prev=null,this.backtraceScore=0}clone(){const x=new q(this.tokenId,this.nodeId,this.pos,this.length,this.score);return x.prev=this.prev,x.backtraceScore=this.backtraceScore,x}}},"./src/utils/devices.js":(Oe,B,c)=>{c.r(B),c.d(B,{DEVICE_TYPES:()=>w});const w=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(Oe,B,c)=>{c.r(B),c.d(B,{DATA_TYPES:()=>J,DEFAULT_DEVICE_DTYPE_MAPPING:()=>q,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>g,isWebGpuFp16Supported:()=>H});var w=c("./src/env.js"),R=c("./src/utils/devices.js");const H=function(){let x;return async function(){if(x===void 0)if(!w.apis.IS_WEBGPU_AVAILABLE)x=!1;else try{x=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{x=!1}return x}}(),J=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),q=Object.freeze({[R.DEVICE_TYPES.wasm]:J.q8}),g=Object.freeze({[J.fp32]:"",[J.fp16]:"_fp16",[J.int8]:"_int8",[J.uint8]:"_uint8",[J.q8]:"_quantized",[J.q4]:"_q4",[J.q4f16]:"_q4f16",[J.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Oe,B,c)=>{c.r(B),c.d(B,{Callable:()=>w});const w=class{constructor(){let R=function(...H){return R._call(...H)};return Object.setPrototypeOf(R,new.target.prototype)}_call(...R){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Oe,B,c)=>{c.r(B),c.d(B,{getFile:()=>E,getModelFile:()=>ue,getModelJSON:()=>le});var w=c("?7a2c"),R=c("?a42a"),H=c("./src/env.js"),J=c("./src/utils/core.js");const q={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class g{constructor(N){if(this.filePath=N,this.headers=new Headers,this.exists=w.existsSync(N),this.exists){this.status=200,this.statusText="OK";let O=w.statSync(N);this.headers.set("content-length",O.size.toString()),this.updateContentType();let _=this;this.body=new ReadableStream({start(k){_.arrayBuffer().then(C=>{k.enqueue(new Uint8Array(C)),k.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const N=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",q[N]??"application/octet-stream")}clone(){let N=new g(this.filePath);return N.exists=this.exists,N.status=this.status,N.statusText=this.statusText,N.headers=new Headers(this.headers),N}async arrayBuffer(){return(await w.promises.readFile(this.filePath)).buffer}async blob(){const N=await w.promises.readFile(this.filePath);return new Blob([N],{type:this.headers.get("content-type")})}async text(){return await w.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function x(ne,N=null,O=null){let _;try{_=new URL(ne)}catch{return!1}return!(N&&!N.includes(_.protocol)||O&&!O.includes(_.hostname))}async function E(ne){var N;if(H.env.useFS&&!x(ne,["http:","https:","blob:"]))return new g(ne);if(typeof process<"u"&&((N=process==null?void 0:process.release)==null?void 0:N.name)==="node"){const O=!!(_s!=null&&_s.TESTING_REMOTELY),_=H.env.version,k=new Headers;if(k.set("User-Agent",`transformers.js/${_}; is_ci/${O};`),x(ne,["http:","https:"],["huggingface.co","hf.co"])){const Z=(_s==null?void 0:_s.HF_TOKEN)??(_s==null?void 0:_s.HF_ACCESS_TOKEN);Z&&k.set("Authorization",`Bearer ${Z}`)}return fetch(ne,{headers:k})}else return fetch(ne)}const $={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function P(ne,N,O){if(!O)return null;const _=$[ne]??`Error (${ne}) occurred while trying to load file`;throw Error(`${_}: "${N}".`)}class Y{constructor(N){this.path=N}async match(N){let O=R.join(this.path,N),_=new g(O);if(_.exists)return _}async put(N,O){const _=Buffer.from(await O.arrayBuffer());let k=R.join(this.path,N);try{await w.promises.mkdir(R.dirname(k),{recursive:!0}),await w.promises.writeFile(k,_)}catch(C){console.warn("An error occurred while writing the file to cache:",C)}}}async function se(ne,...N){for(let O of N)try{let _=await ne.match(O);if(_)return _}catch{continue}}async function ue(ne,N,O=!0,_={}){if(!H.env.allowLocalModels){if(_.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!H.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,J.dispatchCallback)(_.progress_callback,{status:"initiate",name:ne,file:N});let k;if(!k&&H.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{k=await caches.open("transformers-cache")}catch(pe){console.warn("An error occurred while opening the browser cache:",pe)}}if(!k&&H.env.useFSCache&&(k=new Y(_.cache_dir??H.env.cacheDir)),!k&&H.env.useCustomCache){if(!H.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!H.env.customCache.match||!H.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");k=H.env.customCache}const C=_.revision??"main";let Z=Q(ne,N),ee=Q(H.env.localModelPath,Z),_e=Q(H.env.remoteHost,H.env.remotePathTemplate.replaceAll("{model}",ne).replaceAll("{revision}",encodeURIComponent(C)),N),ge=C==="main"?Z:Q(ne,C,N),be,Se=k instanceof Y?ge:_e,Pe=!1,Le;k&&(Le=await se(k,ee,Se));const me=Le!==void 0;if(Le===void 0){if(H.env.allowLocalModels)if(x(Z,["http:","https:"])){if(_.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Z}.`);if(!H.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Z}.`)}else try{Le=await E(ee),be=ee}catch($e){console.warn(`Unable to load from local path "${ee}": "${$e}"`)}if(Le===void 0||Le.status===404){if(_.local_files_only||!H.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ee}".`);return null}if(Le=await E(_e),Le.status!==200)return P(Le.status,_e,O);be=Se}Pe=k&&typeof Response<"u"&&Le instanceof Response&&Le.status===200}(0,J.dispatchCallback)(_.progress_callback,{status:"download",name:ne,file:N});const j={status:"progress",name:ne,file:N};let he;return _.progress_callback?me&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(he=new Uint8Array(await Le.arrayBuffer()),(0,J.dispatchCallback)(_.progress_callback,{...j,progress:100,loaded:he.length,total:he.length})):he=await U(Le,pe=>{(0,J.dispatchCallback)(_.progress_callback,{...j,...pe})}):he=new Uint8Array(await Le.arrayBuffer()),Pe&&be&&await k.match(be)===void 0&&await k.put(be,new Response(he,{headers:Le.headers})).catch(pe=>{console.warn(`Unable to add response to browser cache: ${pe}.`)}),(0,J.dispatchCallback)(_.progress_callback,{status:"done",name:ne,file:N}),he}async function le(ne,N,O=!0,_={}){let k=await ue(ne,N,O,_);if(k===null)return{};let Z=new TextDecoder("utf-8").decode(k);return JSON.parse(Z)}async function U(ne,N){const O=ne.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let _=parseInt(O??"0"),k=new Uint8Array(_),C=0;const Z=ne.body.getReader();async function ee(){const{done:_e,value:ge}=await Z.read();if(_e)return;let be=C+ge.length;if(be>_){_=be;let Pe=new Uint8Array(_);Pe.set(k),k=Pe}k.set(ge,C),C=be;const Se=C/_*100;return N({progress:Se,loaded:C,total:_}),ee()}return await ee(),k}function Q(...ne){return ne=ne.map((N,O)=>(O&&(N=N.replace(new RegExp("^/"),"")),O!==ne.length-1&&(N=N.replace(new RegExp("/$"),"")),N)),ne.join("/")}},"./src/utils/image.js":(Oe,B,c)=>{c.r(B),c.d(B,{RawImage:()=>ue});var w=c("./src/utils/core.js"),R=c("./src/utils/hub.js"),H=c("./src/env.js"),J=c("./src/utils/tensor.js"),q=c("?2b25");const g=typeof self<"u",x=g&&self.constructor.name==="DedicatedWorkerGlobalScope";let E,$,P;if(g)E=(le,U)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(le,U)},P=self.createImageBitmap,$=self.ImageData;else if(q)P=async le=>{const Q=(await le.metadata()).channels,{data:ne,info:N}=await le.rotate().raw().toBuffer({resolveWithObject:!0}),O=new ue(new Uint8ClampedArray(ne),N.width,N.height,N.channels);return Q!==void 0&&Q!==N.channels&&O.convert(Q),O};else throw new Error("Unable to load image processing library.");const Y={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},se=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class ue{constructor(U,Q,ne,N){this.data=U,this.width=Q,this.height=ne,this.channels=N}get size(){return[this.width,this.height]}static async read(U){if(U instanceof ue)return U;if(typeof U=="string"||U instanceof URL)return await this.fromURL(U);throw new Error(`Unsupported input type: ${typeof U}`)}static fromCanvas(U){if(!g)throw new Error("fromCanvas() is only supported in browser environments.");const ne=U.getContext("2d").getImageData(0,0,U.width,U.height).data;return new ue(ne,U.width,U.height,4)}static async fromURL(U){const Q=await(0,R.getFile)(U);if(Q.status!==200)throw new Error(`Unable to read image from "${U}" (${Q.status} ${Q.statusText})`);const ne=await Q.blob();return this.fromBlob(ne)}static async fromBlob(U){if(g){const Q=await P(U),ne=E(Q.width,Q.height).getContext("2d");return ne.drawImage(Q,0,0),new this(ne.getImageData(0,0,Q.width,Q.height).data,Q.width,Q.height,4)}else{const Q=q(await U.arrayBuffer());return await P(Q)}}static fromTensor(U,Q="CHW"){if(U.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${U.dims.length} dimensions.`);if(Q==="CHW")U=U.transpose(1,2,0);else if(Q!=="HWC")throw new Error(`Unsupported channel format: ${Q}`);if(!(U.data instanceof Uint8ClampedArray||U.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${U.type}`);switch(U.dims[2]){case 1:case 2:case 3:case 4:return new ue(U.data,U.dims[1],U.dims[0],U.dims[2]);default:throw new Error(`Unsupported number of channels: ${U.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const U=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let Q=0,ne=0;Q=0?C=ne:ee=-ne,N>=0?Z=N:_e=-N,k.drawImage(_,C,Z,U,Q,ee,_e,U,Q),new ue(k.getImageData(0,0,U,Q).data,U,Q,4).convert(O)}else{let O=this.toSharp();if(ne>=0&&N>=0)O=O.extract({left:Math.floor(ne),top:Math.floor(N),width:U,height:Q});else if(ne<=0&&N<=0){const _=Math.floor(-N),k=Math.floor(-ne);O=O.extend({top:_,left:k,right:U-this.width-k,bottom:Q-this.height-_})}else{let _=[0,0],k=0;N<0?(_[0]=Math.floor(-N),_[1]=Q-this.height-_[0]):k=Math.floor(N);let C=[0,0],Z=0;ne<0?(C[0]=Math.floor(-ne),C[1]=U-this.width-C[0]):Z=Math.floor(ne),O=O.extend({top:_[0],bottom:_[1],left:C[0],right:C[1]}).extract({left:Z,top:k,width:U,height:Q})}return await P(O)}}async toBlob(U="image/png",Q=1){if(!g)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:U,quality:Q})}toTensor(U="CHW"){let Q=new J.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(U!=="HWC")if(U==="CHW")Q=Q.permute(2,0,1);else throw new Error(`Unsupported channel format: ${U}`);return Q}toCanvas(){if(!g)throw new Error("toCanvas() is only supported in browser environments.");const U=this.clone().rgba(),Q=E(U.width,U.height),ne=new $(U.data,U.width,U.height);return Q.getContext("2d").putImageData(ne,0,0),Q}split(){const{data:U,width:Q,height:ne,channels:N}=this,O=U.constructor,_=U.length/N,k=Array.from({length:N},()=>new O(_));for(let C=0;C<_;++C){const Z=N*C;for(let ee=0;eenew ue(C,Q,ne,1))}_update(U,Q,ne,N=null){return this.data=U,this.width=Q,this.height=ne,N!==null&&(this.channels=N),this}clone(){return new ue(this.data.slice(),this.width,this.height,this.channels)}convert(U){if(this.channels===U)return this;switch(U){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(U){if(g){if(x)throw new Error("Unable to save an image from a Web Worker.");const Q=U.split(".").pop().toLowerCase(),ne=se.get(Q)??"image/png",N=await this.toBlob(ne),O=URL.createObjectURL(N),_=document.createElement("a");_.href=O,_.download=U,_.click(),_.remove()}else{if(H.env.useFS)return await this.toSharp().toFile(U);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(g)throw new Error("toSharp() is only supported in server-side environments.");return q(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(Oe,B,c)=>{c.r(B),c.d(B,{FFT:()=>ue,bankers_round:()=>Q,cos_sim:()=>g,dot:()=>q,dynamic_time_warping:()=>ne,interpolate_data:()=>w,log_softmax:()=>J,magnitude:()=>x,max:()=>$,medianFilter:()=>le,min:()=>E,permute_data:()=>R,round:()=>U,softmax:()=>H});function w(N,[O,_,k],[C,Z],ee="bilinear",_e=!1){const ge=Z/k,be=C/_,Se=new N.constructor(C*Z*O),Pe=_*k,Le=C*Z;for(let me=0;me=0;--_e)C[_e]=ge,k[_e]=O[_[_e]],ge*=k[_e];const Z=_.map((_e,ge)=>C[_.indexOf(ge)]),ee=new N.constructor(N.length);for(let _e=0;_e=0;--be)ge+=Se%O[be]*Z[be],Se=Math.floor(Se/O[be]);ee[ge]=N[_e]}return[ee,k]}function H(N){const O=$(N)[0],_=N.map(Z=>Math.exp(Z-O)),k=_.reduce((Z,ee)=>Z+ee,0);return _.map(Z=>Z/k)}function J(N){const O=$(N)[0];let _=0;for(let Z=0;ZZ-O-k)}function q(N,O){let _=0;for(let k=0;kO+_*_,0))}function E(N){if(N.length===0)throw Error("Array must not be empty");let O=N[0],_=0;for(let k=1;kO&&(O=N[k],_=k);return[Number(O),_]}function P(N){return N>0&&(N&N-1)===0}class Y{constructor(O){if(this.size=O|0,this.size<=1||!P(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=O<<1,this.table=new Float64Array(this.size*2);for(let k=0;kk;k<<=1)++_;this._width=_%2===0?_-1:_,this._bitrev=new Int32Array(1<>>C&3)<>>1);for(let C=0;C>>1]=O[C];return k}toComplexArray(O,_){const k=_||this.createComplexArray();for(let C=0;C>>1],k[C+1]=0;return k}transform(O,_){if(O===_)throw new Error("Input and output buffers must be different");this._transform4(O,_,1)}realTransform(O,_){if(O===_)throw new Error("Input and output buffers must be different");this._realTransform4(O,_,1)}inverseTransform(O,_){if(O===_)throw new Error("Input and output buffers must be different");this._transform4(O,_,-1);for(let k=0;k>=2;ee>=2;ee>>=2){_e=C/ee<<1;const Le=_e>>>2;for(ge=0;ge>>1,ee>>>1)}else for(ge=0,be=0;ge>>1,ee>>>1,k)}const Pe=this.table;for(ee>>=2;ee>=2;ee>>=2){_e=C/ee<<1;const me=_e>>>1,j=me>>>1,he=j>>>1;for(ge=0;ge>>1;for(let me=2;me>1;++Se){const Pe=(Se+1-O)**2/2,Le=Math.sqrt(ge**2+be**2)**Pe,me=Pe*Math.atan2(be,ge),j=2*Se;Z[j]=Le*Math.cos(me),Z[j+1]=Le*Math.sin(me),ee[j]=Z[j],ee[j+1]=-Z[j+1]}this._slicedChirpBuffer=Z.subarray(_,k),this._f=new Y(C>>1),this._f.transform(this._chirpBuffer,ee)}_transform(O,_,k){const C=this._buffer1,Z=this._buffer2,ee=this._outBuffer1,_e=this._outBuffer2,ge=this._chirpBuffer,be=this._slicedChirpBuffer,Se=this._a;if(k)for(let Pe=0;Pe>1,j=_[me];C[Pe]=j*be[Pe],C[Le]=j*be[Le]}else for(let Pe=0;Pe=N.length&&(ge=2*(N.length-1)-ge),k[ee++]=N[ge]}k.sort(),_[Z]=k[C]}return _}function U(N,O){const _=Math.pow(10,O);return Math.round(N*_)/_}function Q(N){const O=Math.round(N);return Math.abs(N)%1===.5?O%2===0?O:O-1:O}function ne(N){const O=N.length,_=N[0].length,k=[O+1,_+1],C=Array.from({length:k[0]},()=>Array(k[1]).fill(1/0));C[0][0]=0;const Z=Array.from({length:k[0]},()=>Array(k[1]).fill(-1));for(let Se=1;Se0||_e>0;)switch(ge.push(ee-1),be.push(_e-1),Z[ee][_e]){case 0:--ee,--_e;break;case 1:--ee;break;case 2:--_e;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ee}, ${_e}]. Please file a bug report.`)}return ge.reverse(),be.reverse(),[ge,be]}},"./src/utils/tensor.js":(Oe,B,c)=>{c.r(B),c.d(B,{Tensor:()=>q,cat:()=>N,full:()=>ee,full_like:()=>_e,interpolate:()=>E,interpolate_4d:()=>$,layer_norm:()=>le,matmul:()=>P,mean:()=>k,mean_pooling:()=>ue,ones:()=>ge,ones_like:()=>be,permute:()=>x,quantize_embeddings:()=>Le,rfft:()=>Y,stack:()=>O,std_mean:()=>_,topk:()=>se,zeros:()=>Se,zeros_like:()=>Pe});var w=c("./src/utils/maths.js"),R=c("./src/backends/onnx.js"),H=c("./src/ops/registry.js");const J=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class q{constructor(...j){Te(this,"ort_tensor");return(0,R.isONNXTensor)(j[0])?this.ort_tensor=j[0]:this.ort_tensor=new R.Tensor(j[0],j[1],j[2]),new Proxy(this,{get:(he,pe)=>{if(typeof pe=="string"){let $e=Number(pe);if(Number.isInteger($e))return he._getitem($e)}return he[pe]},set:(he,pe,$e)=>he[pe]=$e})}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,...he]=this.dims;if(he.length>0){const pe=he.reduce(($e,Ne)=>$e*Ne);for(let $e=0;$e0){const $e=pe.reduce((Ne,Ke)=>Ne*Ke);return this._subarray(j,$e,pe)}else return new q(this.type,[this.data[j]],pe)}indexOf(j){const he=this.data;for(let pe=0;peze)throw new Error(`Invalid slice: ${je}`);const we=[Math.max(st,0),Math.min(ze,this.dims[ie])];pe.push(we),he.push(we[1]-we[0])}else throw new Error(`Invalid slice: ${je}`)}const $e=pe.map(([ie,je])=>je-ie),Ne=$e.reduce((ie,je)=>ie*je),Ke=this.data,Je=new Ke.constructor(Ne),lt=this.stride();for(let ie=0;ie=0;--st){const we=$e[st];je+=(ze%we+pe[st][0])*lt[st],ze=Math.floor(ze/we)}Je[ie]=Ke[je]}return new q(this.type,Je,he)}permute(...j){return x(this,j)}transpose(...j){return this.permute(...j)}sum(j=null,he=!1){return this.norm(1,j,he)}norm(j="fro",he=null,pe=!1){if(j==="fro")j=2;else if(typeof j=="string")throw Error(`Unsupported norm: ${j}`);const $e=this.data;if(he===null){let Je=$e.reduce((lt,ie)=>lt+ie**j,0)**(1/j);return new q(this.type,[Je],[])}he=ne(he,this.dims.length);const Ne=this.dims.slice();Ne[he]=1;const Ke=new $e.constructor($e.length/this.dims[he]);for(let Je=0;Je<$e.length;++Je){let lt=0;for(let ie=this.dims.length-1,je=Je,st=1;ie>=0;--ie){const ze=this.dims[ie];if(ie!==he){const we=je%ze;lt+=we*st,st*=Ne[ie]}je=Math.floor(je/ze)}Ke[lt]+=$e[Je]**j}if(j!==1)for(let Je=0;Je=0;--lt){const st=this.dims[lt];if(lt!==he){const ze=ie%st;Je+=ze*je,je*=this.dims[lt]}ie=Math.floor(ie/st)}$e[Ke]/=Ne[Je]}return this}normalize(j=2,he=1){return this.clone().normalize_(j,he)}stride(){return C(this.dims)}squeeze(j=null){return new q(this.type,this.data,U(this.dims,j))}squeeze_(j=null){return this.dims=U(this.dims,j),this}unsqueeze(j=null){return new q(this.type,this.data,Q(this.dims,j))}unsqueeze_(j=null){return this.dims=Q(this.dims,j),this}flatten_(j=0,he=-1){he=(he+this.dims.length)%this.dims.length;let pe=this.dims.slice(0,j),$e=this.dims.slice(j,he+1),Ne=this.dims.slice(he+1);return this.dims=[...pe,$e.reduce((Ke,Je)=>Ke*Je,1),...Ne],this}flatten(j=0,he=-1){return this.clone().flatten_(j,he)}view(...j){let he=-1;for(let $e=0;$eJe!==he?Ne*Ke:Ne,1);j[he]=pe.length/$e}return new q(this.type,pe,j)}neg_(){const j=this.data;for(let he=0;heNe*Ke);if(he!==pe)throw Error(`cannot reshape array of size ${he} into shape (${j})`);let $e=me;for(let Ne=j.length-1;Ne>=0;Ne--)$e=$e.reduce((Ke,Je)=>{let lt=Ke[Ke.length-1];return lt.lengthhe!==1):typeof j=="number"?me[j]===1&&me.splice(j,1):Array.isArray(j)&&(me=me.filter((he,pe)=>he!==1||!j.includes(pe))),me}function Q(me,j){return j=ne(j,me.length+1),me=me.slice(),me.splice(j,0,1),me}function ne(me,j,he=null,pe=!0){if(pe&&(me<-j||me>=j))throw new Error(`IndexError: index ${me} is out of bounds for dimension${he===null?"":" "+he} with size ${j}`);return me<0&&(me=(me%j+j)%j),me}function N(me,j=0){j=ne(j,me[0].dims.length);const he=me[0].dims.slice();he[j]=me.reduce((Ke,Je)=>Ke+Je.dims[j],0);const pe=he.reduce((Ke,Je)=>Ke*Je,1),$e=new me[0].data.constructor(pe),Ne=me[0].type;if(j===0){let Ke=0;for(const Je of me){const lt=Je.data;$e.set(lt,Ke),Ke+=lt.length}}else{let Ke=0;for(let Je=0;Je=0;--ze){const Ze=ie[ze];let Qe=we%Ze;ze===j&&(Qe+=Ke),st+=Qe*Ce,Ce*=he[ze],we=Math.floor(we/Ze)}$e[st]=lt[je]}Ke+=ie[j]}}return new q(Ne,$e,he)}function O(me,j=0){return N(me.map(he=>he.unsqueeze(j)),j)}function _(me,j=null,he=1,pe=!1){const $e=me.data,Ne=me.dims;if(j===null){const ze=$e.reduce((Qe,He)=>Qe+He,0)/$e.length,we=Math.sqrt($e.reduce((Qe,He)=>Qe+(He-ze)**2,0)/($e.length-he)),Ce=new q(me.type,[ze],[]);return[new q(me.type,[we],[]),Ce]}j=ne(j,Ne.length);const Ke=k(me,j,pe),Je=Ke.data,lt=Ne.slice();lt[j]=1;const ie=new $e.constructor($e.length/Ne[j]);for(let st=0;st<$e.length;++st){let ze=0;for(let we=Ne.length-1,Ce=st,Ze=1;we>=0;--we){const Qe=Ne[we];if(we!==j){const He=Ce%Qe;ze+=He*Ze,Ze*=lt[we]}Ce=Math.floor(Ce/Qe)}ie[ze]+=($e[st]-Je[ze])**2}for(let st=0;stlt+ie,0);return new q(me.type,[Je/pe.length],[])}const $e=me.dims;j=ne(j,$e.length);const Ne=$e.slice();Ne[j]=1;const Ke=new pe.constructor(pe.length/$e[j]);for(let Je=0;Je=0;--ie){const ze=$e[ie];if(ie!==j){const we=je%ze;lt+=we*st,st*=Ne[ie]}je=Math.floor(je/ze)}Ke[lt]+=pe[Je]}if($e[j]!==1)for(let Je=0;Je=0;--he)j[he]=pe,pe*=me[he];return j}function Z(me,j,he,pe){const $e=me.reduce((Ne,Ke)=>Ne*Ke,1);return new q(he,new pe($e).fill(j),me)}function ee(me,j){let he,pe;if(typeof j=="number")he="float32",pe=Float32Array;else if(typeof j=="bigint")he="int64",pe=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof j}`);return Z(me,j,he,pe)}function _e(me,j){return ee(me.dims,j)}function ge(me){return Z(me,1n,"int64",BigInt64Array)}function be(me){return ge(me.dims)}function Se(me){return Z(me,0n,"int64",BigInt64Array)}function Pe(me){return Se(me.dims)}function Le(me,j){if(me.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(me.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 he=j==="binary",pe=he?"int8":"uint8",$e=he?Int8Array:Uint8Array,Ne=me.data,Ke=new $e(Ne.length/8);for(let Je=0;Je0?1:0,ie=Math.floor(Je/8),je=Je%8;Ke[ie]|=lt<<7-je,he&&je===0&&(Ke[ie]-=128)}return new q(pe,Ke,[me.dims[0],me.dims[1]/8])}}},co={};function fr(Oe){var B=co[Oe];if(B!==void 0)return B.exports;var c=co[Oe]={exports:{}};return ln[Oe](c,c.exports,fr),c.exports}fr.m=ln,(()=>{var Oe=Object.getPrototypeOf?c=>Object.getPrototypeOf(c):c=>c.__proto__,B;fr.t=function(c,w){if(w&1&&(c=this(c)),w&8||typeof c=="object"&&c&&(w&4&&c.__esModule||w&16&&typeof c.then=="function"))return c;var R=Object.create(null);fr.r(R);var H={};B=B||[null,Oe({}),Oe([]),Oe(Oe)];for(var J=w&2&&c;typeof J=="object"&&!~B.indexOf(J);J=Oe(J))Object.getOwnPropertyNames(J).forEach(q=>H[q]=()=>c[q]);return H.default=()=>c,fr.d(R,H),R}})(),fr.d=(Oe,B)=>{for(var c in B)fr.o(B,c)&&!fr.o(Oe,c)&&Object.defineProperty(Oe,c,{enumerable:!0,get:B[c]})},fr.o=(Oe,B)=>Object.prototype.hasOwnProperty.call(Oe,B),fr.r=Oe=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Oe,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Oe,"__esModule",{value:!0})},(()=>{var Oe;if(typeof self.location.href=="string"&&(Oe=self.location.href),!Oe)throw new Error("Automatic publicPath is not supported in this browser");Oe=Oe.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),fr.p=Oe})(),fr.b=new URL("./",self.location.href);var d={};/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/fr.r(d),fr.d(d,{ASTFeatureExtractor:()=>Mn.ASTFeatureExtractor,ASTForAudioClassification:()=>y.ASTForAudioClassification,ASTModel:()=>y.ASTModel,ASTPreTrainedModel:()=>y.ASTPreTrainedModel,AlbertForMaskedLM:()=>y.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>y.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>y.AlbertForSequenceClassification,AlbertModel:()=>y.AlbertModel,AlbertPreTrainedModel:()=>y.AlbertPreTrainedModel,AlbertTokenizer:()=>Xt.AlbertTokenizer,AudioClassificationPipeline:()=>Dr.AudioClassificationPipeline,AutoConfig:()=>vp.AutoConfig,AutoFeatureExtractor:()=>Xm.AutoFeatureExtractor,AutoImageProcessor:()=>Jm.AutoImageProcessor,AutoModel:()=>y.AutoModel,AutoModelForAudioClassification:()=>y.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>y.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>y.AutoModelForCTC,AutoModelForCausalLM:()=>y.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>y.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>y.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>y.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>y.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>y.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>y.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>y.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>y.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>y.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>y.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>y.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>y.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>y.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>y.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>y.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>y.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>y.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>y.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>y.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>y.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>y.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>y.AutoModelForVision2Seq,AutoModelForXVector:()=>y.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>y.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>ef.AutoProcessor,AutoTokenizer:()=>Xt.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>Dr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>y.BartForConditionalGeneration,BartForSequenceClassification:()=>y.BartForSequenceClassification,BartModel:()=>y.BartModel,BartPretrainedModel:()=>y.BartPretrainedModel,BartTokenizer:()=>Xt.BartTokenizer,BaseModelOutput:()=>y.BaseModelOutput,BaseStreamer:()=>Tp.BaseStreamer,BeitFeatureExtractor:()=>Ht.BeitFeatureExtractor,BeitForImageClassification:()=>y.BeitForImageClassification,BeitModel:()=>y.BeitModel,BeitPreTrainedModel:()=>y.BeitPreTrainedModel,BertForMaskedLM:()=>y.BertForMaskedLM,BertForQuestionAnswering:()=>y.BertForQuestionAnswering,BertForSequenceClassification:()=>y.BertForSequenceClassification,BertForTokenClassification:()=>y.BertForTokenClassification,BertModel:()=>y.BertModel,BertPreTrainedModel:()=>y.BertPreTrainedModel,BertTokenizer:()=>Xt.BertTokenizer,BitImageProcessor:()=>Ht.BitImageProcessor,BlenderbotForConditionalGeneration:()=>y.BlenderbotForConditionalGeneration,BlenderbotModel:()=>y.BlenderbotModel,BlenderbotPreTrainedModel:()=>y.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>y.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>y.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>y.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>Xt.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>Xt.BlenderbotTokenizer,BloomForCausalLM:()=>y.BloomForCausalLM,BloomModel:()=>y.BloomModel,BloomPreTrainedModel:()=>y.BloomPreTrainedModel,BloomTokenizer:()=>Xt.BloomTokenizer,CLIPFeatureExtractor:()=>Ht.CLIPFeatureExtractor,CLIPImageProcessor:()=>Ht.CLIPImageProcessor,CLIPModel:()=>y.CLIPModel,CLIPPreTrainedModel:()=>y.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>y.CLIPSegForImageSegmentation,CLIPSegModel:()=>y.CLIPSegModel,CLIPSegPreTrainedModel:()=>y.CLIPSegPreTrainedModel,CLIPTextModel:()=>y.CLIPTextModel,CLIPTextModelWithProjection:()=>y.CLIPTextModelWithProjection,CLIPTokenizer:()=>Xt.CLIPTokenizer,CLIPVisionModel:()=>y.CLIPVisionModel,CLIPVisionModelWithProjection:()=>y.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>y.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>y.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>y.CamembertForSequenceClassification,CamembertForTokenClassification:()=>y.CamembertForTokenClassification,CamembertModel:()=>y.CamembertModel,CamembertPreTrainedModel:()=>y.CamembertPreTrainedModel,CamembertTokenizer:()=>Xt.CamembertTokenizer,CausalLMOutput:()=>y.CausalLMOutput,CausalLMOutputWithPast:()=>y.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Ht.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>y.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>y.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>y.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Mn.ClapFeatureExtractor,ClapModel:()=>y.ClapModel,ClapPreTrainedModel:()=>y.ClapPreTrainedModel,ClapTextModelWithProjection:()=>y.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>us.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>y.CodeGenForCausalLM,CodeGenModel:()=>y.CodeGenModel,CodeGenPreTrainedModel:()=>y.CodeGenPreTrainedModel,CodeGenTokenizer:()=>Xt.CodeGenTokenizer,CodeLlamaTokenizer:()=>Xt.CodeLlamaTokenizer,CohereForCausalLM:()=>y.CohereForCausalLM,CohereModel:()=>y.CohereModel,CoherePreTrainedModel:()=>y.CoherePreTrainedModel,CohereTokenizer:()=>Xt.CohereTokenizer,ConvBertForMaskedLM:()=>y.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>y.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>y.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>y.ConvBertForTokenClassification,ConvBertModel:()=>y.ConvBertModel,ConvBertPreTrainedModel:()=>y.ConvBertPreTrainedModel,ConvBertTokenizer:()=>Xt.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Ht.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>y.ConvNextForImageClassification,ConvNextImageProcessor:()=>Ht.ConvNextImageProcessor,ConvNextModel:()=>y.ConvNextModel,ConvNextPreTrainedModel:()=>y.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>y.ConvNextV2ForImageClassification,ConvNextV2Model:()=>y.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>y.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Ht.DPTFeatureExtractor,DPTForDepthEstimation:()=>y.DPTForDepthEstimation,DPTImageProcessor:()=>Ht.DPTImageProcessor,DPTModel:()=>y.DPTModel,DPTPreTrainedModel:()=>y.DPTPreTrainedModel,DebertaForMaskedLM:()=>y.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>y.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>y.DebertaForSequenceClassification,DebertaForTokenClassification:()=>y.DebertaForTokenClassification,DebertaModel:()=>y.DebertaModel,DebertaPreTrainedModel:()=>y.DebertaPreTrainedModel,DebertaTokenizer:()=>Xt.DebertaTokenizer,DebertaV2ForMaskedLM:()=>y.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>y.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>y.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>y.DebertaV2ForTokenClassification,DebertaV2Model:()=>y.DebertaV2Model,DebertaV2PreTrainedModel:()=>y.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>Xt.DebertaV2Tokenizer,DecisionTransformerModel:()=>y.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>y.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>Ht.DeiTFeatureExtractor,DeiTForImageClassification:()=>y.DeiTForImageClassification,DeiTImageProcessor:()=>Ht.DeiTImageProcessor,DeiTModel:()=>y.DeiTModel,DeiTPreTrainedModel:()=>y.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>y.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>y.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>Dr.DepthEstimationPipeline,DepthProForDepthEstimation:()=>y.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>y.DepthProPreTrainedModel,DetrFeatureExtractor:()=>Ht.DetrFeatureExtractor,DetrForObjectDetection:()=>y.DetrForObjectDetection,DetrForSegmentation:()=>y.DetrForSegmentation,DetrImageProcessor:()=>Ht.DetrImageProcessor,DetrModel:()=>y.DetrModel,DetrObjectDetectionOutput:()=>y.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>y.DetrPreTrainedModel,DetrSegmentationOutput:()=>y.DetrSegmentationOutput,Dinov2ForImageClassification:()=>y.Dinov2ForImageClassification,Dinov2Model:()=>y.Dinov2Model,Dinov2PreTrainedModel:()=>y.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>y.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>y.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>y.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>y.DistilBertForTokenClassification,DistilBertModel:()=>y.DistilBertModel,DistilBertPreTrainedModel:()=>y.DistilBertPreTrainedModel,DistilBertTokenizer:()=>Xt.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>Dr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Ht.DonutFeatureExtractor,DonutImageProcessor:()=>Ht.DonutImageProcessor,DonutSwinModel:()=>y.DonutSwinModel,DonutSwinPreTrainedModel:()=>y.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>y.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Ht.EfficientNetImageProcessor,EfficientNetModel:()=>y.EfficientNetModel,EfficientNetPreTrainedModel:()=>y.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>y.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>y.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>y.ElectraForSequenceClassification,ElectraForTokenClassification:()=>y.ElectraForTokenClassification,ElectraModel:()=>y.ElectraModel,ElectraPreTrainedModel:()=>y.ElectraPreTrainedModel,ElectraTokenizer:()=>Xt.ElectraTokenizer,EosTokenCriteria:()=>Ba.EosTokenCriteria,EsmForMaskedLM:()=>y.EsmForMaskedLM,EsmForSequenceClassification:()=>y.EsmForSequenceClassification,EsmForTokenClassification:()=>y.EsmForTokenClassification,EsmModel:()=>y.EsmModel,EsmPreTrainedModel:()=>y.EsmPreTrainedModel,EsmTokenizer:()=>Xt.EsmTokenizer,FFT:()=>vs.FFT,FalconForCausalLM:()=>y.FalconForCausalLM,FalconModel:()=>y.FalconModel,FalconPreTrainedModel:()=>y.FalconPreTrainedModel,FalconTokenizer:()=>Xt.FalconTokenizer,FastViTForImageClassification:()=>y.FastViTForImageClassification,FastViTModel:()=>y.FastViTModel,FastViTPreTrainedModel:()=>y.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>Dr.FeatureExtractionPipeline,FeatureExtractor:()=>Qm.FeatureExtractor,FillMaskPipeline:()=>Dr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>y.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>y.Florence2PreTrainedModel,Florence2Processor:()=>qs.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>us.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>us.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>Ht.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>y.GLPNForDepthEstimation,GLPNModel:()=>y.GLPNModel,GLPNPreTrainedModel:()=>y.GLPNPreTrainedModel,GPT2LMHeadModel:()=>y.GPT2LMHeadModel,GPT2Model:()=>y.GPT2Model,GPT2PreTrainedModel:()=>y.GPT2PreTrainedModel,GPT2Tokenizer:()=>Xt.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>y.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>y.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>y.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>y.GPTJForCausalLM,GPTJModel:()=>y.GPTJModel,GPTJPreTrainedModel:()=>y.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>y.GPTNeoForCausalLM,GPTNeoModel:()=>y.GPTNeoModel,GPTNeoPreTrainedModel:()=>y.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>y.GPTNeoXForCausalLM,GPTNeoXModel:()=>y.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>y.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>Xt.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>y.Gemma2ForCausalLM,Gemma2Model:()=>y.Gemma2Model,Gemma2PreTrainedModel:()=>y.Gemma2PreTrainedModel,GemmaForCausalLM:()=>y.GemmaForCausalLM,GemmaModel:()=>y.GemmaModel,GemmaPreTrainedModel:()=>y.GemmaPreTrainedModel,GemmaTokenizer:()=>Xt.GemmaTokenizer,GraniteForCausalLM:()=>y.GraniteForCausalLM,GraniteModel:()=>y.GraniteModel,GranitePreTrainedModel:()=>y.GranitePreTrainedModel,Grok1Tokenizer:()=>Xt.Grok1Tokenizer,GroupViTModel:()=>y.GroupViTModel,GroupViTPreTrainedModel:()=>y.GroupViTPreTrainedModel,HerbertTokenizer:()=>Xt.HerbertTokenizer,HieraForImageClassification:()=>y.HieraForImageClassification,HieraModel:()=>y.HieraModel,HieraPreTrainedModel:()=>y.HieraPreTrainedModel,HubertForCTC:()=>y.HubertForCTC,HubertForSequenceClassification:()=>y.HubertForSequenceClassification,HubertModel:()=>y.HubertModel,HubertPreTrainedModel:()=>y.HubertPreTrainedModel,ImageClassificationPipeline:()=>Dr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>Dr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Mn.ImageFeatureExtractor,ImageMattingOutput:()=>y.ImageMattingOutput,ImageProcessor:()=>Ym.ImageProcessor,ImageSegmentationPipeline:()=>Dr.ImageSegmentationPipeline,ImageToImagePipeline:()=>Dr.ImageToImagePipeline,ImageToTextPipeline:()=>Dr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>Ba.InterruptableStoppingCriteria,JAISLMHeadModel:()=>y.JAISLMHeadModel,JAISModel:()=>y.JAISModel,JAISPreTrainedModel:()=>y.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>Ht.JinaCLIPImageProcessor,JinaCLIPModel:()=>y.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>y.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>qs.JinaCLIPProcessor,JinaCLIPTextModel:()=>y.JinaCLIPTextModel,JinaCLIPVisionModel:()=>y.JinaCLIPVisionModel,LlamaForCausalLM:()=>y.LlamaForCausalLM,LlamaModel:()=>y.LlamaModel,LlamaPreTrainedModel:()=>y.LlamaPreTrainedModel,LlamaTokenizer:()=>Xt.LlamaTokenizer,LlavaForConditionalGeneration:()=>y.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>y.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>Ht.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>y.LlavaPreTrainedModel,LogitsProcessor:()=>us.LogitsProcessor,LogitsProcessorList:()=>us.LogitsProcessorList,LogitsWarper:()=>us.LogitsWarper,LongT5ForConditionalGeneration:()=>y.LongT5ForConditionalGeneration,LongT5Model:()=>y.LongT5Model,LongT5PreTrainedModel:()=>y.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>y.M2M100ForConditionalGeneration,M2M100Model:()=>y.M2M100Model,M2M100PreTrainedModel:()=>y.M2M100PreTrainedModel,M2M100Tokenizer:()=>Xt.M2M100Tokenizer,MBart50Tokenizer:()=>Xt.MBart50Tokenizer,MBartForCausalLM:()=>y.MBartForCausalLM,MBartForConditionalGeneration:()=>y.MBartForConditionalGeneration,MBartForSequenceClassification:()=>y.MBartForSequenceClassification,MBartModel:()=>y.MBartModel,MBartPreTrainedModel:()=>y.MBartPreTrainedModel,MBartTokenizer:()=>Xt.MBartTokenizer,MPNetForMaskedLM:()=>y.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>y.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>y.MPNetForSequenceClassification,MPNetForTokenClassification:()=>y.MPNetForTokenClassification,MPNetModel:()=>y.MPNetModel,MPNetPreTrainedModel:()=>y.MPNetPreTrainedModel,MPNetTokenizer:()=>Xt.MPNetTokenizer,MT5ForConditionalGeneration:()=>y.MT5ForConditionalGeneration,MT5Model:()=>y.MT5Model,MT5PreTrainedModel:()=>y.MT5PreTrainedModel,MarianMTModel:()=>y.MarianMTModel,MarianModel:()=>y.MarianModel,MarianPreTrainedModel:()=>y.MarianPreTrainedModel,MarianTokenizer:()=>Xt.MarianTokenizer,Mask2FormerImageProcessor:()=>Ht.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>Ht.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>y.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>Ht.MaskFormerImageProcessor,MaskFormerModel:()=>y.MaskFormerModel,MaskFormerPreTrainedModel:()=>y.MaskFormerPreTrainedModel,MaskedLMOutput:()=>y.MaskedLMOutput,MaxLengthCriteria:()=>Ba.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>y.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>y.MgpstrModelOutput,MgpstrPreTrainedModel:()=>y.MgpstrPreTrainedModel,MgpstrProcessor:()=>qs.MgpstrProcessor,MgpstrTokenizer:()=>Xt.MgpstrTokenizer,MinLengthLogitsProcessor:()=>us.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>us.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>y.MistralForCausalLM,MistralModel:()=>y.MistralModel,MistralPreTrainedModel:()=>y.MistralPreTrainedModel,MobileBertForMaskedLM:()=>y.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>y.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>y.MobileBertForSequenceClassification,MobileBertModel:()=>y.MobileBertModel,MobileBertPreTrainedModel:()=>y.MobileBertPreTrainedModel,MobileBertTokenizer:()=>Xt.MobileBertTokenizer,MobileLLMForCausalLM:()=>y.MobileLLMForCausalLM,MobileLLMModel:()=>y.MobileLLMModel,MobileLLMPreTrainedModel:()=>y.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>Ht.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>y.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>Ht.MobileNetV1ImageProcessor,MobileNetV1Model:()=>y.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>y.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Ht.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>y.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>Ht.MobileNetV2ImageProcessor,MobileNetV2Model:()=>y.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>y.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Ht.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>y.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>Ht.MobileNetV3ImageProcessor,MobileNetV3Model:()=>y.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>y.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Ht.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>y.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>Ht.MobileNetV4ImageProcessor,MobileNetV4Model:()=>y.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>y.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Ht.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>y.MobileViTForImageClassification,MobileViTImageProcessor:()=>Ht.MobileViTImageProcessor,MobileViTModel:()=>y.MobileViTModel,MobileViTPreTrainedModel:()=>y.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>y.MobileViTV2ForImageClassification,MobileViTV2Model:()=>y.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>y.MobileViTV2PreTrainedModel,ModelOutput:()=>y.ModelOutput,Moondream1ForConditionalGeneration:()=>y.Moondream1ForConditionalGeneration,MptForCausalLM:()=>y.MptForCausalLM,MptModel:()=>y.MptModel,MptPreTrainedModel:()=>y.MptPreTrainedModel,MultiModalityCausalLM:()=>y.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>y.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>y.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>y.MusicgenForConditionalGeneration,MusicgenModel:()=>y.MusicgenModel,MusicgenPreTrainedModel:()=>y.MusicgenPreTrainedModel,NllbTokenizer:()=>Xt.NllbTokenizer,NoBadWordsLogitsProcessor:()=>us.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>us.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>y.NomicBertModel,NomicBertPreTrainedModel:()=>y.NomicBertPreTrainedModel,NougatImageProcessor:()=>Ht.NougatImageProcessor,NougatTokenizer:()=>Xt.NougatTokenizer,OPTForCausalLM:()=>y.OPTForCausalLM,OPTModel:()=>y.OPTModel,OPTPreTrainedModel:()=>y.OPTPreTrainedModel,ObjectDetectionPipeline:()=>Dr.ObjectDetectionPipeline,OlmoForCausalLM:()=>y.OlmoForCausalLM,OlmoModel:()=>y.OlmoModel,OlmoPreTrainedModel:()=>y.OlmoPreTrainedModel,OpenELMForCausalLM:()=>y.OpenELMForCausalLM,OpenELMModel:()=>y.OpenELMModel,OpenELMPreTrainedModel:()=>y.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Ht.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>y.OwlViTForObjectDetection,OwlViTImageProcessor:()=>Ht.OwlViTImageProcessor,OwlViTModel:()=>y.OwlViTModel,OwlViTPreTrainedModel:()=>y.OwlViTPreTrainedModel,OwlViTProcessor:()=>qs.OwlViTProcessor,Owlv2ForObjectDetection:()=>y.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Ht.Owlv2ImageProcessor,Owlv2Model:()=>y.Owlv2Model,Owlv2PreTrainedModel:()=>y.Owlv2PreTrainedModel,PatchTSMixerForPrediction:()=>y.PatchTSMixerForPrediction,PatchTSMixerModel:()=>y.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>y.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>y.PatchTSTForPrediction,PatchTSTModel:()=>y.PatchTSTModel,PatchTSTPreTrainedModel:()=>y.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>y.Phi3ForCausalLM,Phi3Model:()=>y.Phi3Model,Phi3PreTrainedModel:()=>y.Phi3PreTrainedModel,PhiForCausalLM:()=>y.PhiForCausalLM,PhiModel:()=>y.PhiModel,PhiPreTrainedModel:()=>y.PhiPreTrainedModel,Pipeline:()=>Dr.Pipeline,PreTrainedModel:()=>y.PreTrainedModel,PreTrainedTokenizer:()=>Xt.PreTrainedTokenizer,PretrainedConfig:()=>vp.PretrainedConfig,PretrainedMixin:()=>y.PretrainedMixin,Processor:()=>Zm.Processor,PvtForImageClassification:()=>y.PvtForImageClassification,PvtImageProcessor:()=>Ht.PvtImageProcessor,PvtModel:()=>y.PvtModel,PvtPreTrainedModel:()=>y.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>Mn.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>y.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>y.PyAnnoteModel,PyAnnotePreTrainedModel:()=>y.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>qs.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>y.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>Dr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>y.Qwen2ForCausalLM,Qwen2Model:()=>y.Qwen2Model,Qwen2PreTrainedModel:()=>y.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>Xt.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>y.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>Ht.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>y.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>qs.Qwen2VLProcessor,RTDetrForObjectDetection:()=>y.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Ht.RTDetrImageProcessor,RTDetrModel:()=>y.RTDetrModel,RTDetrObjectDetectionOutput:()=>y.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>y.RTDetrPreTrainedModel,RawImage:()=>qm.RawImage,RepetitionPenaltyLogitsProcessor:()=>us.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>y.ResNetForImageClassification,ResNetModel:()=>y.ResNetModel,ResNetPreTrainedModel:()=>y.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>y.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>y.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>y.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>y.RoFormerForTokenClassification,RoFormerModel:()=>y.RoFormerModel,RoFormerPreTrainedModel:()=>y.RoFormerPreTrainedModel,RoFormerTokenizer:()=>Xt.RoFormerTokenizer,RobertaForMaskedLM:()=>y.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>y.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>y.RobertaForSequenceClassification,RobertaForTokenClassification:()=>y.RobertaForTokenClassification,RobertaModel:()=>y.RobertaModel,RobertaPreTrainedModel:()=>y.RobertaPreTrainedModel,RobertaTokenizer:()=>Xt.RobertaTokenizer,SamImageProcessor:()=>Ht.SamImageProcessor,SamImageSegmentationOutput:()=>y.SamImageSegmentationOutput,SamModel:()=>y.SamModel,SamPreTrainedModel:()=>y.SamPreTrainedModel,SamProcessor:()=>qs.SamProcessor,SapiensForDepthEstimation:()=>y.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>y.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>y.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>y.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Mn.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Ht.SegformerFeatureExtractor,SegformerForImageClassification:()=>y.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>y.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>Ht.SegformerImageProcessor,SegformerModel:()=>y.SegformerModel,SegformerPreTrainedModel:()=>y.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>y.Seq2SeqLMOutput,SequenceClassifierOutput:()=>y.SequenceClassifierOutput,SiglipImageProcessor:()=>Ht.SiglipImageProcessor,SiglipModel:()=>y.SiglipModel,SiglipPreTrainedModel:()=>y.SiglipPreTrainedModel,SiglipTextModel:()=>y.SiglipTextModel,SiglipTokenizer:()=>Xt.SiglipTokenizer,SiglipVisionModel:()=>y.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Mn.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>y.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>y.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>y.SpeechT5HifiGan,SpeechT5Model:()=>y.SpeechT5Model,SpeechT5PreTrainedModel:()=>y.SpeechT5PreTrainedModel,SpeechT5Processor:()=>qs.SpeechT5Processor,SpeechT5Tokenizer:()=>Xt.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>y.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>y.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>y.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>y.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>y.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>Xt.SqueezeBertTokenizer,StableLmForCausalLM:()=>y.StableLmForCausalLM,StableLmModel:()=>y.StableLmModel,StableLmPreTrainedModel:()=>y.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>y.Starcoder2ForCausalLM,Starcoder2Model:()=>y.Starcoder2Model,Starcoder2PreTrainedModel:()=>y.Starcoder2PreTrainedModel,StoppingCriteria:()=>Ba.StoppingCriteria,StoppingCriteriaList:()=>Ba.StoppingCriteriaList,SummarizationPipeline:()=>Dr.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>us.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>y.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Ht.Swin2SRImageProcessor,Swin2SRModel:()=>y.Swin2SRModel,Swin2SRPreTrainedModel:()=>y.Swin2SRPreTrainedModel,SwinForImageClassification:()=>y.SwinForImageClassification,SwinModel:()=>y.SwinModel,SwinPreTrainedModel:()=>y.SwinPreTrainedModel,T5ForConditionalGeneration:()=>y.T5ForConditionalGeneration,T5Model:()=>y.T5Model,T5PreTrainedModel:()=>y.T5PreTrainedModel,T5Tokenizer:()=>Xt.T5Tokenizer,TableTransformerForObjectDetection:()=>y.TableTransformerForObjectDetection,TableTransformerModel:()=>y.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>y.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>y.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>us.TemperatureLogitsWarper,Tensor:()=>Yr.Tensor,Text2TextGenerationPipeline:()=>Dr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>Dr.TextClassificationPipeline,TextGenerationPipeline:()=>Dr.TextGenerationPipeline,TextStreamer:()=>Tp.TextStreamer,TextToAudioPipeline:()=>Dr.TextToAudioPipeline,TokenClassificationPipeline:()=>Dr.TokenClassificationPipeline,TokenClassifierOutput:()=>y.TokenClassifierOutput,TokenizerModel:()=>Xt.TokenizerModel,TopKLogitsWarper:()=>us.TopKLogitsWarper,TopPLogitsWarper:()=>us.TopPLogitsWarper,TrOCRForCausalLM:()=>y.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>y.TrOCRPreTrainedModel,TranslationPipeline:()=>Dr.TranslationPipeline,UniSpeechForCTC:()=>y.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>y.UniSpeechForSequenceClassification,UniSpeechModel:()=>y.UniSpeechModel,UniSpeechPreTrainedModel:()=>y.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>y.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>y.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>y.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>y.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>y.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>qs.VLChatProcessor,VLMImageProcessor:()=>Ht.VLMImageProcessor,ViTFeatureExtractor:()=>Ht.ViTFeatureExtractor,ViTForImageClassification:()=>y.ViTForImageClassification,ViTImageProcessor:()=>Ht.ViTImageProcessor,ViTMAEModel:()=>y.ViTMAEModel,ViTMAEPreTrainedModel:()=>y.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>y.ViTMSNForImageClassification,ViTMSNModel:()=>y.ViTMSNModel,ViTMSNPreTrainedModel:()=>y.ViTMSNPreTrainedModel,ViTModel:()=>y.ViTModel,ViTPreTrainedModel:()=>y.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>y.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>y.VitMatteForImageMatting,VitMatteImageProcessor:()=>Ht.VitMatteImageProcessor,VitMattePreTrainedModel:()=>y.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>y.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>Ht.VitPoseImageProcessor,VitPosePreTrainedModel:()=>y.VitPosePreTrainedModel,VitsModel:()=>y.VitsModel,VitsModelOutput:()=>y.VitsModelOutput,VitsPreTrainedModel:()=>y.VitsPreTrainedModel,VitsTokenizer:()=>Xt.VitsTokenizer,Wav2Vec2BertForCTC:()=>y.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>y.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>y.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>y.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>Xt.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Mn.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>y.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>y.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>y.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>y.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>y.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>qs.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>y.WavLMForAudioFrameClassification,WavLMForCTC:()=>y.WavLMForCTC,WavLMForSequenceClassification:()=>y.WavLMForSequenceClassification,WavLMForXVector:()=>y.WavLMForXVector,WavLMModel:()=>y.WavLMModel,WavLMPreTrainedModel:()=>y.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Mn.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>y.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>y.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Mn.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>y.WhisperForConditionalGeneration,WhisperModel:()=>y.WhisperModel,WhisperPreTrainedModel:()=>y.WhisperPreTrainedModel,WhisperProcessor:()=>qs.WhisperProcessor,WhisperTextStreamer:()=>Tp.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>us.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>Xt.WhisperTokenizer,XLMForQuestionAnswering:()=>y.XLMForQuestionAnswering,XLMForSequenceClassification:()=>y.XLMForSequenceClassification,XLMForTokenClassification:()=>y.XLMForTokenClassification,XLMModel:()=>y.XLMModel,XLMPreTrainedModel:()=>y.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>y.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>y.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>y.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>y.XLMRobertaForTokenClassification,XLMRobertaModel:()=>y.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>y.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>Xt.XLMRobertaTokenizer,XLMTokenizer:()=>Xt.XLMTokenizer,XLMWithLMHeadModel:()=>y.XLMWithLMHeadModel,XVectorOutput:()=>y.XVectorOutput,YolosFeatureExtractor:()=>Ht.YolosFeatureExtractor,YolosForObjectDetection:()=>y.YolosForObjectDetection,YolosImageProcessor:()=>Ht.YolosImageProcessor,YolosModel:()=>y.YolosModel,YolosObjectDetectionOutput:()=>y.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>y.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>Dr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>Dr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>Dr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>Dr.ZeroShotObjectDetectionPipeline,bankers_round:()=>vs.bankers_round,cat:()=>Yr.cat,cos_sim:()=>vs.cos_sim,dot:()=>vs.dot,dynamic_time_warping:()=>vs.dynamic_time_warping,env:()=>Hm.env,full:()=>Yr.full,full_like:()=>Yr.full_like,getKeyValueShapes:()=>vp.getKeyValueShapes,hamming:()=>Ho.hamming,hanning:()=>Ho.hanning,interpolate:()=>Yr.interpolate,interpolate_4d:()=>Yr.interpolate_4d,interpolate_data:()=>vs.interpolate_data,is_chinese_char:()=>Xt.is_chinese_char,layer_norm:()=>Yr.layer_norm,log_softmax:()=>vs.log_softmax,magnitude:()=>vs.magnitude,matmul:()=>Yr.matmul,max:()=>vs.max,mean:()=>Yr.mean,mean_pooling:()=>Yr.mean_pooling,medianFilter:()=>vs.medianFilter,mel_filter_bank:()=>Ho.mel_filter_bank,min:()=>vs.min,ones:()=>Yr.ones,ones_like:()=>Yr.ones_like,permute:()=>Yr.permute,permute_data:()=>vs.permute_data,pipeline:()=>Dr.pipeline,quantize_embeddings:()=>Yr.quantize_embeddings,read_audio:()=>Ho.read_audio,rfft:()=>Yr.rfft,round:()=>vs.round,softmax:()=>vs.softmax,spectrogram:()=>Ho.spectrogram,stack:()=>Yr.stack,std_mean:()=>Yr.std_mean,topk:()=>Yr.topk,window_function:()=>Ho.window_function,zeros:()=>Yr.zeros,zeros_like:()=>Yr.zeros_like});var Hm=fr("./src/env.js"),Dr=fr("./src/pipelines.js"),y=fr("./src/models.js"),Xt=fr("./src/tokenizers.js"),vp=fr("./src/configs.js"),Ho=fr("./src/utils/audio.js"),qm=fr("./src/utils/image.js"),Yr=fr("./src/utils/tensor.js"),vs=fr("./src/utils/maths.js"),Qm=fr("./src/base/feature_extraction_utils.js"),Mn=fr("./src/models/feature_extractors.js"),Xm=fr("./src/models/auto/feature_extraction_auto.js"),Ym=fr("./src/base/image_processors_utils.js"),Ht=fr("./src/models/image_processors.js"),Jm=fr("./src/models/auto/image_processing_auto.js"),Zm=fr("./src/base/processing_utils.js"),qs=fr("./src/models/processors.js"),ef=fr("./src/models/auto/processing_auto.js"),Tp=fr("./src/generation/streamers.js"),Ba=fr("./src/generation/stopping_criteria.js"),us=fr("./src/generation/logits_process.js");d.ASTFeatureExtractor,d.ASTForAudioClassification,d.ASTModel,d.ASTPreTrainedModel,d.AlbertForMaskedLM,d.AlbertForQuestionAnswering,d.AlbertForSequenceClassification,d.AlbertModel,d.AlbertPreTrainedModel,d.AlbertTokenizer,d.AudioClassificationPipeline,d.AutoConfig,d.AutoFeatureExtractor,d.AutoImageProcessor,d.AutoModel,d.AutoModelForAudioClassification,d.AutoModelForAudioFrameClassification,d.AutoModelForCTC,d.AutoModelForCausalLM,d.AutoModelForDepthEstimation,d.AutoModelForDocumentQuestionAnswering,d.AutoModelForImageClassification,d.AutoModelForImageFeatureExtraction,d.AutoModelForImageMatting,d.AutoModelForImageSegmentation,d.AutoModelForImageToImage,d.AutoModelForMaskGeneration,d.AutoModelForMaskedLM,d.AutoModelForNormalEstimation,d.AutoModelForObjectDetection,d.AutoModelForPoseEstimation,d.AutoModelForQuestionAnswering,d.AutoModelForSemanticSegmentation,d.AutoModelForSeq2SeqLM,d.AutoModelForSequenceClassification,d.AutoModelForSpeechSeq2Seq,d.AutoModelForTextToSpectrogram,d.AutoModelForTextToWaveform,d.AutoModelForTokenClassification,d.AutoModelForUniversalSegmentation,d.AutoModelForVision2Seq,d.AutoModelForXVector,d.AutoModelForZeroShotObjectDetection;var tf=d.AutoProcessor;d.AutoTokenizer,d.AutomaticSpeechRecognitionPipeline,d.BartForConditionalGeneration,d.BartForSequenceClassification,d.BartModel,d.BartPretrainedModel,d.BartTokenizer,d.BaseModelOutput;var rf=d.BaseStreamer;d.BeitFeatureExtractor,d.BeitForImageClassification,d.BeitModel,d.BeitPreTrainedModel,d.BertForMaskedLM,d.BertForQuestionAnswering,d.BertForSequenceClassification,d.BertForTokenClassification,d.BertModel,d.BertPreTrainedModel,d.BertTokenizer,d.BitImageProcessor,d.BlenderbotForConditionalGeneration,d.BlenderbotModel,d.BlenderbotPreTrainedModel,d.BlenderbotSmallForConditionalGeneration,d.BlenderbotSmallModel,d.BlenderbotSmallPreTrainedModel,d.BlenderbotSmallTokenizer,d.BlenderbotTokenizer,d.BloomForCausalLM,d.BloomModel,d.BloomPreTrainedModel,d.BloomTokenizer,d.CLIPFeatureExtractor,d.CLIPImageProcessor,d.CLIPModel,d.CLIPPreTrainedModel,d.CLIPSegForImageSegmentation,d.CLIPSegModel,d.CLIPSegPreTrainedModel,d.CLIPTextModel,d.CLIPTextModelWithProjection,d.CLIPTokenizer,d.CLIPVisionModel,d.CLIPVisionModelWithProjection,d.CamembertForMaskedLM,d.CamembertForQuestionAnswering,d.CamembertForSequenceClassification,d.CamembertForTokenClassification,d.CamembertModel,d.CamembertPreTrainedModel,d.CamembertTokenizer,d.CausalLMOutput,d.CausalLMOutputWithPast,d.ChineseCLIPFeatureExtractor,d.ChineseCLIPModel,d.ChineseCLIPPreTrainedModel,d.ClapAudioModelWithProjection,d.ClapFeatureExtractor,d.ClapModel,d.ClapPreTrainedModel,d.ClapTextModelWithProjection,d.ClassifierFreeGuidanceLogitsProcessor,d.CodeGenForCausalLM,d.CodeGenModel,d.CodeGenPreTrainedModel,d.CodeGenTokenizer,d.CodeLlamaTokenizer,d.CohereForCausalLM,d.CohereModel,d.CoherePreTrainedModel,d.CohereTokenizer,d.ConvBertForMaskedLM,d.ConvBertForQuestionAnswering,d.ConvBertForSequenceClassification,d.ConvBertForTokenClassification,d.ConvBertModel,d.ConvBertPreTrainedModel,d.ConvBertTokenizer,d.ConvNextFeatureExtractor,d.ConvNextForImageClassification,d.ConvNextImageProcessor,d.ConvNextModel,d.ConvNextPreTrainedModel,d.ConvNextV2ForImageClassification,d.ConvNextV2Model,d.ConvNextV2PreTrainedModel,d.DPTFeatureExtractor,d.DPTForDepthEstimation,d.DPTImageProcessor,d.DPTModel,d.DPTPreTrainedModel,d.DebertaForMaskedLM,d.DebertaForQuestionAnswering,d.DebertaForSequenceClassification,d.DebertaForTokenClassification,d.DebertaModel,d.DebertaPreTrainedModel,d.DebertaTokenizer,d.DebertaV2ForMaskedLM,d.DebertaV2ForQuestionAnswering,d.DebertaV2ForSequenceClassification,d.DebertaV2ForTokenClassification,d.DebertaV2Model,d.DebertaV2PreTrainedModel,d.DebertaV2Tokenizer,d.DecisionTransformerModel,d.DecisionTransformerPreTrainedModel,d.DeiTFeatureExtractor,d.DeiTForImageClassification,d.DeiTImageProcessor,d.DeiTModel,d.DeiTPreTrainedModel,d.DepthAnythingForDepthEstimation,d.DepthAnythingPreTrainedModel,d.DepthEstimationPipeline,d.DepthProForDepthEstimation,d.DepthProPreTrainedModel,d.DetrFeatureExtractor,d.DetrForObjectDetection,d.DetrForSegmentation,d.DetrImageProcessor,d.DetrModel,d.DetrObjectDetectionOutput,d.DetrPreTrainedModel,d.DetrSegmentationOutput,d.Dinov2ForImageClassification,d.Dinov2Model,d.Dinov2PreTrainedModel,d.DistilBertForMaskedLM,d.DistilBertForQuestionAnswering,d.DistilBertForSequenceClassification,d.DistilBertForTokenClassification,d.DistilBertModel,d.DistilBertPreTrainedModel,d.DistilBertTokenizer,d.DocumentQuestionAnsweringPipeline,d.DonutFeatureExtractor,d.DonutImageProcessor,d.DonutSwinModel,d.DonutSwinPreTrainedModel,d.EfficientNetForImageClassification,d.EfficientNetImageProcessor,d.EfficientNetModel,d.EfficientNetPreTrainedModel,d.ElectraForMaskedLM,d.ElectraForQuestionAnswering,d.ElectraForSequenceClassification,d.ElectraForTokenClassification,d.ElectraModel,d.ElectraPreTrainedModel,d.ElectraTokenizer,d.EosTokenCriteria,d.EsmForMaskedLM,d.EsmForSequenceClassification,d.EsmForTokenClassification,d.EsmModel,d.EsmPreTrainedModel,d.EsmTokenizer,d.FFT,d.FalconForCausalLM,d.FalconModel,d.FalconPreTrainedModel,d.FalconTokenizer,d.FastViTForImageClassification,d.FastViTModel,d.FastViTPreTrainedModel,d.FeatureExtractionPipeline,d.FeatureExtractor,d.FillMaskPipeline,d.Florence2ForConditionalGeneration,d.Florence2PreTrainedModel,d.Florence2Processor,d.ForcedBOSTokenLogitsProcessor,d.ForcedEOSTokenLogitsProcessor,d.GLPNFeatureExtractor,d.GLPNForDepthEstimation,d.GLPNModel,d.GLPNPreTrainedModel,d.GPT2LMHeadModel,d.GPT2Model,d.GPT2PreTrainedModel,d.GPT2Tokenizer,d.GPTBigCodeForCausalLM,d.GPTBigCodeModel,d.GPTBigCodePreTrainedModel,d.GPTJForCausalLM,d.GPTJModel,d.GPTJPreTrainedModel,d.GPTNeoForCausalLM,d.GPTNeoModel,d.GPTNeoPreTrainedModel,d.GPTNeoXForCausalLM,d.GPTNeoXModel,d.GPTNeoXPreTrainedModel,d.GPTNeoXTokenizer,d.Gemma2ForCausalLM,d.Gemma2Model,d.Gemma2PreTrainedModel,d.GemmaForCausalLM,d.GemmaModel,d.GemmaPreTrainedModel,d.GemmaTokenizer,d.GraniteForCausalLM,d.GraniteModel,d.GranitePreTrainedModel,d.Grok1Tokenizer,d.GroupViTModel,d.GroupViTPreTrainedModel,d.HerbertTokenizer,d.HieraForImageClassification,d.HieraModel,d.HieraPreTrainedModel,d.HubertForCTC,d.HubertForSequenceClassification,d.HubertModel,d.HubertPreTrainedModel,d.ImageClassificationPipeline,d.ImageFeatureExtractionPipeline,d.ImageFeatureExtractor,d.ImageMattingOutput,d.ImageProcessor,d.ImageSegmentationPipeline,d.ImageToImagePipeline,d.ImageToTextPipeline;var sf=d.InterruptableStoppingCriteria;d.JAISLMHeadModel,d.JAISModel,d.JAISPreTrainedModel,d.JinaCLIPImageProcessor,d.JinaCLIPModel,d.JinaCLIPPreTrainedModel,d.JinaCLIPProcessor,d.JinaCLIPTextModel,d.JinaCLIPVisionModel,d.LlamaForCausalLM,d.LlamaModel,d.LlamaPreTrainedModel,d.LlamaTokenizer,d.LlavaForConditionalGeneration,d.LlavaOnevisionForConditionalGeneration,d.LlavaOnevisionImageProcessor,d.LlavaPreTrainedModel,d.LogitsProcessor,d.LogitsProcessorList,d.LogitsWarper,d.LongT5ForConditionalGeneration,d.LongT5Model,d.LongT5PreTrainedModel,d.M2M100ForConditionalGeneration,d.M2M100Model,d.M2M100PreTrainedModel,d.M2M100Tokenizer,d.MBart50Tokenizer,d.MBartForCausalLM,d.MBartForConditionalGeneration,d.MBartForSequenceClassification,d.MBartModel,d.MBartPreTrainedModel,d.MBartTokenizer,d.MPNetForMaskedLM,d.MPNetForQuestionAnswering,d.MPNetForSequenceClassification,d.MPNetForTokenClassification,d.MPNetModel,d.MPNetPreTrainedModel,d.MPNetTokenizer,d.MT5ForConditionalGeneration,d.MT5Model,d.MT5PreTrainedModel,d.MarianMTModel,d.MarianModel,d.MarianPreTrainedModel,d.MarianTokenizer,d.Mask2FormerImageProcessor,d.MaskFormerFeatureExtractor,d.MaskFormerForInstanceSegmentation,d.MaskFormerImageProcessor,d.MaskFormerModel,d.MaskFormerPreTrainedModel,d.MaskedLMOutput,d.MaxLengthCriteria,d.MgpstrForSceneTextRecognition,d.MgpstrModelOutput,d.MgpstrPreTrainedModel,d.MgpstrProcessor,d.MgpstrTokenizer,d.MinLengthLogitsProcessor,d.MinNewTokensLengthLogitsProcessor,d.MistralForCausalLM,d.MistralModel,d.MistralPreTrainedModel,d.MobileBertForMaskedLM,d.MobileBertForQuestionAnswering,d.MobileBertForSequenceClassification,d.MobileBertModel,d.MobileBertPreTrainedModel,d.MobileBertTokenizer,d.MobileLLMForCausalLM,d.MobileLLMModel,d.MobileLLMPreTrainedModel,d.MobileNetV1FeatureExtractor,d.MobileNetV1ForImageClassification,d.MobileNetV1ImageProcessor,d.MobileNetV1Model,d.MobileNetV1PreTrainedModel,d.MobileNetV2FeatureExtractor,d.MobileNetV2ForImageClassification,d.MobileNetV2ImageProcessor,d.MobileNetV2Model,d.MobileNetV2PreTrainedModel,d.MobileNetV3FeatureExtractor,d.MobileNetV3ForImageClassification,d.MobileNetV3ImageProcessor,d.MobileNetV3Model,d.MobileNetV3PreTrainedModel,d.MobileNetV4FeatureExtractor,d.MobileNetV4ForImageClassification,d.MobileNetV4ImageProcessor,d.MobileNetV4Model,d.MobileNetV4PreTrainedModel,d.MobileViTFeatureExtractor,d.MobileViTForImageClassification,d.MobileViTImageProcessor,d.MobileViTModel,d.MobileViTPreTrainedModel,d.MobileViTV2ForImageClassification,d.MobileViTV2Model,d.MobileViTV2PreTrainedModel,d.ModelOutput,d.Moondream1ForConditionalGeneration,d.MptForCausalLM,d.MptModel,d.MptPreTrainedModel;var nf=d.MultiModalityCausalLM;d.MultiModalityPreTrainedModel,d.MusicgenForCausalLM,d.MusicgenForConditionalGeneration,d.MusicgenModel,d.MusicgenPreTrainedModel,d.NllbTokenizer,d.NoBadWordsLogitsProcessor,d.NoRepeatNGramLogitsProcessor,d.NomicBertModel,d.NomicBertPreTrainedModel,d.NougatImageProcessor,d.NougatTokenizer,d.OPTForCausalLM,d.OPTModel,d.OPTPreTrainedModel,d.ObjectDetectionPipeline,d.OlmoForCausalLM,d.OlmoModel,d.OlmoPreTrainedModel,d.OpenELMForCausalLM,d.OpenELMModel,d.OpenELMPreTrainedModel,d.OwlViTFeatureExtractor,d.OwlViTForObjectDetection,d.OwlViTImageProcessor,d.OwlViTModel,d.OwlViTPreTrainedModel,d.OwlViTProcessor,d.Owlv2ForObjectDetection,d.Owlv2ImageProcessor,d.Owlv2Model,d.Owlv2PreTrainedModel,d.PatchTSMixerForPrediction,d.PatchTSMixerModel,d.PatchTSMixerPreTrainedModel,d.PatchTSTForPrediction,d.PatchTSTModel,d.PatchTSTPreTrainedModel,d.Phi3ForCausalLM,d.Phi3Model,d.Phi3PreTrainedModel,d.PhiForCausalLM,d.PhiModel,d.PhiPreTrainedModel,d.Pipeline,d.PreTrainedModel,d.PreTrainedTokenizer,d.PretrainedConfig,d.PretrainedMixin,d.Processor,d.PvtForImageClassification,d.PvtImageProcessor,d.PvtModel,d.PvtPreTrainedModel,d.PyAnnoteFeatureExtractor,d.PyAnnoteForAudioFrameClassification,d.PyAnnoteModel,d.PyAnnotePreTrainedModel,d.PyAnnoteProcessor,d.QuestionAnsweringModelOutput,d.QuestionAnsweringPipeline,d.Qwen2ForCausalLM,d.Qwen2Model,d.Qwen2PreTrainedModel,d.Qwen2Tokenizer,d.Qwen2VLForConditionalGeneration,d.Qwen2VLImageProcessor,d.Qwen2VLPreTrainedModel,d.Qwen2VLProcessor,d.RTDetrForObjectDetection,d.RTDetrImageProcessor,d.RTDetrModel,d.RTDetrObjectDetectionOutput,d.RTDetrPreTrainedModel,d.RawImage,d.RepetitionPenaltyLogitsProcessor,d.ResNetForImageClassification,d.ResNetModel,d.ResNetPreTrainedModel,d.RoFormerForMaskedLM,d.RoFormerForQuestionAnswering,d.RoFormerForSequenceClassification,d.RoFormerForTokenClassification,d.RoFormerModel,d.RoFormerPreTrainedModel,d.RoFormerTokenizer,d.RobertaForMaskedLM,d.RobertaForQuestionAnswering,d.RobertaForSequenceClassification,d.RobertaForTokenClassification,d.RobertaModel,d.RobertaPreTrainedModel,d.RobertaTokenizer,d.SamImageProcessor,d.SamImageSegmentationOutput,d.SamModel,d.SamPreTrainedModel,d.SamProcessor,d.SapiensForDepthEstimation,d.SapiensForNormalEstimation,d.SapiensForSemanticSegmentation,d.SapiensPreTrainedModel,d.SeamlessM4TFeatureExtractor,d.SegformerFeatureExtractor,d.SegformerForImageClassification,d.SegformerForSemanticSegmentation,d.SegformerImageProcessor,d.SegformerModel,d.SegformerPreTrainedModel,d.Seq2SeqLMOutput,d.SequenceClassifierOutput,d.SiglipImageProcessor,d.SiglipModel,d.SiglipPreTrainedModel,d.SiglipTextModel,d.SiglipTokenizer,d.SiglipVisionModel,d.SpeechT5FeatureExtractor,d.SpeechT5ForSpeechToText,d.SpeechT5ForTextToSpeech,d.SpeechT5HifiGan,d.SpeechT5Model,d.SpeechT5PreTrainedModel,d.SpeechT5Processor,d.SpeechT5Tokenizer,d.SqueezeBertForMaskedLM,d.SqueezeBertForQuestionAnswering,d.SqueezeBertForSequenceClassification,d.SqueezeBertModel,d.SqueezeBertPreTrainedModel,d.SqueezeBertTokenizer,d.StableLmForCausalLM,d.StableLmModel,d.StableLmPreTrainedModel,d.Starcoder2ForCausalLM,d.Starcoder2Model,d.Starcoder2PreTrainedModel,d.StoppingCriteria,d.StoppingCriteriaList,d.SummarizationPipeline,d.SuppressTokensAtBeginLogitsProcessor,d.Swin2SRForImageSuperResolution,d.Swin2SRImageProcessor,d.Swin2SRModel,d.Swin2SRPreTrainedModel,d.SwinForImageClassification,d.SwinModel,d.SwinPreTrainedModel,d.T5ForConditionalGeneration,d.T5Model,d.T5PreTrainedModel,d.T5Tokenizer,d.TableTransformerForObjectDetection,d.TableTransformerModel,d.TableTransformerObjectDetectionOutput,d.TableTransformerPreTrainedModel,d.TemperatureLogitsWarper,d.Tensor,d.Text2TextGenerationPipeline,d.TextClassificationPipeline,d.TextGenerationPipeline;var of=d.TextStreamer;d.TextToAudioPipeline,d.TokenClassificationPipeline,d.TokenClassifierOutput,d.TokenizerModel,d.TopKLogitsWarper,d.TopPLogitsWarper,d.TrOCRForCausalLM,d.TrOCRPreTrainedModel,d.TranslationPipeline,d.UniSpeechForCTC,d.UniSpeechForSequenceClassification,d.UniSpeechModel,d.UniSpeechPreTrainedModel,d.UniSpeechSatForAudioFrameClassification,d.UniSpeechSatForCTC,d.UniSpeechSatForSequenceClassification,d.UniSpeechSatModel,d.UniSpeechSatPreTrainedModel,d.VLChatProcessor,d.VLMImageProcessor,d.ViTFeatureExtractor,d.ViTForImageClassification,d.ViTImageProcessor,d.ViTMAEModel,d.ViTMAEPreTrainedModel,d.ViTMSNForImageClassification,d.ViTMSNModel,d.ViTMSNPreTrainedModel,d.ViTModel,d.ViTPreTrainedModel,d.VisionEncoderDecoderModel,d.VitMatteForImageMatting,d.VitMatteImageProcessor,d.VitMattePreTrainedModel,d.VitPoseForPoseEstimation,d.VitPoseImageProcessor,d.VitPosePreTrainedModel,d.VitsModel,d.VitsModelOutput,d.VitsPreTrainedModel,d.VitsTokenizer,d.Wav2Vec2BertForCTC,d.Wav2Vec2BertForSequenceClassification,d.Wav2Vec2BertModel,d.Wav2Vec2BertPreTrainedModel,d.Wav2Vec2CTCTokenizer,d.Wav2Vec2FeatureExtractor,d.Wav2Vec2ForAudioFrameClassification,d.Wav2Vec2ForCTC,d.Wav2Vec2ForSequenceClassification,d.Wav2Vec2Model,d.Wav2Vec2PreTrainedModel,d.Wav2Vec2ProcessorWithLM,d.WavLMForAudioFrameClassification,d.WavLMForCTC,d.WavLMForSequenceClassification,d.WavLMForXVector,d.WavLMModel,d.WavLMPreTrainedModel,d.WeSpeakerFeatureExtractor,d.WeSpeakerResNetModel,d.WeSpeakerResNetPreTrainedModel,d.WhisperFeatureExtractor,d.WhisperForConditionalGeneration,d.WhisperModel,d.WhisperPreTrainedModel,d.WhisperProcessor,d.WhisperTextStreamer,d.WhisperTimeStampLogitsProcessor,d.WhisperTokenizer,d.XLMForQuestionAnswering,d.XLMForSequenceClassification,d.XLMForTokenClassification,d.XLMModel,d.XLMPreTrainedModel,d.XLMRobertaForMaskedLM,d.XLMRobertaForQuestionAnswering,d.XLMRobertaForSequenceClassification,d.XLMRobertaForTokenClassification,d.XLMRobertaModel,d.XLMRobertaPreTrainedModel,d.XLMRobertaTokenizer,d.XLMTokenizer,d.XLMWithLMHeadModel,d.XVectorOutput,d.YolosFeatureExtractor,d.YolosForObjectDetection,d.YolosImageProcessor,d.YolosModel,d.YolosObjectDetectionOutput,d.YolosPreTrainedModel,d.ZeroShotAudioClassificationPipeline,d.ZeroShotClassificationPipeline,d.ZeroShotImageClassificationPipeline,d.ZeroShotObjectDetectionPipeline,d.bankers_round,d.cat,d.cos_sim,d.dot,d.dynamic_time_warping,d.env,d.full,d.full_like,d.getKeyValueShapes,d.hamming,d.hanning,d.interpolate,d.interpolate_4d,d.interpolate_data,d.is_chinese_char,d.layer_norm,d.log_softmax,d.magnitude,d.matmul,d.max,d.mean,d.mean_pooling,d.medianFilter,d.mel_filter_bank,d.min,d.ones,d.ones_like,d.permute,d.permute_data,d.pipeline,d.quantize_embeddings,d.read_audio,d.rfft,d.round,d.softmax,d.spectrogram,d.stack,d.std_mean,d.topk,d.window_function,d.zeros,d.zeros_like;const dh="/imagine ",af=1024;let xp=!1;async function lf(){try{const Oe=await navigator.gpu.requestAdapter();if(!Oe)throw new Error("WebGPU is not supported (no adapter found)");xp=Oe.features.has("shader-f16"),self.postMessage({status:"success",data:xp})}catch(Oe){self.postMessage({status:"error",data:Oe.toString()})}}class Ep{static async getInstance(B=null){return this.processor??(this.processor=tf.from_pretrained(this.model_id,{progress_callback:B})),this.model??(this.model=nf.from_pretrained(this.model_id,{dtype:xp?{prepare_inputs_embeds:"q4",language_model:"q4f16",lm_head:"fp16",gen_head:"fp16",gen_img_embeds:"fp16",image_decode:"fp32"}:{prepare_inputs_embeds:"fp32",language_model:"q4",lm_head:"fp32",gen_head:"fp32",gen_img_embeds:"fp32",image_decode:"fp32"},device:{prepare_inputs_embeds:"wasm",language_model:"webgpu",lm_head:"webgpu",gen_head:"webgpu",gen_img_embeds:"webgpu",image_decode:"webgpu"},progress_callback:B})),Promise.all([this.processor,this.model])}}Te(Ep,"model_id","onnx-community/Janus-1.3B-ONNX");class uf extends rf{constructor(B,c){super(),this.total=B,this.on_progress=c,this.count=null,this.start_time=null}put(B){if(this.count===null){this.count=0,this.start_time=performance.now();return}const c=++this.count/this.total;this.on_progress({count:this.count,total:this.total,progress:c,time:performance.now()-this.start_time})}end(){}}const fc=new sf;async function df(Oe){const B=Oe.at(-1);self.postMessage({status:"start"});const[c,w]=await Ep.getInstance();if(B.content.startsWith(dh)){const H=[{role:"User",content:B.content.replace(dh,"")}],J=await c(H,{chat_template:"text_to_image"}),q=P=>{self.postMessage({status:"image-update",...P})},g=c.num_image_tokens,x=new uf(g,q),$=await(await w.generate_images({...J,min_new_tokens:g,max_new_tokens:g,do_sample:!0,streamer:x}))[0].toBlob();self.postMessage({status:"image-update",blob:$})}else{const R=await c(B.image?[{role:"User",content:` `+B.content,images:[B.image]}]:[{role:"System",content:"You are a helpful assistant. Answer the user's questions in a concise manner."},{role:"User",content:B.content}]);let H,J=0,q;const g=()=>{H??(H=performance.now()),J++>0&&(q=J/(performance.now()-H)*1e3)},x=$=>{self.postMessage({status:"text-update",output:$,tps:q,numTokens:J})},E=new of(c.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:x,token_callback_function:g});await w.generate({...R,max_new_tokens:af,do_sample:!1,streamer:E,stopping_criteria:fc})}self.postMessage({status:"complete"})}async function cf(){self.postMessage({status:"loading",data:"Loading model..."}),await Ep.getInstance(Oe=>{self.postMessage(Oe)}),self.postMessage({status:"ready"})}self.addEventListener("message",async Oe=>{const{type:B,data:c}=Oe.data;switch(B){case"check":lf();break;case"load":cf();break;case"generate":fc.reset(),df(c);break;case"interrupt":fc.interrupt();break;case"reset":fc.reset();break}})})();