diff --git "a/assets/worker-Bkl-9lyW.js" "b/assets/worker-Bkl-9lyW.js" new file mode 100644--- /dev/null +++ "b/assets/worker-Bkl-9lyW.js" @@ -0,0 +1,2654 @@ +var u_=Object.defineProperty;var d_=(Cn,es,Qs)=>es in Cn?u_(Cn,es,{enumerable:!0,configurable:!0,writable:!0,value:Qs}):Cn[es]=Qs;var xe=(Cn,es,Qs)=>d_(Cn,typeof es!="symbol"?es+"":es,Qs);(function(){"use strict";var Cn={},es={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Et,Se,N)=>{Et.exports=N.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{Environment:()=>Ke,Interpreter:()=>ut,Template:()=>kt,parse:()=>$e,tokenize:()=>A});var O=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),fe=Object.freeze({set:O.Set,for:O.For,in:O.In,is:O.Is,if:O.If,else:O.Else,endif:O.EndIf,elif:O.ElseIf,endfor:O.EndFor,and:O.And,or:O.Or,not:O.Not,"not in":O.NotIn,macro:O.Macro,endmacro:O.EndMacro,true:O.BooleanLiteral,false:O.BooleanLiteral,True:O.BooleanLiteral,False:O.BooleanLiteral}),ye=class{constructor(v,q){this.value=v,this.type=q}};function Te(v){return/\w/.test(v)}function Ce(v){return/[0-9]/.test(v)}var j=[["{%",O.OpenStatement],["%}",O.CloseStatement],["{{",O.OpenExpression],["}}",O.CloseExpression],["(",O.OpenParen],[")",O.CloseParen],["{",O.OpenCurlyBracket],["}",O.CloseCurlyBracket],["[",O.OpenSquareBracket],["]",O.CloseSquareBracket],[",",O.Comma],[".",O.Dot],[":",O.Colon],["|",O.Pipe],["<=",O.ComparisonBinaryOperator],[">=",O.ComparisonBinaryOperator],["==",O.ComparisonBinaryOperator],["!=",O.ComparisonBinaryOperator],["<",O.ComparisonBinaryOperator],[">",O.ComparisonBinaryOperator],["+",O.AdditiveBinaryOperator],["-",O.AdditiveBinaryOperator],["*",O.MultiplicativeBinaryOperator],["/",O.MultiplicativeBinaryOperator],["%",O.MultiplicativeBinaryOperator],["=",O.Equals]],$=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function V(v,q={}){return v.endsWith(` +`)&&(v=v.slice(0,-1)),v=v.replace(/{#.*?#}/gs,"{##}"),q.lstrip_blocks&&(v=v.replace(/^[ \t]*({[#%])/gm,"$1")),q.trim_blocks&&(v=v.replace(/([#%]})\n/g,"$1")),v.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function A(v,q={}){var Ye,Bt,ht;const C=[],Y=V(v,q);let he=0;const Qe=Tt=>{let bt="";for(;Tt(Y[he]);){if(Y[he]==="\\"){if(++he,he>=Y.length)throw new SyntaxError("Unexpected end of input");const Ot=Y[he++],cr=$.get(Ot);if(cr===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ot}`);bt+=cr;continue}if(bt+=Y[he++],he>=Y.length)throw new SyntaxError("Unexpected end of input")}return bt};e:for(;he0){C.push(new ye(Ot,O.Text));continue}}Qe(Ot=>/\s/.test(Ot));const bt=Y[he];if(bt==="-"||bt==="+"){const Ot=(Bt=C.at(-1))==null?void 0:Bt.type;if(Ot===O.Text||Ot===void 0)throw new SyntaxError(`Unexpected character: ${bt}`);switch(Ot){case O.Identifier:case O.NumericLiteral:case O.BooleanLiteral:case O.StringLiteral:case O.CloseParen:case O.CloseSquareBracket:break;default:{++he;const cr=Qe(Ce);C.push(new ye(`${bt}${cr}`,cr.length>0?O.NumericLiteral:O.UnaryOperator));continue}}}for(const[Ot,cr]of j)if(Y.slice(he,he+Ot.length)===Ot){C.push(new ye(Ot,cr)),he+=Ot.length;continue e}if(bt==="'"||bt==='"'){++he;const Ot=Qe(cr=>cr!==bt);C.push(new ye(Ot,O.StringLiteral)),++he;continue}if(Ce(bt)){const Ot=Qe(Ce);C.push(new ye(Ot,O.NumericLiteral));continue}if(Te(bt)){const Ot=Qe(Te),cr=Object.hasOwn(fe,Ot)?fe[Ot]:O.Identifier;cr===O.In&&((ht=C.at(-1))==null?void 0:ht.type)===O.Not?(C.pop(),C.push(new ye("not in",O.NotIn))):C.push(new ye(Ot,cr));continue}throw new SyntaxError(`Unexpected character: ${bt}`)}return C}var ee=class{constructor(){xe(this,"type","Statement")}},ne=class extends ee{constructor(q){super();xe(this,"type","Program");this.body=q}},me=class extends ee{constructor(q,C,Y){super();xe(this,"type","If");this.test=q,this.body=C,this.alternate=Y}},ce=class extends ee{constructor(q,C,Y,he){super();xe(this,"type","For");this.loopvar=q,this.iterable=C,this.body=Y,this.defaultBlock=he}},D=class extends ee{constructor(q,C){super();xe(this,"type","Set");this.assignee=q,this.value=C}},H=class extends ee{constructor(q,C,Y){super();xe(this,"type","Macro");this.name=q,this.args=C,this.body=Y}},te=class extends ee{constructor(){super(...arguments);xe(this,"type","Expression")}},se=class extends te{constructor(q,C,Y){super();xe(this,"type","MemberExpression");this.object=q,this.property=C,this.computed=Y}},X=class extends te{constructor(q,C){super();xe(this,"type","CallExpression");this.callee=q,this.args=C}},R=class extends te{constructor(q){super();xe(this,"type","Identifier");this.value=q}},I=class extends te{constructor(q){super();xe(this,"type","Literal");this.value=q}},B=class extends I{constructor(){super(...arguments);xe(this,"type","NumericLiteral")}},k=class extends I{constructor(){super(...arguments);xe(this,"type","StringLiteral")}},ue=class extends I{constructor(){super(...arguments);xe(this,"type","BooleanLiteral")}},ve=class extends I{constructor(){super(...arguments);xe(this,"type","ArrayLiteral")}},Ee=class extends I{constructor(){super(...arguments);xe(this,"type","TupleLiteral")}},Ie=class extends I{constructor(){super(...arguments);xe(this,"type","ObjectLiteral")}},Ae=class extends te{constructor(q,C,Y){super();xe(this,"type","BinaryExpression");this.operator=q,this.left=C,this.right=Y}},tt=class extends te{constructor(q,C){super();xe(this,"type","FilterExpression");this.operand=q,this.filter=C}},Xe=class extends te{constructor(q,C){super();xe(this,"type","SelectExpression");this.iterable=q,this.test=C}},dt=class extends te{constructor(q,C,Y){super();xe(this,"type","TestExpression");this.operand=q,this.negate=C,this.test=Y}},ge=class extends te{constructor(q,C){super();xe(this,"type","UnaryExpression");this.operator=q,this.argument=C}},W=class extends te{constructor(q=void 0,C=void 0,Y=void 0){super();xe(this,"type","SliceExpression");this.start=q,this.stop=C,this.step=Y}},de=class extends te{constructor(q,C){super();xe(this,"type","KeywordArgumentExpression");this.key=q,this.value=C}};function $e(v){const q=new ne([]);let C=0;function Y(Me,et){const ot=v[C++];if(!ot||ot.type!==Me)throw new Error(`Parser Error: ${et}. ${ot.type} !== ${Me}.`);return ot}function he(){switch(v[C].type){case O.Text:return Bt();case O.OpenStatement:return ht();case O.OpenExpression:return Tt();default:throw new SyntaxError(`Unexpected token type: ${v[C].type}`)}}function Qe(...Me){return C+Me.length<=v.length&&Me.some((et,ot)=>et!==v[C+ot].type)}function Ye(...Me){return C+Me.length<=v.length&&Me.every((et,ot)=>et===v[C+ot].type)}function Bt(){return new k(Y(O.Text,"Expected text token").value)}function ht(){Y(O.OpenStatement,"Expected opening statement token");let Me;switch(v[C].type){case O.Set:++C,Me=bt(),Y(O.CloseStatement,"Expected closing statement token");break;case O.If:++C,Me=Ot(),Y(O.OpenStatement,"Expected {% token"),Y(O.EndIf,"Expected endif token"),Y(O.CloseStatement,"Expected %} token");break;case O.Macro:++C,Me=cr(),Y(O.OpenStatement,"Expected {% token"),Y(O.EndMacro,"Expected endmacro token"),Y(O.CloseStatement,"Expected %} token");break;case O.For:++C,Me=Yr(),Y(O.OpenStatement,"Expected {% token"),Y(O.EndFor,"Expected endfor token"),Y(O.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${v[C].type}`)}return Me}function Tt(){Y(O.OpenExpression,"Expected opening expression token");const Me=Br();return Y(O.CloseExpression,"Expected closing expression token"),Me}function bt(){const Me=Br();if(Ye(O.Equals)){++C;const et=bt();return new D(Me,et)}return Me}function Ot(){var Ht,gr,Lr,mr,yr,Tr,En,Rr;const Me=Br();Y(O.CloseStatement,"Expected closing statement token");const et=[],ot=[];for(;!(((Ht=v[C])==null?void 0:Ht.type)===O.OpenStatement&&(((gr=v[C+1])==null?void 0:gr.type)===O.ElseIf||((Lr=v[C+1])==null?void 0:Lr.type)===O.Else||((mr=v[C+1])==null?void 0:mr.type)===O.EndIf));)et.push(he());if(((yr=v[C])==null?void 0:yr.type)===O.OpenStatement&&((Tr=v[C+1])==null?void 0:Tr.type)!==O.EndIf)if(++C,Ye(O.ElseIf))Y(O.ElseIf,"Expected elseif token"),ot.push(Ot());else for(Y(O.Else,"Expected else token"),Y(O.CloseStatement,"Expected closing statement token");!(((En=v[C])==null?void 0:En.type)===O.OpenStatement&&((Rr=v[C+1])==null?void 0:Rr.type)===O.EndIf);)ot.push(he());return new me(Me,et,ot)}function cr(){const Me=Gt();if(Me.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const et=gt();Y(O.CloseStatement,"Expected closing statement token");const ot=[];for(;Qe(O.OpenStatement,O.EndMacro);)ot.push(he());return new H(Me,et,ot)}function xr(Me=!1){const et=Me?Gt:Br,ot=[et()],Ht=Ye(O.Comma);for(;Ht&&(++C,ot.push(et()),!!Ye(O.Comma)););return Ht?new Ee(ot):ot[0]}function Yr(){const Me=xr(!0);if(!(Me instanceof R||Me instanceof Ee))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Me.type} instead`);Y(O.In,"Expected `in` keyword following loop variable");const et=Br();Y(O.CloseStatement,"Expected closing statement token");const ot=[];for(;Qe(O.OpenStatement,O.EndFor)&&Qe(O.OpenStatement,O.Else);)ot.push(he());const Ht=[];if(Ye(O.OpenStatement,O.Else))for(++C,++C,Y(O.CloseStatement,"Expected closing statement token");Qe(O.OpenStatement,O.EndFor);)Ht.push(he());return new ce(Me,et,ot,Ht)}function Br(){return Kr()}function Kr(){const Me=at();if(Ye(O.If)){++C;const et=at();if(Ye(O.Else)){++C;const ot=at();return new me(et,[Me],[ot])}else return new Xe(Me,et)}return Me}function at(){let Me=U();for(;Ye(O.Or);){const et=v[C];++C;const ot=U();Me=new Ae(et,Me,ot)}return Me}function U(){let Me=_e();for(;Ye(O.And);){const et=v[C];++C;const ot=_e();Me=new Ae(et,Me,ot)}return Me}function _e(){let Me;for(;Ye(O.Not);){const et=v[C];++C;const ot=_e();Me=new ge(et,ot)}return Me??Pe()}function Pe(){let Me=rt();for(;Ye(O.ComparisonBinaryOperator)||Ye(O.In)||Ye(O.NotIn);){const et=v[C];++C;const ot=rt();Me=new Ae(et,Me,ot)}return Me}function rt(){let Me=Ft();for(;Ye(O.AdditiveBinaryOperator);){const et=v[C];++C;const ot=Ft();Me=new Ae(et,Me,ot)}return Me}function we(){const Me=mt();return Ye(O.OpenParen)?Je(Me):Me}function Je(Me){let et=new X(Me,gt());return Ye(O.OpenParen)&&(et=Je(et)),et}function gt(){Y(O.OpenParen,"Expected opening parenthesis for arguments list");const Me=ft();return Y(O.CloseParen,"Expected closing parenthesis for arguments list"),Me}function ft(){const Me=[];for(;!Ye(O.CloseParen);){let et=Br();if(Ye(O.Equals)){if(++C,!(et instanceof R))throw new SyntaxError("Expected identifier for keyword argument");const ot=Br();et=new de(et,ot)}Me.push(et),Ye(O.Comma)&&++C}return Me}function St(){const Me=[];let et=!1;for(;!Ye(O.CloseSquareBracket);)Ye(O.Colon)?(Me.push(void 0),++C,et=!0):(Me.push(Br()),Ye(O.Colon)&&(++C,et=!0));if(Me.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(et){if(Me.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new W(...Me)}return Me[0]}function mt(){let Me=Gt();for(;Ye(O.Dot)||Ye(O.OpenSquareBracket);){const et=v[C];++C;let ot;const Ht=et.type!==O.Dot;if(Ht)ot=St(),Y(O.CloseSquareBracket,"Expected closing square bracket");else if(ot=Gt(),ot.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Me=new se(Me,ot,Ht)}return Me}function Ft(){let Me=Nt();for(;Ye(O.MultiplicativeBinaryOperator);){const et=v[C];++C;const ot=Nt();Me=new Ae(et,Me,ot)}return Me}function Nt(){let Me=Rt();for(;Ye(O.Is);){++C;const et=Ye(O.Not);et&&++C;let ot=Gt();if(ot instanceof ue&&(ot=new R(ot.value.toString())),!(ot instanceof R))throw new SyntaxError("Expected identifier for the test");Me=new dt(Me,et,ot)}return Me}function Rt(){let Me=we();for(;Ye(O.Pipe);){++C;let et=Gt();if(!(et instanceof R))throw new SyntaxError("Expected identifier for the filter");Ye(O.OpenParen)&&(et=Je(et)),Me=new tt(Me,et)}return Me}function Gt(){const Me=v[C];switch(Me.type){case O.NumericLiteral:return++C,new B(Number(Me.value));case O.StringLiteral:return++C,new k(Me.value);case O.BooleanLiteral:return++C,new ue(Me.value.toLowerCase()==="true");case O.Identifier:return++C,new R(Me.value);case O.OpenParen:{++C;const et=xr();if(v[C].type!==O.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${v[C].type} instead`);return++C,et}case O.OpenSquareBracket:{++C;const et=[];for(;!Ye(O.CloseSquareBracket);)et.push(Br()),Ye(O.Comma)&&++C;return++C,new ve(et)}case O.OpenCurlyBracket:{++C;const et=new Map;for(;!Ye(O.CloseCurlyBracket);){const ot=Br();Y(O.Colon,"Expected colon between key and value in object literal");const Ht=Br();et.set(ot,Ht),Ye(O.Comma)&&++C}return++C,new Ie(et)}default:throw new SyntaxError(`Unexpected token: ${Me.type}`)}}for(;C=0?(q=(q??(q=0))<0?Math.max(v.length+q,0):Math.min(q,v.length),C=(C??(C=v.length))<0?Math.max(v.length+C,0):Math.min(C,v.length)):(q=(q??(q=v.length-1))<0?Math.max(v.length+q,-1):Math.min(q,v.length-1),C=(C??(C=-1))<-1?Math.max(v.length+C,-1):Math.min(C,v.length-1));const Qe=[];for(let Ye=q;he*Yeq.toUpperCase())}var nt=class{constructor(v=void 0){xe(this,"type","RuntimeValue");xe(this,"value");xe(this,"builtins",new Map);this.value=v}__bool__(){return new st(!!this.value)}},lt=class extends nt{constructor(){super(...arguments);xe(this,"type","NumericValue")}},je=class extends nt{constructor(){super(...arguments);xe(this,"type","StringValue");xe(this,"builtins",new Map([["upper",new Ve(()=>new je(this.value.toUpperCase()))],["lower",new Ve(()=>new je(this.value.toLowerCase()))],["strip",new Ve(()=>new je(this.value.trim()))],["title",new Ve(()=>new je(ct(this.value)))],["length",new lt(this.value.length)]]))}},st=class extends nt{constructor(){super(...arguments);xe(this,"type","BooleanValue")}},Pt=class extends nt{constructor(){super(...arguments);xe(this,"type","ObjectValue");xe(this,"builtins",new Map([["get",new Ve(([q,C])=>{if(!(q instanceof je))throw new Error(`Object key must be a string: got ${q.type}`);return this.value.get(q.value)??C??new qe})],["items",new Ve(()=>new re(Array.from(this.value.entries()).map(([q,C])=>new re([new je(q),C]))))]]))}__bool__(){return new st(this.value.size>0)}},Le=class extends Pt{constructor(){super(...arguments);xe(this,"type","KeywordArgumentsValue")}},re=class extends nt{constructor(){super(...arguments);xe(this,"type","ArrayValue");xe(this,"builtins",new Map([["length",new lt(this.value.length)]]))}__bool__(){return new st(this.value.length>0)}},ke=class extends re{constructor(){super(...arguments);xe(this,"type","TupleValue")}},Ve=class extends nt{constructor(){super(...arguments);xe(this,"type","FunctionValue")}},qe=class extends nt{constructor(){super(...arguments);xe(this,"type","NullValue")}},We=class extends nt{constructor(){super(...arguments);xe(this,"type","UndefinedValue")}},Ke=class{constructor(v){xe(this,"variables",new Map([["namespace",new Ve(v=>{if(v.length===0)return new Pt(new Map);if(v.length!==1||!(v[0]instanceof Pt))throw new Error("`namespace` expects either zero arguments or a single object argument");return v[0]})]]));xe(this,"tests",new Map([["boolean",v=>v.type==="BooleanValue"],["callable",v=>v instanceof Ve],["odd",v=>{if(v.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${v.type}`);return v.value%2!==0}],["even",v=>{if(v.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${v.type}`);return v.value%2===0}],["false",v=>v.type==="BooleanValue"&&!v.value],["true",v=>v.type==="BooleanValue"&&v.value],["string",v=>v.type==="StringValue"],["number",v=>v.type==="NumericValue"],["integer",v=>v.type==="NumericValue"&&Number.isInteger(v.value)],["iterable",v=>v instanceof re||v instanceof je],["lower",v=>{const q=v.value;return v.type==="StringValue"&&q===q.toLowerCase()}],["upper",v=>{const q=v.value;return v.type==="StringValue"&&q===q.toUpperCase()}],["none",v=>v.type==="NullValue"],["defined",v=>v.type!=="UndefinedValue"],["undefined",v=>v.type==="UndefinedValue"],["equalto",(v,q)=>v.value===q.value],["eq",(v,q)=>v.value===q.value]]));this.parent=v}set(v,q){return this.declareVariable(v,yt(q))}declareVariable(v,q){if(this.variables.has(v))throw new SyntaxError(`Variable already declared: ${v}`);return this.variables.set(v,q),q}setVariable(v,q){return this.variables.set(v,q),q}resolve(v){if(this.variables.has(v))return this;if(this.parent)return this.parent.resolve(v);throw new Error(`Unknown variable: ${v}`)}lookupVariable(v){try{return this.resolve(v).variables.get(v)??new We}catch{return new We}}},ut=class{constructor(v){xe(this,"global");this.global=v??new Ke}run(v){return this.evaluate(v,this.global)}evaluateBinaryExpression(v,q){const C=this.evaluate(v.left,q);switch(v.operator.value){case"and":return C.__bool__().value?this.evaluate(v.right,q):C;case"or":return C.__bool__().value?C:this.evaluate(v.right,q)}const Y=this.evaluate(v.right,q);switch(v.operator.value){case"==":return new st(C.value==Y.value);case"!=":return new st(C.value!=Y.value)}if(C instanceof We||Y instanceof We)throw new Error("Cannot perform operation on undefined values");if(C instanceof qe||Y instanceof qe)throw new Error("Cannot perform operation on null values");if(C instanceof lt&&Y instanceof lt)switch(v.operator.value){case"+":return new lt(C.value+Y.value);case"-":return new lt(C.value-Y.value);case"*":return new lt(C.value*Y.value);case"/":return new lt(C.value/Y.value);case"%":return new lt(C.value%Y.value);case"<":return new st(C.value":return new st(C.value>Y.value);case">=":return new st(C.value>=Y.value);case"<=":return new st(C.value<=Y.value)}else if(C instanceof re&&Y instanceof re)switch(v.operator.value){case"+":return new re(C.value.concat(Y.value))}else if(Y instanceof re){const he=Y.value.find(Qe=>Qe.value===C.value)!==void 0;switch(v.operator.value){case"in":return new st(he);case"not in":return new st(!he)}}if(C instanceof je||Y instanceof je)switch(v.operator.value){case"+":return new je(C.value.toString()+Y.value.toString())}if(C instanceof je&&Y instanceof je)switch(v.operator.value){case"in":return new st(Y.value.includes(C.value));case"not in":return new st(!Y.value.includes(C.value))}if(C instanceof je&&Y instanceof Pt)switch(v.operator.value){case"in":return new st(Y.value.has(C.value));case"not in":return new st(!Y.value.has(C.value))}throw new SyntaxError(`Unknown operator "${v.operator.value}" between ${C.type} and ${Y.type}`)}evaluateArguments(v,q){const C=[],Y=new Map;for(const he of v)if(he.type==="KeywordArgumentExpression"){const Qe=he;Y.set(Qe.key.value,this.evaluate(Qe.value,q))}else{if(Y.size>0)throw new Error("Positional arguments must come before keyword arguments");C.push(this.evaluate(he,q))}return[C,Y]}evaluateFilterExpression(v,q){const C=this.evaluate(v.operand,q);if(v.filter.type==="Identifier"){const Y=v.filter;if(Y.value==="tojson")return new je(vt(C));if(C instanceof re)switch(Y.value){case"list":return C;case"first":return C.value[0];case"last":return C.value[C.value.length-1];case"length":return new lt(C.value.length);case"reverse":return new re(C.value.reverse());case"sort":return new re(C.value.sort((he,Qe)=>{if(he.type!==Qe.type)throw new Error(`Cannot compare different types: ${he.type} and ${Qe.type}`);switch(he.type){case"NumericValue":return he.value-Qe.value;case"StringValue":return he.value.localeCompare(Qe.value);default:throw new Error(`Cannot compare type: ${he.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Y.value}`)}else if(C instanceof je)switch(Y.value){case"length":return new lt(C.value.length);case"upper":return new je(C.value.toUpperCase());case"lower":return new je(C.value.toLowerCase());case"title":return new je(ct(C.value));case"capitalize":return new je(C.value.charAt(0).toUpperCase()+C.value.slice(1));case"trim":return new je(C.value.trim());case"indent":return new je(C.value.split(` +`).map((he,Qe)=>Qe===0||he.length===0?he:" "+he).join(` +`));case"string":return C;default:throw new Error(`Unknown StringValue filter: ${Y.value}`)}else if(C instanceof lt)switch(Y.value){case"abs":return new lt(Math.abs(C.value));default:throw new Error(`Unknown NumericValue filter: ${Y.value}`)}else if(C instanceof Pt)switch(Y.value){case"items":return new re(Array.from(C.value.entries()).map(([he,Qe])=>new re([new je(he),Qe])));case"length":return new lt(C.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Y.value}`)}throw new Error(`Cannot apply filter "${Y.value}" to type: ${C.type}`)}else if(v.filter.type==="CallExpression"){const Y=v.filter;if(Y.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Y.callee.type}`);const he=Y.callee.value;if(he==="tojson"){const[,Qe]=this.evaluateArguments(Y.args,q),Ye=Qe.get("indent")??new qe;if(!(Ye instanceof lt||Ye instanceof qe))throw new Error("If set, indent must be a number");return new je(vt(C,Ye.value))}if(C instanceof re){switch(he){case"selectattr":{if(C.value.some(bt=>!(bt instanceof Pt)))throw new Error("`selectattr` can only be applied to array of objects");if(Y.args.some(bt=>bt.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Qe,Ye,Bt]=Y.args.map(bt=>this.evaluate(bt,q));let ht;if(Ye){const bt=q.tests.get(Ye.value);if(!bt)throw new Error(`Unknown test: ${Ye.value}`);ht=bt}else ht=(...bt)=>bt[0].__bool__().value;const Tt=C.value.filter(bt=>{const Ot=bt.value.get(Qe.value);return Ot?ht(Ot,Bt):!1});return new re(Tt)}case"map":{const[,Qe]=this.evaluateArguments(Y.args,q);if(Qe.has("attribute")){const Ye=Qe.get("attribute");if(!(Ye instanceof je))throw new Error("attribute must be a string");const Bt=Qe.get("default"),ht=C.value.map(Tt=>{if(!(Tt instanceof Pt))throw new Error("items in map must be an object");return Tt.value.get(Ye.value)??Bt??new We});return new re(ht)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${he}`)}else if(C instanceof je){switch(he){case"indent":{const[Qe,Ye]=this.evaluateArguments(Y.args,q),Bt=Qe.at(0)??Ye.get("width")??new lt(4);if(!(Bt instanceof lt))throw new Error("width must be a number");const ht=Qe.at(1)??Ye.get("first")??new st(!1),Tt=Qe.at(2)??Ye.get("blank")??new st(!1),bt=C.value.split(` +`),Ot=" ".repeat(Bt.value),cr=bt.map((xr,Yr)=>!ht.value&&Yr===0||!Tt.value&&xr.length===0?xr:Ot+xr);return new je(cr.join(` +`))}}throw new Error(`Unknown StringValue filter: ${he}`)}else throw new Error(`Cannot apply filter "${he}" to type: ${C.type}`)}throw new Error(`Unknown filter: ${v.filter.type}`)}evaluateTestExpression(v,q){const C=this.evaluate(v.operand,q),Y=q.tests.get(v.test.value);if(!Y)throw new Error(`Unknown test: ${v.test.value}`);const he=Y(C);return new st(v.negate?!he:he)}evaluateUnaryExpression(v,q){const C=this.evaluate(v.argument,q);switch(v.operator.value){case"not":return new st(!C.value);default:throw new SyntaxError(`Unknown operator: ${v.operator.value}`)}}evalProgram(v,q){return this.evaluateBlock(v.body,q)}evaluateBlock(v,q){let C="";for(const Y of v){const he=this.evaluate(Y,q);he.type!=="NullValue"&&he.type!=="UndefinedValue"&&(C+=he.value)}return new je(C)}evaluateIdentifier(v,q){return q.lookupVariable(v.value)}evaluateCallExpression(v,q){const[C,Y]=this.evaluateArguments(v.args,q);Y.size>0&&C.push(new Le(Y));const he=this.evaluate(v.callee,q);if(he.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${he.type}`);return he.value(C,q)}evaluateSliceExpression(v,q,C){if(!(v instanceof re||v instanceof je))throw new Error("Slice object must be an array or string");const Y=this.evaluate(q.start,C),he=this.evaluate(q.stop,C),Qe=this.evaluate(q.step,C);if(!(Y instanceof lt||Y instanceof We))throw new Error("Slice start must be numeric or undefined");if(!(he instanceof lt||he instanceof We))throw new Error("Slice stop must be numeric or undefined");if(!(Qe instanceof lt||Qe instanceof We))throw new Error("Slice step must be numeric or undefined");return v instanceof re?new re(He(v.value,Y.value,he.value,Qe.value)):new je(He(Array.from(v.value),Y.value,he.value,Qe.value).join(""))}evaluateMemberExpression(v,q){const C=this.evaluate(v.object,q);let Y;if(v.computed){if(v.property.type==="SliceExpression")return this.evaluateSliceExpression(C,v.property,q);Y=this.evaluate(v.property,q)}else Y=new je(v.property.value);let he;if(C instanceof Pt){if(!(Y instanceof je))throw new Error(`Cannot access property with non-string: got ${Y.type}`);he=C.value.get(Y.value)??C.builtins.get(Y.value)}else if(C instanceof re||C instanceof je)if(Y instanceof lt)he=C.value.at(Y.value),C instanceof je&&(he=new je(C.value.at(Y.value)));else if(Y instanceof je)he=C.builtins.get(Y.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Y.type}`);else{if(!(Y instanceof je))throw new Error(`Cannot access property with non-string: got ${Y.type}`);he=C.builtins.get(Y.value)}return he instanceof nt?he:new We}evaluateSet(v,q){const C=this.evaluate(v.value,q);if(v.assignee.type==="Identifier"){const Y=v.assignee.value;q.setVariable(Y,C)}else if(v.assignee.type==="MemberExpression"){const Y=v.assignee,he=this.evaluate(Y.object,q);if(!(he instanceof Pt))throw new Error("Cannot assign to member of non-object");if(Y.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");he.value.set(Y.property.value,C)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(v.assignee)}`);return new qe}evaluateIf(v,q){const C=this.evaluate(v.test,q);return this.evaluateBlock(C.__bool__().value?v.body:v.alternate,q)}evaluateFor(v,q){const C=new Ke(q);let Y,he;if(v.iterable.type==="SelectExpression"){const Tt=v.iterable;he=this.evaluate(Tt.iterable,C),Y=Tt.test}else he=this.evaluate(v.iterable,C);if(!(he instanceof re))throw new Error(`Expected iterable type in for loop: got ${he.type}`);const Qe=[],Ye=[];for(let Tt=0;Ttxr.setVariable(v.loopvar.value,Ot);else if(v.loopvar.type==="TupleLiteral"){const xr=v.loopvar;if(Ot.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Ot.type}`);const Yr=Ot;if(xr.value.length!==Yr.value.length)throw new Error(`Too ${xr.value.length>Yr.value.length?"few":"many"} items to unpack`);cr=Br=>{for(let Kr=0;Kr0?Qe[Tt-1]:new We],["nextitem",Tt{var Ye;const he=new Ke(Y);C=C.slice();let Qe;((Ye=C.at(-1))==null?void 0:Ye.type)==="KeywordArgumentsValue"&&(Qe=C.pop());for(let Bt=0;Btthis.evaluate(C,q)));case"TupleLiteral":return new ke(v.value.map(C=>this.evaluate(C,q)));case"ObjectLiteral":{const C=new Map;for(const[Y,he]of v.value){const Qe=this.evaluate(Y,q);if(!(Qe instanceof je))throw new Error(`Object keys must be strings: got ${Qe.type}`);C.set(Qe.value,this.evaluate(he,q))}return new Pt(C)}case"Identifier":return this.evaluateIdentifier(v,q);case"CallExpression":return this.evaluateCallExpression(v,q);case"MemberExpression":return this.evaluateMemberExpression(v,q);case"UnaryExpression":return this.evaluateUnaryExpression(v,q);case"BinaryExpression":return this.evaluateBinaryExpression(v,q);case"FilterExpression":return this.evaluateFilterExpression(v,q);case"TestExpression":return this.evaluateTestExpression(v,q);default:throw new SyntaxError(`Unknown node type: ${v.type}`)}}};function yt(v){switch(typeof v){case"number":return new lt(v);case"string":return new je(v);case"boolean":return new st(v);case"undefined":return new We;case"object":return v===null?new qe:Array.isArray(v)?new re(v.map(yt)):new Pt(new Map(Object.entries(v).map(([q,C])=>[q,yt(C)])));case"function":return new Ve((q,C)=>{const Y=v(...q.map(he=>he.value))??null;return yt(Y)});default:throw new Error(`Cannot convert to runtime value: ${v}`)}}function vt(v,q,C){const Y=C??0;switch(v.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(v.value);case"ArrayValue":case"ObjectValue":{const he=q?" ".repeat(q):"",Qe=` +`+he.repeat(Y),Ye=Qe+he;if(v.type==="ArrayValue"){const Bt=v.value.map(ht=>vt(ht,q,Y+1));return q?`[${Ye}${Bt.join(`,${Ye}`)}${Qe}]`:`[${Bt.join(", ")}]`}else{const Bt=Array.from(v.value.entries()).map(([ht,Tt])=>{const bt=`"${ht}": ${vt(Tt,q,Y+1)}`;return q?`${Ye}${bt}`:bt});return q?`{${Bt.join(",")}${Qe}}`:`{${Bt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${v.type}`)}}var kt=class{constructor(v){xe(this,"parsed");const q=A(v,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=$e(q)}render(v){const q=new Ke;q.set("false",!1),q.set("true",!0),q.set("raise_exception",he=>{throw new Error(he)}),q.set("range",J);for(const[he,Qe]of Object.entries(v))q.set(he,Qe);return new ut(q).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{registerBackend:()=>ye,resolveBackendAndExecutionProviders:()=>Ce});const O=new Map,fe=[],ye=(j,$,V)=>{if($&&typeof $.init=="function"&&typeof $.createInferenceSessionHandler=="function"){const A=O.get(j);if(A===void 0)O.set(j,{backend:$,priority:V});else{if(A.priority>V)return;if(A.priority===V&&A.backend!==$)throw new Error(`cannot register backend "${j}" using priority ${V}`)}if(V>=0){const ee=fe.indexOf(j);ee!==-1&&fe.splice(ee,1);for(let ne=0;ne{const $=O.get(j);if(!$)return"backend not found.";if($.initialized)return $.backend;if($.aborted)return $.error;{const V=!!$.initPromise;try{return V||($.initPromise=$.backend.init(j)),await $.initPromise,$.initialized=!0,$.backend}catch(A){return V||($.error=`${A}`,$.aborted=!0),$.error}finally{delete $.initPromise}}},Ce=async j=>{const $=j.executionProviders||[],V=$.map(D=>typeof D=="string"?D:D.name),A=V.length===0?fe:V;let ee;const ne=[],me=new Set;for(const D of A){const H=await Te(D);typeof H=="string"?ne.push({name:D,err:H}):(ee||(ee=H),ee===H&&me.add(D))}if(!ee)throw new Error(`no available backend found. ERR: ${ne.map(D=>`[${D.name}] ${D.err}`).join(", ")}`);for(const{name:D,err:H}of ne)V.includes(D)&&console.warn(`removing requested execution provider "${D}" from session options because it is not available: ${H}`);const ce=$.filter(D=>me.has(typeof D=="string"?D:D.name));return[ee,new Proxy(j,{get:(D,H)=>H==="executionProviders"?ce:Reflect.get(D,H)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{registerBackend:()=>O.registerBackend});var O=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{env:()=>ye});var O=N("./node_modules/onnxruntime-common/dist/esm/version.js");let fe="warning";const ye={wasm:{},webgl:{},webgpu:{},versions:{common:O.version},set logLevel(Te){if(Te!==void 0){if(typeof Te!="string"||["verbose","info","warning","error","fatal"].indexOf(Te)===-1)throw new Error(`Unsupported logging level: ${Te}`);fe=Te}},get logLevel(){return fe}};Object.defineProperty(ye,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{env:()=>fe});var O=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const fe=O.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{InferenceSession:()=>ye.InferenceSession,TRACE:()=>Ce.TRACE,TRACE_FUNC_BEGIN:()=>Ce.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Ce.TRACE_FUNC_END,Tensor:()=>Te.Tensor,TrainingSession:()=>j.TrainingSession,env:()=>fe.env,registerBackend:()=>O.registerBackend});var O=N("./node_modules/onnxruntime-common/dist/esm/backend.js"),fe=N("./node_modules/onnxruntime-common/dist/esm/env.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Te=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),N("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Ce=N("./node_modules/onnxruntime-common/dist/esm/trace.js");N("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),N("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var j=N("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{InferenceSession:()=>Te});var O=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),fe=N("./node_modules/onnxruntime-common/dist/esm/tensor.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/trace.js");class Te{constructor(j){this.handler=j}async run(j,$,V){(0,ye.TRACE_FUNC_BEGIN)();const A={};let ee={};if(typeof j!="object"||j===null||j instanceof fe.Tensor||Array.isArray(j))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ne=!0;if(typeof $=="object"){if($===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if($ instanceof fe.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray($)){if($.length===0)throw new TypeError("'fetches' cannot be an empty array.");ne=!1;for(const D of $){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);A[D]=null}if(typeof V=="object"&&V!==null)ee=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const H=Object.getOwnPropertyNames($);for(const te of this.outputNames)if(H.indexOf(te)!==-1){const se=$[te];(se===null||se instanceof fe.Tensor)&&(D=!0,ne=!1,A[te]=se)}if(D){if(typeof V=="object"&&V!==null)ee=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else ee=$}}else if(typeof $<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of this.inputNames)if(typeof j[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ne)for(const D of this.outputNames)A[D]=null;const me=await this.handler.run(j,A,ee),ce={};for(const D in me)if(Object.hasOwnProperty.call(me,D)){const H=me[D];H instanceof fe.Tensor?ce[D]=H:ce[D]=new fe.Tensor(H.type,H.data,H.dims)}return(0,ye.TRACE_FUNC_END)(),ce}async release(){return this.handler.dispose()}static async create(j,$,V,A){(0,ye.TRACE_FUNC_BEGIN)();let ee,ne={};if(typeof j=="string"){if(ee=j,typeof $=="object"&&$!==null)ne=$;else if(typeof $<"u")throw new TypeError("'options' must be an object.")}else if(j instanceof Uint8Array){if(ee=j,typeof $=="object"&&$!==null)ne=$;else if(typeof $<"u")throw new TypeError("'options' must be an object.")}else if(j instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&j instanceof SharedArrayBuffer){const H=j;let te=0,se=j.byteLength;if(typeof $=="object"&&$!==null)ne=$;else if(typeof $=="number"){if(te=$,!Number.isSafeInteger(te))throw new RangeError("'byteOffset' must be an integer.");if(te<0||te>=H.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${H.byteLength}).`);if(se=j.byteLength-te,typeof V=="number"){if(se=V,!Number.isSafeInteger(se))throw new RangeError("'byteLength' must be an integer.");if(se<=0||te+se>H.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${H.byteLength-te}].`);if(typeof A=="object"&&A!==null)ne=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(typeof V<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof $<"u")throw new TypeError("'options' must be an object.");ee=new Uint8Array(H,te,se)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[me,ce]=await(0,O.resolveBackendAndExecutionProviders)(ne),D=await me.createInferenceSessionHandler(ee,ce);return(0,ye.TRACE_FUNC_END)(),new Te(D)}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":(Et,Se,N)=>{N.r(Se),N.d(Se,{InferenceSession:()=>fe});var O=N("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const fe=O.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Et,Se,N)=>{N.r(Se)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Et,Se,N)=>{N.r(Se)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{tensorToDataURL:()=>O,tensorToImageData:()=>fe});const O=(ye,Te)=>{const Ce=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Ce.width=ye.dims[3],Ce.height=ye.dims[2];const j=Ce.getContext("2d");if(j!=null){let $,V;(Te==null?void 0:Te.tensorLayout)!==void 0&&Te.tensorLayout==="NHWC"?($=ye.dims[2],V=ye.dims[3]):($=ye.dims[3],V=ye.dims[2]);const A=(Te==null?void 0:Te.format)!==void 0?Te.format:"RGB",ee=Te==null?void 0:Te.norm;let ne,me;ee===void 0||ee.mean===void 0?ne=[255,255,255,255]:typeof ee.mean=="number"?ne=[ee.mean,ee.mean,ee.mean,ee.mean]:(ne=[ee.mean[0],ee.mean[1],ee.mean[2],0],ee.mean[3]!==void 0&&(ne[3]=ee.mean[3])),ee===void 0||ee.bias===void 0?me=[0,0,0,0]:typeof ee.bias=="number"?me=[ee.bias,ee.bias,ee.bias,ee.bias]:(me=[ee.bias[0],ee.bias[1],ee.bias[2],0],ee.bias[3]!==void 0&&(me[3]=ee.bias[3]));const ce=V*$;let D=0,H=ce,te=ce*2,se=-1;A==="RGBA"?(D=0,H=ce,te=ce*2,se=ce*3):A==="RGB"?(D=0,H=ce,te=ce*2):A==="RBG"&&(D=0,te=ce,H=ce*2);for(let X=0;X{const Ce=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let j;if(Ce!=null){let $,V,A;(Te==null?void 0:Te.tensorLayout)!==void 0&&Te.tensorLayout==="NHWC"?($=ye.dims[2],V=ye.dims[1],A=ye.dims[3]):($=ye.dims[3],V=ye.dims[2],A=ye.dims[1]);const ee=Te!==void 0&&Te.format!==void 0?Te.format:"RGB",ne=Te==null?void 0:Te.norm;let me,ce;ne===void 0||ne.mean===void 0?me=[255,255,255,255]:typeof ne.mean=="number"?me=[ne.mean,ne.mean,ne.mean,ne.mean]:(me=[ne.mean[0],ne.mean[1],ne.mean[2],255],ne.mean[3]!==void 0&&(me[3]=ne.mean[3])),ne===void 0||ne.bias===void 0?ce=[0,0,0,0]:typeof ne.bias=="number"?ce=[ne.bias,ne.bias,ne.bias,ne.bias]:(ce=[ne.bias[0],ne.bias[1],ne.bias[2],0],ne.bias[3]!==void 0&&(ce[3]=ne.bias[3]));const D=V*$;if(Te!==void 0&&(Te.format!==void 0&&A===4&&Te.format!=="RGBA"||A===3&&Te.format!=="RGB"&&Te.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const H=4;let te=0,se=1,X=2,R=3,I=0,B=D,k=D*2,ue=-1;ee==="RGBA"?(I=0,B=D,k=D*2,ue=D*3):ee==="RGB"?(I=0,B=D,k=D*2):ee==="RBG"&&(I=0,k=D,B=D*2),j=Ce.createImageData($,V);for(let ve=0;ve{N.r(Se)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{bufferToTensor:()=>fe,tensorFromGpuBuffer:()=>Ce,tensorFromImage:()=>ye,tensorFromPinnedBuffer:()=>j,tensorFromTexture:()=>Te});var O=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const fe=($,V)=>{if($===void 0)throw new Error("Image buffer must be defined");if(V.height===void 0||V.width===void 0)throw new Error("Image height and width must be defined");if(V.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:A,width:ee}=V,ne=V.norm??{mean:255,bias:0};let me,ce;typeof ne.mean=="number"?me=[ne.mean,ne.mean,ne.mean,ne.mean]:me=[ne.mean[0],ne.mean[1],ne.mean[2],ne.mean[3]??255],typeof ne.bias=="number"?ce=[ne.bias,ne.bias,ne.bias,ne.bias]:ce=[ne.bias[0],ne.bias[1],ne.bias[2],ne.bias[3]??0];const D=V.format!==void 0?V.format:"RGBA",H=V.tensorFormat!==void 0&&V.tensorFormat!==void 0?V.tensorFormat:"RGB",te=A*ee,se=H==="RGBA"?new Float32Array(te*4):new Float32Array(te*3);let X=4,R=0,I=1,B=2,k=3,ue=0,ve=te,Ee=te*2,Ie=-1;D==="RGB"&&(X=3,R=0,I=1,B=2,k=-1),H==="RGBA"?Ie=te*3:H==="RBG"?(ue=0,Ee=te,ve=te*2):H==="BGR"&&(Ee=0,ve=te,ue=te*2);for(let tt=0;tt{const A=typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement,ee=typeof ImageData<"u"&&$ instanceof ImageData,ne=typeof ImageBitmap<"u"&&$ instanceof ImageBitmap,me=typeof $=="string";let ce,D=V??{};const H=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},te=se=>se instanceof HTMLCanvasElement||se instanceof OffscreenCanvas?se.getContext("2d"):null;if(A){const se=H();se.width=$.width,se.height=$.height;const X=te(se);if(X!=null){let R=$.height,I=$.width;if(V!==void 0&&V.resizedHeight!==void 0&&V.resizedWidth!==void 0&&(R=V.resizedHeight,I=V.resizedWidth),V!==void 0){if(D=V,V.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");D.tensorFormat="RGBA",D.height=R,D.width=I}else D.tensorFormat="RGBA",D.height=R,D.width=I;X.drawImage($,0,0),ce=X.getImageData(0,0,I,R).data}else throw new Error("Can not access image data")}else if(ee){let se,X;if(V!==void 0&&V.resizedWidth!==void 0&&V.resizedHeight!==void 0?(se=V.resizedHeight,X=V.resizedWidth):(se=$.height,X=$.width),V!==void 0&&(D=V),D.format="RGBA",D.height=se,D.width=X,V!==void 0){const R=H();R.width=X,R.height=se;const I=te(R);if(I!=null)I.putImageData($,0,0),ce=I.getImageData(0,0,X,se).data;else throw new Error("Can not access image data")}else ce=$.data}else if(ne){if(V===void 0)throw new Error("Please provide image config with format for Imagebitmap");const se=H();se.width=$.width,se.height=$.height;const X=te(se);if(X!=null){const R=$.height,I=$.width;return X.drawImage($,0,0,I,R),ce=X.getImageData(0,0,I,R).data,D.height=R,D.width=I,fe(ce,D)}else throw new Error("Can not access image data")}else{if(me)return new Promise((se,X)=>{const R=H(),I=te(R);if(!$||!I)return X();const B=new Image;B.crossOrigin="Anonymous",B.src=$,B.onload=()=>{R.width=B.width,R.height=B.height,I.drawImage(B,0,0,R.width,R.height);const k=I.getImageData(0,0,R.width,R.height);D.height=R.height,D.width=R.width,se(fe(k.data,D))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ce!==void 0)return fe(ce,D);throw new Error("Input data provided is not supported - aborted tensor creation")},Te=($,V)=>{const{width:A,height:ee,download:ne,dispose:me}=V,ce=[1,ee,A,4];return new O.Tensor({location:"texture",type:"float32",texture:$,dims:ce,download:ne,dispose:me})},Ce=($,V)=>{const{dataType:A,dims:ee,download:ne,dispose:me}=V;return new O.Tensor({location:"gpu-buffer",type:A??"float32",gpuBuffer:$,dims:ee,download:ne,dispose:me})},j=($,V,A)=>new O.Tensor({location:"cpu-pinned",type:$,data:V,dims:A??[V.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Et,Se,N)=>{N.r(Se)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>fe,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>O,checkTypedArray:()=>Te});const O=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),fe=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ye=!1;const Te=()=>{if(!ye){ye=!0;const Ce=typeof BigInt64Array<"u"&&BigInt64Array.from,j=typeof BigUint64Array<"u"&&BigUint64Array.from,$=typeof Float16Array<"u"&&Float16Array.from;Ce&&(O.set("int64",BigInt64Array),fe.set(BigInt64Array,"int64")),j&&(O.set("uint64",BigUint64Array),fe.set(BigUint64Array,"uint64")),$?(O.set("float16",Float16Array),fe.set(Float16Array,"float16")):O.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{Tensor:()=>Ce});var O=N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),fe=N("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Te=N("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Ce{constructor($,V,A){(0,ye.checkTypedArray)();let ee,ne;if(typeof $=="object"&&"location"in $)switch(this.dataLocation=$.location,ee=$.type,ne=$.dims,$.location){case"cpu-pinned":{const ce=ye.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(ee);if(!ce)throw new TypeError(`unsupported type "${ee}" to create tensor from pinned buffer`);if(!($.data instanceof ce))throw new TypeError(`buffer should be of type ${ce.name}`);this.cpuData=$.data;break}case"texture":{if(ee!=="float32")throw new TypeError(`unsupported type "${ee}" to create tensor from texture`);this.gpuTextureData=$.texture,this.downloader=$.download,this.disposer=$.dispose;break}case"gpu-buffer":{if(ee!=="float32"&&ee!=="float16"&&ee!=="int32"&&ee!=="int64"&&ee!=="uint32"&&ee!=="uint8"&&ee!=="bool")throw new TypeError(`unsupported type "${ee}" to create tensor from gpu buffer`);this.gpuBufferData=$.gpuBuffer,this.downloader=$.download,this.disposer=$.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ce,D;if(typeof $=="string")if(ee=$,D=A,$==="string"){if(!Array.isArray(V))throw new TypeError("A string tensor's data must be a string array.");ce=V}else{const H=ye.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get($);if(H===void 0)throw new TypeError(`Unsupported tensor type: ${$}.`);if(Array.isArray(V)){if($==="float16"&&H===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");$==="uint64"||$==="int64"?ce=H.from(V,BigInt):ce=H.from(V)}else if(V instanceof H)ce=V;else throw new TypeError(`A ${ee} tensor's data must be type of ${H}`)}else if(D=V,Array.isArray($)){if($.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const H=typeof $[0];if(H==="string")ee="string",ce=$;else if(H==="boolean")ee="bool",ce=Uint8Array.from($);else throw new TypeError(`Invalid element type of data array: ${H}.`)}else{const H=ye.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get($.constructor);if(H===void 0)throw new TypeError(`Unsupported type for tensor data: ${$.constructor}.`);ee=H,ce=$}if(D===void 0)D=[ce.length];else if(!Array.isArray(D))throw new TypeError("A tensor's dims must be a number array");ne=D,this.cpuData=ce,this.dataLocation="cpu"}const me=(0,Te.calculateSize)(ne);if(this.cpuData&&me!==this.cpuData.length)throw new Error(`Tensor's size(${me}) does not match data length(${this.cpuData.length}).`);this.type=ee,this.dims=ne,this.size=me}static async fromImage($,V){return(0,fe.tensorFromImage)($,V)}static fromTexture($,V){return(0,fe.tensorFromTexture)($,V)}static fromGpuBuffer($,V){return(0,fe.tensorFromGpuBuffer)($,V)}static fromPinnedBuffer($,V,A){return(0,fe.tensorFromPinnedBuffer)($,V,A)}toDataURL($){return(0,O.tensorToDataURL)(this,$)}toImageData($){return(0,O.tensorToImageData)(this,$)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData($){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const V=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=V,$&&this.disposer&&(this.disposer(),this.disposer=void 0),V}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape($){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Te.tensorReshape)(this,$)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{calculateSize:()=>fe,tensorReshape:()=>ye});var O=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const fe=Te=>{let Ce=1;for(let j=0;j{switch(Te.location){case"cpu":return new O.Tensor(Te.type,Te.data,Ce);case"cpu-pinned":return new O.Tensor({location:"cpu-pinned",data:Te.data,type:Te.type,dims:Ce});case"texture":return new O.Tensor({location:"texture",texture:Te.texture,type:Te.type,dims:Ce});case"gpu-buffer":return new O.Tensor({location:"gpu-buffer",gpuBuffer:Te.gpuBuffer,type:Te.type,dims:Ce});default:throw new Error(`tensorReshape: tensor location ${Te.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{Tensor:()=>fe});var O=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const fe=O.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{TRACE:()=>fe,TRACE_FUNC_BEGIN:()=>Te,TRACE_FUNC_END:()=>Ce});var O=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const fe=(j,$)=>{(typeof O.env.trace>"u"?!O.env.wasm.trace:!O.env.trace)||console.timeStamp(`${j}::ORT::${$}`)},ye=(j,$)=>{var ee;const V=((ee=new Error().stack)==null?void 0:ee.split(/\r\n|\r|\n/g))||[];let A=!1;for(let ne=0;ne{(typeof O.env.trace>"u"?!O.env.wasm.trace:!O.env.trace)||ye("BEGIN",j)},Ce=j=>{(typeof O.env.trace>"u"?!O.env.wasm.trace:!O.env.trace)||ye("END",j)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{TrainingSession:()=>Te});var O=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),fe=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");const ye="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Te{constructor(j,$,V){this.handler=j,this.hasOptimizerModel=$,this.hasEvalModel=V}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(j,$){const V=j.evalModel||"",A=j.optimizerModel||"",ee=$||{},[ne,me]=await(0,O.resolveBackendAndExecutionProviders)(ee);if(ne.createTrainingSessionHandler){const ce=await ne.createTrainingSessionHandler(j.checkpointState,j.trainModel,V,A,me);return new Te(ce,!!j.optimizerModel,!!j.evalModel)}else throw new Error(ye)}typeNarrowingForRunStep(j,$,V,A,ee){const ne={};let me={};if(typeof V!="object"||V===null||V instanceof fe.Tensor||Array.isArray(V))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ce=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof fe.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");ce=!1;for(const D of A){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if($.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);ne[D]=null}if(typeof ee=="object"&&ee!==null)me=ee;else if(typeof ee<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const H=Object.getOwnPropertyNames(A);for(const te of $)if(H.indexOf(te)!==-1){const se=A[te];(se===null||se instanceof fe.Tensor)&&(D=!0,ce=!1,ne[te]=se)}if(D){if(typeof ee=="object"&&ee!==null)me=ee;else if(typeof ee<"u")throw new TypeError("'options' must be an object.")}else me=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of j)if(typeof V[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ce)for(const D of $)ne[D]=null;return[ne,me]}convertHandlerReturnTypeToMapOfTensors(j){const $={};for(const V in j)if(Object.hasOwnProperty.call(j,V)){const A=j[V];A instanceof fe.Tensor?$[V]=A:$[V]=new fe.Tensor(A.type,A.data,A.dims)}return $}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(j,$,V){const[A,ee]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,j,$,V),ne=await this.handler.runTrainStep(j,A,ee);return this.convertHandlerReturnTypeToMapOfTensors(ne)}async runOptimizerStep(j){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(j||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(j,$,V){if(this.hasEvalModel){const[A,ee]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,j,$,V),ne=await this.handler.runEvalStep(j,A,ee);return this.convertHandlerReturnTypeToMapOfTensors(ne)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(j=!0){return this.handler.getParametersSize(j)}async loadParametersBuffer(j,$=!0){const V=await this.getParametersSize($);if(j.length!==4*V)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(j,$)}async getContiguousParameters(j=!0){return this.handler.getContiguousParameters(j)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{TrainingSession:()=>fe});var O=N("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const fe=O.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{version:()=>O});const O="1.19.2"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(Et,Se,N)=>{N.r(Se),N.d(Se,{InferenceSession:()=>vt,TRACE:()=>ke,TRACE_FUNC_BEGIN:()=>qe,TRACE_FUNC_END:()=>We,Tensor:()=>Le,TrainingSession:()=>Bt,default:()=>Gf,env:()=>k,registerBackend:()=>me});/*! + * ONNX Runtime Web v1.20.0-dev.20240908-de7a02beef + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var O=Object.defineProperty,fe=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyNames,Te=Object.prototype.hasOwnProperty,Ce=(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')}),j=(e,t)=>()=>(e&&(t=e(e=0)),t),$=(e,t)=>{for(var r in t)O(e,r,{get:t[r],enumerable:!0})},V=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ye(t))!Te.call(e,s)&&s!==r&&O(e,s,{get:()=>t[s],enumerable:!(n=fe(t,s))||n.enumerable});return e},A=e=>V(O({},"__esModule",{value:!0}),e),ee,ne,me,ce,D,H=j(()=>{ee=new Map,ne=[],me=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=ee.get(e);if(n===void 0)ee.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=ne.indexOf(e);s!==-1&&ne.splice(s,1);for(let a=0;a{let t=ee.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},D=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?ne:r,s,a=[],i=new Set;for(let d of n){let p=await ce(d);typeof p=="string"?a.push({name:d,err:p}):(s||(s=p),s===p&&i.add(d))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:p}of a)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${p}`);let u=t.filter(d=>i.has(typeof d=="string"?d:d.name));return[s,new Proxy(e,{get:(d,p)=>p==="executionProviders"?u:Reflect.get(d,p)})]}}),te=j(()=>{H()}),se,X=j(()=>{se="1.20.0-dev.20240827-5d54dc1462"}),R,I,B=j(()=>{X(),R="warning",I={wasm:{},webgl:{},webgpu:{},versions:{common:se},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}`);R=e}},get logLevel(){return R}},Object.defineProperty(I,"logLevel",{enumerable:!0})}),k,ue=j(()=>{B(),k=I}),ve,Ee,Ie=j(()=>{ve=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,d,p;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?p=[0,0,0,0]:typeof u.bias=="number"?p=[u.bias,u.bias,u.bias,u.bias]:(p=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(p[3]=u.bias[3]));let w=a*s,g=0,l=w,M=w*2,T=-1;i==="RGBA"?(g=0,l=w,M=w*2,T=w*3):i==="RGB"?(g=0,l=w,M=w*2):i==="RBG"&&(g=0,M=w,l=w*2);for(let E=0;E{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,p,w;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean=="number"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?w=[0,0,0,0]:typeof d.bias=="number"?w=[d.bias,d.bias,d.bias,d.bias]:(w=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(w[3]=d.bias[3]));let g=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,M=0,T=1,E=2,L=3,G=0,z=g,ae=g*2,Q=-1;u==="RGBA"?(G=0,z=g,ae=g*2,Q=g*3):u==="RGB"?(G=0,z=g,ae=g*2):u==="RBG"&&(G=0,ae=g,z=g*2),n=r.createImageData(s,a);for(let oe=0;oe{Pt(),Ae=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*n,w=d==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),g=4,l=0,M=1,T=2,E=3,L=0,G=p,z=p*2,ae=-1;u==="RGB"&&(g=3,l=0,M=1,T=2,E=-1),d==="RGBA"?ae=p*3:d==="RBG"?(L=0,z=p,G=p*2):d==="BGR"&&(z=0,G=p,L=p*2);for(let Q=0;Q{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,u=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=w=>w instanceof HTMLCanvasElement||w instanceof OffscreenCanvas?w.getContext("2d"):null;if(r){let w=d();w.width=e.width,w.height=e.height;let g=p(w);if(g!=null){let l=e.height,M=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,M=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=M}else u.tensorFormat="RGBA",u.height=l,u.width=M;g.drawImage(e,0,0),i=g.getImageData(0,0,M,l).data}else throw new Error("Can not access image data")}else if(n){let w,g;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(w=t.resizedHeight,g=t.resizedWidth):(w=e.height,g=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=w,u.width=g,t!==void 0){let l=d();l.width=g,l.height=w;let M=p(l);if(M!=null)M.putImageData(e,0,0),i=M.getImageData(0,0,g,w).data;else throw new Error("Can not access image data")}else i=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let w=d();w.width=e.width,w.height=e.height;let g=p(w);if(g!=null){let l=e.height,M=e.width;return g.drawImage(e,0,0,M,l),i=g.getImageData(0,0,M,l).data,u.height=l,u.width=M,Ae(i,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((w,g)=>{let l=d(),M=p(l);if(!e||!M)return g();let T=new Image;T.crossOrigin="Anonymous",T.src=e,T.onload=()=>{l.width=T.width,l.height=T.height,M.drawImage(T,0,0,l.width,l.height);let E=M.getImageData(0,0,l.width,l.height);u.height=l.height,u.width=l.width,w(Ae(E.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ae(i,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Xe=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new st({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},dt=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new st({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},ge=(e,t,r)=>new st({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),de,$e,J,He,ct=j(()=>{de=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"]]),J=!1,He=()=>{if(!J){J=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(de.set("int64",BigInt64Array),$e.set(BigInt64Array,"int64")),t&&(de.set("uint64",BigUint64Array),$e.set(BigUint64Array,"uint64")),r?(de.set("float16",Float16Array),$e.set(Float16Array,"float16")):de.set("float16",Uint16Array)}}}),nt,lt,je=j(()=>{Pt(),nt=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});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),st,Pt=j(()=>{Ie(),W(),ct(),je(),st=class{constructor(e,t,r){He();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let i=de.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let d=de.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&d===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${d.name} as data.`);e==="uint64"||e==="int64"?i=d.from(t,BigInt):i=d.from(t)}else if(t instanceof d)i=t;else throw new TypeError(`A ${n} tensor's data must be type of ${d}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")n="string",i=e;else if(d==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else{let d=$e.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=d,i=e}if(u===void 0)u=[i.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");s=u,this.cpuData=i,this.dataLocation="cpu"}let a=nt(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return tt(e,t)}static fromTexture(e,t){return Xe(e,t)}static fromGpuBuffer(e,t){return dt(e,t)}static fromPinnedBuffer(e,t,r){return ge(e,t,r)}toDataURL(e){return ve(this,e)}toImageData(e){return Ee(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return lt(this,e)}}}),Le,re=j(()=>{Pt(),Le=st}),ke,Ve,qe,We,Ke=j(()=>{B(),ke=(e,t)=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ve=(e,t)=>{var s;let r=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||Ve("BEGIN",e)},We=e=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||Ve("END",e)}}),ut,yt=j(()=>{H(),re(),Ke(),ut=class yf{constructor(t){this.handler=t}async run(t,r,n){qe();let s={},a={};if(typeof t!="object"||t===null||t instanceof Le||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Le)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let p of r){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);s[p]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,w=Object.getOwnPropertyNames(r);for(let g of this.outputNames)if(w.indexOf(g)!==-1){let l=r[g];(l===null||l instanceof Le)&&(p=!0,i=!1,s[g]=l)}if(p){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(i)for(let p of this.outputNames)s[p]=null;let u=await this.handler.run(t,s,a),d={};for(let p in u)if(Object.hasOwnProperty.call(u,p)){let w=u[p];w instanceof Le?d[p]=w:d[p]=new Le(w.type,w.data,w.dims)}return We(),d}async release(){return this.handler.dispose()}static async create(t,r,n,s){qe();let a,i={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let w=t,g=0,l=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(g=r,!Number.isSafeInteger(g))throw new RangeError("'byteOffset' must be an integer.");if(g<0||g>=w.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${w.byteLength}).`);if(l=t.byteLength-g,typeof n=="number"){if(l=n,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||g+l>w.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${w.byteLength-g}].`);if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(w,g,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await D(i),p=await u.createInferenceSessionHandler(a,d);return We(),new yf(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),vt,kt=j(()=>{yt(),vt=ut}),v=j(()=>{}),q=j(()=>{}),C=j(()=>{}),Y=j(()=>{}),he,Qe,Ye=j(()=>{H(),re(),he="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Qe=class bf{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}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 n=t.evalModel||"",s=t.optimizerModel||"",a=r||{},[i,u]=await D(a);if(i.createTrainingSessionHandler){let d=await i.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,s,u);return new bf(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(he)}typeNarrowingForRunStep(t,r,n,s,a){let i={},u={};if(typeof n!="object"||n===null||n instanceof Le||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof Le)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let p of s){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);i[p]=null}if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,w=Object.getOwnPropertyNames(s);for(let g of r)if(w.indexOf(g)!==-1){let l=s[g];(l===null||l instanceof Le)&&(p=!0,d=!1,i[g]=l)}if(p){if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else u=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of t)if(typeof n[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(d)for(let p of r)i[p]=null;return[i,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let s=t[n];s instanceof Le?r[n]=s:r[n]=new Le(s.type,s.data,s.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[s,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),i=await this.handler.runTrainStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}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,n){if(this.hasEvalModel){let[s,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),i=await this.handler.runEvalStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}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 n=await this.getParametersSize(r);if(t.length!==4*n)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()}}}),Bt,ht=j(()=>{Ye(),Bt=Qe}),Tt={};$(Tt,{InferenceSession:()=>vt,TRACE:()=>ke,TRACE_FUNC_BEGIN:()=>qe,TRACE_FUNC_END:()=>We,Tensor:()=>Le,TrainingSession:()=>Bt,env:()=>k,registerBackend:()=>me});var bt=j(()=>{te(),ue(),kt(),re(),v(),q(),Ke(),C(),Y(),ht()}),Ot=j(()=>{}),cr={};$(cr,{default:()=>Br});var xr,Yr,Br,Kr=j(()=>{var e;Lp(),yr(),Rt(),xr="ort-wasm-proxy-worker",Yr=((e=globalThis.self)==null?void 0:e.name)===xr,Yr&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Lr(n.wasm).then(()=>{vc(n).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:a}=n;xc(a,s).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})});break}case"copy-from":{let{buffer:s}=n,a=Yd(s);postMessage({type:r,out:a});break}case"create":{let{model:s,options:a}=n;Tc(s,a).then(i=>{postMessage({type:r,out:i})},i=>{postMessage({type:r,err:i})});break}case"release":Sc(n),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:a,inputs:i,outputIndices:u,options:d}=n;Ec(s,a,i,u,new Array(u.length).fill(null),d).then(p=>{p.some(w=>w[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:p},kc([...i,...p]))},p=>{postMessage({type:r,err:p})});break}case"end-profiling":$c(n),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),Br=Yr?null:t=>new Worker(t??we,{type:"module",name:xr})}),at={};$(at,{default:()=>Pe});var U,_e,Pe,rt=j(()=>{var e;_e=(U=self.location.href,async function(t={}){function r(){return Mr.buffer!=dr.buffer&&bn(),dr}function n(){return Mr.buffer!=dr.buffer&&bn(),Or}function s(){return Mr.buffer!=dr.buffer&&bn(),Ue}function a(){return Mr.buffer!=dr.buffer&&bn(),$t}function i(){return Mr.buffer!=dr.buffer&&bn(),rr}function u(){return Mr.buffer!=dr.buffer&&bn(),Ur}function d(){return Mr.buffer!=dr.buffer&&bn(),nn}function p(){return Mr.buffer!=dr.buffer&&bn(),ec}var w,g,l=Object.assign({},t),M=new Promise((o,h)=>{w=o,g=h}),T=typeof window=="object",E=typeof importScripts=="function",L=E&&self.name=="em-pthread";l.mountExternalData=(o,h)=>{o.startsWith("./")&&(o=o.substring(2)),(l.Fb||(l.Fb=new Map)).set(o,h)},l.unmountExternalData=()=>{delete l.Fb};var G=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let z=()=>{let o=(y,x,F)=>(...le)=>{let Ge=us,it=x==null?void 0:x();le=y(...le);let At=x==null?void 0:x();return it!==At&&(y=At,F(it),x=F=null),us!=Ge?new Promise((Lt,Yt)=>{Hc={resolve:Lt,reject:Yt}}):le},h=y=>async(...x)=>{var F;try{if(l.Eb)throw Error("Session already started");let le=l.Eb={cc:x[0],errors:[]},Ge=await y(...x);if(l.Eb!==le)throw Error("Session mismatch");(F=l.Mb)==null||F.flush();let it=le.errors;if(0Lt),0l._OrtCreateSession,y=>l._OrtCreateSession=y),l._OrtRun=h(o(l._OrtRun,()=>l._OrtRun,y=>l._OrtRun=y)),l._OrtRunWithBinding=h(o(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,y=>l._OrtRunWithBinding=y)),l._OrtBindInput=o(l._OrtBindInput,()=>l._OrtBindInput,y=>l._OrtBindInput=y),z=void 0};l.jsepInit=(o,h)=>{if(z==null||z(),o==="webgpu"){[l.Mb,l.Tb,l.Xb,l.Nb,l.Wb,l.jb,l.Yb,l.$b,l.Ub,l.Vb,l.Zb]=h;let y=l.Mb;l.jsepRegisterBuffer=(x,F,le,Ge)=>y.registerBuffer(x,F,le,Ge),l.jsepGetBuffer=x=>y.getBuffer(x),l.jsepCreateDownloader=(x,F,le)=>y.createDownloader(x,F,le),l.jsepOnReleaseSession=x=>{y.onReleaseSession(x)},l.jsepOnRunStart=x=>y.onRunStart(x),l.ac=(x,F)=>{y.upload(x,F)}}};var ae,Q,oe=Object.assign({},l),Re="./this.program",Ne=(o,h)=>{throw h},_t="";(T||E)&&(E?_t=self.location.href:typeof document<"u"&&document.currentScript&&(_t=document.currentScript.src),U&&(_t=U),_t=_t.startsWith("blob:")?"":_t.substr(0,_t.replace(/[?#].*/,"").lastIndexOf("/")+1),E&&(Q=o=>{var h=new XMLHttpRequest;return h.open("GET",o,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),ae=(o,h,y)=>{var x=new XMLHttpRequest;x.open("GET",o,!0),x.responseType="arraybuffer",x.onload=()=>{x.status==200||x.status==0&&x.response?h(x.response):y()},x.onerror=y,x.send(null)});var Dt,Vt=console.log.bind(console),lr=console.error.bind(console),fr=Vt,tr=lr;if(Object.assign(l,oe),oe=null,L){let o=function(h){try{var y=h.data,x=y.cmd;if(x==="load"){let F=[];self.onmessage=le=>F.push(le),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let le of F)o(le);self.onmessage=o};for(let le of y.handlers)l[le]&&!l[le].proxy||(l[le]=(...Ge)=>{postMessage({Lb:"callHandler",lc:le,args:Ge})},le=="print"&&(fr=l[le]),le=="printErr"&&(tr=l[le]));Mr=y.wasmMemory,bn(),Vr(y.wasmModule)}else if(x==="run"){Yc(y.pthread_ptr,0,0,1,0,0),Wc(y.pthread_ptr),Kf(),uh(),Qr||(of(),Qr=!0);try{Xf(y.start_routine,y.arg)}catch(F){if(F!="unwind")throw F}}else x==="cancel"?Ja()&&pc(-1):y.target!=="setimmediate"&&(x==="checkMailbox"?Qr&&nc():x&&(tr(`worker: received unknown command ${x}`),tr(y)))}catch(F){throw lf(),F}};var Vr,Qr=!1;tr=function(...h){h=h.join(" "),console.error(h)},self.alert=function(...h){postMessage({Lb:"alert",text:h.join(" "),nc:Ja()})},l.instantiateWasm=(h,y)=>new Promise(x=>{Vr=F=>{F=new WebAssembly.Instance(F,sh()),y(F),x()}}),self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=o}l.wasmBinary&&(Dt=l.wasmBinary);var Mr,Wr,Zt,dr,Or,Ue,$t,rr,Ur,nn,fn,Ws,ec,Nn=!1;function bn(){var o=Mr.buffer;l.HEAP8=dr=new Int8Array(o),l.HEAP16=Ue=new Int16Array(o),l.HEAPU8=Or=new Uint8Array(o),l.HEAPU16=$t=new Uint16Array(o),l.HEAP32=rr=new Int32Array(o),l.HEAPU32=Ur=new Uint32Array(o),l.HEAPF32=nn=new Float32Array(o),l.HEAPF64=ec=new Float64Array(o),l.HEAP64=fn=new BigInt64Array(o),l.HEAPU64=Ws=new BigUint64Array(o)}if(!L){if(!((Mr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof G))throw tr("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");bn()}var dd=[],Mn=[],Pn=[],Wn=0,Gs=null;function tc(){if(--Wn==0&&Gs){var o=Gs;Gs=null,o()}}function Qa(o){throw tr(o="Aborted("+o+")"),Nn=!0,Zt=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),g(o),o}var Ic,eh=o=>o.startsWith("data:application/octet-stream;base64,"),th=o=>o.startsWith("file://");function rh(o){if(o==Ic&&Dt)return new Uint8Array(Dt);if(Q)return Q(o);throw"both async and sync fetching of the wasm failed"}function nh(o,h,y){return function(x){if(!Dt&&(T||E)){if(typeof fetch=="function"&&!th(x))return fetch(x,{credentials:"same-origin"}).then(F=>{if(!F.ok)throw`failed to load wasm binary file at '${x}'`;return F.arrayBuffer()}).catch(()=>rh(x));if(ae)return new Promise((F,le)=>{ae(x,Ge=>F(new Uint8Array(Ge)),le)})}return Promise.resolve().then(()=>rh(x))}(o).then(x=>WebAssembly.instantiate(x,h)).then(y,x=>{tr(`failed to asynchronously prepare wasm: ${x}`),Qa(x)})}function sh(){return{a:{M:Hf,za:qf,b:Yf,$:hh,z:_h,pa:gh,X:yh,Z:bh,qa:Mh,na:vh,ga:xh,ma:Th,J:Sh,Y:Ch,V:Eh,oa:$h,W:kh,va:Zf,D:Jf,P:em,O:rm,C:sm,s:im,p:am,E:om,y:fm,Q:mm,ta:_m,ja:gm,T:wm,aa:ym,F:bm,ia:Wc,sa:Mm,u:vm,B:Sm,o:Cm,m:$m,c:Vc,n:km,k:Im,Aa:Fm,r:Om,g:zm,v:Dm,l:Bm,f:Lm,i:Rm,j:Nm,h:jm,e:Vm,da:Um,ea:Wm,fa:Gm,ba:Uh,ca:Wh,S:qm,d:Hm,N:Km,G:Xm,K:Qm,w:Ym,ra:Zm,U:Jm,t:qh,x:e_,L:t_,R:r_,ya:n_,xa:s_,ka:Xh,la:Qh,_:Bc,A:Yh,I:Zh,ha:Jh,H:ef,a:Mr,wa:Dc,ua:nf,q:o_}}}var Fc={859316:(o,h,y,x,F)=>{if(l===void 0||!l.Fb)return 1;if((o=gn(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=l.Fb.get(o)))return 2;if(x>>>=0,(h>>>=0)+(y>>>=0)>o.byteLength)return 3;try{let le=o.subarray(h,h+y);switch(F){case 0:n().set(le,x>>>0);break;case 1:l.ac(x,le);break;default:return 4}return 0}catch{return 4}},859999:()=>{l.Ub()},860030:()=>{l.Vb()},860059:()=>{l.Zb()},860084:o=>l.Tb(o),860117:o=>l.Xb(o),860149:(o,h,y)=>{l.Nb(o,h,y,!0)},860188:(o,h,y)=>{l.Nb(o,h,y)},860221:()=>typeof wasmOffsetConverter<"u",860278:o=>{l.jb("Abs",o,void 0)},860329:o=>{l.jb("Neg",o,void 0)},860380:o=>{l.jb("Floor",o,void 0)},860433:o=>{l.jb("Ceil",o,void 0)},860485:o=>{l.jb("Reciprocal",o,void 0)},860543:o=>{l.jb("Sqrt",o,void 0)},860595:o=>{l.jb("Exp",o,void 0)},860646:o=>{l.jb("Erf",o,void 0)},860697:o=>{l.jb("Sigmoid",o,void 0)},860752:(o,h,y)=>{l.jb("HardSigmoid",o,{alpha:h,beta:y})},860831:o=>{l.jb("Log",o,void 0)},860882:o=>{l.jb("Sin",o,void 0)},860933:o=>{l.jb("Cos",o,void 0)},860984:o=>{l.jb("Tan",o,void 0)},861035:o=>{l.jb("Asin",o,void 0)},861087:o=>{l.jb("Acos",o,void 0)},861139:o=>{l.jb("Atan",o,void 0)},861191:o=>{l.jb("Sinh",o,void 0)},861243:o=>{l.jb("Cosh",o,void 0)},861295:o=>{l.jb("Asinh",o,void 0)},861348:o=>{l.jb("Acosh",o,void 0)},861401:o=>{l.jb("Atanh",o,void 0)},861454:o=>{l.jb("Tanh",o,void 0)},861506:o=>{l.jb("Not",o,void 0)},861557:(o,h,y)=>{l.jb("Clip",o,{min:h,max:y})},861626:o=>{l.jb("Clip",o,void 0)},861678:(o,h)=>{l.jb("Elu",o,{alpha:h})},861736:o=>{l.jb("Gelu",o,void 0)},861788:o=>{l.jb("Relu",o,void 0)},861840:(o,h)=>{l.jb("LeakyRelu",o,{alpha:h})},861904:(o,h)=>{l.jb("ThresholdedRelu",o,{alpha:h})},861974:(o,h)=>{l.jb("Cast",o,{to:h})},862032:o=>{l.jb("Add",o,void 0)},862083:o=>{l.jb("Sub",o,void 0)},862134:o=>{l.jb("Mul",o,void 0)},862185:o=>{l.jb("Div",o,void 0)},862236:o=>{l.jb("Pow",o,void 0)},862287:o=>{l.jb("Equal",o,void 0)},862340:o=>{l.jb("Greater",o,void 0)},862395:o=>{l.jb("GreaterOrEqual",o,void 0)},862457:o=>{l.jb("Less",o,void 0)},862509:o=>{l.jb("LessOrEqual",o,void 0)},862568:(o,h,y,x,F)=>{l.jb("ReduceMean",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},862727:(o,h,y,x,F)=>{l.jb("ReduceMax",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},862885:(o,h,y,x,F)=>{l.jb("ReduceMin",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},863043:(o,h,y,x,F)=>{l.jb("ReduceProd",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},863202:(o,h,y,x,F)=>{l.jb("ReduceSum",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},863360:(o,h,y,x,F)=>{l.jb("ReduceL1",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},863517:(o,h,y,x,F)=>{l.jb("ReduceL2",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},863674:(o,h,y,x,F)=>{l.jb("ReduceLogSum",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},863835:(o,h,y,x,F)=>{l.jb("ReduceSumSquare",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},863999:(o,h,y,x,F)=>{l.jb("ReduceLogSumExp",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},864163:o=>{l.jb("Where",o,void 0)},864216:(o,h,y)=>{l.jb("Transpose",o,{perm:h?Array.from(i().subarray(h>>>0,y>>>0)):[]})},864324:(o,h,y,x)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:gn(y),format:x?"NHWC":"NCHW"})},864457:(o,h,y,x)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:gn(y),format:x?"NHWC":"NCHW"})},864590:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be,vr)=>{l.jb("ConvTranspose",o,{format:At?"NHWC":"NCHW",autoPad:h,dilations:[y],group:x,kernelShape:[F],pads:[le,Ge],strides:[it],wIsConst:()=>!!r()[Lt>>>0],outputPadding:Yt?Array.from(i().subarray(Yt>>>0,Pr>>>0)):[],outputShape:jr?Array.from(i().subarray(jr>>>0,Be>>>0)):[],activation:gn(vr)})},864991:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:h,dilations:Array.from(i().subarray(y>>>0,2+(y>>>0)>>>0)),group:x,kernelShape:Array.from(i().subarray(F>>>0,2+(F>>>0)>>>0)),pads:Array.from(i().subarray(le>>>0,4+(le>>>0)>>>0)),strides:Array.from(i().subarray(Ge>>>0,2+(Ge>>>0)>>>0)),wIsConst:()=>!!r()[At>>>0],outputPadding:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],outputShape:Pr?Array.from(i().subarray(Pr>>>0,jr>>>0)):[],activation:gn(Be)})},865556:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be,vr)=>{l.jb("ConvTranspose",o,{format:At?"NHWC":"NCHW",autoPad:h,dilations:[y],group:x,kernelShape:[F],pads:[le,Ge],strides:[it],wIsConst:()=>!!r()[Lt>>>0],outputPadding:Yt?Array.from(i().subarray(Yt>>>0,Pr>>>0)):[],outputShape:jr?Array.from(i().subarray(jr>>>0,Be>>>0)):[],activation:gn(vr)})},865957:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:h,dilations:Array.from(i().subarray(y>>>0,2+(y>>>0)>>>0)),group:x,kernelShape:Array.from(i().subarray(F>>>0,2+(F>>>0)>>>0)),pads:Array.from(i().subarray(le>>>0,4+(le>>>0)>>>0)),strides:Array.from(i().subarray(Ge>>>0,2+(Ge>>>0)>>>0)),wIsConst:()=>!!r()[At>>>0],outputPadding:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],outputShape:Pr?Array.from(i().subarray(Pr>>>0,jr>>>0)):[],activation:gn(Be)})},866522:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},866613:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:x,storage_order:F,dilations:le?Array.from(i().subarray(le>>>0,Ge>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,At>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],strides:Pr?Array.from(i().subarray(Pr>>>0,jr>>>0)):[]})},867028:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},867119:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:x,storage_order:F,dilations:le?Array.from(i().subarray(le>>>0,Ge>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,At>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],strides:Pr?Array.from(i().subarray(Pr>>>0,jr>>>0)):[]})},867534:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},867621:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:x,storage_order:F,dilations:le?Array.from(i().subarray(le>>>0,Ge>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,At>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],strides:Pr?Array.from(i().subarray(Pr>>>0,jr>>>0)):[]})},868032:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},868119:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:x,storage_order:F,dilations:le?Array.from(i().subarray(le>>>0,Ge>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,At>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],strides:Pr?Array.from(i().subarray(Pr>>>0,jr>>>0)):[]})},868530:(o,h,y,x,F)=>{l.jb("Gemm",o,{alpha:h,beta:y,transA:x,transB:F})},868634:o=>{l.jb("MatMul",o,void 0)},868688:(o,h,y,x)=>{l.jb("ArgMax",o,{keepDims:!!h,selectLastIndex:!!y,axis:x})},868796:(o,h,y,x)=>{l.jb("ArgMin",o,{keepDims:!!h,selectLastIndex:!!y,axis:x})},868904:(o,h)=>{l.jb("Softmax",o,{axis:h})},868967:(o,h)=>{l.jb("Concat",o,{axis:h})},869027:(o,h,y,x,F)=>{l.jb("Split",o,{axis:h,numOutputs:y,splitSizes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},869167:o=>{l.jb("Expand",o,void 0)},869221:(o,h)=>{l.jb("Gather",o,{axis:Number(h)})},869292:(o,h)=>{l.jb("GatherElements",o,{axis:Number(h)})},869371:(o,h,y,x,F,le,Ge,it,At,Lt,Yt)=>{l.jb("Resize",o,{antialias:h,axes:y?Array.from(i().subarray(y>>>0,x>>>0)):[],coordinateTransformMode:gn(F),cubicCoeffA:le,excludeOutside:Ge,extrapolationValue:it,keepAspectRatioPolicy:gn(At),mode:gn(Lt),nearestMode:gn(Yt)})},869717:(o,h,y,x,F,le,Ge)=>{l.jb("Slice",o,{starts:h?Array.from(i().subarray(h>>>0,y>>>0)):[],ends:x?Array.from(i().subarray(x>>>0,F>>>0)):[],axes:le?Array.from(i().subarray(le>>>0,Ge>>>0)):[]})},869933:o=>{l.jb("Tile",o,void 0)},869985:(o,h,y)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:y?"NHWC":"NCHW"})},870099:(o,h,y)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:y?"NHWC":"NCHW"})},870213:o=>{l.jb("Range",o,void 0)},870266:(o,h)=>{l.jb("Einsum",o,{equation:gn(h)})},870347:(o,h,y,x,F)=>{l.jb("Pad",o,{mode:h,value:y,pads:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},870474:(o,h,y,x,F,le)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:y,spatial:!!F,trainingMode:!!x,format:le?"NHWC":"NCHW"})},870643:(o,h,y,x,F,le)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:y,spatial:!!F,trainingMode:!!x,format:le?"NHWC":"NCHW"})},870812:(o,h,y)=>{l.jb("CumSum",o,{exclusive:Number(h),reverse:Number(y)})},870909:(o,h,y)=>{l.jb("DequantizeLinear",o,{axis:h,blockSize:y})},870999:(o,h,y,x,F,le,Ge,it,At)=>{l.jb("Attention",o,{numHeads:h,isUnidirectional:y,maskFilterValue:x,scale:F,doRotary:le,qkvHiddenSizes:Ge?Array.from(i().subarray(Number(it)>>>0,Number(it)+Ge>>>0)):[],pastPresentShareBuffer:!!At})},871271:o=>{l.jb("BiasAdd",o,void 0)},871326:o=>{l.jb("BiasSplitGelu",o,void 0)},871387:o=>{l.jb("FastGelu",o,void 0)},871443:(o,h,y,x,F,le,Ge,it,At,Lt,Yt,Pr,jr,Be,vr,Jr)=>{l.jb("Conv",o,{format:Pr?"NHWC":"NCHW",auto_pad:h,dilations:y?Array.from(i().subarray(y>>>0,x>>>0)):[],group:F,kernel_shape:le?Array.from(i().subarray(le>>>0,Ge>>>0)):[],pads:it?Array.from(i().subarray(it>>>0,At>>>0)):[],strides:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],w_is_const:()=>!!r()[jr>>>0],activation:gn(Be),activation_params:vr?Array.from(d().subarray(vr>>>0,Jr>>>0)):[]})},871939:o=>{l.jb("Gelu",o,void 0)},871991:(o,h,y,x)=>{l.jb("GroupQueryAttention",o,{numHeads:h,kvNumHeads:y,scale:x})},872104:(o,h,y,x)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:y,simplified:!!x})},872215:(o,h,y,x)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:y,simplified:!!x})},872326:(o,h,y,x,F,le)=>{l.jb("MatMulNBits",o,{k:h,n:y,accuracyLevel:x,bits:F,blockSize:le})},872453:(o,h,y,x,F,le)=>{l.jb("MultiHeadAttention",o,{numHeads:h,isUnidirectional:y,maskFilterValue:x,scale:F,doRotary:le})},872612:(o,h)=>{l.jb("QuickGelu",o,{alpha:h})},872676:(o,h,y,x,F)=>{l.jb("RotaryEmbedding",o,{interleaved:!!h,numHeads:y,rotaryEmbeddingDim:x,scale:F})},872815:(o,h,y)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!y})},872917:(o,h,y)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!y})},873019:(o,h,y,x)=>{l.jb("GatherBlockQuantized",o,{gatherAxis:h,quantizeAxis:y,blockSize:x})},873140:o=>{l.Yb(o)},873174:(o,h)=>l.$b(o,h,l.Eb.cc,l.Eb.errors)};function qf(o,h,y){return Lh(async()=>{await l.Wb(o,h,y)})}function Hf(){return typeof wasmOffsetConverter<"u"}function Oc(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var zc=o=>{o.terminate(),o.onmessage=()=>{}},ih=o=>{qs.length==0&&(ch(),dh(qs[0]));var h=qs.pop();if(!h)return 6;gi.push(h),os[o.Ab]=h,h.Ab=o.Ab;var y={cmd:"run",start_routine:o.dc,arg:o.Pb,pthread_ptr:o.Ab};return h.postMessage(y,o.jc),0},_i=0,Zr=(o,h,...y)=>{for(var x=2*y.length,F=ep(),le=Jc(8*x),Ge=le>>>3,it=0;it>>0]=At)}return o=uf(o,0,x,le,h),hc(F),o};function Dc(o){if(L)return Zr(0,1,o);if(Zt=o,!(0<_i)){for(var h of gi)zc(h);for(h of qs)zc(h);qs=[],gi=[],os=[],Nn=!0}Ne(o,new Oc(o))}function ah(o){if(L)return Zr(1,0,o);Bc(o)}var Bc=o=>{if(Zt=o,L)throw ah(o),"unwind";Dc(o)},qs=[],gi=[],oh=[],os={},lh=o=>{var h=o.Ab;delete os[h],qs.push(o),gi.splice(gi.indexOf(o),1),o.Ab=0,Zc(h)};function uh(){oh.forEach(o=>o())}var dh=o=>new Promise(h=>{o.onmessage=F=>{var le=(F=F.data).cmd;if(F.targetThread&&F.targetThread!=Ja()){var Ge=os[F.targetThread];Ge?Ge.postMessage(F,F.transferList):tr(`Internal error! Worker sent a message "${le}" to target pthread ${F.targetThread}, but that thread no longer exists!`)}else le==="checkMailbox"?nc():le==="spawnThread"?ih(F):le==="cleanupThread"?lh(os[F.thread]):le==="killThread"?(F=F.thread,le=os[F],delete os[F],zc(le),Zc(F),gi.splice(gi.indexOf(le),1),le.Ab=0):le==="cancelThread"?os[F.thread].postMessage({cmd:"cancel"}):le==="loaded"?(o.loaded=!0,h(o)):le==="alert"?alert(`Thread ${F.threadId}: ${F.text}`):F.target==="setimmediate"?o.postMessage(F):le==="callHandler"?l[F.handler](...F.args):le&&tr(`worker sent an unknown command ${le}`)},o.onerror=F=>{throw tr(`worker sent an error! ${F.filename}:${F.lineno}: ${F.message}`),F};var y,x=[];for(y of[])l.hasOwnProperty(y)&&x.push(y);o.postMessage({cmd:"load",handlers:x,wasmMemory:Mr,wasmModule:Wr})});function ch(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});qs.push(o)}var rc=o=>{for(;0{var o=Ja(),h=u()[o+52>>>2>>>0];o=u()[o+56>>>2>>>0],cf(h,h-o),hc(h)},Xf=(o,h)=>{_i=0,o=pf(o,h),0<_i?Zt=o:pc(o)};class Qf{constructor(h){this.Ib=h-24}}function Yf(o,h,y){var x=new Qf(o>>>=0);throw h>>>=0,y>>>=0,u()[x.Ib+16>>>2>>>0]=0,u()[x.Ib+4>>>2>>>0]=h,u()[x.Ib+8>>>2>>>0]=y,o}function ph(o,h,y,x){return L?Zr(2,1,o,h,y,x):hh(o,h,y,x)}function hh(o,h,y,x){if(o>>>=0,h>>>=0,y>>>=0,x>>>=0,G===void 0)return tr("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var F=[];return L&&F.length===0?ph(o,h,y,x):(o={dc:y,Ab:o,Pb:x,jc:F},L?(o.Lb="spawnThread",postMessage(o,F),0):ih(o))}var fh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,mh=(o,h,y)=>{var x=(h>>>=0)+y;for(y=h;o[y]&&!(y>=x);)++y;if(16(F=(240&F)==224?(15&F)<<12|le<<6|Ge:(7&F)<<18|le<<12|Ge<<6|63&o[h++])?x+=String.fromCharCode(F):(F-=65536,x+=String.fromCharCode(55296|F>>10,56320|1023&F))}}else x+=String.fromCharCode(F)}return x},gn=(o,h)=>(o>>>=0)?mh(n(),o,h):"";function _h(o,h,y){return L?Zr(3,1,o,h,y):0}function gh(o,h){if(L)return Zr(4,1,o,h)}var Lc=o=>{for(var h=0,y=0;y=x?h++:2047>=x?h+=2:55296<=x&&57343>=x?(h+=4,++y):h+=3}return h},wh=(o,h,y,x)=>{if(!(0>>=0;x=y+x-1;for(var le=0;le=Ge&&(Ge=65536+((1023&Ge)<<10)|1023&o.charCodeAt(++le)),127>=Ge){if(y>=x)break;h[y++>>>0]=Ge}else{if(2047>=Ge){if(y+1>=x)break;h[y++>>>0]=192|Ge>>6}else{if(65535>=Ge){if(y+2>=x)break;h[y++>>>0]=224|Ge>>12}else{if(y+3>=x)break;h[y++>>>0]=240|Ge>>18,h[y++>>>0]=128|Ge>>12&63}h[y++>>>0]=128|Ge>>6&63}h[y++>>>0]=128|63&Ge}}return h[y>>>0]=0,y-F},Ya=(o,h,y)=>wh(o,n(),h,y);function yh(o,h){if(L)return Zr(5,1,o,h)}function bh(o,h,y){if(L)return Zr(6,1,o,h,y)}function Mh(o,h,y){return L?Zr(7,1,o,h,y):0}function vh(o,h){if(L)return Zr(8,1,o,h)}function xh(o,h,y){if(L)return Zr(9,1,o,h,y)}function Th(o,h,y,x){if(L)return Zr(10,1,o,h,y,x)}function Sh(o,h,y,x){if(L)return Zr(11,1,o,h,y,x)}function Ch(o,h,y,x){if(L)return Zr(12,1,o,h,y,x)}function Eh(o){if(L)return Zr(13,1,o)}function $h(o,h){if(L)return Zr(14,1,o,h)}function kh(o,h,y){if(L)return Zr(15,1,o,h,y)}var Ph,Hs,Zf=()=>{Qa("")},ls=o=>{for(var h="";n()[o>>>0];)h+=Ph[n()[o++>>>0]];return h},Rc={},Nc={};function bs(o,h,y={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(x,F,le={}){var Ge=F.name;if(!x)throw new Hs(`type "${Ge}" must have a positive integer typeid pointer`);if(Nc.hasOwnProperty(x)){if(le.Rb)return;throw new Hs(`Cannot register type '${Ge}' twice`)}Nc[x]=F,Rc.hasOwnProperty(x)&&(F=Rc[x],delete Rc[x],F.forEach(it=>it()))}(o,h,y)}var Ah=(o,h,y)=>{switch(h){case 1:return y?x=>r()[x>>>0]:x=>n()[x>>>0];case 2:return y?x=>s()[x>>>1>>>0]:x=>a()[x>>>1>>>0];case 4:return y?x=>i()[x>>>2>>>0]:x=>u()[x>>>2>>>0];case 8:return y?x=>fn[x>>>3]:x=>Ws[x>>>3];default:throw new TypeError(`invalid integer width (${h}): ${o}`)}};function Jf(o,h,y){y>>>=0,bs(o>>>=0,{name:h=ls(h>>>0),fromWireType:x=>x,toWireType:function(x,F){if(typeof F!="bigint"&&typeof F!="number")throw F=F===null?"null":(x=typeof F)=="object"||x==="array"||x==="function"?F.toString():""+F,new TypeError(`Cannot convert "${F}" to ${this.name}`);return typeof F=="number"&&(F=BigInt(F)),F},argPackAdvance:Ks,readValueFromPointer:Ah(h,y,h.indexOf("u")==-1),Db:null})}var Ks=8;function em(o,h,y,x){bs(o>>>=0,{name:h=ls(h>>>0),fromWireType:function(F){return!!F},toWireType:function(F,le){return le?y:x},argPackAdvance:Ks,readValueFromPointer:function(F){return this.fromWireType(n()[F>>>0])},Db:null})}var jc=[],Ms=[];function Vc(o){9<(o>>>=0)&&--Ms[o+1]==0&&(Ms[o]=void 0,jc.push(o))}var Gn=o=>{if(!o)throw new Hs("Cannot use deleted val. handle = "+o);return Ms[o]},qn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=jc.pop()||Ms.length;return Ms[h]=o,Ms[h+1]=1,h}};function Uc(o){return this.fromWireType(u()[o>>>2>>>0])}var tm={name:"emscripten::val",fromWireType:o=>{var h=Gn(o);return Vc(o),h},toWireType:(o,h)=>qn(h),argPackAdvance:Ks,readValueFromPointer:Uc,Db:null};function rm(o){return bs(o>>>0,tm)}var nm=(o,h)=>{switch(h){case 4:return function(y){return this.fromWireType(d()[y>>>2>>>0])};case 8:return function(y){return this.fromWireType(p()[y>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${o}`)}};function sm(o,h,y){y>>>=0,bs(o>>>=0,{name:h=ls(h>>>0),fromWireType:x=>x,toWireType:(x,F)=>F,argPackAdvance:Ks,readValueFromPointer:nm(h,y),Db:null})}function im(o,h,y,x,F){if(o>>>=0,y>>>=0,h=ls(h>>>0),F===-1&&(F=4294967295),F=it=>it,x===0){var le=32-8*y;F=it=>it<>>le}var Ge=h.includes("unsigned")?function(it,At){return At>>>0}:function(it,At){return At};bs(o,{name:h,fromWireType:F,toWireType:Ge,argPackAdvance:Ks,readValueFromPointer:Ah(h,y,x!==0),Db:null})}function am(o,h,y){function x(le){var Ge=u()[le>>>2>>>0];return le=u()[le+4>>>2>>>0],new F(r().buffer,le,Ge)}var F=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];bs(o>>>=0,{name:y=ls(y>>>0),fromWireType:x,argPackAdvance:Ks,readValueFromPointer:x},{Rb:!0})}function om(o,h){o>>>=0;var y=(h=ls(h>>>0))==="std::string";bs(o,{name:h,fromWireType:function(x){var F=u()[x>>>2>>>0],le=x+4;if(y)for(var Ge=le,it=0;it<=F;++it){var At=le+it;if(it==F||n()[At>>>0]==0){if(Ge=gn(Ge,At-Ge),Lt===void 0)var Lt=Ge;else Lt+="\0",Lt+=Ge;Ge=At+1}}else{for(Lt=Array(F),it=0;it>>0]);Lt=Lt.join("")}return ds(x),Lt},toWireType:function(x,F){F instanceof ArrayBuffer&&(F=new Uint8Array(F));var le=typeof F=="string";if(!(le||F instanceof Uint8Array||F instanceof Uint8ClampedArray||F instanceof Int8Array))throw new Hs("Cannot pass non-string to std::string");var Ge=y&&le?Lc(F):F.length,it=cc(4+Ge+1),At=it+4;if(u()[it>>>2>>>0]=Ge,y&&le)Ya(F,At,Ge+1);else if(le)for(le=0;le>>0]=Lt}else for(le=0;le>>0]=F[le];return x!==null&&x.push(ds,it),it},argPackAdvance:Ks,readValueFromPointer:Uc,Db(x){ds(x)}})}var Ih=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,lm=(o,h)=>{for(var y=o>>1,x=y+h/2;!(y>=x)&&a()[y>>>0];)++y;if(32<(y<<=1)-o&&Ih)return Ih.decode(n().slice(o,y));for(y="",x=0;!(x>=h/2);++x){var F=s()[o+2*x>>>1>>>0];if(F==0)break;y+=String.fromCharCode(F)}return y},um=(o,h,y)=>{if(y??(y=2147483647),2>y)return 0;var x=h;y=(y-=2)<2*o.length?y/2:o.length;for(var F=0;F>>1>>>0]=le,h+=2}return s()[h>>>1>>>0]=0,h-x},dm=o=>2*o.length,cm=(o,h)=>{for(var y=0,x="";!(y>=h/4);){var F=i()[o+4*y>>>2>>>0];if(F==0)break;++y,65536<=F?(F-=65536,x+=String.fromCharCode(55296|F>>10,56320|1023&F)):x+=String.fromCharCode(F)}return x},pm=(o,h,y)=>{if(h>>>=0,y??(y=2147483647),4>y)return 0;var x=h;y=x+y-4;for(var F=0;F=le&&(le=65536+((1023&le)<<10)|1023&o.charCodeAt(++F)),i()[h>>>2>>>0]=le,(h+=4)+4>y)break}return i()[h>>>2>>>0]=0,h-x},hm=o=>{for(var h=0,y=0;y=x&&++y,h+=4}return h};function fm(o,h,y){if(o>>>=0,h>>>=0,y=ls(y>>>=0),h===2)var x=lm,F=um,le=dm,Ge=it=>a()[it>>>1>>>0];else h===4&&(x=cm,F=pm,le=hm,Ge=it=>u()[it>>>2>>>0]);bs(o,{name:y,fromWireType:it=>{for(var At,Lt=u()[it>>>2>>>0],Yt=it+4,Pr=0;Pr<=Lt;++Pr){var jr=it+4+Pr*h;Pr!=Lt&&Ge(jr)!=0||(Yt=x(Yt,jr-Yt),At===void 0?At=Yt:(At+="\0",At+=Yt),Yt=jr+h)}return ds(it),At},toWireType:(it,At)=>{if(typeof At!="string")throw new Hs(`Cannot pass non-string to C++ string type ${y}`);var Lt=le(At),Yt=cc(4+Lt+h);return u()[Yt>>>2>>>0]=Lt/h,F(At,Yt+4,Lt+h),it!==null&&it.push(ds,Yt),Yt},argPackAdvance:Ks,readValueFromPointer:Uc,Db(it){ds(it)}})}function mm(o,h){bs(o>>>=0,{Sb:!0,name:h=ls(h>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var _m=()=>1;function gm(o){Yc(o>>>0,!E,1,!T,131072,!1),uh()}var Fh=o=>{if(!Nn)try{if(o(),!(0<_i))try{L?pc(Zt):Bc(Zt)}catch(h){h instanceof Oc||h=="unwind"||Ne(1,h)}}catch(h){h instanceof Oc||h=="unwind"||Ne(1,h)}};function Wc(o){o>>>=0,typeof Atomics.kc=="function"&&(Atomics.kc(i(),o>>>2,o).value.then(nc),o+=128,Atomics.store(i(),o>>>2,1))}var nc=()=>{var o=Ja();o&&(Wc(o),Fh(df))};function wm(o,h){(o>>>=0)==h>>>0?setTimeout(nc):L?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=os[o])&&o.postMessage({cmd:"checkMailbox"})}var Gc=[];function ym(o,h,y,x,F){for(h>>>=0,x/=2,Gc.length=x,y=F>>>0>>>3,F=0;F>>0];return(h?Fc[h]:l_[o])(...Gc)}function bm(o){o>>>=0,L?postMessage({cmd:"cleanupThread",thread:o}):lh(os[o])}function Mm(o){}var qc=(o,h)=>{var y=Nc[o];if(y===void 0)throw o=af(o),y=ls(o),ds(o),new Hs(`${h} has unknown type ${y}`);return y},Oh=(o,h,y)=>{var x=[];return o=o.toWireType(x,y),x.length&&(u()[h>>>2>>>0]=qn(x)),o};function vm(o,h,y){return h>>>=0,y>>>=0,o=Gn(o>>>0),h=qc(h,"emval::as"),Oh(h,y,o)}var sc=o=>{try{o()}catch(h){Qa(h)}},Xs=0,us=null,zh=0,ic=[],Dh={},Bh={},xm=0,Hc=null,Tm=[];function Lh(o){return function(h){if(!Nn){if(Xs===0){var y=!1,x=!1;h((F=0)=>{if(!Nn&&(zh=F,y=!0,x)){Xs=2,sc(()=>mf(us)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),F=!1;try{var le=function(){var At=i()[us+8>>>2>>>0];return At=Kt[Bh[At]],--_i,At()}()}catch(At){le=At,F=!0}var Ge=!1;if(!us){var it=Hc;it&&(Hc=null,(F?it.reject:it.resolve)(le),Ge=!0)}if(F&&!Ge)throw le}}),x=!0,y||(Xs=1,us=function(){var F=cc(65548),le=F+12;u()[F>>>2>>>0]=le,u()[F+4>>>2>>>0]=le+65536,le=ic[0];var Ge=Dh[le];return Ge===void 0&&(Ge=xm++,Dh[le]=Ge,Bh[Ge]=le),le=Ge,i()[F+8>>>2>>>0]=le,F}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),sc(()=>hf(us)))}else Xs===2?(Xs=0,sc(_f),ds(us),us=null,Tm.forEach(Fh)):Qa(`invalid state: ${Xs}`);return zh}}(h=>{o().then(h)})}function Sm(o){return o>>>=0,Lh(()=>(o=Gn(o)).then(qn))}var ac=[];function Cm(o,h,y,x){return y>>>=0,x>>>=0,(o=ac[o>>>0])(null,h=Gn(h>>>0),y,x)}var Em={},oc=o=>{var h=Em[o];return h===void 0?ls(o):h};function $m(o,h,y,x,F){return y>>>=0,x>>>=0,F>>>=0,(o=ac[o>>>0])(h=Gn(h>>>0),h[y=oc(y)],x,F)}var Rh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function km(o){return(o>>>=0)==0?qn(Rh()):(o=oc(o),qn(Rh()[o]))}var Pm=o=>{var h=ac.length;return ac.push(o),h},Am=(o,h)=>{for(var y=Array(o),x=0;x>>2>>>0],"parameter "+x);return y},Nh=(o,h)=>Object.defineProperty(h,"name",{value:o});function Im(o,h,y){var x=(h=Am(o,h>>>0)).shift();o--;var F=`return function (obj, func, destructorsRef, args) { +`,le=0,Ge=[];y===0&&Ge.push("obj");for(var it=["retType"],At=[x],Lt=0;LtYt.name).join(", ")}) => ${x.name}>`,Pm(Nh(y,o))}function Fm(o){return o=oc(o>>>0),qn(l[o])}function Om(o,h){return h>>>=0,o=Gn(o>>>0),h=Gn(h),qn(o[h])}function zm(o){9<(o>>>=0)&&(Ms[o+1]+=1)}function Dm(){return qn([])}function Bm(o){o=Gn(o>>>0);for(var h=Array(o.length),y=0;y>>0))}function Rm(){return qn({})}function Nm(o){for(var h=Gn(o>>>=0);h.length;){var y=h.pop();h.pop()(y)}Vc(o)}function jm(o,h,y){h>>>=0,y>>>=0,o=Gn(o>>>0),h=Gn(h),y=Gn(y),o[h]=y}function Vm(o,h){return h>>>=0,o=(o=qc(o>>>0,"_emval_take_value")).readValueFromPointer(h),qn(o)}function Um(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[h>>>2>>>0]=o.getUTCSeconds(),i()[h+4>>>2>>>0]=o.getUTCMinutes(),i()[h+8>>>2>>>0]=o.getUTCHours(),i()[h+12>>>2>>>0]=o.getUTCDate(),i()[h+16>>>2>>>0]=o.getUTCMonth(),i()[h+20>>>2>>>0]=o.getUTCFullYear()-1900,i()[h+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[h+28>>>2>>>0]=o}var Za=o=>o%4==0&&(o%100!=0||o%400==0),jh=[0,31,60,91,121,152,182,213,244,274,305,335],Vh=[0,31,59,90,120,151,181,212,243,273,304,334];function Wm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[h>>>2>>>0]=o.getSeconds(),i()[h+4>>>2>>>0]=o.getMinutes(),i()[h+8>>>2>>>0]=o.getHours(),i()[h+12>>>2>>>0]=o.getDate(),i()[h+16>>>2>>>0]=o.getMonth(),i()[h+20>>>2>>>0]=o.getFullYear()-1900,i()[h+24>>>2>>>0]=o.getDay();var y=(Za(o.getFullYear())?jh:Vh)[o.getMonth()]+o.getDate()-1|0;i()[h+28>>>2>>>0]=y,i()[h+36>>>2>>>0]=-60*o.getTimezoneOffset(),y=new Date(o.getFullYear(),6,1).getTimezoneOffset();var x=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(y!=x&&o.getTimezoneOffset()==Math.min(x,y)),i()[h+32>>>2>>>0]=o}function Gm(o){o>>>=0;var h=new Date(i()[o+20>>>2>>>0]+1900,i()[o+16>>>2>>>0],i()[o+12>>>2>>>0],i()[o+8>>>2>>>0],i()[o+4>>>2>>>0],i()[o>>>2>>>0],0),y=i()[o+32>>>2>>>0],x=h.getTimezoneOffset(),F=new Date(h.getFullYear(),6,1).getTimezoneOffset(),le=new Date(h.getFullYear(),0,1).getTimezoneOffset(),Ge=Math.min(le,F);return 0>y?i()[o+32>>>2>>>0]=+(F!=le&&Ge==x):0>>2>>>0]=h.getDay(),y=(Za(h.getFullYear())?jh:Vh)[h.getMonth()]+h.getDate()-1|0,i()[o+28>>>2>>>0]=y,i()[o>>>2>>>0]=h.getSeconds(),i()[o+4>>>2>>>0]=h.getMinutes(),i()[o+8>>>2>>>0]=h.getHours(),i()[o+12>>>2>>>0]=h.getDate(),i()[o+16>>>2>>>0]=h.getMonth(),i()[o+20>>>2>>>0]=h.getYear(),o=h.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Uh(o,h,y,x,F,le,Ge){return L?Zr(16,1,o,h,y,x,F,le,Ge):-52}function Wh(o,h,y,x,F,le){if(L)return Zr(17,1,o,h,y,x,F,le)}function qm(o,h,y,x){o>>>=0,h>>>=0,y>>>=0,x>>>=0;var F=new Date().getFullYear(),le=new Date(F,0,1),Ge=new Date(F,6,1);F=le.getTimezoneOffset();var it=Ge.getTimezoneOffset(),At=Math.max(F,it);u()[o>>>2>>>0]=60*At,i()[h>>>2>>>0]=+(F!=it),le=(o=Lt=>Lt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(le),Ge=o(Ge),it{Kc.length=0;for(var y;y=n()[o++>>>0];){var x=y!=105;h+=(x&=y!=112)&&h%8?4:0,Kc.push(y==112?u()[h>>>2>>>0]:y==106?fn[h>>>3]:y==105?i()[h>>>2>>>0]:p()[h>>>3>>>0]),h+=x?8:4}return Kc};function Hm(o,h,y){return o>>>=0,h=Gh(h>>>0,y>>>0),Fc[o](...h)}function Km(o,h,y){return o>>>=0,h=Gh(h>>>0,y>>>0),Fc[o](...h)}var Xm=()=>{},Qm=()=>Date.now();function Ym(o,h){return tr(gn(o>>>0,h>>>0))}var qh,Zm=()=>{throw _i+=1,"unwind"};function Jm(){return 4294901760}qh=()=>performance.timeOrigin+performance.now();var e_=()=>navigator.hardwareConcurrency;function t_(){return Qa("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function r_(o){o>>>=0;var h=n().length;if(o<=h||4294901760=y;y*=2){var x=h*(1+.2/y);x=Math.min(x,o+100663296);var F=Math;x=Math.max(o,x);e:{F=(F.min.call(F,4294901760,x+(65536-x%65536)%65536)-Mr.buffer.byteLength+65535)/65536;try{Mr.grow(F),bn();var le=1;break e}catch{}le=void 0}if(le)return!0}return!1}var lc=()=>(Qa("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),cd={},Hh=o=>{o.forEach(h=>{lc()})};function n_(){var o=Error().stack.toString().split(` +`);return o[0]=="Error"&&o.shift(),Hh(o),cd.Ob=lc(),cd.bc=o,cd.Ob}function s_(o,h,y){if(o>>>=0,h>>>=0,cd.Ob==o)var x=cd.bc;else(x=Error().stack.toString().split(` +`))[0]=="Error"&&x.shift(),Hh(x);for(var F=3;x[F]&&lc()!=o;)++F;for(o=0;o>>2>>>0]=lc();return o}var Xc,Qc={},Kh=()=>{if(!Xc){var o,h={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",_:Re};for(o in Qc)Qc[o]===void 0?delete h[o]:h[o]=Qc[o];var y=[];for(o in h)y.push(`${o}=${h[o]}`);Xc=y}return Xc};function Xh(o,h){if(L)return Zr(18,1,o,h);o>>>=0,h>>>=0;var y=0;return Kh().forEach((x,F)=>{var le=h+y;for(F=u()[o+4*F>>>2>>>0]=le,le=0;le>>0]=x.charCodeAt(le);r()[F>>>0]=0,y+=x.length+1}),0}function Qh(o,h){if(L)return Zr(19,1,o,h);o>>>=0,h>>>=0;var y=Kh();u()[o>>>2>>>0]=y.length;var x=0;return y.forEach(F=>x+=F.length+1),u()[h>>>2>>>0]=x,0}function Yh(o){return L?Zr(20,1,o):52}function Zh(o,h,y,x){return L?Zr(21,1,o,h,y,x):52}function Jh(o,h,y,x){return L?Zr(22,1,o,h,y,x):70}var i_=[null,[],[]];function ef(o,h,y,x){if(L)return Zr(23,1,o,h,y,x);h>>>=0,y>>>=0,x>>>=0;for(var F=0,le=0;le>>2>>>0],it=u()[h+4>>>2>>>0];h+=8;for(var At=0;At>>0],Yt=i_[o];Lt===0||Lt===10?((o===1?fr:tr)(mh(Yt,0)),Yt.length=0):Yt.push(Lt)}F+=it}return u()[x>>>2>>>0]=F,0}var tf=[31,29,31,30,31,30,31,31,30,31,30,31],rf=[31,28,31,30,31,30,31,31,30,31,30,31],a_=(o,h)=>{r().set(o,h>>>0)};function nf(o,h,y,x){function F(Be,vr,Jr){for(Be=typeof Be=="number"?Be.toString():Be||"";Be.lengthwf?-1:0wi-Be.getDate())){Be.setDate(Be.getDate()+vr);break}vr-=wi-Be.getDate()+1,Be.setDate(1),11>Jr?Be.setMonth(Jr+1):(Be.setMonth(0),Be.setFullYear(Be.getFullYear()+1))}return Jr=new Date(Be.getFullYear()+1,0,4),vr=it(new Date(Be.getFullYear(),0,4)),Jr=it(Jr),0>=Ge(vr,Be)?0>=Ge(Jr,Be)?Be.getFullYear()+1:Be.getFullYear():Be.getFullYear()-1}o>>>=0,h>>>=0,y>>>=0,x>>>=0;var Lt=u()[x+40>>>2>>>0];for(var Yt in x={hc:i()[x>>>2>>>0],fc:i()[x+4>>>2>>>0],Gb:i()[x+8>>>2>>>0],Kb:i()[x+12>>>2>>>0],Hb:i()[x+16>>>2>>>0],Cb:i()[x+20>>>2>>>0],ub:i()[x+24>>>2>>>0],Bb:i()[x+28>>>2>>>0],oc:i()[x+32>>>2>>>0],ec:i()[x+36>>>2>>>0],ic:Lt?gn(Lt):""},y=gn(y),Lt={"%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"})y=y.replace(new RegExp(Yt,"g"),Lt[Yt]);var Pr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),jr="January February March April May June July August September October November December".split(" ");for(Yt in Lt={"%a":Be=>Pr[Be.ub].substring(0,3),"%A":Be=>Pr[Be.ub],"%b":Be=>jr[Be.Hb].substring(0,3),"%B":Be=>jr[Be.Hb],"%C":Be=>le((Be.Cb+1900)/100|0,2),"%d":Be=>le(Be.Kb,2),"%e":Be=>F(Be.Kb,2," "),"%g":Be=>At(Be).toString().substring(2),"%G":At,"%H":Be=>le(Be.Gb,2),"%I":Be=>((Be=Be.Gb)==0?Be=12:12{for(var vr=0,Jr=0;Jr<=Be.Hb-1;vr+=(Za(Be.Cb+1900)?tf:rf)[Jr++]);return le(Be.Kb+vr,3)},"%m":Be=>le(Be.Hb+1,2),"%M":Be=>le(Be.fc,2),"%n":()=>` +`,"%p":Be=>0<=Be.Gb&&12>Be.Gb?"AM":"PM","%S":Be=>le(Be.hc,2),"%t":()=>" ","%u":Be=>Be.ub||7,"%U":Be=>le(Math.floor((Be.Bb+7-Be.ub)/7),2),"%V":Be=>{var vr=Math.floor((Be.Bb+7-(Be.ub+6)%7)/7);if(2>=(Be.ub+371-Be.Bb-2)%7&&vr++,vr)vr==53&&((Jr=(Be.ub+371-Be.Bb)%7)==4||Jr==3&&Za(Be.Cb)||(vr=1));else{vr=52;var Jr=(Be.ub+7-Be.Bb-1)%7;(Jr==4||Jr==5&&Za(Be.Cb%400-1))&&vr++}return le(vr,2)},"%w":Be=>Be.ub,"%W":Be=>le(Math.floor((Be.Bb+7-(Be.ub+6)%7)/7),2),"%y":Be=>(Be.Cb+1900).toString().substring(2),"%Y":Be=>Be.Cb+1900,"%z":Be=>{var vr=0<=(Be=Be.ec);return Be=Math.abs(Be)/60,(vr?"+":"-")+("0000"+(Be/60*100+Be%60)).slice(-4)},"%Z":Be=>Be.ic,"%%":()=>"%"},y=y.replace(/%%/g,"\0\0"),Lt)y.includes(Yt)&&(y=y.replace(new RegExp(Yt,"g"),Lt[Yt](x)));return Yt=function(Be){var vr=Array(Lc(Be)+1);return wh(Be,vr,0,vr.length),vr}(y=y.replace(/\0\0/g,"%")),Yt.length>h?0:(a_(Yt,o),Yt.length-1)}function o_(o,h,y,x){return nf(o>>>0,h>>>0,y>>>0,x>>>0)}L||function(){for(var o=l.numThreads-1;o--;)ch();dd.unshift(()=>{Wn++,function(h){L?h():Promise.all(qs.map(dh)).then(h)}(()=>tc())})}();for(var sf=Array(256),uc=0;256>uc;++uc)sf[uc]=String.fromCharCode(uc);Ph=sf,Hs=l.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},l.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},Ms.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>Ms.length/2-5-jc.length;var l_=[Dc,ah,ph,_h,gh,yh,bh,Mh,vh,xh,Th,Sh,Ch,Eh,$h,kh,Uh,Wh,Xh,Qh,Yh,Zh,Jh,ef],Kt=function(){function o(y,x){return Kt=y.exports,Kt=function(){var F=Kt,le={};for(let[Ge,it]of Object.entries(F))le[Ge]=typeof it=="function"?(...At)=>{ic.push(Ge);try{return it(...At)}finally{Nn||(ic.pop(),us&&Xs===1&&ic.length===0&&(Xs=0,_i+=1,sc(ff),typeof Fibers<"u"&&Fibers.pc()))}}:it;return le}(),Kt=function(){var F=Kt,le=it=>At=>it(At)>>>0,Ge=it=>()=>it()>>>0;return(F=Object.assign({},F)).Ca=le(F.Ca),F.fb=Ge(F.fb),F.gb=le(F.gb),F.emscripten_main_runtime_thread_id=Ge(F.emscripten_main_runtime_thread_id),F.sb=le(F.sb),F.tb=Ge(F.tb),F}(),oh.push(Kt.ib),Mn.unshift(Kt.Ba),Wr=x,tc(),Kt}var h=sh();if(Wn++,l.instantiateWasm)try{return l.instantiateWasm(h,o)}catch(y){tr(`Module.instantiateWasm callback failed with error: ${y}`),g(y)}return Ic||(Ic=l.locateFile?eh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",_t):_t+"ort-wasm-simd-threaded.jsep.wasm":new URL(N("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),N.b).href),function(y,x){var F=Ic;return Dt||typeof WebAssembly.instantiateStreaming!="function"||eh(F)||th(F)||typeof fetch!="function"?nh(F,y,x):fetch(F,{credentials:"same-origin"}).then(le=>WebAssembly.instantiateStreaming(le,y).then(x,function(Ge){return tr(`wasm streaming compile failed: ${Ge}`),tr("falling back to ArrayBuffer instantiation"),nh(F,y,x)}))}(h,function(y){o(y.instance,y.module)}).catch(g),{}}(),af=o=>(af=Kt.Ca)(o),of=()=>(of=Kt.Da)();l._OrtInit=(o,h)=>(l._OrtInit=Kt.Ea)(o,h),l._OrtGetLastError=(o,h)=>(l._OrtGetLastError=Kt.Fa)(o,h),l._OrtCreateSessionOptions=(o,h,y,x,F,le,Ge,it,At,Lt)=>(l._OrtCreateSessionOptions=Kt.Ga)(o,h,y,x,F,le,Ge,it,At,Lt),l._OrtAppendExecutionProvider=(o,h)=>(l._OrtAppendExecutionProvider=Kt.Ha)(o,h),l._OrtAddFreeDimensionOverride=(o,h,y)=>(l._OrtAddFreeDimensionOverride=Kt.Ia)(o,h,y),l._OrtAddSessionConfigEntry=(o,h,y)=>(l._OrtAddSessionConfigEntry=Kt.Ja)(o,h,y),l._OrtReleaseSessionOptions=o=>(l._OrtReleaseSessionOptions=Kt.Ka)(o),l._OrtCreateSession=(o,h,y)=>(l._OrtCreateSession=Kt.La)(o,h,y),l._OrtReleaseSession=o=>(l._OrtReleaseSession=Kt.Ma)(o),l._OrtGetInputOutputCount=(o,h,y)=>(l._OrtGetInputOutputCount=Kt.Na)(o,h,y),l._OrtGetInputName=(o,h)=>(l._OrtGetInputName=Kt.Oa)(o,h),l._OrtGetOutputName=(o,h)=>(l._OrtGetOutputName=Kt.Pa)(o,h),l._OrtFree=o=>(l._OrtFree=Kt.Qa)(o),l._OrtCreateTensor=(o,h,y,x,F,le)=>(l._OrtCreateTensor=Kt.Ra)(o,h,y,x,F,le),l._OrtGetTensorData=(o,h,y,x,F)=>(l._OrtGetTensorData=Kt.Sa)(o,h,y,x,F),l._OrtReleaseTensor=o=>(l._OrtReleaseTensor=Kt.Ta)(o),l._OrtCreateRunOptions=(o,h,y,x)=>(l._OrtCreateRunOptions=Kt.Ua)(o,h,y,x),l._OrtAddRunConfigEntry=(o,h,y)=>(l._OrtAddRunConfigEntry=Kt.Va)(o,h,y),l._OrtReleaseRunOptions=o=>(l._OrtReleaseRunOptions=Kt.Wa)(o),l._OrtCreateBinding=o=>(l._OrtCreateBinding=Kt.Xa)(o),l._OrtBindInput=(o,h,y)=>(l._OrtBindInput=Kt.Ya)(o,h,y),l._OrtBindOutput=(o,h,y,x)=>(l._OrtBindOutput=Kt.Za)(o,h,y,x),l._OrtClearBoundOutputs=o=>(l._OrtClearBoundOutputs=Kt._a)(o),l._OrtReleaseBinding=o=>(l._OrtReleaseBinding=Kt.$a)(o),l._OrtRunWithBinding=(o,h,y,x,F)=>(l._OrtRunWithBinding=Kt.ab)(o,h,y,x,F),l._OrtRun=(o,h,y,x,F,le,Ge,it)=>(l._OrtRun=Kt.bb)(o,h,y,x,F,le,Ge,it),l._OrtEndProfiling=o=>(l._OrtEndProfiling=Kt.cb)(o),l._JsepOutput=(o,h,y)=>(l._JsepOutput=Kt.db)(o,h,y),l._JsepGetNodeName=o=>(l._JsepGetNodeName=Kt.eb)(o);var dc,Ja=()=>(Ja=Kt.fb)(),cc=l._malloc=o=>(cc=l._malloc=Kt.gb)(o),ds=l._free=o=>(ds=l._free=Kt.hb)(o),Yc=(o,h,y,x,F,le)=>(Yc=Kt.kb)(o,h,y,x,F,le),lf=()=>(lf=Kt.lb)(),uf=(o,h,y,x,F)=>(uf=Kt.mb)(o,h,y,x,F),Zc=o=>(Zc=Kt.nb)(o),pc=o=>(pc=Kt.ob)(o),df=()=>(df=Kt.pb)(),cf=(o,h)=>(cf=Kt.qb)(o,h),hc=o=>(hc=Kt.rb)(o),Jc=o=>(Jc=Kt.sb)(o),ep=()=>(ep=Kt.tb)(),pf=l.dynCall_ii=(o,h)=>(pf=l.dynCall_ii=Kt.vb)(o,h),hf=o=>(hf=Kt.wb)(o),ff=()=>(ff=Kt.xb)(),mf=o=>(mf=Kt.yb)(o),_f=()=>(_f=Kt.zb)();function gf(){0ep(),l.stackRestore=o=>hc(o),l.stackAlloc=o=>Jc(o),l.UTF8ToString=gn,l.stringToUTF8=Ya,l.lengthBytesUTF8=Lc,Gs=function o(){dc||gf(),dc||(Gs=o)},gf(),M}),Pe=_e,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&_e()}),we,Je,gt,ft,St,mt,Ft,Nt,Rt=j(()=>{var e,t;Ot(),we=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),Je=typeof location>"u"?void 0:location.origin,gt=(r,n)=>{try{let s=n??we;return(s?new URL(r,s):new URL(r)).origin===Je}catch{return!1}},ft=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},St=(Kr(),A(cr)).default,mt=async()=>{if(!we)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(gt(we))return[void 0,St()];let r=await ft(we);return[r,St(r)]},Ft=(rt(),A(at)).default,Nt=async(r,n,s)=>[void 0,Ft]}),Gt,Me,et,ot,Ht,gr,Lr,mr,yr=j(()=>{Rt(),Me=!1,et=!1,ot=!1,Ht=()=>{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}},gr=()=>{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}},Lr=async e=>{if(Me)return Promise.resolve();if(et)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ot)throw new Error("previous call to 'initializeWebAssembly()' failed.");et=!0;let t=e.initTimeout,r=e.numThreads;if(!gr())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Ht();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,i=s==null?void 0:s.mjs,u=(i==null?void 0:i.href)??i,d=s==null?void 0:s.wasm,p=(d==null?void 0:d.href)??d,w=e.wasmBinary,[g,l]=await Nt(u,a,r>1),M=!1,T=[];if(t>0&&T.push(new Promise(E=>{setTimeout(()=>{M=!0,E()},t)})),T.push(new Promise((E,L)=>{let G={numThreads:r};w?G.wasmBinary=w:(p||a)&&(G.locateFile=(z,ae)=>p??(a??ae)+z),l(G).then(z=>{et=!1,Me=!0,Gt=z,E(),g&&URL.revokeObjectURL(g)},z=>{et=!1,ot=!0,L(z)})})),await Promise.race(T),M)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},mr=()=>{if(Me&&Gt)return Gt;throw new Error("WebAssembly is not initialized yet.")}}),Tr,En,Rr,Hn=j(()=>{yr(),Tr=(e,t)=>{let r=mr(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},En=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let i=t?t+s:s;if(typeof a=="object")En(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Rr=e=>{let t=mr(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let s=t.HEAP32[n/4],a=t.HEAPU32[n/4+1],i=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),jn,Ys=j(()=>{yr(),Hn(),jn=e=>{let t=mr(),r=0,n=[],s=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)s.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)s.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&&(s.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Tr(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Rr("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&En(e.extra,"",new WeakSet,(i,u)=>{let d=Tr(i,n),p=Tr(u,n);t._OrtAddRunConfigEntry(r,d,p)!==0&&Rr(`Can't set a run config entry: ${i} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),vs,xs,Ts,Ss,Kn,Zs=j(()=>{yr(),Hn(),vs=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}`)}},xs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ts=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)},Ss=(e,t,r)=>{for(let n of t){let s=typeof n=="string"?n:n.name;switch(s){case"webnn":if(s="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let u=Tr("deviceType",r),d=Tr(i,r);mr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Rr(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(s="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let u=Tr("preferredLayout",r),d=Tr(i.preferredLayout,r);mr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Rr(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Tr(s,r);mr()._OrtAppendExecutionProvider(e,a)!==0&&Rr(`Can't append execution provider: ${s}.`)}},Kn=e=>{let t=mr(),r=0,n=[],s=e||{};Ts(s);try{let a=vs(s.graphOptimizationLevel??"all"),i=xs(s.executionMode??"sequential"),u=typeof s.logId=="string"?Tr(s.logId,n):0,d=s.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let p=s.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let w=typeof s.optimizedModelFilePath=="string"?Tr(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,u,d,p,w),r===0&&Rr("Can't create session options."),s.executionProviders&&Ss(r,s.executionProviders,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);let g=Tr("enableGraphCapture",n),l=Tr(s.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,g,l)!==0&&Rr(`Can't set a session config entry: 'enableGraphCapture' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[g,l]of Object.entries(s.freeDimensionOverrides)){if(typeof g!="string")throw new Error(`free dimension override name must be a string: ${g}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let M=Tr(g,n);t._OrtAddFreeDimensionOverride(r,M,l)!==0&&Rr(`Can't set a free dimension override: ${g} - ${l}.`)}return s.extra!==void 0&&En(s.extra,"",new WeakSet,(g,l)=>{let M=Tr(g,n),T=Tr(l,n);t._OrtAddSessionConfigEntry(r,M,T)!==0&&Rr(`Can't set a session config entry: ${g} - ${l}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(i=>t._free(i)),a}}}),cs,Bn,Xn,Vn,ts,ps,hs,Xt=j(()=>{cs=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}`)}},Bn=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}`)}},Xn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},Vn=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}`)}},ts=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}`)}},ps=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",hs=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}}),rs,Cs=j(()=>{Ot(),rs=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let d=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let i=0;for(;;){let{done:u,value:d}=await s.read();if(u)break;let p=d.byteLength;new Uint8Array(a,i,p).set(d),i+=p}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Es,fs,$s,ks,ms,Ps,Gr,vn=j(()=>{Xt(),Es=["V","I","W","E","F"],fs=(e,t)=>{console.log(`[${Es[e]},${new Date().toISOString()}]${t}`)},ms=(e,t)=>{$s=e,ks=t},Ps=(e,t)=>{let r=ts(e),n=ts($s);r>=n&&fs(r,typeof t=="function"?t():t)},Gr=(...e)=>{ks&&Ps(...e)}}),be,_=j(()=>{Xt(),be=(e,t)=>new(Vn(t))(e)}),P=j(()=>{}),K,ie,pe,De,wt,xt,Mt,zt,er,zr=j(()=>{vn(),P(),K=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]]),ie=[],pe=e=>Math.ceil(e/16)*16,De=e=>{for(let t=0;twt++,Mt=async(e,t,r,n)=>{let s=pe(r),a=e.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,s),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(u,0,r)),d}else return new Uint8Array(u.slice(0,r))}finally{a.destroy()}},zt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[t]of K)ie.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,s=t.byteLength,a=pe(s),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${s}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(r,n,s)),u.unmap();let p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(u,0,i.gpuData.buffer,0,a),Gr("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 n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=pe(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(e,t,r){let n;if(r){if(n=this.externalBuffers.get(r),n===void 0)throw new Error("previous buffer is not registered");if(e===r)return Gr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`);this.externalBuffers.delete(r)}else n=xt();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,n),Gr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(e),Gr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=De(e),n,s=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||a){let u=(s?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let i={id:xt(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:e}),Gr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return Gr("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 Mt(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=K.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))}},er=(...e)=>new zt(...e)}),ir,qt,pr=j(()=>{ir=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 ir(e)}),mn,ln,Oe,$n,Sr,sn,xn,Qt=j(()=>{mn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},ln=class{static calcShape(e,t,r=!1){let n=e.length,s=t.length;if(n===0)return t;if(s===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(r){if(n<2||s<2)return;let u=mn.calcMatMulShape([e[n-2],e[n-1]],[t[s-2],t[s-1]]);if(u===void 0)return;[i[a-2],i[a-1]]=u}for(let u=r?3:1;u<=a;u++){let d=n-u<0?1:e[n-u],p=s-u<0?1:t[s-u];if(d!==p&&d>1&&p>1)return;let w=Math.max(d,p);if(d&&p)i[a-u]=Math.max(d,p);else{if(w>1)return;i[a-u]=0}}return i}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let s=1;s<=r;s++)if(e[r-s]!==1&&e[r-s]!==t[n-s])return!1;return!0}},Oe=class fc{static size(t){return fc.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let s=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){s[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");s[a]=1,r/=t[a],a--}for(a--;a>=0;a--)s[a]=t[a];return s}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 fc.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 fc.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let s=1;for(let a=r;a=0;--s)n[s]=n[s+1]*t[s+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((s,a)=>s+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,s)=>n===r[s])}},$n=class pd{static adjustPoolAttributes(t,r,n,s,a,i){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||i[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,s,a,i,u){if(u){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{Xt(),Qt(),Tn=64,pn=(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}`)}},Ar=(e,t=1)=>{let r=pn(e,t);return typeof r=="string"?r:r[0]},Cr=(e,t=1)=>{let r=pn(e,t);return typeof r=="string"?r:r[1]},It=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:Oe.computeStrides(r)})}),t},br=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})`,Xr=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Sn=(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,jt=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Js=(e,t,r,n,s)=>{let a=typeof r=="number",i=a?r:r.length,u=[...new Array(i).keys()],d=i<2?"u32":i<=4?`vec${i}`:`array`,p=pn(t,s),w=typeof p=="string"?p:p[1],g=typeof p=="string"?p:p[0],l={indices:d,value:w,storage:g,tensor:t},M=Ue=>typeof Ue=="string"?Ue:`${Ue}u`,T={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},E=a?"uniforms.":"",L=`${E}${e}_shape`,G=`${E}${e}_strides`,z="";for(let Ue=0;Ue ${l.indices} { + var indices: ${l.indices}; + var current = offset; + ${z} + return indices; + }`,Q=Ue=>(T.offsetToIndices=!0,i<2?Ue:`o2i_${e}(${Ue})`),oe=[];if(i>=2)for(let Ue=i-1;Ue>=0;Ue--)oe.push(`${jt(G,Ue,i)} * (indices[${Ue}])`);let Re=i<2?"":` + fn i2o_${e}(indices: ${l.indices}) -> u32 { + return ${oe.join("+")}; + }`,Ne=Ue=>(T.indicesToOffset=!0,i<2?Ue:`i2o_${e}(${Ue})`),_t=(...Ue)=>i===0?"0u":`${l.indices}(${Ue.map(M).join(",")})`,Dt=(Ue,$t)=>i<2?`${Ue}`:`${jt(Ue,$t,i)}`,Vt=(Ue,$t,rr)=>i<2?`${Ue}=${rr};`:`${jt(Ue,$t,i)}=${rr};`,lr={},fr=(Ue,$t)=>{T.broadcastedIndicesToOffset=!0;let rr=`${$t.name}broadcastedIndicesTo${e}Offset`;if(rr in lr)return`${rr}(${Ue})`;let Ur=[];for(let nn=i-1;nn>=0;nn--){let fn=$t.indicesGet("outputIndices",nn+$t.rank-i);Ur.push(`${Dt(G,nn)} * (${fn} % ${Dt(L,nn)})`)}return lr[rr]=`fn ${rr}(outputIndices: ${$t.type.indices}) -> u32 { + return ${Ur.length>0?Ur.join("+"):"0u"}; + }`,`${rr}(${Ue})`},tr=(Ue,$t)=>(()=>{if(l.storage===l.value)return`${e}[${Ue}]=${$t};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${Ue}]=vec2(u32(${$t}), select(0u, 0xFFFFFFFFu, ${$t} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${Ue}]=vec2(u32(${$t}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${Ue}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${$t}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Vr=Ue=>(()=>{if(l.storage===l.value)return`${e}[${Ue}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${Ue}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${Ue}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${Ue}] & 0xFFu), bool(${e}[${Ue}] & 0xFF00u), bool(${e}[${Ue}] & 0xFF0000u), bool(${e}[${Ue}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Qr=i<2?"":` + fn get_${e}ByIndices(indices: ${l.indices}) -> ${w} { + return ${Vr(`i2o_${e}(indices)`)}; + }`,Mr=i<2?"":(()=>{let Ue=u.map(rr=>`d${rr}: u32`).join(", "),$t=u.map(rr=>`d${rr}`).join(", ");return` + fn get_${e}(${Ue}) -> ${w} { + return get_${e}ByIndices(${_t($t)}); + }`})(),Wr=(...Ue)=>{if(Ue.length!==i)throw new Error(`indices length must be ${i}`);let $t=Ue.map(M).join(",");return i===0?Vr("0u"):i===1?Vr($t[0]):(T.get=!0,T.getByIndices=!0,T.indicesToOffset=!0,`get_${e}(${$t})`)},Zt=Ue=>i<2?Vr(Ue):(T.getByIndices=!0,T.indicesToOffset=!0,`get_${e}ByIndices(${Ue})`),dr=i<2?"":` + fn set_${e}ByIndices(indices: ${l.indices}, value: ${w}) { + ${tr(`i2o_${e}(indices)`,"value")} + }`,Or=i<2?"":(()=>{let Ue=u.map(rr=>`d${rr}: u32`).join(", "),$t=u.map(rr=>`d${rr}`).join(", ");return` + fn set_${e}(${Ue}, value: ${w}) { + set_${e}ByIndices(${_t($t)}, value); + }`})();return{impl:()=>{let Ue=[],$t=!1;return T.offsetToIndices&&(Ue.push(ae),$t=!0),T.indicesToOffset&&(Ue.push(Re),$t=!0),T.broadcastedIndicesToOffset&&(Object.values(lr).forEach(rr=>Ue.push(rr)),$t=!0),T.set&&(Ue.push(Or),$t=!0),T.setByIndices&&(Ue.push(dr),$t=!0),T.get&&(Ue.push(Mr),$t=!0),T.getByIndices&&(Ue.push(Qr),$t=!0),!a&&$t&&Ue.unshift(`const ${L} = ${l.indices}(${r.join(",")});`,`const ${G} = ${l.indices}(${Oe.computeStrides(r).join(",")});`),Ue.join(` +`)},type:l,offsetToIndices:Q,indicesToOffset:Ne,broadcastedIndicesToOffset:fr,indices:_t,indicesGet:Dt,indicesSet:Vt,set:(...Ue)=>{if(Ue.length!==i+1)throw new Error(`indices length must be ${i}`);let $t=Ue[i];if(typeof $t!="string")throw new Error("value must be string");let rr=Ue.slice(0,i).map(M).join(",");return i===0?tr("0u",$t):i===1?tr(rr[0],$t):(T.set=!0,T.setByIndices=!0,T.indicesToOffset=!0,`set_${e}(${rr}, ${$t})`)},setByOffset:tr,setByIndices:(Ue,$t)=>i<2?tr(Ue,$t):(T.setByIndices=!0,T.indicesToOffset=!0,`set_${e}ByIndices(${Ue}, ${$t});`),get:Wr,getByOffset:Vr,getByIndices:Zt,usage:n,name:e,strides:G,shape:L,rank:i}},Ze=(e,t,r,n=1)=>Js(e,t,r,"input",n),Wt=(e,t,r,n=1)=>Js(e,t,r,"output",n),bi=(e,t,r,n=1)=>Js(e,t,r,"internal",n),Mi=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=Tn){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=s?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=s?`let global_idx = global_id.x; + let local_idx = local_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) + fn main(${a}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",n=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${s}`)}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])}},to=(e,t)=>new Mi(e,t),_s=(e,t)=>{let r=e.length,n=[];for(let s=0;s1&&i===1&&n.unshift(a)}return n}}),ro,vi,ns,no,fd,Ln,md,so,ss=j(()=>{Xt(),Qt(),pr(),ar(),ro=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},vi=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,ns=(e,t)=>Oe.sortBasedOnPerm(e,vi(e.length,t)),no=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let a=0;a{let r=[],n=[];for(let s=0;s{let r=e.dataType,n=e.dims.length,s=vi(n,t),a=ns(e.dims,s),{newShape:i,newPerm:u}=fd(e.dims,s),d=Oe.areEqual(u,[2,3,1]),p=Oe.areEqual(u,[3,1,2]),w=i.length===2&&u[0]>u[1]||d||p,g=w?i:e.dims,l=a;w&&(g=d?[i[0],i[1]*i[2]]:p?[i[0]*i[1],i[2]]:i,l=[g[1],g[0]]);let M=Ze("a",r,g.length),T=Wt("output",r,l.length),E=16,L;return w?L=G=>` + ${G.registerUniform("output_size","u32").declareVariables(M,T)} + var tile : array, ${E}>; + ${G.mainStart([E,E,1])} + let stride = (uniforms.output_shape[1] - 1) / ${E} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${E}u + local_id.x; + let input_row = workgroup_id_x * ${E}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${M.getByIndices(`${M.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${E}u + local_id.x; + let output_row = workgroup_id_y * ${E}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${T.setByIndices(`${T.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`:L=G=>` + ${G.registerUniform("output_size","u32").declareVariables(M,T)} + + ${no(s,n,M,T)} + + ${G.mainStart()} + ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${T.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${T.setByOffset("global_idx",M.getByIndices("aIndices"))} + }`,{name:w?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let G=Oe.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:w?{x:Math.ceil(l[1]/E),y:Math.ceil(l[0]/E)}:{x:Math.ceil(G/64)},programUniforms:[{type:12,data:G},...It(g,l)]}},getShaderSource:L}},md=(e,t)=>{ro(e.inputs),e.compute(Ln(e.inputs[0],t.perm))},so=e=>qt({perm:e.perm})}),io,ao,oo,lo,uo,xi,co,po,Ti,ho,In,Si,fo,mo,Ci,_o,go,Ei,wo,yo,$i,_d=j(()=>{Xt(),Qt(),ar(),Li(),ss(),io={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"},ao={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},oo={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},lo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},uo=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,s]},co=(e,t)=>{let r=e.length+t.length,n=[],s=0;for(let a=0;a{for(let r=0;r{let r=[];if(!po(e,t)){for(let n=0;nr.push(n))}return r},ho=(e,t,r,n,s,a,i)=>{let u=r[0].dims,d=Oe.size(a),p=Oe.size(i),w=Ze("_A",r[0].dataType,u),g=Wt("output",s,a),l=32,M=` + var aBestValues : array; + `;return{name:e,shaderCache:t,getShaderSource:T=>` + ${T.registerUniform("reduceSize","u32").declareVariables(w,g)} + ${M} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${T.mainStart(l)} + + let outputIndex = global_idx / ${l}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${oo[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${l}) { + let candidate = f32(${w.getByOffset("offset + k")}); + bestValue = ${io[n]}; + } + 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 = ${ao[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${g.setByOffset("outputIndex",`${n==="mean"?`${g.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${g.type.storage}(${lo[n]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:d},programUniforms:[{type:12,data:p}]})}},In=(e,t,r,n)=>{let s=e.inputs.length===1?r:Pi(e.inputs,r),a=s.axes;a.length===0&&!s.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((M,T)=>T));let i=Oe.normalizeAxes(a,e.inputs[0].dims.length),u=i,d=e.inputs[0],p=Ti(u,e.inputs[0].dims.length);p.length>0&&(d=e.compute(Ln(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],u=uo(u.length,d.dims.length));let[w,g]=xi(d.dims,u),l=w;s.keepDims&&(l=co(w,i)),e.compute(ho(t,{hint:s.cacheKey,inputDependencies:["type"]},[d],n,e.inputs[0].dataType,l,g),{inputs:[d]})},Si=(e,t)=>{In(e,"ReduceMeanShared",t,"mean")},fo=(e,t)=>{In(e,"ReduceL1Shared",t,"l1")},mo=(e,t)=>{In(e,"ReduceL2Shared",t,"l2")},Ci=(e,t)=>{In(e,"ReduceLogSumExpShared",t,"logSumExp")},_o=(e,t)=>{In(e,"ReduceMaxShared",t,"max")},go=(e,t)=>{In(e,"ReduceMinShared",t,"min")},Ei=(e,t)=>{In(e,"ReduceProdShared",t,"prod")},wo=(e,t)=>{In(e,"ReduceSumShared",t,"sum")},yo=(e,t)=>{In(e,"ReduceSumSquareShared",t,"sumSquare")},$i=(e,t)=>{In(e,"ReduceLogSumShared",t,"logSum")}}),Fn,ki,ei,Pi,kn,bo,Mo,Ai,vo,xo,Ii,To,So,Fi,Co,On,Oi,Eo,$o,zi,ko,Po,Di,Ao,Io,Bi,Li=j(()=>{Xt(),Qt(),pr(),ar(),_d(),Fn=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.")},ki=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ei=(e,t,r,n,s,a,i=!1,u=!1)=>{let d=[],p=r[0].dims,w=p.length,g=Oe.normalizeAxes(s,w),l=!u&&g.length===0;p.forEach((E,L)=>{l||g.indexOf(L)>=0?i&&d.push(1):d.push(E)});let M=d.length,T=Oe.size(d);return{name:e,shaderCache:t,getShaderSource:E=>{let L=[],G=Ze("_A",r[0].dataType,w),z=Wt("output",a,M),ae=n(G,z,g),Q=ae[2];for(let oe=0,Re=0;oe=0?(i&&Re++,Q=`for(var j${oe}: u32 = 0; j${oe} < ${p[oe]}; j${oe}++) { + ${ae[2].includes("last_index")?`let last_index = j${oe};`:""} + ${G.indicesSet("input_indices",oe,`j${oe}`)} + ${Q} + }`):(L.push(`${G.indicesSet("input_indices",oe,z.indicesGet("output_indices",Re))};`),Re++);return` + + ${E.registerUniform("output_size","u32").declareVariables(G,z)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${G.type.indices}; + let output_indices = ${z.offsetToIndices("global_idx")}; + + ${L.join(` +`)} + ${ae[0]} // init ops for reduce max/min + ${ae[1]} + ${Q} + ${ae[3]} + ${ae.length===4?z.setByOffset("global_idx","value"):ae.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:d,dataType:a}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:[{type:12,data:T},...It(p,d)]})}},Pi=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),qt({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},kn=(e,t,r,n)=>{let s=e.inputs,a=s.length===1?r:Pi(s,r);e.compute(ei(t,{hint:a.cacheKey,inputDependencies:["rank"]},[s[0]],a.noopWithEmptyAxes&&a.axes.length===0?ki:n,a.axes,s[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},bo=(e,t)=>{Fn(e.inputs),kn(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Mo=(e,t)=>{Fn(e.inputs),kn(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Ai=(e,t)=>{Fn(e.inputs),kn(e,"ReduceL2",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},vo=(e,t)=>{Fn(e.inputs),kn(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},xo=(e,t)=>{Fn(e.inputs),kn(e,"ReduceMax",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(r.indicesSet("input_indices",i,0));return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},Ii=(e,t)=>{Fn(e.inputs),kn(e,"ReduceMean",t,(r,n,s)=>{let a=1;for(let i=0;i=0||s.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},To=(e,t)=>{Fn(e.inputs),kn(e,"ReduceMin",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},So=(e,t)=>{Fn(e.inputs),kn(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Fi=(e,t)=>{Fn(e.inputs),kn(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Co=(e,t)=>{Fn(e.inputs),kn(e,"ReduceSumSquare",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},On=(e,t,r)=>{if(t.length===0)return r;let n=1,s=1;for(let a=0;a1024},Oi=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ii(e,t):Si(e,t)},Eo=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Mo(e,t):fo(e,t)},$o=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ai(e,t):mo(e,t)},zi=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vo(e,t):Ci(e,t)},ko=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xo(e,t):_o(e,t)},Po=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?To(e,t):go(e,t)},Di=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?So(e,t):Ei(e,t)},Ao=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fi(e,t):wo(e,t)},Io=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Co(e,t):yo(e,t)},Bi=(e,t)=>{On(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bo(e,t):$i(e,t)}}),Ri,Ni,Fo,ji,Oo=j(()=>{Xt(),pr(),Li(),Ri=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.")},Ni=(e,t)=>{Ri(e.inputs);let r=(n,s,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",s.setByOffset("global_idx","best_index")]};e.compute(ei("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Fo=(e,t)=>{Ri(e.inputs);let r=(n,s,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",s.setByOffset("global_idx","best_index")]};e.compute(ei("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ji=e=>qt(e)}),zo,Do,Vi,Bo,As,Ui,Lo,Wi=j(()=>{Xt(),Qt(),P(),ar(),zo=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4],u=e[5];if(i&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],p=r.dims[1],w=r.dims[2];if(s.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==w)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(s.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let g=s.dims[0]/3,l=g,M=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ae of t.qkvHiddenSizes)if(ae%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");g=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],M=t.qkvHiddenSizes[2]}let T=p;if(g!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==g+l+M)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let E=0;if(i){if(l!==M)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(E=i.dims[3])}let L=T+E,G=-1,z=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==t.numHeads||u.dims[2]!==p||u.dims[3]!==L)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:p,pastSequenceLength:E,kvSequenceLength:T,totalSequenceLength:L,maxSequenceLength:G,inputHiddenSize:w,hiddenSize:g,vHiddenSize:M,headSize:Math.floor(g/t.numHeads),vHeadSize:Math.floor(M/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:z,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Do=(e,t,r)=>{let n=br(r),s=64,a=r/n;a{let M=Wt("x",e.dataType,e.dims,n),T=Cr(e.dataType),E=[{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(E).declareVariables(M)} + ${l.mainStart([s,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${s}) * uniforms.d_comp + local_offset; + + var thread_max_vector = ${p}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${p}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(n){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: ${n}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${s}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${p}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${p}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(n){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: ${n}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${s}; 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] = ${M.type.value}(${T}(uniforms.d_inv)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${p}(x[offset + i]); + x[offset + i] = ${M.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${d};${n}`,inputDependencies:w},getShaderSource:g,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:u})}},Vi=(e,t,r,n,s,a,i,u)=>{let d=u+a.kvSequenceLength,p=[a.batchSize,a.numHeads,a.sequenceLength,d],w=a.kvNumHeads===void 0&&e>1&&n,g=w?[a.batchSize,a.numHeads,d,a.headSize]:void 0,l=i.scale===0?1/Math.sqrt(a.headSize):i.scale,M=br(a.headSize),T=a.headSize/M,E=12,L={x:Math.ceil(d/E),y:Math.ceil(a.sequenceLength/E),z:a.batchSize*a.numHeads},G=[{type:12,data:a.sequenceLength},{type:12,data:T},{type:12,data:d},{type:12,data:a.numHeads},{type:1,data:l},{type:12,data:u},{type:12,data:a.kvSequenceLength}],z=w&&n&&Oe.size(n.dims)>0,ae=["type","type"];z&&ae.push("type"),s&&ae.push("type");let Q=[{dims:p,dataType:t.dataType,gpuDataType:0}];w&&Q.push({dims:g,dataType:t.dataType,gpuDataType:0});let oe=Re=>{let Ne=Ze("q",t.dataType,t.dims,M),_t=Ze("key",r.dataType,r.dims,M),Dt=[Ne,_t];if(z){let Vr=Ze("past_key",n.dataType,n.dims,M);Dt.push(Vr)}s&&Dt.push(Ze("attention_bias",s.dataType,s.dims));let Vt=Wt("output",t.dataType,p),lr=[Vt];w&&lr.push(Wt("present_key",t.dataType,g,M));let fr=Cr(1,M),tr=[{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 = ${E}u; + + var tileQ: array<${Ne.type.storage}, ${E*E}>; + var tileK: array<${Ne.type.storage}, ${E*E}>; + ${Re.registerUniforms(tr).declareVariables(...Dt,...lr)} + ${Re.mainStart([E,E,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; + ${z&&w?` + 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;`} + ${w?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${fr}(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; + ${z&&w?` + 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];"} + ${w?"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 += ${fr}(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(M){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: ${M}`)}})()}; + output[outputIdx] = ${Vt.type.value} (sum * uniforms.alpha) + ${s?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${s!==void 0};${n!==void 0};${e}`,inputDependencies:ae},getRunData:()=>({outputs:Q,dispatchGroup:L,programUniforms:G}),getShaderSource:oe}},Bo=(e,t,r,n,s,a)=>{let i=a+s.kvSequenceLength,u=s.nReps?s.nReps:1,d=s.vHiddenSize*u,p=s.kvNumHeads==null&&e>1&&n,w=p?[s.batchSize,s.numHeads,i,s.headSize]:void 0,g=[s.batchSize,s.sequenceLength,d],l=12,M={x:Math.ceil(s.vHeadSize/l),y:Math.ceil(s.sequenceLength/l),z:s.batchSize*s.numHeads},T=[{type:12,data:s.sequenceLength},{type:12,data:i},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:d},{type:12,data:a},{type:12,data:s.kvSequenceLength}],E=p&&n&&Oe.size(n.dims)>0,L=["type","type"];E&&L.push("type");let G=[{dims:g,dataType:t.dataType,gpuDataType:0}];p&&G.push({dims:w,dataType:t.dataType,gpuDataType:0});let z=ae=>{let Q=Ze("probs",t.dataType,t.dims),oe=Ze("v",r.dataType,r.dims),Re=[Q,oe];E&&Re.push(Ze("past_value",n.dataType,n.dims));let Ne=[Wt("output",t.dataType,g)];p&&Ne.push(Wt("present_value",t.dataType,w));let _t=[{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<${Q.type.value}, ${l*l}>; + var tileK: array<${Q.type.value}, ${l*l}>; + ${ae.registerUniforms(_t).declareVariables(...Re,...Ne)} + ${ae.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; + ${E&&p?` + 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; + `} + ${p?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${Q.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; + ${E&&p?` + 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]; + `} + ${p?"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:`${n!==void 0};${e}`,inputDependencies:L},getRunData:()=>({outputs:G,dispatchGroup:M,programUniforms:T}),getShaderSource:z}},As=(e,t,r,n,s,a,i,u,d,p,w)=>{let g=Math.min(e.outputCount,1+(i?1:0)+(u?1:0)),l=p.kvNumHeads!==void 0||g>1?p.pastSequenceLength:0,M=l+p.kvSequenceLength,T=d&&Oe.size(d.dims)>0?d:void 0,E=[t,r];p.kvNumHeads===void 0&&g>1&&i&&Oe.size(i.dims)>0&&E.push(i),T&&E.push(T);let L=e.compute(Vi(g,t,r,i,T,p,w,l),{inputs:E,outputs:p.kvNumHeads===void 0&&g>1?[-1,1]:[-1]})[0];e.compute(Do(L,p.batchSize*p.numHeads*p.sequenceLength,M),{inputs:[L],outputs:[]});let G=[L,n];p.kvNumHeads===void 0&&g>1&&u&&Oe.size(u.dims)>0&&G.push(u),e.compute(Bo(g,L,n,u,p,l),{inputs:G,outputs:p.kvNumHeads===void 0&&g>1?[0,2]:[0]})},Ui=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,s=t.inputHiddenSize,a=t.headSize,i=12,u={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:s},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],w=g=>{let l=Wt("output_q",d[0].dataType,r),M=Wt("output_k",d[0].dataType,r),T=Wt("output_v",d[0].dataType,r),E=Ze("input",d[0].dataType,d[0].dims),L=Ze("weight",d[1].dataType,d[1].dims),G=Ze("bias",d[2].dataType,d[2].dims),z=E.type.storage,ae=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${i}u; + var tileInput: array<${z}, ${i*i}>; + var tileWeightQ: array<${z}, ${i*i}>; + var tileWeightK: array<${z}, ${i*i}>; + var tileWeightV: array<${z}, ${i*i}>; + ${g.registerUniforms(ae).declareVariables(E,L,G,l,M,T)} + ${g.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${z}(0); + var valueK = ${z}(0); + var valueV = ${z}(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:p}),getShaderSource:w},{inputs:d,outputs:[-1,-1,-1]})},Lo=(e,t)=>{let r=zo(e.inputs,t),[n,s,a]=Ui(e,r);return As(e,n,s,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),Gi,Ro,No,qi,gd=j(()=>{bt(),Xt(),Qt(),pr(),ar(),Gi=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,s,a)=>{let i=s.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);s.forEach((u,d)=>{if(u!==n[d])throw new Error(`${a}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Ro=(e,t)=>{let{epsilon:r,spatial:n,format:s}=t,a=e[0].dims,i=n?br(a[a.length-1]):1,u=s==="NHWC"&&a.length>1?i:1,d=Oe.size(a)/i,p=n,w=p?a.length:a,g=Ze("x",e[0].dataType,e[0].dims,i),l=Ze("scale",e[1].dataType,e[1].dims,u),M=Ze("bias",e[2].dataType,e[2].dims,u),T=Ze("inputMean",e[3].dataType,e[3].dims,u),E=Ze("inputVar",e[4].dataType,e[4].dims,u),L=Wt("y",e[0].dataType,w,i),G=()=>{let ae="";if(n)ae=`let cOffset = ${a.length===1?"0u":s==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(s==="NCHW")ae=` + ${L.indicesSet("outputIndices","0","0")} + let cOffset = ${L.indicesToOffset("outputIndices")};`;else{ae=`var cIndices = ${l.type.indices}(0); + cIndices[0] = outputIndices[${a.length-1}];`;for(let Q=1;Q` + const epsilon = ${r}; + ${ae.registerUniform("outputSize","u32").declareVariables(g,l,M,T,E,L)} + ${ae.mainStart()} + ${ae.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${L.offsetToIndices(`global_idx * ${i}`)}; + ${G()} + let scale = ${l.getByOffset("cOffset")}; + let bias = ${M.getByOffset("cOffset")}; + let inputMean = ${T.getByOffset("cOffset")}; + let inputVar = ${E.getByOffset("cOffset")}; + let x = ${g.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${L.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:z,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p?[{type:12,data:d},...It(a)]:[{type:12,data:d}]})}},No=e=>qt(e),qi=(e,t)=>{let{inputs:r,outputCount:n}=e,s=No({...t,outputCount:n});if(k.webgpu.validateInputContent&&Gi(r,s),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ro(r,s))}}),jo,Vo,Uo,Wo=j(()=>{Qt(),ar(),jo=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")},Vo=e=>{let t=e[0].dims,r=e[0].dims[2],n=Oe.size(t)/4,s=e[0].dataType,a=Ze("input",s,t,4),i=Ze("bias",s,[r],4),u=Ze("residual",s,t,4),d=Wt("output",s,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:p=>` + const channels = ${r}u / 4; + ${p.declareVariables(a,i,u,d)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${a.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${d.setByOffset("global_idx","value")} + }`}},Uo=e=>{jo(e.inputs),e.compute(Vo(e.inputs))}}),Go,Er,qo,Ho,Hi,Ko,Xo,Qo,Yo,Ki,Zo,Jo,Xi,el,tl,Qi,Is,rl,Fs,nl,sl,Yi,il,al,ti,ol,ll,Zi,Ji,ul,ea,dl,cl,pl,ta,ra,hl,na,ri,fl,ml,sa,_l,gl,ia,aa=j(()=>{Xt(),Qt(),pr(),ar(),Go=(e,t,r,n,s,a,i)=>{let u=Math.ceil(t/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let p=Ze("inputData",r,[u],4),w=Wt("outputData",n,[u],4),g=[{name:"vec_size",type:"u32"}];return i&&g.push(...i),` + ${e.registerUniforms(g).declareVariables(p,w)} + + ${a??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${p.getByOffset("global_idx")}; + ${w.setByOffset("global_idx",d)} + }`},Er=(e,t,r,n,s,a=e.dataType,i,u)=>{let d=[{type:12,data:Math.ceil(Oe.size(e.dims)/4)}];return i&&d.push(...i),{name:t,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:p=>Go(p,Oe.size(e.dims),e.dataType,a,r,n,u),getRunData:p=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Oe.size(p[0].dims)/64/4)},programUniforms:d})}},qo=e=>{e.compute(Er(e.inputs[0],"Abs","abs"))},Ho=e=>{e.compute(Er(e.inputs[0],"Acos","acos"))},Hi=e=>{e.compute(Er(e.inputs[0],"Acosh","acosh"))},Ko=e=>{e.compute(Er(e.inputs[0],"Asin","asin"))},Xo=e=>{e.compute(Er(e.inputs[0],"Asinh","asinh"))},Qo=e=>{e.compute(Er(e.inputs[0],"Atan","atan"))},Yo=e=>{e.compute(Er(e.inputs[0],"Atanh","atanh"))},Ki=e=>qt(e),Zo=(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(Er(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Jo=e=>{let t,r,n=e.length>=2&&e[1].data!==0,s=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=s?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=s?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return qt({min:t,max:r})},Xi=(e,t)=>{let r=t||Jo(e.inputs),n=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"Clip",s=>`clamp(${s}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},el=e=>{e.compute(Er(e.inputs[0],"Ceil","ceil"))},tl=e=>{e.compute(Er(e.inputs[0],"Cos","cos"))},Qi=e=>{e.compute(Er(e.inputs[0],"Cosh","cosh"))},Is=e=>qt(e),rl=(e,t)=>{let r=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${r}(${t.alpha}); + + fn elu_f32(a: ${r}) -> ${r} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},Fs=(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)); +}`,nl=e=>{let t=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Fs(t)))},sl=e=>{e.compute(Er(e.inputs[0],"Exp","exp"))},Yi=e=>{e.compute(Er(e.inputs[0],"Floor","floor"))},il=e=>{let t=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Fs(t)))},al=(e,t)=>{let r=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},ti=e=>{e.compute(Er(e.inputs[0],"Not",t=>`!${t}`))},ol=e=>{e.compute(Er(e.inputs[0],"Neg",t=>`-${t}`))},ll=e=>{e.compute(Er(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Zi=e=>{let t=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Ji=e=>{e.compute(Er(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ul=e=>qt(e),ea=(e,t)=>{let r=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},dl=e=>{e.compute(Er(e.inputs[0],"Sin","sin"))},cl=e=>{e.compute(Er(e.inputs[0],"Sinh","sinh"))},pl=e=>{e.compute(Er(e.inputs[0],"Sqrt","sqrt"))},ta=e=>{e.compute(Er(e.inputs[0],"Tan","tan"))},ra=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,hl=e=>{e.compute(Er(e.inputs[0],"Tanh",ra))},na=(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 ${ra("v")}; +} +`,ri=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,fl=e=>{let t=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"FastGelu",ri,na(t),void 0,e.inputs[0].dataType))},ml=(e,t)=>{let r=Cr(e.inputs[0].dataType);return e.compute(Er(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},sa=e=>{e.compute(Er(e.inputs[0],"Log","log"))},_l=(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; +} +`,gl=e=>`quick_gelu_impl(${e})`,ia=(e,t)=>{let r=Cr(e.inputs[0].dataType);e.compute(Er(e.inputs[0],"QuickGelu",gl,_l(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),wl,oa,yl,wd=j(()=>{Qt(),ar(),aa(),wl=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")},oa=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Ze("input",e[0].dataType,e[0].dims,4),n=Ze("bias",e[0].dataType,[e[0].dims[2]],4),s=Wt("output",e[0].dataType,t,4),a=Oe.size(t)/4,i=Ar(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${u.declareVariables(r,n,s)} + + ${Fs(i)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${s.setByOffset("global_idx","valueLeft * geluRight")} + }`}},yl=e=>{wl(e.inputs),e.compute(oa(e.inputs))}}),la,bl,zn,ua,Ml,vl,xl,Tl,ni,Sl,Cl,El,da,yd=j(()=>{Xt(),Qt(),ar(),la=(e,t,r,n,s,a,i,u,d,p,w,g)=>{let l,M;typeof u=="string"?l=M=(z,ae)=>`${u}((${z}),(${ae}))`:typeof u=="function"?l=M=u:(l=u.scalar,M=u.vector);let T=Wt("outputData",w,n.length,4),E=Ze("aData",d,t.length,4),L=Ze("bData",p,r.length,4),G;if(s)if(a){let z=Oe.size(t)===1,ae=Oe.size(r)===1,Q=t.length>0&&t[t.length-1]%4===0,oe=r.length>0&&r[r.length-1]%4===0;z||ae?G=T.setByOffset("global_idx",M(z?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),ae?`${L.type.value}(${L.getByOffset("0")}.x)`:L.getByOffset("global_idx"))):G=` + let outputIndices = ${T.offsetToIndices("global_idx * 4u")}; + let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",T)}; + let offsetB = ${L.broadcastedIndicesToOffset("outputIndices",T)}; + ${T.setByOffset("global_idx",M(i||Q?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||oe?L.getByOffset("offsetB / 4u"):`${L.type.value}(${L.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else G=T.setByOffset("global_idx",M(E.getByOffset("global_idx"),L.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let z=(ae,Q,oe="")=>{let Re=`aData[indexA${Q}][componentA${Q}]`,Ne=`bData[indexB${Q}][componentB${Q}]`;return` + let outputIndices${Q} = ${T.offsetToIndices(`global_idx * 4u + ${Q}u`)}; + let offsetA${Q} = ${E.broadcastedIndicesToOffset(`outputIndices${Q}`,T)}; + let offsetB${Q} = ${L.broadcastedIndicesToOffset(`outputIndices${Q}`,T)}; + let indexA${Q} = offsetA${Q} / 4u; + let indexB${Q} = offsetB${Q} / 4u; + let componentA${Q} = offsetA${Q} % 4u; + let componentB${Q} = offsetB${Q} % 4u; + ${ae}[${Q}] = ${oe}(${l(Re,Ne)}); + `};w===9?G=` + var data = vec4(0); + ${z("data",0,"u32")} + ${z("data",1,"u32")} + ${z("data",2,"u32")} + ${z("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:G=` + ${z("outputData[global_idx]",0)} + ${z("outputData[global_idx]",1)} + ${z("outputData[global_idx]",2)} + ${z("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(E,L,T)} + + ${g??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${G} + }`},bl=(e,t,r,n,s,a,i=r.dataType)=>{let u=!Oe.areEqual(r.dims,n.dims),d=r.dims,p=Oe.size(r.dims),w=!1,g=!1,l=[u];if(u){let M=ln.calcShape(r.dims,n.dims,!1);if(!M)throw new Error("Can't perform binary op on the given tensors");d=M,p=Oe.size(d);let T=Oe.size(r.dims)===1,E=Oe.size(n.dims)===1,L=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,G=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;l.push(T),l.push(E),l.push(L),l.push(G);let z=1;for(let ae=1;aeM.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:M=>la(M,r.dims,n.dims,d,w,u,g,s,r.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:[{type:12,data:Math.ceil(Oe.size(d)/4)},...It(r.dims,n.dims,d)]})}},zn=(e,t,r,n,s,a)=>{e.compute(bl(t,s??"",e.inputs[0],e.inputs[1],r,n,a))},ua=e=>{zn(e,"Add",(t,r)=>`${t}+${r}`)},Ml=e=>{zn(e,"Div",(t,r)=>`${t}/${r}`)},vl=e=>{zn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},xl=e=>{zn(e,"Mul",(t,r)=>`${t}*${r}`)},Tl=e=>{let t=Ze("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;zn(e,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},ni=e=>{zn(e,"Sub",(t,r)=>`${t}-${r}`)},Sl=e=>{zn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Cl=e=>{zn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},El=e=>{zn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},da=e=>{zn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),$l,ca,kl,Pl,Al,Il,Fl=j(()=>{Xt(),Qt(),pr(),ar(),$l=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],s=n.dataType,a=n.dims.length;e.forEach((i,u)=>{if(u!==r){if(i.dataType!==s)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((d,p)=>{if(p!==t&&d!==n.dims[p])throw new Error("non concat dimensions must match")})}})},ca=(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; + }`,kl=(e,t)=>{let r=e.length,n=[];for(let s=0;s{let s=Oe.size(r),a=new Array(e.length),i=new Array(e.length),u=0,d=[],p=[],w=[{type:12,data:s}];for(let E=0;E`uniforms.sizeInConcatAxis${E}`).join(","),T=E=>` + + ${(()=>{E.registerUniform("outputSize","u32");for(let L=0;L(${M}); + ${l} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${kl(i,g)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:w}),getShaderSource:T}},Al=(e,t)=>{let r=e.inputs,n=r[0].dims,s=Oe.normalizeAxis(t.axis,n.length);$l(r,s);let a=n.slice();a[s]=r.reduce((u,d)=>u+(d.dims.length>s?d.dims[s]:0),0);let i=r.filter(u=>Oe.size(u.dims)>0);e.compute(Pl(i,s,a,r[0].dataType),{inputs:i})},Il=e=>qt({axis:e.axis})}),Qn,Yn,Un,pa,Zn=j(()=>{Xt(),Qt(),Qn=(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}`)}},Yn=(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})},Un=(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"})},pa=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[r,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=(e==null?void 0:e.activation_params)||[sn,xn];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),un,ha,si=j(()=>{un=(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.`)}},ha=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),ii,Ol=j(()=>{ii=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)); +} +`}),zl,Dl,ai,fa,Bl,Os,Ll,ma,zs=j(()=>{Xt(),Qt(),ar(),Zn(),si(),zl=(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":""}); + `,Dl=(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];"} + }`,ai=(e,t,r="f32",n,s=!1,a=32,i=!1,u=32)=>{let d=t[1]*e[1],p=t[0]*e[0],w=s?d:a,g=s?a:d,l=w/t[0],M=a/t[1];if(!((s&&l===4&&e[1]===4||!s&&(l===3||l===4))&&w%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${l} must be 3 or 4. + tileAWidth ${w} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${w/l}>, ${g}>; +var mm_Bsub: array, ${p/e[0]}>, ${a}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${l}; +const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${d}; + + let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${M}; + 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; + ${zl(s,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${M}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${l===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${Dl(s,l)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},fa=(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":""}); + `,Bl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Os=(e,t,r="f32",n,s=!1,a=32,i=!1,u=32,d=!1)=>{let p=e[1]*t[1],w=e[0]*t[0],g=s?p:a,l=s?a:p;if(!(l%t[1]===0&&g%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let M=l/t[1],T=g/t[0],E=a/t[1],L=d?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${p}; + let globalColStart = i32(workgroupId.x) * ${w}; + + // 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 < ${g}; inputCol = inputCol + ${t[0]}) { + ${fa(s,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${w}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${s?`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) * ${p}; + +let tileRowA = i32(localId.y) * ${M}; +let tileColA = i32(localId.x) * ${T}; +let tileRowB = i32(localId.y) * ${E}; +// 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 < ${M}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${T}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${fa(s,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${E}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${Bl(s)} + 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, ${a}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; + + var acc : array, rowPerThread>; + ${L} + } +`},Ll=(e,t,r,n,s,a=!1)=>{let[i,u,d]=s,[p,w,g,l]=n,M=_s(i,d),T=_s(u,d),E=Ar(n[0].type.tensor),L=()=>{let z=w.rank,ae=p.rank,Q=`var aIndices: ${w.type.indices};`;for(let oe=z-2-1,Re=ae-1;oe>=0;oe--,Re--)Q+=` +aIndices[${oe}] = ${ae>1?`batchIndices[${Re}]`:"batchIndices"};`;return M.forEach(oe=>{Q+=` +aIndices[${oe}] = 0;`}),Q+=` +aIndices[${z-2}] = u32(row); + aIndices[${z-1}] = u32(colIn);`,Q},G=()=>{let z=g.rank,ae=p.rank,Q=`var bIndices: ${g.type.indices};`;for(let oe=z-2-1,Re=ae-1;oe>=0;oe--,Re--)Q+=` +bIndices[${oe}] = ${ae>1?`batchIndices[${Re}]`:"batchIndices"};`;return T.forEach(oe=>{Q+=` +bIndices[${oe}] = 0;`}),Q+=` +bIndices[${z-2}] = u32(row); + bIndices[${z-1}] = u32(colIn);`,Q};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${un(e,E)} { + var value = ${un(e,E)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${L()} + value = ${w.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${un(e,E)} { + var value = ${un(e,E)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${G()} + value = ${g.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${un(e,E)}) { + 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 + ${a?"bias[colIn]":`${un(e,E)}(bias[row])`};`:""} + ${r} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},ma=(e,t,r,n,s=!1,a)=>{let i=e[0].dims,u=e[1].dims,d=i.slice(0,-2),p=u.slice(0,-2),w=n?n.slice(0,-2):r.slice(0,-2),g=Oe.size(w),l=i[i.length-2],M=i[i.length-1],T=u[u.length-1],E=M%4===0&&T%4===0,L=l<=8?[4,1,1]:[4,4,1],G=[8,8,1],z=[Math.ceil(T/G[0]/L[0]),Math.ceil(l/G[1]/L[1]),Math.ceil(g/G[2]/L[2])],ae=E?4:1,Q=[...d,l,M/ae],oe=Q.length,Re=[...p,M,T/ae],Ne=Re.length,_t=[g,l,T/ae],Dt=[{type:6,data:l},{type:6,data:T},{type:6,data:M}];Yn(t,Dt),Dt.push(...It(w,Q,Re));let Vt=["rank","rank"],lr=e.length>2;lr&&(Dt.push(...It(e[2].dims)),Vt.push("rank")),Dt.push(...It(_t));let fr=tr=>{let Vr=w.length,Qr=bi("batchDims",e[0].dataType,Vr,1),Mr=Ar(e[0].dataType),Wr=Ze("a",e[0].dataType,oe,ae),Zt=Ze("b",e[1].dataType,Ne,ae),dr=Wt("result",e[0].dataType,_t.length,ae),Or=[Wr,Zt];if(lr){let nn=s?ae:1;Or.push(Ze("bias",e[2].dataType,e[2].dims.length,nn))}let Ue=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Un(t,Ue);let $t=Ar(dr.type.tensor),rr=Qn(t,dr.type.value,$t),Ur=Ll(ae,lr,rr,[Qr,Wr,Zt,dr],[d,p,w],s);return` + ${tr.registerUniforms(Ue).registerInternalVariables(Qr).declareVariables(...Or,dr)} + ${Ur} + ${E?ai(L,G,Mr,Qr):Os(L,G,Mr,Qr)} + `};return{name:"MatMul",shaderCache:{hint:`${L};${t.activation};${E};${s}`,inputDependencies:Vt},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:z[0],y:z[1],z:z[2]},programUniforms:Dt}),getShaderSource:fr}}}),Rl,Nl,is=j(()=>{Xt(),vn(),ar(),Zn(),si(),Ol(),zs(),Rl=(e,t,r,n,s=!1,a,i=4,u=4,d=4,p="f32")=>{let w=Dt=>{switch(Dt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},g=Dt=>{switch(Dt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},l=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,M=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,T=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",E=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",L=e?"row":"col",G=e?"col":"row",z=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${L} / outWidth; + let outCol = ${L} % outWidth; + + let WRow = ${G} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${G} / 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 = ${G} % inChannels; + var resData = ${un(i,p)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${T} && xCol >= 0 && xCol < ${E}) { + ${l} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${w(i)} + } + return resData;`,ae=e?t&&n?` + let col = colIn * ${i}; + ${z}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${z} + } + return ${un(i,p)}(0.0);`:n&&r?` + let col = colIn * ${i}; + ${z}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${z} + } + return ${un(i,p)}(0.0);`,Q=`${g(u)}`,oe=un(d,p),Re=un(e?i:u,p),Ne=un(e?u:i,p),_t=Qn(a,oe,p);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Re} { + ${e?ae:Q} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ne} { + ${e?Q:ae} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${oe}) { + let col = colIn * ${d}; + 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])"}; + ${M} + ${ha(s)} + ${_t} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Nl=(e,t,r,n,s,a,i,u,d)=>{let p=t.format==="NHWC",w=p?e[0].dims[3]:e[0].dims[1],g=r[0],l=p?r[2]:r[3],M=p?r[1]:r[2],T=p?r[3]:r[1],E=p&&(w%4===0||w%3===0)&&T%4===0,L=p?T:l*M,G=p?l*M:T,z=[8,8,1],ae=n<=8?[4,1,1]:[4,4,1],Q=[Math.ceil(L/z[0]/ae[0]),Math.ceil(G/z[1]/ae[1]),Math.ceil(g/z[2]/ae[2])];Gr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${Q}`);let oe=E?p&&w%4!==0?3:4:1,Re=z[1]*ae[1],Ne=z[0]*ae[0],_t=Math.max(z[0]*oe,z[1]),Dt=n%Re===0,Vt=s%Ne===0,lr=a%_t===0,fr=E?[oe,4,4]:[1,1,1],tr=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Yn(t,tr),tr.push(...It(e[0].dims,e[1].dims));let Vr=["rank","rank"];i&&(tr.push(...It(e[2].dims)),Vr.push("rank")),tr.push(...It(r));let Qr=Mr=>{let Wr=[{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}];Un(t,Wr);let Zt=E?4:1,dr=Ar(e[0].dataType),Or=` + fn setOutputAtIndex(flatIndex : i32, value : ${E?`vec4<${dr}>`:dr}) { + result[flatIndex] = ${E?`vec4<${dr}>`:dr}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${E?`vec4<${dr}>`:dr}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${E?"/ 4":""}, value); + }`,Ue=Ze("x",e[0].dataType,e[0].dims.length,oe===3?1:oe),$t=Ze("w",e[1].dataType,e[1].dims.length,Zt),rr=[Ue,$t],Ur=Wt("result",e[0].dataType,r.length,Zt);if(i){let nn=Ze("bias",e[2].dataType,e[2].dims.length,Zt);rr.push(nn),Or+=` + fn getBiasByOutputCoords(coords : vec4) -> ${E?`vec4<${dr}>`:dr} { + return bias[coords.${p?"w":"y"}${E?"/ 4":""}]; + }`}return` + ${ii("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 }; + ${Mr.registerUniforms(Wr).declareVariables(...rr,Ur)} + ${Or} + ${Rl(p,Dt,Vt,lr,i,t,fr[0],fr[1],fr[2],dr)} + ${E?ai(ae,z,dr,void 0,!p,_t):Os(ae,z,dr,void 0,!p,_t,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${oe};${E};${Dt};${Vt};${lr};${Re};${Ne};${_t}`,inputDependencies:Vr},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Q[0],y:Q[1],z:Q[2]},programUniforms:tr}),getShaderSource:Qr}}}),jl,_a,Ds,Vl,oi,Ul,Wl,Gl,bd=j(()=>{Xt(),vn(),Qt(),ar(),Zn(),si(),jl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Ds=(e,t)=>t<=1?e:e+(e-1)*(t-1),Vl=(e,t,r,n=1)=>{let s=Ds(t,n);return Math.floor((e[0]*(r-1)-r+s)/2)},oi=(e,t,r,n,s)=>{s==null&&(s=Vl(e,t[0],n[0]));let a=[0,0,0,r];for(let i=0;i<3;i++)e[i]+2*s>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*s)/n[i]+1));return a},Ul=(e,t,r,n,s,a,i,u,d,p)=>{let w,g,l,M;if(e==="VALID"&&(e=0),typeof e=="number"){w={top:e,bottom:e,left:e,right:e,front:e,back:e};let T=oi([t,r,n,1],[u,d,p],1,[s,a,i],e);g=T[0],l=T[1],M=T[2]}else if(Array.isArray(e)){if(!e.every((E,L,G)=>E===G[0]))throw Error(`Unsupported padding parameter: ${e}`);w={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let T=oi([t,r,n,1],[u,d,p],1,[s,a,i],e[0]);g=T[0],l=T[1],M=T[2]}else if(e==="SAME_UPPER"){g=Math.ceil(t/s),l=Math.ceil(r/a),M=Math.ceil(n/i);let T=(g-1)*s+u-t,E=(l-1)*a+d-r,L=(M-1)*i+p-n,G=Math.floor(T/2),z=T-G,ae=Math.floor(E/2),Q=E-ae,oe=Math.floor(L/2),Re=L-oe;w={top:ae,bottom:Q,left:oe,right:Re,front:G,back:z}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:w,outDepth:g,outHeight:l,outWidth:M}},Wl=(e,t,r,n,s,a=!1,i="channelsLast")=>{let u,d,p,w,g;if(i==="channelsLast")[u,d,p,w,g]=e;else if(i==="channelsFirst")[u,g,d,p,w]=e;else throw new Error(`Unknown dataFormat ${i}`);let[l,,M,T,E]=t,[L,G,z]=_a(r),[ae,Q,oe]=_a(n),Re=Ds(M,ae),Ne=Ds(T,Q),_t=Ds(E,oe),{padInfo:Dt,outDepth:Vt,outHeight:lr,outWidth:fr}=Ul(s,d,p,w,L,G,z,Re,Ne,_t),tr=a?l*g:l,Vr=[0,0,0,0,0];return i==="channelsFirst"?Vr=[u,tr,Vt,lr,fr]:i==="channelsLast"&&(Vr=[u,Vt,lr,fr,tr]),{batchSize:u,dataFormat:i,inDepth:d,inHeight:p,inWidth:w,inChannels:g,outDepth:Vt,outHeight:lr,outWidth:fr,outChannels:tr,padInfo:Dt,strideDepth:L,strideHeight:G,strideWidth:z,filterDepth:M,filterHeight:T,filterWidth:E,effectiveFilterDepth:Re,effectiveFilterHeight:Ne,effectiveFilterWidth:_t,dilationDepth:ae,dilationHeight:Q,dilationWidth:oe,inShape:e,outShape:Vr,filterShape:t}},Gl=(e,t,r,n,s,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],d={x:r.map((L,G)=>G)},p=[Math.ceil(jl(d.x.map(L=>r[L]))/u[0]),1,1];Gr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);let w=1,g=Oe.size(r),l=[{type:12,data:g},{type:12,data:n},{type:12,data:s},{type:12,data:t.strides},{type:12,data:t.dilations}];Yn(t,l),l.push(...It(e[0].dims,e[1].dims));let M=["rank","rank"],T=e.length===3;T&&(l.push(...It(e[2].dims)),M.push("rank")),l.push(...It(r));let E=L=>{let G=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:s.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Un(t,G);let z=1,ae=Ar(e[0].dataType),Q=Ze("x",e[0].dataType,e[0].dims.length,w),oe=Ze("W",e[1].dataType,e[1].dims.length,z),Re=[Q,oe],Ne=Wt("result",e[0].dataType,r.length,z),_t="";if(T){let lr=Ze("bias",e[2].dataType,e[2].dims.length,z);Re.push(lr),_t+=` + fn getBiasByOutputCoords(coords : array) -> ${ae} { + return bias[${i?jt("coords",4,5):jt("coords",1,5)}]; + }`}let Dt=un(w,ae),Vt=Qn(t,Dt,ae);return` + ${_t} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Q.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${oe.getByIndices("aIndices")}; + } + ${L.registerUniforms(G).declareVariables(...Re,Ne)} + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Ne.offsetToIndices("global_idx")}; + let batch = ${jt("coords",0,Q.rank)}; + let d2 = ${i?jt("coords",Q.rank-1,Q.rank):jt("coords",1,Q.rank)}; + let xFRCCorner = vec3(${i?jt("coords",1,Q.rank):jt("coords",2,Q.rank)}, + ${i?jt("coords",2,Q.rank):jt("coords",3,Q.rank)}, + ${i?jt("coords",3,Q.rank):jt("coords",4,Q.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?jt("uniforms.x_shape",1,Q.rank):jt("uniforms.x_shape",2,Q.rank)}; + let xShapeZ = ${i?jt("uniforms.x_shape",2,Q.rank):jt("uniforms.x_shape",3,Q.rank)}; + let xShapeW = ${i?jt("uniforms.x_shape",3,Q.rank):jt("uniforms.x_shape",4,Q.rank)}; + let xShapeU = ${i?jt("uniforms.x_shape",4,Q.rank):jt("uniforms.x_shape",1,Q.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${T?"value = value + getBiasByOutputCoords(coords)":""}; + ${Vt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${w};${T}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:l}),getShaderSource:E}}}),li,ql,Md=j(()=>{Xt(),Qt(),ar(),Zn(),li=(e,t,r,n)=>{let s=e.length>2,a=s?"value += b[output_channel];":"",i=e[0].dims,u=e[1].dims,d=t.format==="NHWC",p=d?r[3]:r[1],w=p/t.group,g=d&&w>=4?br(p):1,l=Oe.size(r)/g,M=[{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:w}];Yn(t,M),M.push(...It(i,[u[0],u[1],u[2],u[3]/g]));let T=s?["rank","rank","rank"]:["rank","rank"];M.push(...It([r[0],r[1],r[2],r[3]/g]));let E=L=>{let G=Wt("output",e[0].dataType,r.length,g),z=Ar(G.type.tensor),ae=Qn(t,G.type.value,z),Q=Ze("x",e[0].dataType,i.length),oe=Ze("w",e[1].dataType,u.length,g),Re=[Q,oe];s&&Re.push(Ze("b",e[2].dataType,e[2].dims,g));let Ne=[{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"}];Un(t,Ne);let _t=d?` + 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 = ${Q.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${oe.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 = ${Q.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${oe.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${L.registerUniforms(Ne).declareVariables(...Re,G)} + + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${G.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${d?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${g} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; + + var value: ${G.type.value} = ${G.type.value}(0); + ${_t} + ${a} + ${ae} + ${G.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${g}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:M}),getShaderSource:E}},ql=(e,t,r,n)=>{let s=e.length>2,a=br(r[3]),i=br(r[2]),u=Oe.size(r)/a/i,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],w=[r[0],r[1],r[2],r[3]/a],g=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Yn(t,g),g.push(...It(d,p,w));let l=(i-1)*t.strides[1]+p[1],M=T=>{let E=Wt("output",e[0].dataType,w.length,a),L=Ar(E.type.tensor),G=Qn(t,E.type.value,L),z=Ze("x",e[0].dataType,d.length,a),ae=Ze("w",e[1].dataType,p.length,a),Q=[z,ae];s&&Q.push(Ze("b",e[2].dataType,e[2].dims,a));let oe=s?"value += b[output_channel];":"",Re=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Un(t,Re),` + ${T.registerUniforms(Re).declareVariables(...Q,E)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${z.type.value}, ${l}>; + var values: array<${E.type.value}, ${i}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${p[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] = ${z.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${z.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) { + let w_val = ${ae.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${oe} + ${G} + ${E.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${l};${p[0]};${p[1]}`,inputDependencies:s?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:g}),getShaderSource:M}}}),ga,Bs,Hl,Kl=j(()=>{Xt(),Qt(),zs(),ar(),Zn(),ga=(e,t,r,n,s=!1,a)=>{let i=e[0].dims,u=e[1].dims,d=i[i.length-2],p=u[u.length-1],w=i[i.length-1],g=br(p),l=br(w),M=br(d),T=Oe.size(r)/g/M,E=e.length>2,L=n?n.slice(0,-2):r.slice(0,-2),G=[Oe.size(L),d,p],z=[{type:12,data:T},{type:12,data:d},{type:12,data:p},{type:12,data:w}];Yn(t,z),z.push(...It(L,i,u)),E&&z.push(...It(e[2].dims)),z.push(...It(G));let ae=Q=>{let oe=bi("batch_dims",e[0].dataType,L.length),Re=Ze("a",e[0].dataType,i.length,l),Ne=Ze("b",e[1].dataType,u.length,g),_t=Wt("output",e[0].dataType,G.length,g),Dt=Ar(_t.type.tensor),Vt=Qn(t,_t.type.value,Dt),lr=[Re,Ne],fr="";if(E){let Or=s?g:1;lr.push(Ze("bias",e[2].dataType,e[2].dims.length,Or)),fr=`${s?`value += bias[col / ${Or}];`:`value += ${_t.type.value}(bias[row + i]);`}`}let tr=i.slice(0,-2),Vr=u.slice(0,-2),Qr=_s(tr,L),Mr=_s(Vr,L),Wr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Un(t,Wr);let Zt=(Or,Ue)=>{let $t=Or.rank,rr=Or.name;if($t===2)return`var ${rr}_indices = ${Or.type.indices}(0u, 0u);`;let Ur=oe.rank,nn=`var ${rr}_indices: ${Or.type.indices};`;for(let fn=$t-2-1,Ws=Ur-1;fn>=0;fn--,Ws--)nn+=` +${rr}_indices[${fn}] = ${Ur>1?`batch_indices[${Ws}]`:"batch_indices"};`;return Ue.forEach(fn=>{nn+=` +${rr}_indices[${fn}] = 0;`}),nn+=`${rr}_indices[${$t-2}] = 0u; + ${rr}_indices[${$t-1}] = 0u;`,nn},dr=()=>{let Or=`var a_data: ${Re.type.value};`;for(let Ue=0;Ue; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { + ${dr()} + } + for (var i = 0u; i < ${M}u; i++) { + var value = values[i]; + ${fr} + ${Vt} + let cur_indices = ${_t.type.indices}(batch, row + i, col); + let offset = ${_t.indicesToOffset("cur_indices")}; + ${_t.setByOffset(`offset / ${g}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${g};${l};${M};${s}`,inputDependencies:E?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:z}),getShaderSource:ae}},Bs=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.")},Hl=e=>{Bs(e.inputs);let t=ln.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&n<8?e.compute(ga(e.inputs,{activation:""},t)):e.compute(ma(e.inputs,{activation:""},t))}}),Xl,ui,di,ci,wa,ya,vd,Ql,ba,xd=j(()=>{Qt(),is(),bd(),zs(),Md(),Zn(),Kl(),ss(),Xl=(e,t,r,n,s,a)=>{let i=e[0],u=e.slice(a?1:2,a?3:4),d=u.length,p=t[0],w=t.slice(2).map((l,M)=>l+(l-1)*(r[M]-1)),g=u.map((l,M)=>l+n[M]+n[M+d]).map((l,M)=>Math.floor((l-w[M]+s[M])/s[M]));return g.splice(0,0,i),g.splice(a?3:1,0,p),g},ui=[2,3,1,0],di=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ci=(e,t)=>{let r=e.kernelShape.slice();for(let a=2;a{let t=pa(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],s=e.dilations,a=e.group,i=e.kernel_shape,u=e.pads,d=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,pads:u,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},ya=(e,t,r,n)=>{let s=r.format==="NHWC",a=Xl(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,s);if(r.group!==1){let Re=[t[0]];if(s){let Ne=e.kernelCustomData.wT??e.compute(Ln(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ne),Re.push(Ne)}else Re.push(t[1]);t.length===3&&Re.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&s&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(ql(Re,r,a,n),{inputs:Re}):e.compute(li(Re,r,a,n),{inputs:Re});return}let i=t.length===3,u=t[0].dims[s?1:2],d=t[0].dims[s?2:3],p=t[0].dims[s?3:1],w=t[1].dims[2],g=t[1].dims[3],l=a[s?1:2],M=a[s?2:3],T=a[s?3:1],E=s&&w===u&&g===d&&r.pads[0]===0&&r.pads[1]===0;if(E||w===1&&g===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 Re=a[0],Ne,_t,Dt,Vt=[];if(s){let tr=e.kernelCustomData.wT??e.compute(Ln(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=tr),E){let Vr=u*d*p;Ne=t[0].reshape([1,Re,Vr]),_t=tr.reshape([1,Vr,T]),Dt=[1,Re,T]}else Ne=t[0].reshape([Re,u*d,p]),_t=tr.reshape([1,p,T]),Dt=[Re,l*M,T];Vt.push(Ne),Vt.push(_t)}else Ne=t[0].reshape([Re,p,u*d]),_t=t[1].reshape([1,T,p]),Dt=[Re,T,l*M],Vt.push(_t),Vt.push(Ne);i&&Vt.push(t[2]);let lr=Dt[2],fr=Vt[0].dims[Vt[0].dims.length-1];lr<8&&fr<8?e.compute(ga(Vt,r,a,Dt,s,n),{inputs:Vt}):e.compute(ma(Vt,r,a,Dt,s,n),{inputs:Vt});return}let L=!0,G=e.kernelCustomData.wT??e.compute(Ln(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=G);let z=[t[0],G];i&&z.push(t[2]);let ae=s?l*M:T,Q=s?T:l*M,oe=w*g*p;e.compute(Nl(z,r,a,ae,Q,oe,i,L,n),{inputs:z})},vd=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=ci({...t,pads:s,strides:a,dilations:i,kernelShape:u},n);ya(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Ql=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",s=ci(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,i=Wl(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(Gl(t,s,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},ba=(e,t)=>{if(di(e.inputs,t),e.inputs[0].dims.length===3)vd(e,t);else if(e.inputs[0].dims.length===5)Ql(e,e.inputs,t);else{let r=ci(t,e.inputs);ya(e,e.inputs,r)}}}),gs,Yl,Td=j(()=>{Xt(),vn(),ar(),Zn(),si(),Ol(),zs(),gs=(e,t=!1,r,n,s=4)=>{let a=L=>{switch(L){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 ${n}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${L} is not supported.`)}},i=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); + `,d=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",p=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",w=e?"row":"col",g=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 = ${w} / outWidth; + let outCol = ${w} % outWidth; + + let WRow = ${g} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${g} / 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(${d}) || fract(xR) > 0.0) { + return ${n}(0.0); + } + if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) { + return ${n}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${g} % inChannels; + ${i} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,M=e?` + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${l} + } + return ${n}(0.0);`:` + let col = colIn * ${s}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${l} + } + return ${n}(0.0);`,T=` + let col = colIn * ${s}; + 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); + ${a(s)} + } + return ${n}(0.0); + `,E=Qn(r,n);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { + ${e?M:T} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { + ${e?T:M} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { + let col = colIn * ${s}; + 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} + ${ha(t)} + ${E} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; + } + }`},Yl=(e,t,r,n,s,a,i,u)=>{let d=t.format==="NHWC",p=d?e[0].dims[3]:e[0].dims[1],w=r[0],g=d?r[2]:r[3],l=d?r[1]:r[2],M=d?r[3]:r[1],T=d&&p%4===0&&p%3&&M%4===0,E=d?M:g*l,L=d?g*l:M,G=[8,8,1],z=n<=8?[4,1,1]:[4,4,1],ae=[Math.ceil(E/G[0]/z[0]),Math.ceil(L/G[1]/z[1]),Math.ceil(w/G[2]/z[2])];Gr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ae}`);let Q=T?4:1,oe=Math.max(G[0]*Q,G[1]),Re=T?4:1,Ne=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],_t=[Ne[0]+(t.dilations[0]<=1?0:(Ne[0]-1)*(t.dilations[0]-1)),Ne[1]+(t.dilations[1]<=1?0:(Ne[1]-1)*(t.dilations[1]-1))],Dt=[_t[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),_t[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Vt=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Ne},{type:6,data:Dt}];Yn(t,Vt),Vt.push(...It(e[0].dims,e[1].dims));let lr=["rank","rank"];i&&(Vt.push(...It(e[2].dims)),lr.push("rank")),Vt.push(...It(r));let fr=tr=>{let Vr=Ze("x",e[0].dataType,e[0].dims.length,Re),Qr=Ze("w",e[1].dataType,e[1].dims.length,1),Mr=Wt("result",e[0].dataType,r.length,Re),Wr=[Vr,Qr],Zt="";if(i){let Ue=Ze("bias",e[2].dataType,e[2].dims.length,Re);Wr.push(Ue),Zt+=` + fn getBiasByOutputCoords(coords : vec4) -> ${Ue.type.value} { + return bias[coords.${d?"w":"y"}${T?"/ 4":""}]; + }`}let dr=[{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:Ne.length},{name:"pads",type:"i32",length:Dt.length}];Un(t,dr);let Or=Ar(e[0].dataType,1);if(Or!=="f16"&&Or!=="f32")throw new Error(`elemType ${Or} is not supported.`);return` + ${ii("uniforms.result_strides")} + ${tr.registerUniforms(dr).declareVariables(...Wr,Mr)}; + ${Zt} + ${gs(d,i,t,Vr.type.value,Q)} + ${T?ai(z,G,Or,void 0,!d,oe):Os(z,G,Or,void 0,!d,oe,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${z};${G};${T}`,inputDependencies:lr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ae[0],y:ae[1],z:ae[2]},programUniforms:Vt}),getShaderSource:fr}}}),Zl,Ma,Sd=j(()=>{Xt(),vn(),Qt(),ar(),Zl=(e,t,r,n,s,a=!1,i,u,d=!1)=>{let p=d?1:2,w=d?2:3,g=d?3:1,l=a?2:1,M=` + fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${i}>`:i}) { + result[flatIndex] = ${a?`vec4<${i}>`:i}(value); + }`;n&&(M+=` + fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${i}>`:i} { + return bias[coords.${d?"w":"y"}${a?"/ 4":""}]; + }`);let T=a?4:1,E=Ze("W",t[1].dataType,t[1].dims.length,T),L=Ze("Dy",t[0].dataType,t[0].dims.length,T),G=[L,E];n&&G.push(Ze("bias",t[2].dataType,[r[g]].length,T));let z=Wt("result",t[0].dataType,r.length,T),ae=`{ + let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${s?"global_id.y":"workgroup_id.y"} * ${l}; + let d1: u32 = ${s?"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<${i}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${i}(dyCorner.x) + ${i}(wR)) / ${i}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${i}(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 = (${i}(dyCorner.y) + ${i}(wC)) / ${i}(uniforms.strides.y); + let dyC2 = (${i}(dyCorner.y) + 1.0 + ${i}(wC)) / ${i}(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 >= ${i}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${i}(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 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${L.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${L.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${g}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${L.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${i}>(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 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${L.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${i}>(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] + ${n?"bias[c+i]":`vec4<${i}>(0.0)`}; + ${z.set("batch","r","c + i","d1","value")}; + } + }`,Q=` + let outputIndices = ${z.offsetToIndices("global_idx")}; + let batch = ${z.indicesGet("outputIndices",0)}; + let d1 = ${z.indicesGet("outputIndices",g)}; + let r = ${z.indicesGet("outputIndices",p)}; + let c = ${z.indicesGet("outputIndices",w)}; + 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 = ${i}(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 = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[${p}]) || 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 = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[${w}]) || + 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 = ${d?L.get("batch","idyR","idyC","inputChannel"):L.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${E.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${n?"bias[d1]":`${i}(0.0)`}; + ${z.setByOffset("global_idx","value")}; + `;return` + ${e.registerUniforms(u).declareVariables(...G,z)} + ${M} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${a?ae:Q}}`},Ma=(e,t,r)=>{let n=e.length>2,s=t.outputShape,a=Oe.size(s),i=[Math.ceil(a/64),1,1];Gr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let u=t.format==="NHWC",d=["rank","rank"],p=[t.strides[0],t.strides[1]],w=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],g=[t.dilations[0],t.dilations[1]],l=[w[0]+(t.dilations[0]<=1?0:(t.kernelShape[u?1:2]-1)*(t.dilations[0]-1)),w[1]+(t.dilations[1]<=1?0:(t.kernelShape[u?2:3]-1)*(t.dilations[1]-1))],M=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],T=!1,E=t.group,L=e[1].dims,G=L[0]/E,z=L[1],ae=[{type:12,data:a},{type:12,data:p},{type:12,data:w},{type:12,data:g},{type:12,data:l},{type:6,data:M},{type:12,data:G},{type:12,data:z},...It(e[0].dims,e[1].dims)];n&&(ae.push(...It(e[2].dims)),d.push("rank")),ae.push(...It(s));let Q=i[1]===1&&i[2]===1,oe=Re=>{let Ne=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:p.length},{name:"filter_dims",type:"u32",length:w.length},{name:"dilations",type:"u32",length:w.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:M.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],_t=Ar(e[0].dataType);return`${Zl(Re,e,s,n,Q,T,_t,Ne,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:r?r(s):s,dataType:e[0].dataType}],programUniforms:ae}),getShaderSource:oe}}}),pi,Cd,Jl,va,eu,tu,ru,xa,nu,su,iu=j(()=>{Td(),Sd(),Zn(),ss(),pi=(e,t,r,n,s,a)=>(e-1)*t+r+(n-1)*s+1-a,Cd=(e,t,r,n,s)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[s]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[s]=a)},Jl=(e,t,r,n,s,a,i,u,d,p)=>{let w=e.length-2,g=p.length===0;if(d.length===0)for(let T=0;T{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((g,l)=>g*l,1)===0){r.length=0;for(let g=2;gg+l,0)===0){let g=t[0].dims.length-2;d=new Array(g).fill(1)}let p=e.strides.slice();if(p.reduce((g,l)=>g+l,0)===0){let g=t[0].dims.length-2;p=new Array(g).fill(1)}Jl(u,r,d,e.autoPad,e.group,s,p,n,i,a);let w=Object.assign({},e);return Object.assign(w,{kernelShape:r,pads:s,outputPadding:i,outputShape:a,dilations:d,strides:p}),w},eu=e=>{let t=pa(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],s=e.dilations,a=e.group,i=e.kernelShape,u=e.pads,d=e.strides,p=e.wIsConst(),w=e.outputPadding,g=e.outputShape;return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,outputPadding:w,outputShape:g,pads:u,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},tu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==s))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,u)=>i+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,u)=>i+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,u)=>i+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,u)=>i+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},ru=[2,3,1,0],xa=(e,t,r)=>{let n=va(r,t),s=r.format==="NHWC",a=n.outputShape,i=a[s?3:1],u=t[0].dims[s?3:1];if(n.group!==1||i===1&&u===1){e.compute(Ma(t,n));return}let d=a[s?1:2],p=a[s?2:3],w=t[1].dims[2],g=t[1].dims[3],l=s?d*p:i,M=s?i:d*p,T=w*g*u,E=!0,L=e.kernelCustomData.wT??e.compute(Ln(t[1],ru),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=L);let G=[t[0],L],z=t.length===3;z&&(!s&&t[2].dims.length===1?G.push(t[2].reshape([t[2].dims[0],1,1])):G.push(t[2])),e.compute(Yl(G,n,a,l,M,T,z,E),{inputs:G})},nu=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=t.kernelShape;(s.length===0||s[0]===0)&&(s=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],i=[1].concat(i),a=[1].concat(a),s=[1].concat(s);let d=va({...t,pads:u,strides:i,dilations:a,kernelShape:s},n);e.compute(Ma(n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},su=(e,t)=>{tu(e.inputs,t),e.inputs[0].dims.length===3?nu(e,t):xa(e,e.inputs,t)}}),au,ou,Ta,Ed=j(()=>{Xt(),Qt(),pr(),ar(),au=(e,t,r,n)=>{let s=Oe.size(t),a=t.length,i=Ze("input",e,a),u=Wt("output",e,a),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=Oe.normalizeAxis(d,a),w=g=>{let l=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,M=jt("uniforms.input_shape","uniforms.axis",a),T=n.reverse?l+(n.exclusive?" + 1":""):"0",E=n.reverse?M:l+(n.exclusive?"":" + 1");return` + ${g.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,u)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${T}; + let last : i32 = ${E}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},{type:12,data:p},...It(t,t)]}),getShaderSource:w}},ou=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,s=e.inputs[1];e.compute(au(n,r,s,t),{inputs:[0]})},Ta=e=>{let t=e.exclusive===1,r=e.reverse===1;return qt({exclusive:t,reverse:r})}}),lu,hi,uu,du,cu,$d=j(()=>{Xt(),Qt(),pr(),ar(),lu=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},hi=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let a=0;a{let r,n,s,a,i,u,d=t.format==="NHWC",p=t.blocksize,w=t.mode==="DCR";d?([r,n,s,a]=e.dims,i=w?[r,n,s,p,p,a/p**2]:[r,n,s,a/p**2,p,p],u=w?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,s,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=w?[r,p,p,a/p**2,n,s]:[r,a/p**2,p,p,n,s],u=w?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let g=e.reshape(i),l=g.dims.length,M=e.dataType,T=Ze("a",M,l),E=Wt("output",M,l),L=G=>` + ${G.registerUniform("output_size","u32").declareVariables(T,E)} + + ${hi(u,l,T,E)} + + ${G.mainStart()} + ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${E.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${E.setByOffset("global_idx",T.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:G=>{let z=d?[r,n*p,s*p,a/p**2]:[r,a/p**2,n*p,s*p],ae=Oe.size(z),Q=g.dims,oe=Oe.sortBasedOnPerm(Q,u);return{outputs:[{dims:z,dataType:G[0].dataType}],dispatchGroup:{x:Math.ceil(ae/64)},programUniforms:[{type:12,data:ae},...It(Q,oe)]}},getShaderSource:L}},du=(e,t)=>{lu(e.inputs),e.compute(uu(e.inputs[0],t))},cu=e=>qt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ls,as,pu,hu,fu,Sa,mu,Ca,Ea,_u,gu,wu=j(()=>{Xt(),Qt(),pr(),ar(),Ls="[a-zA-Z]|\\.\\.\\.",as="("+Ls+")+",pu="^"+as+"$",hu="("+as+",)*"+as,fu="^"+hu+"$",Sa=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)}},mu=class{constructor(e,t){var s;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(fu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let u=e[i].dims.slice();if(!a.match(RegExp(pu)))throw new Error("Invalid LHS term");let d=this.processTerm(a,!0,u,i);this.lhs.push(d)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(as)))throw new Error("Invalid RHS");(s=n.match(RegExp(Ls,"g")))==null||s.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let s=r.length,a=!1,i=[],u=0;if(!e.match(RegExp(pu))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(Ls,"g")),p=new Sa(n);return d==null||d.forEach((w,g)=>{if(w==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let l=s-d.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(u,u+l),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let M=0;Me+"_max",Ea=(e,t,r,n)=>{let s=e.map(p=>p.length).map((p,w)=>Ze(`input${w}`,t,p)),a=Oe.size(n),i=Wt("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(p=>!r.rhs.symbolToIndices.has(p)),d=p=>{let w=[],g="var prod = 1.0;",l="var sum = 0.0;",M="sum += prod;",T=[],E=[],L=[],G=[],z=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((Q,oe)=>{var Re;if(r.rhs.symbolToIndices.has(oe)){let Ne=(Re=r.rhs.symbolToIndices.get(oe))==null?void 0:Re[0];Ne!==void 0&&r.lhs.forEach((_t,Dt)=>{if(Q.inputIndices.includes(Dt)){let Vt=_t.symbolToIndices.get(oe);if(Vt===void 0)throw new Error("Invalid symbol error");Vt.forEach(lr=>{w.push(`${s[Dt].indicesSet(`input${Dt}Indices`,lr,i.indicesGet("outputIndices",Ne))}`)})}})}else r.lhs.forEach((Ne,_t)=>{if(Q.inputIndices.includes(_t)){let Dt=Ne.symbolToIndices.get(oe);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(Vt=>{T.push(`${s[_t].indicesSet(`input${_t}Indices`,Vt,`${oe}`)}`)}),G.push(`prod *= ${s[_t].getByIndices(`input${_t}Indices`)};`)}}),E.push(`for(var ${oe}: u32 = 0; ${oe} < uniforms.${Ca(oe)}; ${oe}++) {`),L.push("}")});let ae=z?[...w,`let sum = ${s.map((Q,oe)=>Q.getByIndices(`input${oe}Indices`)).join(" * ")};`]:[...w,l,...E,...T,g,...G,M,...L];return` + ${p.registerUniforms(u.map(Q=>({name:`${Ca(Q)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,i)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${s.map((Q,oe)=>`var input${oe}Indices: ${s[oe].type.indices};`).join(` +`)} + ${ae.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=u.filter(g=>r.symbolToInfo.has(g)).map(g=>{var l;return{type:12,data:((l=r.symbolToInfo.get(g))==null?void 0:l.dimValue)||0}});p.push({type:12,data:a});let w=e.map((g,l)=>[...It(g)]).reduce((g,l)=>g.concat(l),p);return w.push(...It(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:w}},getShaderSource:d}},_u=(e,t)=>{let r=new mu(e.inputs,t.equation),n=r.outputDims,s=e.inputs.map((a,i)=>a.dims);e.compute(Ea(s,e.inputs[0].dataType,r,n))},gu=e=>{let t=e.equation.replace(/\s+/g,"");return qt({equation:t})}}),kd,yu,$a,ka,bu,Pd=j(()=>{Xt(),Qt(),ar(),kd=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let s=0;se.length>t.length?yu(e,t):yu(t,e),ka=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=$a(t,r),s=e[0].dataType,a=s===9?4:1,i=Math.ceil(Oe.size(n)/a),u=p=>{let w=Ze("input",s,t.length,a),g=Wt("output",s,n.length,a),l;if(s===9){let M=(T,E,L="")=>` + let outputIndices${E} = ${g.offsetToIndices(`outputOffset + ${E}u`)}; + let offset${E} = ${w.broadcastedIndicesToOffset(`outputIndices${E}`,g)}; + let index${E} = offset${E} / 4u; + let component${E} = offset${E} % 4u; + ${T}[${E}] = ${L}(${w.getByOffset(`index${E}`)}[component${E}]); + `;l=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${M("data",0,"u32")} + ${M("data",1,"u32")} + ${M("data",2,"u32")} + ${M("data",3,"u32")} + ${g.setByOffset("global_idx","data")} + }`}else l=` + let outputIndices = ${g.offsetToIndices("global_idx")}; + let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",g)}; + ${g.setByOffset("global_idx",w.getByOffset("inputOffset"))} + }`;return` + ${p.registerUniform("vec_size","u32").declareVariables(w,g)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${l}`},d=[{type:12,data:i},...It(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d})}},bu=e=>{kd(e.inputs),e.compute(ka(e.inputs),{inputs:[0]})}}),Pa,Mu,Ad=j(()=>{Xt(),Qt(),ar(),aa(),Pa=e=>{let t=e[0].dataType,r=Oe.size(e[0].dims),n=Oe.size(e[1].dims),s=n%4===0,a=i=>{let u=Ze("x",t,[1],4),d=Ze("bias",t,[1],4),p=Wt("y",t,[1],4),w=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],g=M=>` + let bias${M}_offset: u32 = (global_idx * 4 + ${M}) % uniforms.bias_size; + let bias${M} = ${d.getByOffset(`bias${M}_offset / 4`)}[bias${M}_offset % 4];`,l=s?` + let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${g(0)}${g(1)}${g(2)}${g(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(w).declareVariables(u,d,p)} + + ${na(Cr(t))} + + ${i.mainStart(Tn)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${l} + let x_in = x + bias; + ${p.setByOffset("global_idx",ri("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Tn/4)}})}},Mu=e=>{e.inputs.length<2||Oe.size(e.inputs[1].dims)===0?fl(e):e.compute(Pa(e.inputs))}}),Aa,vu,xu,Ia,Id=j(()=>{Xt(),Qt(),pr(),ar(),Aa=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},vu=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Oe.normalizeAxis(t.axis,s),i=r.slice(0);i.splice(a,1,...n);let u=r[a],d=e[0].dataType===9?4:1,p=Math.ceil(Oe.size(i)/d),w=[{type:12,data:p},{type:6,data:u},{type:12,data:a},...It(e[0].dims,e[1].dims,i)],g=l=>{let M=Ze("data",e[0].dataType,e[0].dims.length,d),T=Ze("inputIndices",e[1].dataType,e[1].dims.length),E=Wt("output",e[0].dataType,i.length,d),L=z=>{let ae=n.length,Q=`var indicesIndices${z} = ${T.type.indices}(0);`;for(let oe=0;oe1?`indicesIndices${z}[${oe}]`:`indicesIndices${z}`} = ${i.length>1?`outputIndices${z}[uniforms.axis + ${oe}]`:`outputIndices${z}`};`;Q+=` + var idx${z} = ${T.getByIndices(`indicesIndices${z}`)}; + if (idx${z} < 0) { + idx${z} = idx${z} + uniforms.axisDimLimit; + } + var dataIndices${z} : ${M.type.indices}; + `;for(let oe=0,Re=0;oe1?`dataIndices${z}[${oe}]`:`dataIndices${z}`} = u32(idx${z});`,Re+=ae):(Q+=`${s>1?`dataIndices${z}[${oe}]`:`dataIndices${z}`} = ${i.length>1?`outputIndices${z}[${Re}]`:`outputIndices${z}`};`,Re++);return Q},G;if(e[0].dataType===9){let z=(ae,Q,oe="")=>` + let outputIndices${Q} = ${E.offsetToIndices(`outputOffset + ${Q}u`)}; + ${L(Q)}; + let offset${Q} = ${M.indicesToOffset(`dataIndices${Q}`)}; + let index${Q} = offset${Q} / 4u; + let component${Q} = offset${Q} % 4u; + ${ae}[${Q}] = ${oe}(${M.getByOffset(`index${Q}`)}[component${Q}]); + `;G=` + let outputOffset = global_idx * ${d}; + var value = vec4(0); + ${z("value",0,"u32")} + ${z("value",1,"u32")} + ${z("value",2,"u32")} + ${z("value",3,"u32")} + ${E.setByOffset("global_idx","value")} + `}else G=` + let outputIndices = ${E.offsetToIndices("global_idx")}; + ${L("")}; + let value = ${M.getByIndices("dataIndices")}; + ${E.setByOffset("global_idx","value")}; + `;return` + ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(M,T,E)} + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${G} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:w}),getShaderSource:g}},xu=e=>qt({axis:e.axis}),Ia=(e,t)=>{let r=e.inputs;Aa(r),e.compute(vu(e.inputs,t))}}),Tu,Su,Cu,Dr,yc=j(()=>{Xt(),Qt(),pr(),ar(),Tu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=Oe.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,s=e[0],a=e[2],i=e.length===4?e[3]:void 0;if(a.dims.length!==s.dims.length||!s.dims.map((u,d)=>d===r?Math.ceil(u/n)===a.dims[d]:u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==s.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==a.dims.length||!i.dims.map((u,d)=>u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Su=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Oe.normalizeAxis(t.gatherAxis,s),i=Oe.normalizeAxis(t.quantizeAxis,s),u=r.slice(0);u.splice(a,1,...n);let d=Oe.size(u),p=e[2].dataType,w=e[0].dataType===22,g=[{type:12,data:d},{type:12,data:i},{type:12,data:a},{type:12,data:t.blockSize},...It(...e.map((M,T)=>M.dims),u)],l=M=>{let T=Ze("data",e[0].dataType,e[0].dims.length),E=Ze("inputIndices",e[1].dataType,e[1].dims.length),L=Ze("scales",e[2].dataType,e[2].dims.length),G=e.length>3?Ze("zeroPoint",e[3].dataType,e[3].dims.length):void 0,z=Wt("output",p,u.length),ae=[T,E,L];G&&ae.push(G);let Q=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${M.registerUniforms(Q).declareVariables(...ae,z)} + ${M.mainStart()} + let output_indices = ${z.offsetToIndices("global_idx")}; + var indices_indices = ${E.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${z.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${E.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${z.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${T.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${z.indicesGet("output_indices","i")}; + ${T.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${E.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${r[a]}; + } + ${T.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { + let index = ${z.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${T.indicesSet("data_indices","i","index")}; + } + let data_offset = ${T.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${T.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${w?"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 = ${L.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${L.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${L.getByIndices("scale_indices")}; + ${G?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${G.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${G.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${w?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Cr(p)}(quantized_data - zero_point) * scale; + ${z.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((M,T)=>T!==1).map(M=>M.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(M,T)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:p}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:g}),getShaderSource:l}},Cu=(e,t)=>{let r=e.inputs;Tu(r,t),e.compute(Su(e.inputs,t))},Dr=e=>qt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Fd,Od,Fa,Eu,zd=j(()=>{Xt(),Qt(),pr(),ar(),Fd=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Od=(e,t)=>{let r=e[0].dims,n=e[0].dataType,s=r.length,a=e[1].dims,i=e[1].dataType,u=Oe.normalizeAxis(t.axis,s),d=r[u],p=a.slice(0),w=Oe.size(p),g=Ze("input",n,s),l=Ze("indicesInput",i,a.length),M=Wt("output",n,p.length),T=[{type:12,data:w},{type:6,data:d},{type:12,data:u}];return T.push(...It(r,a,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:T}),getShaderSource:E=>` + ${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,l,M)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${M.offsetToIndices("global_idx")}; + + var idx = ${l.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${g.type.indices}(outputIndices); + ${g.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${g.getByIndices("inputIndices")}; + + ${M.setByOffset("global_idx","value")}; + }`}},Fa=e=>qt({axis:e.axis}),Eu=(e,t)=>{let r=e.inputs;Fd(r),e.compute(Od(e.inputs,t))}}),$u,ku,Oa,za,Dd=j(()=>{Xt(),Qt(),ar(),$u=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")},ku=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[s,a,i]=Sr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[s,a];if(!u)throw new Error("Can't use gemm on the given tensors");let d=Oe.size(u),p=[{type:12,data:d},{type:12,data:s},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],w=["type","type"];e.length===3&&(p.push(...It(e[2].dims)),w.push("rank")),p.push(...It(u));let g=l=>{let M="";t.transA&&t.transB?M="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?M="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?M="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(M="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let T=t.alpha===1?"":"value *= uniforms.alpha;",E=Ze("a",e[0].dataType,e[0].dims),L=Ze("b",e[1].dataType,e[1].dims),G=E.type.value,z=null,ae=[E,L];e.length===3&&(z=Ze("c",e[2].dataType,e[2].dims.length),ae.push(z));let Q=Wt("output",e[0].dataType,u.length);ae.push(Q);let oe=[{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(oe).declareVariables(...ae)} + + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${G}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${M} + } + + ${T} + ${z!=null?`let cOffset = ${z.broadcastedIndicesToOffset("vec2(m, n)",Q)}; value += ${G}(uniforms.beta) * ${z.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:g}},Oa=e=>{let t=e.transA,r=e.transB,n=e.alpha,s=e.beta;return{transA:t,transB:r,alpha:n,beta:s,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},za=(e,t)=>{$u(e.inputs),e.compute(ku(e.inputs,t))}}),_n,Da,Bd,Pu,Au,Rs,Iu,Fu=j(()=>{Xt(),Qt(),pr(),P(),Wi(),ar(),ss(),_n=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Da=(e,t)=>{let r=e[0],n=_n(e,1),s=_n(e,2),a=_n(e,3),i=_n(e,4),u=_n(e,5),d=_n(e,6),p=_n(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 w=r.dims[0],g=r.dims[1],l=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],M=g,T=0,E=0,L=Math.floor(l/t.numHeads);if(d&&p&&Oe.size(d.dims)&&Oe.size(p.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==w||d.dims[1]!==t.numHeads||d.dims[3]!==L)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==w||p.dims[1]!==t.numHeads||p.dims[3]!==L)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');T=d.dims[2],E=d.dims[2]}else if(d&&Oe.size(d.dims)||p&&Oe.size(p.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let G;if(n&&Oe.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');G=2,M=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==L)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');G=5,M=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==L)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');G=0,M=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');G=3}if(a&&Oe.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let z=T+M,ae=0;if(i&&Oe.size(i.dims)>0){ae=8;let Ne=i.dims;throw Ne.length===1?Ne[0]===w?ae=1:Ne[0]===3*w+2&&(ae=3):Ne.length===2&&Ne[0]===w&&Ne[1]===z&&(ae=5),ae===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let Q=!1,oe=l;if(s&&Oe.size(s.dims)>0){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(M!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');oe=s.dims[2]}else{if(M!==s.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');oe=s.dims[1]*s.dims[3],Q=!0}}let Re=!1;if(i&&Oe.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(u&&Oe.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]!==w||u.dims[1]!==t.numHeads||u.dims[2]!==g||u.dims[3]!==z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:w,sequenceLength:g,pastSequenceLength:T,kvSequenceLength:M,totalSequenceLength:z,maxSequenceLength:E,inputHiddenSize:0,hiddenSize:l,vHiddenSize:oe,headSize:L,vHeadSize:Math.floor(oe/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ae,scale:t.scale,broadcastResPosBias:Re,passPastInKv:Q,qkvFormat:G}},Bd=e=>qt({...e}),Pu=qt({perm:[0,2,1,3]}),Au=(e,t,r,n,s,a,i)=>{let u=[n,s,a],d=Oe.size(u),p=[{type:12,data:d},{type:12,data:i},{type:12,data:a}],w=g=>{let l=Wt("qkv_with_bias",t.dataType,u),M=Ze("qkv",t.dataType,u),T=Ze("bias",r.dataType,u),E=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${g.registerUniforms(E).declareVariables(M,T,l)} + ${g.mainStart()} + ${g.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(d/64)},programUniforms:p}),getShaderSource:w},{inputs:[t,r],outputs:[-1]})[0]},Rs=(e,t,r,n,s,a,i,u)=>{let d=a;if(i&&Oe.size(i.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Au(e,a,i,t,n,r*s,u),d=d.reshape([t,n,r,s]),e.compute(Ln(d,Pu.perm),{inputs:[d],outputs:[-1]})[0]}else return a.dims.length===3&&(d=a.reshape([t,n,r,s])),e.compute(Ln(d,Pu.perm),{inputs:[d],outputs:[-1]})[0]},Iu=(e,t)=>{let r=Da(e.inputs,t),n=e.inputs[0],s=_n(e.inputs,1),a=_n(e.inputs,2),i=_n(e.inputs,3),u=_n(e.inputs,4),d=_n(e.inputs,5),p=_n(e.inputs,6),w=_n(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((s==null?void 0:s.dims.length)===5)throw new Error("Packed KV is not implemented");let g=s&&a&&s.dims.length===4&&a.dims.length===4,l=Rs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(g)return As(e,l,s,a,u,void 0,p,w,d,r,t);if(!s||!a)throw new Error("key and value must be provided");let M=Rs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,s,i,r.hiddenSize),T=Rs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,i,2*r.hiddenSize);As(e,l,M,T,u,void 0,p,w,d,r,t)}}),Ba,Ou,zu,La,Du,Bu=j(()=>{Xt(),Qt(),ar(),Ba=e=>Array.from(e.getBigInt64Array(),Number),Ou=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(Ba(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")},zu=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Ba(e[1]),s=zu(r,n),a=Oe.size(s),i=e[0].dataType,u=Ze("input",i,r.length),d=Wt("output",i,s.length),p=w=>` + const inputShape = ${u.indices(...r)}; + ${w.registerUniform("output_size","u32").declareVariables(u,d)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${d.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 = ${d.indicesGet("output_indices","i")} % input_dim_i; + + ${u.indicesSet("input_indices","i","input_dim_value")} + } + ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...It(e[0].dims,s)]}),getShaderSource:p}},Du=e=>{Ou(e.inputs),e.compute(La(e.inputs),{inputs:[0]})}}),Lu,Ra,Ru,Nu,Na,ju,Ld=j(()=>{Xt(),Qt(),pr(),Wi(),ar(),Fu(),Bu(),ss(),Lu=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=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,d=r.dims[0],p=r.dims[1],w=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],g=p,l=0,M=0,T=Math.floor(w/t.numHeads),E=a&&a.dims.length!==0,L=i&&i.dims.length!==0,G=!0;if(E&&L){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=a.dims[1],M=a.dims[1]}else if(E||L)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let z;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');z=2,g=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==T)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');z=5,g=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==T)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');z=0,g=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');z=3}let ae=0,Q=!1,oe=w;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(g!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');oe=s.dims[2]}else{if(g!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');oe=s.dims[1]*s.dims[3],Q=!0}}let Re=l+g;return{batchSize:d,sequenceLength:p,pastSequenceLength:l,kvSequenceLength:g,totalSequenceLength:Re,maxSequenceLength:M,inputHiddenSize:0,hiddenSize:w,vHiddenSize:oe,headSize:T,vHeadSize:Math.floor(oe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:ae,scale:t.scale,broadcastResPosBias:!1,passPastInKv:Q,qkvFormat:z,isPastkvBSNH:G}},Ra=(e,t,r,n)=>{let s=[n.batchSize,n.totalSequenceLength,n.kvNumHeads,n.headSize],a=4,i=Oe.size(s)/a,u=n.totalSequenceLength,d=Wt("present_kv",r,s.length,a),p=Ze("new_kv",e.dataType,e.dims.length,a),w=t?Ze("past_kv",t.dataType,t.dims.length,a):void 0,g=Math.ceil(n.headSize/a),l={x:u,y:e.dims[0],z:1},M=t?["rank","rank"]:["rank"],T=[{type:12,data:i},{type:12,data:n.pastSequenceLength},{type:12,data:n.kvSequenceLength},{type:12,data:n.totalSequenceLength}],E=[p];w?(T.push(...It(e.dims),...It(t.dims),...It(s)),E.push(w)):T.push(...It(e.dims),...It(s));let L=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],G=` 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];`,z=` 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];`,ae=t?`if (s < past_seqlen) { + ${G} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${z} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${z} + }`,Q=oe=>` + + ${oe.registerUniforms(L).declareVariables(...E,d)} + ${oe.mainStart([g,n.kvNumHeads,1])} + ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${d.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 = ${n.kvNumHeads}u; + let H = ${g}u; + + let present_seqlen = uniforms.present_seqlen; + let present_batch_stride = present_seqlen * num_heads * H; + var row_stride = H; + let is_bsnh = ${n.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; + ${ae} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${n.kvNumHeads}${g}${!!t}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:l,programUniforms:T}),getShaderSource:Q}},Ru=e=>qt({...e}),Nu=qt({perm:[0,2,1,3]}),Na=(e,t,r,n,s)=>{let a=t,i=n.kvNumHeads,u=n.nReps;return t.dims.length===3&&n.kvSequenceLength!==0&&(a=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize])),r?a=e.compute(Ra(a,r,a.dataType,n),{inputs:[a,r],outputs:[n.isPastkvBSNH?s:-1]})[0]:a=e.compute(Ra(a,void 0,a.dataType,n),{inputs:[a],outputs:[n.isPastkvBSNH?s:-1]})[0],u!==1&&(a=e.compute(La([a],[1,1,1,u]),{inputs:[a],outputs:[-1]})[0],a=a.reshape([n.batchSize,n.totalSequenceLength,i*u,n.headSize])),e.compute(Ln(a,Nu.perm),{inputs:[a],outputs:[-1]})[0]},ju=(e,t)=>{var d;let r=Lu(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((d=e.inputs[1])==null?void 0:d.dims.length)===5)throw new Error("Packed KV is not implemented");let n=Rs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],void 0,0),s=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,i=Na(e,e.inputs[1],s,r,1),u=Na(e,e.inputs[2],a,r,2);As(e,n,i,u,void 0,void 0,void 0,void 0,void 0,r,t)}}),Rd,ja,Vu,Uu,Nd=j(()=>{Xt(),Qt(),ar(),Rd=(e,t)=>{let r=e[0].dims,n=r,s=2,a=Oe.sizeToDimension(r,s),i=Oe.sizeFromDimension(r,s),u=br(i),d=i/u,p=[r[0],r[1],d],w=["rank","type","type"],g=[{type:12,data:i},{type:12,data:d}];g.push(...It(p,p));let l=M=>{let T=Ze("x",e[0].dataType,p.length,u),E=Ze("scale",e[1].dataType,e[1].dims),L=Ze("bias",e[2].dataType,e[2].dims),G=Wt("output",e[0].dataType,p.length,u),z=[T,E,L,G],ae=T.type.value,Q=u===1?"f32":`vec${u}`,oe=64,Re=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${Q}, ${oe}>; + const workgroupSize = ${oe}u; + ${M.registerUniforms(Re).declareVariables(...z)} + ${M.mainStart(oe)} + let norm = global_idx / workgroupSize; + let batch = norm / uniforms.x_shape[1]; + let channel = norm % uniforms.x_shape[1]; + let localIndex = local_id.x; + + // initialize workgroup memory + var initial = ${Q}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${Q}(${T.get("batch","channel","h")}); + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the mean of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + meanShared = ${Sn("workgroupShared[0]",u)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${Q}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${Q}(${T.get("batch","channel","h")}) - ${Q}(meanShared); + initial = initial + deviation * deviation; + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the sum of square of deviation of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + squaredNormShared = ${Sn("workgroupShared[0]",u)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); + let channelScale = invStdDev * f32(${E.getByOffset("channel")}); + let channelShift = f32(${L.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${T.get("batch","channel","h")} * ${ae}(${Q}(channelScale)) + ${ae}(${Q}(channelShift)); + ${G.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${u}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:a},programUniforms:g}),getShaderSource:l}},ja=(e,t,r,n,s,a,i,u)=>{let d=br(i),p=64,w=d===1?"vec2f":`mat2x${d}f`,g=d===1?"f32":`vec${d}f`,l=(Re,Ne)=>`${w}(${Re}, ${Ne})`,M=s*i/d,T=Math.ceil(a/p),E=["type"],L=[{type:12,data:T},{type:12,data:a},{type:12,data:Math.floor(i/d)},{type:12,data:Math.floor(a*i/d)}],G=Re=>{let Ne=Ze("input",t.dataType,t.dims,d);return` + ${Re.declareVariables(Ne)} + @group(0) @binding(1) var output : array<${w}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${Re.mainStart(p)} + let currentImageNumber = global_idx / ${p} / uniforms.C; + let currentChannelNumber = (global_idx / ${p}) % uniforms.C; + let wgOffset = local_id.x * uniforms.wg_size; + if (wgOffset >= uniforms.H) { + return; + } + let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); + + let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; + var sum = ${Nr("f32",d)}; + var squaredSum = ${Nr("f32",d)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${g}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${l("sum","squaredSum")}; + }`},z=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${d}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:[s,i,p,2],dataType:1}],dispatchGroup:{x:s*i/d},programUniforms:L}),getShaderSource:G},{inputs:[t],outputs:[-1]})[0],ae=[{type:12,data:M},{type:12,data:a},{type:12,data:Math.floor(i/d)},{type:12,data:Math.floor(p*i/d)}],Q=["type","type","type"],oe=Re=>{let Ne=Ze("scale",r.dataType,r.dims,d),_t=Ze("bias",n.dataType,n.dims,d);return` + @group(0) @binding(0) var input : array<${w}>; + @group(0) @binding(1) var scale : array<${Ne.type.storage}>; + @group(0) @binding(2) var bias : array<${_t.type.storage}>; + @group(0) @binding(3) var output : array<${w}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${Re.mainStart()} + ${Re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} + let currentImageNumber = global_idx / uniforms.C; + let currentChannelNumber = global_idx % uniforms.C; + + let offset = currentImageNumber * uniforms.image_size; + var sum = ${Nr("f32",d)}; + var squaredSum = ${Nr("f32",d)}; + for (var i: u32 = 0; i < min(${p}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${p}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${u})); + let channelScale = invStdDev * ${g}(scale[currentChannelNumber]); + let channelShift = ${g}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${l("channelScale","channelShift")}; + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u}`,inputDependencies:Q},getRunData:()=>({outputs:[{dims:[s,i,2],dataType:1}],dispatchGroup:{x:Math.ceil(M/64)},programUniforms:ae}),getShaderSource:oe},{inputs:[z,r,n],outputs:[-1]})[0]},Vu=(e,t,r)=>{let n=t[0].dims,s=n,a=n[0],i=n[n.length-1],u=Oe.sizeFromDimension(n,1)/i,d=br(i),p=Oe.size(s)/d,w=[{type:12,data:u},{type:12,data:Math.floor(i/d)}],g=["type","type"],l=ja(e,t[0],t[1],t[2],a,u,i,r.epsilon),M=T=>{let E=Ar(t[0].dataType),L=d===1?"vec2f":`mat2x${d}f`,G=d===1?E:`vec${d}<${E}>`,z=Ze("input",t[0].dataType,t[0].dims,d),ae=Wt("output",t[0].dataType,s,d);return` + @group(0) @binding(0) var input : array<${z.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${L}>; + @group(0) @binding(2) var output : array<${ae.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${T.mainStart()} + let currentImageNumber = global_idx / (uniforms.C * uniforms.H); + let currentChannelNumber = global_idx % uniforms.C; + + let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; + let scale = scaleInput[scaleOffset]; + output[global_idx] = fma(input[global_idx], ${G}(scale[0]), ${G}(scale[1])); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:w}),getShaderSource:M},{inputs:[t[0],l]})},Uu=(e,t)=>{t.format==="NHWC"?Vu(e,e.inputs,t):e.compute(Rd(e.inputs,t))}}),Wu,Gu,qu,jd=j(()=>{Xt(),Qt(),ar(),Wu=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Gu=(e,t,r)=>{let n=t.simplified,s=e[0].dims,a=e[1],i=!n&&e[2],u=s,d=Oe.normalizeAxis(t.axis,s.length),p=Oe.sizeToDimension(s,d),w=Oe.sizeFromDimension(s,d),g=Oe.size(a.dims),l=i?Oe.size(i.dims):0;if(g!==w||i&&l!==w)throw new Error(`Size of X.shape()[axis:] == ${w}. + Size of scale and bias (if provided) must match this. + Got scale size of ${g} and bias size of ${l}`);let M=[];for(let oe=0;oe1,z=r>2,ae=oe=>{let Re=Ar(e[0].dataType),Ne=[Ze("x",e[0].dataType,e[0].dims,T),Ze("scale",a.dataType,a.dims,T)];i&&Ne.push(Ze("bias",i.dataType,i.dims,T)),Ne.push(Wt("output",e[0].dataType,u,T)),G&&Ne.push(Wt("mean_data_output",1,M)),z&&Ne.push(Wt("inv_std_output",1,M));let _t=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${oe.registerUniforms(_t).declareVariables(...Ne)} + ${oe.mainStart()} + ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Nr("f32",T)}; + var mean_square_vector = ${Nr("f32",T)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Xr(Re,T,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Sn("mean_vector",T)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Sn("mean_square_vector",T)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Xr(Re,T,"x[j + offset]")}; + let f32scale = ${Xr(Re,T,"scale[j]")}; + output[j + offset] = ${Ne[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Xr(Re,T,"bias[j]")}`:""} + ); + } + + ${G?"mean_data_output[global_idx] = mean":""}; + ${z?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},Q=[{dims:u,dataType:e[0].dataType}];return G&&Q.push({dims:M,dataType:1}),z&&Q.push({dims:M,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${T};${r};${n}`,inputDependencies:E},getRunData:()=>({outputs:Q,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:L}),getShaderSource:ae}},qu=(e,t)=>{Wu(e.inputs),e.compute(Gu(e.inputs,t,e.outputCount))}}),Hu,Ku,Xu,Qu,Vd=j(()=>{Xt(),Qt(),pr(),ar(),Hu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let s=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!Oe.areEqual(i.dims,[t.n,s,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(Oe.size(u)!==t.n*s)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,p=t.bits>4?t.n*s:t.n*Math.floor((s+1)/2);if(Oe.size(d)!==p)throw new Error("zeroPoints input size error.")}},Ku=(e,t)=>{let r=e[0].dims,n=r.length,s=r[n-2],a=t.k,i=t.n,u=r.slice(0,n-2),d=Oe.size(u),p=e[1].dims[2]/4,w=e[0].dataType,g=br(t.k),l=br(p),M=br(i),T=u.concat([s,i]),E=s>1&&i/M%2===0?2:1,L=Oe.size(T)/M/E,G=64,z=[],ae=[d,s,a/g],Q=Oe.convertShape(e[1].dims).slice();Q.splice(-1,1,p/l),z.push(...It(ae)),z.push(...It(Q)),z.push(...It(e[2].dims)),e.length===4&&z.push(...It(Oe.convertShape(e[3].dims)));let oe=[d,s,i/M];z.push(...It(oe));let Re=Ne=>{let _t=ae.length,Dt=Ze("a",e[0].dataType,_t,g),Vt=Ze("b",12,Q.length,l),lr=Ze("scales",e[2].dataType,e[2].dims.length),fr=[Dt,Vt,lr],tr=e.length===4?Ze("zero_points",12,e[3].dims.length):void 0;tr&&fr.push(tr);let Vr=oe.length,Qr=Wt("output",e[0].dataType,Vr,M),Mr=Ar(e[0].dataType),Wr=(()=>{switch(g){case 1:return`array<${Mr}, 8>`;case 2:return`mat4x2<${Mr}>`;case 4:return`mat2x4<${Mr}>`;default:throw new Error(`${g}-component is not supported.`)}})(),Zt=()=>{let Ue=` + // reuse a data + var input_offset = ${Dt.indicesToOffset(`${Dt.type.indices}(batch, row, word_offset)`)}; + var a_data: ${Wr}; + for (var j: u32 = 0; j < ${8/g}; j++) { + a_data[j] = ${Dt.getByOffset("input_offset")}; + input_offset++; + } + `;for(let $t=0;$t> 4) & b_mask); + b_quantized_values = ${Wr}(${Array.from({length:4},(rr,Ur)=>`${Mr}(b_value_lower[${Ur}]), ${Mr}(b_value_upper[${Ur}])`).join(", ")}); + b_dequantized_values = ${g===1?`${Wr}(${Array.from({length:8},(rr,Ur)=>`(b_quantized_values[${Ur}] - ${tr?`zero_point${$t}`:"zero_point"}) * scale${$t}`).join(", ")});`:`(b_quantized_values - ${Wr}(${Array(8).fill(`${tr?`zero_point${$t}`:"zero_point"}`).join(",")})) * scale${$t};`}; + workgroup_shared[local_id.x * ${E} + ${Math.floor($t/M)}]${M>1?`[${$t%M}]`:""} += ${Array.from({length:8/g},(rr,Ur)=>`${g===1?`a_data[${Ur}] * b_dequantized_values[${Ur}]`:`dot(a_data[${Ur}], b_dequantized_values[${Ur}])`}`).join(" + ")}; + `;return Ue},dr=()=>{let Ue=` + var col_index = col * ${M}; + ${tr?` + 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 = ${Mr}(8);`} + `;for(let $t=0;$t> 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 = ${tr.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${$t} = ${Mr}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return Ue},Or=()=>{let Ue=`col_index = col * ${M};`;for(let $t=0;$t; + var b_value_upper: vec4; + var b_quantized_values: ${Wr}; + var b_dequantized_values: ${Wr};`,Ue};return` + var workgroup_shared: array<${Qr.type.value}, ${E*G}>; + ${Ne.declareVariables(...fr,Qr)} + ${Ne.mainStart([G,1,1])} + let output_indices = ${Qr.offsetToIndices(`(global_idx / ${G}) * ${E}`)}; + 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 += ${G}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/g}; + ${dr()} + for (var word: u32 = 0; word < ${p}; word += ${l}) { + ${Or()} + for (var i: u32 = 0; i < ${l}; i++) { + ${Zt()} + word_offset += ${8/g}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${E}) { + var output_value: ${Qr.type.value} = ${Qr.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${G}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${E}; + } + ${Qr.setByIndices(`${Qr.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${g};${l};${M};${E};${G}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:T,dataType:w}],dispatchGroup:{x:L},programUniforms:z}),getShaderSource:Re}},Xu=(e,t)=>{Hu(e.inputs,t),e.compute(Ku(e.inputs,t))},Qu=e=>qt(e)}),Yu,Zu,Ju,ed,td,rd,nd,sd,id,Ud=j(()=>{Xt(),Qt(),ar(),Yu=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].")}},Zu=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; + if (k < 0) { + break; + } + if (k >= i32(${jt("uniforms.x_shape",s,t)})) { + break; + } + offset += k * i32(${jt("uniforms.x_strides",s,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},Ju=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${jt("uniforms.x_shape",s,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${jt("uniforms.x_shape",s,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${jt("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},ed=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${jt("uniforms.x_shape",s,t)})) { + k = i32(${jt("uniforms.x_shape",s,t)}) - 1; + } + offset += k * i32(${jt("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},td=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; + if (k < 0) { + k += i32(${jt("uniforms.x_shape",s,t)}]); + } + if (k >= i32(${jt("uniforms.x_shape",s,t)})) { + k -= i32(${jt("uniforms.x_shape",s,t)}); + } + offset += k * i32(${jt("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},rd=(e,t,r)=>{switch(r.mode){case 0:return Zu(e,t,r.pads.length);case 1:return Ju(e,t,r.pads.length);case 2:return ed(e,t,r.pads.length);case 3:return td(e,t,r.pads.length);default:throw new Error("Invalid mode")}},nd=(e,t)=>{let r=Oe.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,s=Oe.size(r),a=[{type:12,data:s},{type:6,data:t.pads}],i=e.length>=3&&e[2].data;t.mode===0&&a.push({type:i?e[2].dataType:1,data:t.value}),a.push(...It(e[0].dims,r));let u=["rank"],d=p=>{let w=Wt("output",e[0].dataType,r.length),g=Ze("x",e[0].dataType,n.length),l=g.type.value,M=rd(w,n.length,t),T=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&T.push({name:"constant_value",type:i?l:"f32"}),` + ${p.registerUniforms(T).declareVariables(g,w)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${w.offsetToIndices("global_idx")}; + + var value = ${l}(0); + ${M} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${i}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Oe.size(r)/64)},programUniforms:a}),getShaderSource:d}},sd=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,s=e[0].dims.length,a=new Int32Array(2*s).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;da[Number(d)]=Number(u));let i=[];return a.forEach(u=>i.push(u)),{mode:t.mode,value:n,pads:i}}else return t},id=(e,t)=>{Yu(e.inputs);let r=sd(e.inputs,t);e.compute(nd(e.inputs,r),{inputs:[0]})}}),Ns,Va,Ua,Wa,Ga,Wd,or,qa,en,dn,hn,Jn,Gd,ad,Ha,f,m,S,Z,Fe=j(()=>{bt(),Xt(),Qt(),ar(),Ns=e=>{if(k.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Va=(e,t,r)=>{let n=t.format==="NHWC",s=e.dims.slice();n&&s.splice(1,0,s.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),u=t.strides.slice(),d=a?t.dilations.slice():[],p=t.pads.slice();$n.adjustPoolAttributes(r,s,i,u,d,p);let w=$n.computePoolOutputShape(r,s,u,d,i,p,t.autoPad),g=Object.assign({},t);a?Object.assign(g,{kernelShape:i,strides:u,pads:p,dilations:d,cacheKey:t.cacheKey}):Object.assign(g,{kernelShape:i,strides:u,pads:p,cacheKey:t.cacheKey});let l=w.slice();return l.push(l.splice(1,1)[0]),[g,n?l:w]},Ua=(e,t)=>{let r=t.format==="NHWC",n=Oe.size(e),s=Oe.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:s}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],w=t.pads[t.pads.length-1],g=!!(p+w);a.push({type:12,data:u},{type:12,data:d},{type:12,data:p},{type:12,data:w}),i.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 M=t.kernelShape[t.kernelShape.length-2],T=t.strides[t.strides.length-2],E=t.pads[t.pads.length/2-2],L=t.pads[t.pads.length-2];l=!!(E+L),a.push({type:12,data:M},{type:12,data:T},{type:12,data:E},{type:12,data:L}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,g,l]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=Oe.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((p,w)=>p+w);return[a,i,!!d,!1,!1]}},Wa=(e,t,r,n,s,a,i,u,d,p,w,g)=>{let l=s.format==="NHWC",M=t.type.value,T=Wt("output",t.type.tensor,n);if(s.kernelShape.length<=2){let E="",L="",G="",z=r-(l?2:1);if(w?E=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${z}] = indices[${z}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${z}] < 0 || xIndices[${z}] + >= uniforms.x_shape[${z}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:E=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${z}] = indices[${z}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`,s.kernelShape.length===2){let ae=r-(l?3:2);g?L=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ae}] = indices[${ae}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${ae}] < 0 || xIndices[${ae}] >= uniforms.x_shape[${ae}]) { + pad += i32(uniforms.kw); + continue; + } + `:L=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ae}] = indices[${ae}] * uniforms.sh - uniforms.phStart + j; + `,G=` + } + `}return` + ${e.registerUniforms(d).declareVariables(t,T)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${T.offsetToIndices("global_idx")}; + var xIndices = ${T.offsetToIndices("global_idx")}; + + var value = ${M}(${u}); + var pad = 0; + ${L} + ${E} + ${G} + ${i} + + output[global_idx] = value; + }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let E=s.kernelShape.length,L=s.pads.length,G="";return p?G=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:G=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + `,` + ${e.registerUniforms(d).declareVariables(t,T)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${T.offsetToIndices("global_idx")}; + var xIndices = ${T.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${M}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${E-1}u; j++) { + offsets[j] = offset / ${jt("uniforms.kernelStrides","j",E)}; + offset -= offsets[j] * ${jt("uniforms.kernelStrides","j",E)}; + } + offsets[${E-1}] = offset; + + isPad = false; + for (var j = ${r-E}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${jt("uniforms.strides",`j - ${r-E}u`,E)} + + offsets[j - ${r-E}u] - ${jt("uniforms.pads","j - 2u",L)}; + ${G} + } + ${i} + + output[global_idx] = value; + }`}},Ga=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Wd=e=>`${Ga(e)};${e.countIncludePad}`,or=e=>`${Ga(e)};${e.storageOrder};${e.dilations}`,qa=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}),en=(e,t,r,n)=>{let[s,a]=Va(t,n,r),i=Ze("x",t.dataType,t.dims.length),u=i.type.value,d="value += x_val;",p="";s.countIncludePad?p+=`value /= ${u}(uniforms.kernelSize);`:p+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[w,g,l,M,T]=Ua(a,s);w.push(...It(t.dims,a));let E=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${l};${M};${T}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Oe.size(a)/64)},programUniforms:w}),getShaderSource:L=>Wa(L,i,t.dims.length,a.length,s,d,p,0,g,l,M,T)}},dn=e=>{let t=e.count_include_pad!==0,r=qa(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:Wd(n)}},hn=(e,t)=>{Ns(e.inputs),e.compute(en("AveragePool",e.inputs[0],!1,t))},Jn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Gd=e=>{let t=e.format;return{format:t,...Jn,cacheKey:t}},ad=(e,t)=>{Ns(e.inputs),e.compute(en("GlobalAveragePool",e.inputs[0],!0,t))},Ha=(e,t,r,n)=>{let[s,a]=Va(t,n,r),i=` + value = max(x_val, value); + `,u="",d=Ze("x",t.dataType,t.dims.length),p=["rank"],[w,g,l,M,T]=Ua(a,s);return w.push(...It(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${l};${M};${T}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Oe.size(a)/64)},programUniforms:w}),getShaderSource:E=>Wa(E,d,t.dims.length,a.length,s,i,u,t.dataType===10?-65504:-1e5,g,l,M,T)}},f=(e,t)=>{Ns(e.inputs),e.compute(Ha("MaxPool",e.inputs[0],!1,t))},m=e=>{let t=e.storage_order,r=e.dilations,n=qa(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let s={storageOrder:t,dilations:r,...n,cacheKey:""};return{...s,cacheKey:or(s)}},S=e=>{let t=e.format;return{format:t,...Jn,cacheKey:t}},Z=(e,t)=>{Ns(e.inputs),e.compute(Ha("GlobalMaxPool",e.inputs[0],!0,t))}}),ze,pt,Ct,Ut,sr=j(()=>{Xt(),Qt(),pr(),ar(),ze=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((s,a)=>a===t.axis||s===e[0].dims[a]).reduce((s,a)=>s&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},pt=(e,t)=>{let r=Oe.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,s=n===3,a=e[0].dims,i=e[1].dataType,u=Oe.size(a),d=n===3||n===2,p=d?[Math.ceil(Oe.size(e[0].dims)/4)]:e[0].dims,w=e[1].dims,g=e.length>2?e[2]:void 0,l=g?d?[Math.ceil(Oe.size(g.dims)/4)]:g.dims:void 0,M=w.length===0||w.length===1&&w[0]===1,T=M===!1&&w.length===1,E=br(u),L=M&&(!d||E===4),G=L?E:1,z=L&&!d?E:1,ae=Ze("input",d?12:n,p.length,z),Q=Ze("scale",i,w.length),oe=g?Ze("zero_point",d?12:n,l.length):void 0,Re=Wt("output",i,a.length,G),Ne=[ae,Q];oe&&Ne.push(oe);let _t=[p,w];g&&_t.push(l);let Dt=[{type:12,data:u/G},{type:12,data:r},{type:12,data:t.blockSize},...It(..._t,a)],Vt=lr=>{let fr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${lr.registerUniforms(fr).declareVariables(...Ne,Re)} + ${lr.mainStart()} + ${lr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Re.offsetToIndices("global_idx")}; + + // Set input x + ${d?` + let input = ${ae.getByOffset("global_idx / 4")}; + let x_vec = ${s?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${G===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ae.getByOffset("global_idx")};`}; + + // Set scale input + ${M?`let scale_value= ${Q.getByOffset("0")}`:T?` + let scale_index = ${Re.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${Q.getByOffset("scale_index")};`:` + var scale_indices: ${Q.type.indices} = output_indices; + let index = ${Q.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${Q.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${Q.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${oe?M?d?` + let zero_point_input = ${oe.getByOffset("0")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${oe.getByOffset("0")}`:T?d?` + let zero_point_index = ${Re.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${oe.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Re.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${oe.getByOffset("zero_point_index")};`:d?` + let zero_point_offset = ${Q.indicesToOffset("scale_indices")}; + let zero_point_input = ${oe.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${oe.getByIndices("scale_indices")};`:`let zero_point_value = ${d?s?"i32":"u32":ae.type.value}(0);`}; + // Compute and write output + ${Re.setByOffset("global_idx",`${Re.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:oe?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Vt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(u/G/64),y:1,z:1},programUniforms:Dt})}},Ct=(e,t)=>{ze(e.inputs,t),e.compute(pt(e.inputs,t))},Ut=e=>qt({axis:e.axis,blockSize:e.blockSize})}),Ir,ur,hr,wr=j(()=>{bt(),Xt(),ar(),Ir=(e,t,r)=>{let n=e===t,s=et&&r>0;if(n||s||a)throw new Error("Range these inputs' contents are invalid.")},ur=(e,t,r,n)=>{let s=Math.abs(Math.ceil((t-e)/r)),a=[s],i=s,u=[{type:12,data:i},{type:n,data:e},{type:n,data:r},...It(a)],d=p=>{let w=Wt("output",n,a.length),g=w.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:g},{name:"delta",type:g}];return` + ${p.registerUniforms(l).declareVariables(w)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${g}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:u})}},hr=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),k.webgpu.validateInputContent&&Ir(t,r,n),e.compute(ur(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),$r,Fr,kr,_r,tn,rn,wn,cn,an,yn,ws,js,Ka,bc,Rn,ys,qd,Hd,Kd,Xd=j(()=>{Xt(),Qt(),pr(),ar(),$r=(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")}},Fr=(e,t,r)=>{t.every(s=>s>=0&&s{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((s,a)=>n[s]=e[a]),n},kr=(e,t,r,n,s,a)=>{let[i,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(w=>a.push(w));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>0){if(e[u].getFloat32Array().forEach(w=>n.push(w)),n.length!==0&&n.length!==p&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");$r(n,t),t.axes.length>0&&Fr(n,t.axes,p).forEach((w,g)=>n[g]=w)}if(d>0&&e.length>d&&(e[d].getBigInt64Array().forEach(w=>s.push(Number(w))),s.length!==p||r>=18&&s.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(s.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof s<"u"&&n.length>0&&s.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},_r=(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`)}})()+"}",tn=(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`)}})()+"}",rn=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),s=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=s[i],n[i+r]=s[t.length+i]}),n):s},wn=(e,t,r,n)=>{let s=[];if(r.length>0)if(n.length>0){if(e.forEach(a=>s.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>s[a]=r[i])}else r.forEach(a=>s.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");s=e.map((a,i)=>Math.round(a*t[i]))}return s},cn=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let s=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.axes.forEach(a=>s[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),s.forEach((a,i)=>s[i]=Math.round(a*t[i]))),s},an=(e,t,r,n,s)=>` + 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 = ${jt("uniforms.scales","i",n)}; + var roi_low = ${jt("uniforms.roi","i",s)}; + var roi_hi = ${jt("uniforms.roi",`i + ${t.length}`,s)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${jt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${jt("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; + }`,yn=(e,t,r,n,s,a,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${jt("uniforms.scales","i",s)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${jt("uniforms.roi","i",a)}; + var roi_hi = ${jt("uniforms.roi",`i + ${r.length}`,a)}; + var input_shape_i = ${jt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${jt("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,ws=(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 >= ${jt("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,js=(e,t,r,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",r,"batch")}; +`:"",Ka=(e,t,r,n,s)=>{let[a,i,u,d]=r.length===2?[-1,0,1,-1]:[0,2,3,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${r[i]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; + ${js(e,d,a,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${p} = originalIndices[${i}]; + var col:${p} = originalIndices[${u}]; + ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[u]} - 1)) { + return ${s}; + }`:""}; + row = max(0, min(row, ${r[i]} - 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[${d}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; + var x11: ${p} = getInputValue(batch, channel, row1, col1); + var x12: ${p} = getInputValue(batch, channel, row1, col2); + var x21: ${p} = getInputValue(batch, channel, row2, col1); + var x22: ${p} = getInputValue(batch, channel, row2, col2); + var dx1: ${p} = abs(row - ${p}(row1)); + var dx2: ${p} = abs(${p}(row2) - row); + var dy1: ${p} = abs(col - ${p}(col1)); + var dy2: ${p} = abs(${p}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},bc=(e,t,r,n,s,a,i,u,d,p)=>{let w=r.length===2,[g,l]=w?[0,1]:[2,3],M=e.type.value,T=E=>{let L=E===g?"row":"col";return` + fn ${L}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${M} { + var output_index = ${t.indicesGet("output_indices",E)}; + var originalIdx: ${M} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[E]}, + ${n[E]}, ${r[E]}, ${a[E]}, ${a[E]} + ${r.length}); + var fractOriginalIdx: ${M} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${r[E]} - 1))) { + return ${d}; + } + var data: array<${M}, 4> = array<${M}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${L}: ${M} = originalIdx + ${M}(i); + if (${L} < 0 || ${L} >= ${r[E]}) { + ${p?`coefs[i + 1] = 0.0; + continue;`:u?`return ${d};`:`${L} = max(0, min(${L}, ${r[E]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",E,`u32(${L})`)}; + data[i + 1] = ${E===g?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${T(g)}; + ${T(l)}; + fn getCubicInterpolationCoefs(s: ${M}) -> array<${M}, 4> { + var absS = abs(s); + var coeffs: array<${M}, 4> = array<${M}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${M} = 1.0 - absS; + var twoMinusAbsS: ${M} = 2.0 - absS; + var onePlusAbsS: ${M} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${M}, 4>, coefs: array<${M}, 4>) -> ${M} { + var coefsSum: ${M} = 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}) -> ${M} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Rn=(e,t,r,n,s)=>{let[a,i,u,d,p]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],w=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${w} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${r[i]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; + ${e.indicesSet("input_indices",d,`max(0, min(width, ${r[d]} - 1))`)}; + ${js(e,p,a,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${w} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${w} = originalIndices[${i}]; + var height:${w} = originalIndices[${u}]; + var width:${w} = originalIndices[${d}]; + ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { + return ${s}; + }`:""}; + + depth = max(0, min(depth, ${r[i]} - 1)); + height = max(0, min(height, ${r[u]} - 1)); + width = max(0, min(width, ${r[d]} - 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[${p}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; + + var x111: ${w} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${w} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${w} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${w} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${w} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${w} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${w} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${w} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${w} = abs(depth - ${w}(depth1)); + var dx2: ${w} = abs(${w}(depth2) - depth); + var dy1: ${w} = abs(height - ${w}(height1)); + var dy2: ${w} = abs(${w}(height2) - height); + var dz1: ${w} = abs(width - ${w}(width1)); + var dz2: ${w} = abs(${w}(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); + }`},ys=(e,t,r,n,s,a)=>{let i=e.dims,u=rn(a,t.axes,i.length),d=wn(i,n,s,t.axes),p=n.slice();n.length===0&&(p=i.map((z,ae)=>z===0?1:d[ae]/z),t.keepAspectRatioPolicy!=="stretch"&&(d=cn(i,p,t)));let w=Wt("output",e.dataType,d.length),g=Ze("input",e.dataType,i.length),l=Oe.size(d),M=i.length===d.length&&i.every((z,ae)=>z===d[ae]),T=t.coordinateTransformMode==="tf_crop_and_resize",E=t.extrapolationValue,L=g.type.value,G=z=>` + ${M?"":` + ${_r(t.coordinateTransformMode,L)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${ws(g,i)}; + ${tn(t.nearestMode,r,L)}; + ${yn(g,w,i,d,p.length,u.length,T)}; + `;case"linear":return` + ${an(w,i,d,p.length,u.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${Ka(g,w,i,T,E)}`;if(i.length===3||i.length===5)return`${Rn(g,w,i,T,E)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${bc(g,w,i,d,p,u,t.cubicCoeffA,T,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")}})()}; + `} + ${z.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",u.length).declareVariables(g,w)} + ${z.mainStart()} + ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${M?"output[global_idx] = input[global_idx];":` + let output_indices = ${w.offsetToIndices("global_idx")}; + var input_indices: ${g.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${g.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${s.length>0?s:""}|${u.length>0?u:""}|${M}|${i}`,inputDependencies:["rank"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:p},{type:1,data:u},...It(i,d)]})}},qd=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Hd=(e,t)=>{let r=[],n=[],s=[],a=qd(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");kr(e.inputs,t,a,r,n,s),e.compute(ys(e.inputs[0],t,a,r,n,s),{inputs:[0]})},Kd=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,s=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return qt({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:s,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:u,mode:d,nearestMode:p})}}),tp,rp,np,Af=j(()=>{Xt(),Qt(),pr(),ar(),tp=(e,t)=>{let[r,n,s,a]=e,{numHeads:i,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(!Oe.areEqual(n.dims,[])&&!Oe.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(s.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Oe.areEqual(s.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],p=r.dims[r.dims.length-2],w=s.dims[0],g=Oe.sizeFromDimension(r.dims,1)/p,l=u===0?s.dims[1]*2:g/i;if(u>l)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(p!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(l/2!==s.dims[1]&&u/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(p>w)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},rp=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:s,scale:a}=t,i=e[0].dims[0],u=Oe.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],p=u/d,w=e[2].dims[1],g=s===0?w*2:p/n,l=new Array(i,d,p/g,g-w),M=Oe.computeStrides(l),T=[{type:1,data:a},{type:12,data:l},{type:12,data:M},...e[0].dims.length===3?new Array({type:12,data:[u,p,g,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,g,d*g,1]}):[],...It(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],E=L=>{let G=Ze("input",e[0].dataType,e[0].dims.length),z=Ze("position_ids",e[1].dataType,e[1].dims.length),ae=Ze("cos_cache",e[2].dataType,e[2].dims.length),Q=Ze("sin_cache",e[3].dataType,e[3].dims.length),oe=Wt("output",e[0].dataType,e[0].dims.length);return L.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:M.length},{name:"input_output_strides",type:"u32",length:M.length}]),` + ${L.declareVariables(G,z,ae,Q,oe)} + + ${L.mainStart(Tn)} + let half_rotary_emb_dim = uniforms.${ae.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${L.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${z.broadcastedIndicesToOffset("bsnh.xy",Wt("",z.type.tensor,2))}; + let position_id = + u32(${z.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 = ${G.getByOffset("i")} * ${ae.get("position_id","bsnh[3]")} - + ${G.getByOffset("j")} * ${Q.get("position_id","bsnh[3]")}; + ${oe.setByOffset("i","re")} + let im = ${G.getByOffset("i")} * ${Q.get("position_id","bsnh[3]")} + + ${G.getByOffset("j")} * ${ae.get("position_id","bsnh[3]")}; + ${oe.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${oe.setByOffset("k",G.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:qt({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Oe.size(l)/Tn)},programUniforms:T})}},np=(e,t)=>{tp(e.inputs,t),e.compute(rp(e.inputs,t))}}),sp,ip,ap,If=j(()=>{Xt(),Qt(),ar(),sp=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let s=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==s)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==s)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},ip=(e,t,r,n)=>{let s=t.simplified,a=e[0].dims,i=Oe.size(a),u=a,d=i,p=a.slice(-1)[0],w=n?a.slice(0,-1).concat(1):[],g=!s&&e.length>3,l=e.length>4,M=n&&r>1,T=n&&r>2,E=r>3,L=64,G=br(p),z=[{type:12,data:d},{type:12,data:G},{type:12,data:p},{type:1,data:t.epsilon}],ae=oe=>{let Re=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ne=[Ze("x",e[0].dataType,e[0].dims,G),Ze("skip",e[1].dataType,e[1].dims,G),Ze("gamma",e[2].dataType,e[2].dims,G)];g&&Ne.push(Ze("beta",e[3].dataType,e[3].dims,G)),l&&Ne.push(Ze("bias",e[4].dataType,e[4].dims,G)),Ne.push(Wt("output",e[0].dataType,u,G)),M&&Ne.push(Wt("mean_output",1,w)),T&&Ne.push(Wt("inv_std_output",1,w)),E&&Ne.push(Wt("input_skip_bias_sum",e[0].dataType,u,G));let _t=Ar(e[0].dataType),Dt=Ar(1,G);return` + + ${oe.registerUniforms(Re).declareVariables(...Ne)} + var sum_shared : array<${Dt}, ${L}>; + var sum_squared_shared : array<${Dt}, ${L}>; + + ${oe.mainStart([L,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${L}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${L}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${L-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]":_t+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${E?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Xr(_t,G,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${L}; + 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 = ${Sn("sum",G)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Sn("square_sum",G)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); + ${M?"mean_output[global_idx] = mean;":""} + ${T?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${s?"":`- ${_t}(mean)`}) * + ${_t}(inv_std_dev) * gamma[offset1d + i] + ${g?"+ beta[offset1d + i]":""}; + } + }`},Q=[{dims:u,dataType:e[0].dataType}];return r>1&&Q.push({dims:w,dataType:1}),r>2&&Q.push({dims:w,dataType:1}),r>3&&Q.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${G};${M};${T};${E}`,inputDependencies:e.map((oe,Re)=>"type")},getShaderSource:ae,getRunData:()=>({outputs:Q,dispatchGroup:{x:Math.ceil(d/p)},programUniforms:z})}},ap=(e,t)=>{sp(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(ip(e.inputs,t,e.outputCount,!1),{outputs:r})}}),op,od,lp,Mc,up,dp,cp,pp,Ff=j(()=>{Xt(),Qt(),pr(),ar(),op=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},od=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},lp=(e,t)=>{if(e.length>1){let r=od(e,1),n=od(e,2),s=od(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),qt({starts:r,ends:n,axes:s})}else return t},Mc=(e,t,r,n,s)=>{let a=e;return e<0&&(a+=r[n[t]]),s[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},up=(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 = ${jt("uniforms.input_shape","i",r.length)}; + let steps_i = ${jt("uniforms.steps","i",r.length)}; + let signs_i = ${jt("uniforms.signs","i",r.length)}; + let starts_i = ${jt("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; + }`,dp=(e,t)=>{let r=e[0].dims,n=Oe.size(r),s=t.axes.length>0?Oe.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=od(e,4);a.forEach(G=>G!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(s.length).fill(1));let i=t.starts.map((G,z)=>Mc(G,z,r,s,a)),u=t.ends.map((G,z)=>Mc(G,z,r,s,a));if(s.length!==i.length||s.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==r.length)for(let G=0;GMath.sign(G));a.forEach((G,z,ae)=>{if(G<0){let Q=(u[z]-i[z])/G,oe=i[z],Re=oe+Q*a[z];i[z]=Re,u[z]=oe,ae[z]=-G}});let p=r.slice(0);s.forEach((G,z)=>{p[G]=Math.ceil((u[G]-i[G])/a[G])});let w={dims:p,dataType:e[0].dataType},g=Wt("output",e[0].dataType,p.length),l=Ze("input",e[0].dataType,e[0].dims.length),M=Oe.size(p),T=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:a.length}],E=[{type:12,data:M},{type:12,data:i},{type:6,data:d},{type:12,data:a},...It(e[0].dims,p)],L=G=>` + ${G.registerUniforms(T).declareVariables(l,g)} + ${up(l,g,r)} + ${G.mainStart()} + ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${g.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${g.setByOffset("global_idx",l.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:L,getRunData:()=>({outputs:[w],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:E})}},cp=(e,t)=>{op(e.inputs,t);let r=lp(e.inputs,t);e.compute(dp(e.inputs,r),{inputs:[0]})},pp=e=>{let t=e.starts,r=e.ends,n=e.axes;return qt({starts:t,ends:r,axes:n})}}),hp,fp,mp,_p,Of=j(()=>{Xt(),Qt(),pr(),ar(),hp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},fp=(e,t)=>{let r=e.dims,n=Oe.size(r),s=64,a=t.axis;if(a<0&&(a=r.length+a),aG===4?`max(max(${L}.x, ${L}.y), max(${L}.z, ${L}.w))`:G===2?`max(${L}.x, ${L}.y)`:G===3?`max(max(${L}.x, ${L}.y), ${L}.z)`:L,g=Ze("x",e.dataType,e.dims,d),l=Wt("result",e.dataType,e.dims,d),M=g.type.value,T=Ar(e.dataType)==="f32"?`var threadMax = ${M}(-3.402823e+38f);`:`var threadMax = ${M}(-65504.0h);`,E=L=>` + var rowMaxShared : ${M}; + var rowSumShared : ${M}; + var threadShared : array<${M}, ${s}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${M} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${M}) { + let index = row * row_stride + col; + result[index] = value; + } + ${L.registerUniform("packedCols","i32").declareVariables(g,l)} + ${L.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${s}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${T} + 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 = ${M}(${w("threadShared[0]",d)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${M}(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 = ${M}(${Sn("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); + } + }`;return{name:"Softmax",shaderCache:{hint:`${d}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:p}]}),getShaderSource:E}},mp=(e,t)=>{hp(e.inputs),e.compute(fp(e.inputs[0],t))},_p=e=>qt({axis:e.axis})}),gp,wp,yp,bp,Mp,vp,xp,zf=j(()=>{Xt(),Qt(),pr(),ar(),gp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},wp=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),n=r.length),qt({numOutputs:n,axis:t.axis,splitSizes:r})},yp=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${jt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,bp=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=Oe.size(r),s=e[0].dataType,a=Oe.normalizeAxis(t.axis,r.length),i=new Array(t.numOutputs),u=Ze("input",s,r.length),d=new Array(t.numOutputs),p=[],w=[],g=0,l=[{type:12,data:n}];for(let T=0;T` + ${T.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...i)} + ${yp(d.length)} + ${bp(i)} + + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",a)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${jt("uniforms.size_in_split_axis","output_number - 1u",d.length)}; + ${u.indicesSet("indices",a,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:l})}},vp=(e,t)=>{gp(e.inputs);let r=e.inputs.length===1?t:wp(e.inputs,t);e.compute(Mp(e.inputs,r),{inputs:[0]})},xp=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qt({axis:t,numOutputs:n,splitSizes:r})}}),Tp,Sp,Cp,Df=j(()=>{Xt(),Qt(),ar(),Tp=(e,t,r,n,s)=>{let a=Wt("output_data",s,r.length,4),i=Ze("a_data",t[1].dataType,t[1].dims.length,4),u=Ze("b_data",t[2].dataType,t[2].dims.length,4),d=Ze("c_data",t[0].dataType,t[0].dims.length,4),p,w=(g,l,M)=>`select(${l}, ${g}, ${M})`;if(!n)p=a.setByOffset("global_idx",w(i.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let g=(l,M,T="")=>{let E=`a_data[index_a${M}][component_a${M}]`,L=`b_data[index_b${M}][component_b${M}]`,G=`bool(c_data[index_c${M}] & (0xffu << (component_c${M} * 8)))`;return` + let output_indices${M} = ${a.offsetToIndices(`global_idx * 4u + ${M}u`)}; + let offset_a${M} = ${i.broadcastedIndicesToOffset(`output_indices${M}`,a)}; + let offset_b${M} = ${u.broadcastedIndicesToOffset(`output_indices${M}`,a)}; + let offset_c${M} = ${d.broadcastedIndicesToOffset(`output_indices${M}`,a)}; + let index_a${M} = offset_a${M} / 4u; + let index_b${M} = offset_b${M} / 4u; + let index_c${M} = offset_c${M} / 4u; + let component_a${M} = offset_a${M} % 4u; + let component_b${M} = offset_b${M} % 4u; + let component_c${M} = offset_c${M} % 4u; + ${l}[${M}] = ${T}(${w(E,L,G)}); + `};s===9?p=` + var data = vec4(0); + ${g("data",0,"u32")} + ${g("data",1,"u32")} + ${g("data",2,"u32")} + ${g("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=` + ${g("output_data[global_idx]",0)} + ${g("output_data[global_idx]",1)} + ${g("output_data[global_idx]",2)} + ${g("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(d,i,u,a)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${p} + }`},Sp=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,s=e[1].dataType,a=!(Oe.areEqual(t,r)&&Oe.areEqual(r,n)),i=t,u=Oe.size(t);if(a){let p=ln.calcShape(ln.calcShape(t,r,!1),n,!1);if(!p)throw new Error("Can't perform where op on the given tensors");i=p,u=Oe.size(i)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>Tp(p,e,i,a,s),getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...It(n,t,r,i)]})}},Cp=e=>{e.compute(Sp(e.inputs))}}),Ep,Bf=j(()=>{Oo(),Wi(),gd(),Wo(),wd(),yd(),Fl(),xd(),iu(),Ed(),$d(),wu(),Pd(),Ad(),Id(),yc(),zd(),Dd(),Ld(),Nd(),jd(),Kl(),Vd(),Fu(),Ud(),Fe(),sr(),wr(),Li(),Xd(),Af(),If(),Ff(),Of(),zf(),Bu(),ss(),aa(),Df(),Ep=new Map([["Abs",[qo]],["Acos",[Ho]],["Acosh",[Hi]],["Add",[ua]],["ArgMax",[Fo,ji]],["ArgMin",[Ni,ji]],["Asin",[Ko]],["Asinh",[Xo]],["Atan",[Qo]],["Atanh",[Yo]],["Attention",[Lo]],["AveragePool",[hn,dn]],["BatchNormalization",[qi]],["BiasAdd",[Uo]],["BiasSplitGelu",[yl]],["Cast",[Zo,Ki]],["Ceil",[el]],["Clip",[Xi]],["Concat",[Al,Il]],["Conv",[ba,wa]],["ConvTranspose",[su,eu]],["Cos",[tl]],["Cosh",[Qi]],["CumSum",[ou,Ta]],["DepthToSpace",[du,cu]],["DequantizeLinear",[Ct,Ut]],["Div",[Ml]],["Einsum",[_u,gu]],["Elu",[rl,Is]],["Equal",[vl]],["Erf",[nl]],["Exp",[sl]],["Expand",[bu]],["FastGelu",[Mu]],["Floor",[Yi]],["FusedConv",[ba,wa]],["Gather",[Ia,xu]],["GatherElements",[Eu,Fa]],["GatherBlockQuantized",[Cu,Dr]],["Gelu",[il]],["Gemm",[za,Oa]],["GlobalAveragePool",[ad,Gd]],["GlobalMaxPool",[Z,S]],["Greater",[Sl]],["GreaterOrEqual",[El]],["GroupQueryAttention",[ju,Ru]],["HardSigmoid",[ea,ul]],["InstanceNormalization",[Uu]],["LayerNormalization",[qu]],["LeakyRelu",[al,Is]],["Less",[Cl]],["LessOrEqual",[da]],["Log",[sa]],["MatMul",[Hl]],["MatMulNBits",[Xu,Qu]],["MaxPool",[f,m]],["Mul",[xl]],["MultiHeadAttention",[Iu,Bd]],["Neg",[ol]],["Not",[ti]],["Pad",[id]],["Pow",[Tl]],["QuickGelu",[ia,Is]],["Range",[hr]],["Reciprocal",[ll]],["ReduceMin",[Po]],["ReduceMean",[Oi]],["ReduceMax",[ko]],["ReduceSum",[Ao]],["ReduceProd",[Di]],["ReduceL1",[Eo]],["ReduceL2",[$o]],["ReduceLogSum",[Bi]],["ReduceLogSumExp",[zi]],["ReduceSumSquare",[Io]],["Relu",[Zi]],["Resize",[Hd,Kd]],["RotaryEmbedding",[np]],["Sigmoid",[Ji]],["Sin",[dl]],["Sinh",[cl]],["Slice",[cp,pp]],["SkipLayerNormalization",[ap]],["Split",[vp,xp]],["Sqrt",[pl]],["Softmax",[mp,_p]],["Sub",[ni]],["Tan",[ta]],["Tanh",[hl]],["ThresholdedRelu",[ml,Is]],["Tile",[Du]],["Transpose",[md,so]],["Where",[Cp]]])}),$p,Lf=j(()=>{bt(),vn(),ar(),$p=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,s){qe(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let p of t)u.push({binding:u.length,resource:{buffer:p.buffer}});for(let p of r)u.push({binding:u.length,resource:{buffer:p.buffer}});s&&u.push({binding:u.length,resource:s});let d=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:d,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}i.setPipeline(e.computePipeline),i.setBindGroup(0,d),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),We(e.programInfo.name)}dispose(){}build(e,t){qe(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let s=to(t,this.backend.device.limits),a=e.getShaderSource(s),i=`${n.join(` +`)} +${s.additionalImplementations} +${a}`,u=r.createShaderModule({code:i,label:e.name});Gr("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let d=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return We(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:s.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=s&&r<=s&&n<=s)return[t,r,n];let a=t*r*n,i=Math.ceil(Math.sqrt(a));if(i>s){if(i=Math.ceil(Math.cbrt(a)),i>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),kp,Pp,Ap,Ip,Rf=j(()=>{bt(),Xt(),vn(),_(),zr(),Bf(),Lf(),kp=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{var s,a;let n=e.name;return(s=e.shaderCache)!=null&&s.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${kp(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Ap=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Ip=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};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(n),this.adapterInfo=new Ap(t.info||await t.requestAdapterInfo()),this.gpuDataManager=er(this),this.programManager=new $p(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ms(e.logLevel,!!e.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;qe(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=M);let E=Number(M-this.queryTimeBase),L=Number(T-this.queryTimeBase);if(!Number.isSafeInteger(E)||!Number.isSafeInteger(L))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map(G=>({dims:G.dims,dataType:Bn(G.dataType)})),outputsMetadata:l.map(G=>({dims:G.dims,dataType:Bn(G.dataType)})),kernelId:i,kernelType:d,kernelName:p,programName:w,startTime:E,endTime:L});else{let G="";g.forEach((ae,Q)=>{G+=`input[${Q}]: [${ae.dims}] | ${Bn(ae.dataType)}, `});let z="";l.forEach((ae,Q)=>{z+=`output[${Q}]: [${ae.dims}] | ${Bn(ae.dataType)}, `}),console.log(`[profiling] kernel "${i}|${d}|${p}|${w}" ${G}${z}execution time: ${L-E} ns`)}ke("GPU",`${w}::${M}::${T}`)}e.unmap(),this.pendingQueries.delete(e)}),We()}run(e,t,r,n,s,a){qe(e.name);let i=[];for(let z=0;zae):r;if(w.length!==u.length)throw new Error(`Output size ${w.length} must be equal to ${u.length}.`);let g=[],l=[];for(let z=0;z=a)throw new Error(`Invalid output index: ${w[z]}`);if(w[z]===-3)continue;let ae=w[z]===-1,Q=w[z]===-2,oe=ae||Q?s(u[z].dataType,u[z].dims):n(w[z],u[z].dataType,u[z].dims);if(g.push(oe),oe.data===0)continue;let Re=this.gpuDataManager.get(oe.data);if(!Re)throw new Error(`no GPU data for output: ${oe.data}`);if(ae&&this.temporaryData.push(Re),Q){let Ne=this.kernelPersistentData.get(this.currentKernelId);Ne||(Ne=[],this.kernelPersistentData.set(this.currentKernelId,Ne)),Ne.push(Re)}l.push(Re)}if(i.length!==t.length||l.length!==g.length){if(l.length===0)return We(e.name),g;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let M;if(p){let z=0,ae=[];p.forEach(Ne=>{let _t=typeof Ne.data=="number"?[Ne.data]:Ne.data;if(_t.length===0)return;let Dt=Ne.type===10?2:4,Vt,lr;Ne.type===10?(lr=_t.length>4?16:_t.length>2?8:_t.length*Dt,Vt=_t.length>4?16:Dt*_t.length):(lr=_t.length<=2?_t.length*Dt:16,Vt=16),z=Math.ceil(z/lr)*lr,ae.push(z);let fr=Ne.type===10?8:4;z+=_t.length>4?Math.ceil(_t.length/fr)*Vt:_t.length*Dt});let Q=16;z=Math.ceil(z/Q)*Q;let oe=new ArrayBuffer(z);p.forEach((Ne,_t)=>{let Dt=ae[_t],Vt=typeof Ne.data=="number"?[Ne.data]:Ne.data;if(Ne.type===6)new Int32Array(oe,Dt,Vt.length).set(Vt);else if(Ne.type===12)new Uint32Array(oe,Dt,Vt.length).set(Vt);else if(Ne.type===10)new Uint16Array(oe,Dt,Vt.length).set(Vt);else if(Ne.type===1)new Float32Array(oe,Dt,Vt.length).set(Vt);else throw new Error(`Unsupported uniform type: ${Bn(Ne.type)}`)});let Re=this.gpuDataManager.create(z,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Re.buffer,0,oe,0,z),this.gpuDataManager.release(Re.id),M={offset:0,size:z,buffer:Re.buffer}}let T=this.programManager.normalizeDispatchGroupSize(d),E=T[1]===1&&T[2]===1,L=Pp(e,t,E),G=this.programManager.getArtifact(L);if(G||(G=this.programManager.build(e,T),this.programManager.setArtifact(L,G),Gr("info",()=>`[artifact] key: ${L}, programName: ${e.name}`)),p&&G.uniformVariablesInfo){if(p.length!==G.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${G.uniformVariablesInfo.length}, got ${p.length} in program "${G.programInfo.name}".`);for(let z=0;z`[ProgramManager] run "${e.name}" (key=${L}) with ${T[0]}x${T[1]}x${T[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let z={kernelId:this.currentKernelId,programName:G.programInfo.name,inputTensorViews:t,outputTensorViews:g};this.pendingKernels.push(z),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(z)}return this.programManager.run(G,i,l,T,M),We(e.name),g}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,n){let s=Ep.get(e);if(!s)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:s[0],attributes:[s[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let s=n.kernelType,a=n.kernelName,i=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),Gr("info",()=>`[WebGPU] Start to run kernel "[${s}] ${a}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),i(t,u[1]),0}catch(p){return r.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${a}" failed. ${p}`)),1}finally{d&&r.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${s}] ${a}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let s=this.sessionExternalDataMapping.get(e);s||(s=new Map,this.sessionExternalDataMapping.set(e,s));let a=s.get(t),i=this.gpuDataManager.registerExternalBuffer(r,n,a==null?void 0:a[1]);return s.set(t,[i,r]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[1])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let n=await Mt(this,e,t);return be(n.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Gr("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(){Gr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Gr("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}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()}}}),Fp={};$(Fp,{init:()=>zp});var Qd,Op,zp,Nf=j(()=>{Xt(),Rf(),vn(),Qt(),Qd=class Mf{constructor(t,r,n,s){this.module=t,this.dataType=r,this.data=n,this.dims=s}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Oe.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=Oe.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=Oe.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=Oe.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Oe.size(t)!==Oe.size(this.dims))throw new Error("Invalid new shape");return new Mf(this.module,this.dataType,this.data,t)}},Op=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.HEAPU32,s=r>>>2;this.opKernelContext=n[s++];let a=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let i=[];for(let u=0;utypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],s=(u,d,p)=>new Qd(this.module,d,this.output(u,p),p),a=(u,d)=>{let p=Xn(u,d);if(!p)throw new Error(`Unsupported data type: ${u}`);let w=p>0?this.backend.gpuDataManager.create(p).id:0;return new Qd(this.module,u,w,d)};return this.backend.run(e,r,n,s,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),s=n>>2;this.module.HEAPU32[s++]=t.length;for(let a=0;a{let s=t.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Ip;await a.initialize(r,n),s("webgpu",[a,i=>a.alloc(i),i=>a.free(i),(i,u,d,p=!1)=>{if(p)Gr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${u}, size=${d}`),a.memcpy(i,u);else{Gr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${u}, size=${d}`);let w=t.HEAPU8.subarray(i>>>0,(i>>>0)+d);a.upload(u,w)}},async(i,u,d)=>{Gr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${u}, size=${d}`),await a.download(i,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+d))},(i,u,d)=>a.createKernel(i,u,d,t.UTF8ToString(t._JsepGetNodeName(u))),i=>a.releaseKernel(i),(i,u,d,p)=>{Gr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${i}, contextDataOffset=${u}`);let w=new Op(t,a,u);return a.computeKernel(i,w,p)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else s("webnn")}}),Dp,vc,xc,Vs,Bp,Yd,Tc,Sc,Cc,Ec,$c,kc,Lp=j(()=>{Ys(),Zs(),Xt(),yr(),Hn(),Cs(),Dp=(e,t)=>{mr()._OrtInit(e,t)!==0&&Rr("Can't initialize onnxruntime.")},vc=async e=>{Dp(e.wasm.numThreads,ts(e.logLevel))},xc=async(e,t)=>{{let r=(Nf(),A(Fp)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",mr(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",mr(),e)}}},Vs=new Map,Bp=e=>{let t=mr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Rr("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},Yd=e=>{let t=mr(),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]},Tc=async(e,t)=>{var g,l;let r,n,s=mr();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Yd(e);let a=0,i=0,u=0,d=[],p=[],w=[];try{if([i,d]=Kn(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let Q=[];for(let oe of t.externalData){let Re=typeof oe=="string"?oe:oe.path;Q.push(rs(typeof oe=="string"?oe:oe.data).then(Ne=>{s.mountExternalData(Re,Ne)}))}await Promise.all(Q)}for(let Q of(t==null?void 0:t.executionProviders)??[])if((typeof Q=="string"?Q:Q.name)==="webnn"){if(s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof Q!="string"){let oe=Q,Re=oe==null?void 0:oe.context,Ne=oe==null?void 0:oe.gpuDevice,_t=oe==null?void 0:oe.deviceType,Dt=oe==null?void 0:oe.numThreads,Vt=oe==null?void 0:oe.powerPreference;Re?s.currentContext=Re:Ne?s.currentContext=await navigator.ml.createContext(Ne):s.currentContext=await navigator.ml.createContext({deviceType:_t,numThreads:Dt,powerPreference:Vt})}else s.currentContext=await navigator.ml.createContext();break}a=await s._OrtCreateSession(r,n,i),a===0&&Rr("Can't create a session."),s.currentContext&&(s.currentContext=void 0);let[M,T]=Bp(a),E=!!(t!=null&&t.enableGraphCapture),L=[],G=[],z=[];for(let Q=0;QQ==="gpu-buffer")&&(u=s._OrtCreateBinding(a),u===0&&Rr("Can't create IO binding."),ae={handle:u,outputPreferredLocations:z,outputPreferredLocationsEncoded:z.map(Q=>hs(Q))}),Vs.set(a,[a,p,w,ae,E,!1]),[a,L,G]}catch(M){throw p.forEach(T=>s._OrtFree(T)),w.forEach(T=>s._OrtFree(T)),u!==0&&s._OrtReleaseBinding(u),a!==0&&s._OrtReleaseSession(a),M}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i),d.forEach(M=>s._free(M)),(l=s.unmountExternalData)==null||l.call(s)}},Sc=e=>{var d;let t=mr(),r=Vs.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,i,u]=r;i&&(u&&t._OrtClearBoundOutputs(i.handle),t._OrtReleaseBinding(i.handle)),(d=t.jsepOnReleaseSession)==null||d.call(t,e),s.forEach(p=>t._OrtFree(p)),a.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n),Vs.delete(e)},Cc=(e,t,r,n,s,a=!1)=>{if(!e){t.push(0);return}let i=mr(),u=e[0],d=e[1],p=e[3],w,g;if(u==="string"&&p==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let T=e[2].gpuBuffer;g=Xn(cs(u),d);let E=i.jsepRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');w=E(n,s,T,g)}else{let T=e[2];if(Array.isArray(T)){g=4*T.length,w=i._malloc(g),r.push(w);let E=w/4;for(let L=0;Li.HEAP32[T++]=L);let E=i._OrtCreateTensor(cs(u),w,g,M,d.length,hs(p));E===0&&Rr(`Can't create tensor for input/output. session=${n}, index=${s}.`),t.push(E)}finally{i.stackRestore(l)}},Ec=async(e,t,r,n,s,a)=>{var Vt,lr;let i=mr(),u=Vs.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=u[0],p=u[1],w=u[2],g=u[3],l=u[4],M=u[5],T=t.length,E=n.length,L=0,G=[],z=[],ae=[],Q=[],oe=i.stackSave(),Re=i.stackAlloc(T*4),Ne=i.stackAlloc(T*4),_t=i.stackAlloc(E*4),Dt=i.stackAlloc(E*4);try{[L,G]=jn(a);for(let Zt=0;ZtMn*Pn,1);rr=Bn(fn);let dd=g==null?void 0:g.outputPreferredLocations[n[Zt]];if(rr==="string"){if(dd==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Mn=[],Pn=Ur/4;for(let Wn=0;Wn0){let Mn=i.jsepGetBuffer;if(!Mn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Pn=Mn(Ur),Wn=Xn(fn,bn);if(Wn===void 0||!ps(rr))throw new Error(`Unsupported data type: ${rr}`);$t=!0,Wr.push([rr,Nn,{gpuBuffer:Pn,download:i.jsepCreateDownloader(Pn,Wn,rr),dispose:()=>{i._OrtReleaseTensor(dr)}},"gpu-buffer"])}else{let Mn=Vn(rr),Pn=new Mn(bn);new Uint8Array(Pn.buffer,Pn.byteOffset,Pn.byteLength).set(i.HEAPU8.subarray(Ur,Ur+Pn.byteLength)),Wr.push([rr,Nn,Pn,"cpu"])}}finally{i.stackRestore(Or),rr==="string"&&Ur&&i._free(Ur),$t||i._OrtReleaseTensor(dr)}}return g&&!l&&(i._OrtClearBoundOutputs(g.handle),Vs.set(e,[d,p,w,g,l,!1])),Wr}finally{i.stackRestore(oe),z.forEach(fr=>i._OrtReleaseTensor(fr)),ae.forEach(fr=>i._OrtReleaseTensor(fr)),Q.forEach(fr=>i._free(fr)),L!==0&&i._OrtReleaseRunOptions(L),G.forEach(fr=>i._free(fr))}},$c=e=>{let t=mr(),r=Vs.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Rr("Can't get an profile file name."),t._OrtFree(s)},kc=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Us,Dn,Xa,ld,ud,Zd,Pc,Jd,fi,mi,Rp,Np,jp,Vp,Up,Wp,Gp,qp,Hp=j(()=>{bt(),Lp(),yr(),Rt(),Us=()=>!!k.wasm.proxy&&typeof document<"u",Xa=!1,ld=!1,ud=!1,Jd=new Map,fi=(e,t)=>{let r=Jd.get(e);r?r.push(t):Jd.set(e,[t])},mi=()=>{if(Xa||!ld||ud||!Dn)throw new Error("worker not ready")},Rp=e=>{switch(e.data.type){case"init-wasm":Xa=!1,e.data.err?(ud=!0,Pc[1](e.data.err)):(ld=!0,Pc[0]()),Zd&&(URL.revokeObjectURL(Zd),Zd=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Jd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Np=async()=>{if(!ld){if(Xa)throw new Error("multiple calls to 'initWasm()' detected.");if(ud)throw new Error("previous call to 'initWasm()' failed.");if(Xa=!0,Us())return new Promise((e,t)=>{Dn==null||Dn.terminate(),mt().then(([r,n])=>{try{Dn=n,Dn.onerror=a=>t(a),Dn.onmessage=Rp,Pc=[e,t];let s={type:"init-wasm",in:k};Dn.postMessage(s),Zd=r}catch(s){t(s)}},t)});try{await Lr(k.wasm),await vc(k),ld=!0}catch(e){throw ud=!0,e}finally{Xa=!1}}},jp=async e=>{if(Us())return mi(),new Promise((t,r)=>{fi("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:k}};Dn.postMessage(n)});await xc(k,e)},Vp=async e=>Us()?(mi(),new Promise((t,r)=>{fi("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Dn.postMessage(n,[e.buffer])})):Yd(e),Up=async(e,t)=>{if(Us()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return mi(),new Promise((r,n)=>{fi("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Dn.postMessage(s,a)})}else return Tc(e,t)},Wp=async e=>{if(Us())return mi(),new Promise((t,r)=>{fi("release",[t,r]);let n={type:"release",in:e};Dn.postMessage(n)});Sc(e)},Gp=async(e,t,r,n,s,a)=>{if(Us()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return mi(),new Promise((i,u)=>{fi("run",[i,u]);let d=r,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:a}};Dn.postMessage(p,kc(d))})}else return Ec(e,t,r,n,s,a)},qp=async e=>{if(Us())return mi(),new Promise((t,r)=>{fi("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Dn.postMessage(n)});$c(e)}}),Ac,Kp,Xp,jf=j(()=>{bt(),Hp(),Xt(),Ot(),Cs(),Ac=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Kp=e=>{switch(e[3]){case"cpu":return new Le(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ps(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Le.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},Xp=class{async fetchModelAndCopyToWasmMemory(e){return Vp(await rs(e))}async loadModel(e,t){qe();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await Up(r,t),We()}async dispose(){return Wp(this.sessionId)}async run(e,t,r){qe();let n=[],s=[];Object.entries(e).forEach(g=>{let l=g[0],M=g[1],T=this.inputNames.indexOf(l);if(T===-1)throw new Error(`invalid input '${l}'`);n.push(M),s.push(T)});let a=[],i=[];Object.entries(t).forEach(g=>{let l=g[0],M=g[1],T=this.outputNames.indexOf(l);if(T===-1)throw new Error(`invalid output '${l}'`);a.push(M),i.push(T)});let u=n.map((g,l)=>Ac(g,()=>`input "${this.inputNames[s[l]]}"`)),d=a.map((g,l)=>g?Ac(g,()=>`output "${this.outputNames[i[l]]}"`):null),p=await Gp(this.sessionId,s,u,i,d,r),w={};for(let g=0;g{bt(),Hp(),jf(),Rt(),Qp=()=>{if((typeof k.wasm.initTimeout!="number"||k.wasm.initTimeout<0)&&(k.wasm.initTimeout=0),k.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 k.wasm.proxy!="boolean"&&(k.wasm.proxy=!1),typeof k.wasm.trace!="boolean"&&(k.wasm.trace=!1),typeof k.wasm.numThreads!="number"||!Number.isInteger(k.wasm.numThreads)||k.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)k.wasm.numThreads=1;else{let e=typeof navigator>"u"?Ce("node:os").cpus().length:navigator.hardwareConcurrency;k.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Yp=class{async init(e){Qp(),await Np(),await jp(e)}async createInferenceSessionHandler(e,t){let r=new Xp;return await r.loadModel(e,t),Promise.resolve(r)}}}),Zp={};$(Zp,{wasmBackend:()=>Jp});var Jp,Uf=j(()=>{Vf(),Jp=new Yp});bt(),bt(),bt();var Wf="1.20.0-dev.20240908-de7a02beef",Gf=Tt;{let e=(Uf(),A(Zp)).wasmBackend;me("webgpu",e,5),me("webnn",e,5),me("cpu",e,10),me("wasm",e,10)}Object.defineProperty(k.versions,"web",{value:Wf,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":(Et,Se,N)=>{var O;N.r(Se),N.d(Se,{Tensor:()=>Ce.Tensor,createInferenceSession:()=>ce,deviceToExecutionProviders:()=>ne,isONNXProxy:()=>te,isONNXTensor:()=>D});var fe=N("./src/env.js"),ye=N("?2ce3"),Te=N("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Ce=N("./node_modules/onnxruntime-common/dist/esm/index.js");const j=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"}}),$=[];let V,A;if(fe.apis.IS_NODE_ENV){switch(A=ye??(O||(O=N.t(ye,2))),process.platform){case"win32":$.push("dml");break;case"linux":process.arch==="x64"&&$.push("cuda");break}$.push("cpu"),V=["cpu"]}else A=Te,fe.apis.IS_WEBNN_AVAILABLE&&$.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),fe.apis.IS_WEBGPU_AVAILABLE&&$.push("webgpu"),$.push("wasm"),V=["wasm"];const ee=A.InferenceSession;function ne(se=null){if(!se)return V;switch(se){case"auto":return $;case"gpu":return $.filter(X=>["webgpu","cuda","dml","webnn-gpu"].includes(X))}if($.includes(se))return[j[se]??se];throw new Error(`Unsupported device: "${se}". Should be one of: ${$.join(", ")}.`)}let me=null;async function ce(se,X){me&&await me;const R=ee.create(se,X);return me??(me=R),await R}function D(se){return se instanceof A.Tensor}const H=A==null?void 0:A.env;H!=null&&H.wasm&&(H.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${fe.env.version}/dist/`,H.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(H.wasm.numThreads=1)),H!=null&&H.webgpu&&(H.webgpu.powerPreference="high-performance");function te(){var se;return(se=H==null?void 0:H.wasm)==null?void 0:se.proxy}fe.env.backends.onnx=H},"./src/configs.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{AutoConfig:()=>$,PretrainedConfig:()=>j,getKeyValueShapes:()=>Ce});var O=N("./src/utils/core.js"),fe=N("./src/utils/hub.js");async function ye(V,A){return await(0,fe.getModelJSON)(V,"config.json",!0,A)}function Te(V){const A={};let ee={};switch(V.model_type){case"llava":case"paligemma":case"florence2":ee=Te(V.text_config);break;case"moondream1":ee=Te(V.phi_config);break;case"musicgen":ee=Te(V.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":A.num_heads="n_head",A.num_layers="n_layer",A.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":A.num_heads="num_attention_heads",A.num_layers="num_hidden_layers",A.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":A.num_heads="num_key_value_heads",A.num_layers="num_hidden_layers",A.hidden_size="hidden_size",A.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":A.num_heads="num_key_value_heads",A.num_layers="num_hidden_layers",A.dim_kv="head_dim";break;case"openelm":A.num_heads="num_kv_heads",A.num_layers="num_transformer_layers",A.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":A.num_heads="num_heads",A.num_layers="num_layers",A.hidden_size="hidden_size";break;case"bloom":A.num_heads="n_head",A.num_layers="n_layer",A.hidden_size="hidden_size";break;case"mpt":A.num_heads="n_heads",A.num_layers="n_layers",A.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":A.num_decoder_layers="num_decoder_layers",A.num_decoder_heads="num_heads",A.decoder_dim_kv="d_kv",A.num_encoder_layers="num_layers",A.num_encoder_heads="num_heads",A.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":A.num_decoder_layers="decoder_layers",A.num_decoder_heads="decoder_attention_heads",A.decoder_hidden_size="d_model",A.num_encoder_layers="encoder_layers",A.num_encoder_heads="encoder_attention_heads",A.encoder_hidden_size="d_model";break;case"speecht5":A.num_decoder_layers="decoder_layers",A.num_decoder_heads="decoder_attention_heads",A.decoder_hidden_size="hidden_size",A.num_encoder_layers="encoder_layers",A.num_encoder_heads="encoder_attention_heads",A.encoder_hidden_size="hidden_size";break;case"trocr":A.num_encoder_layers=A.num_decoder_layers="decoder_layers",A.num_encoder_heads=A.num_decoder_heads="decoder_attention_heads",A.encoder_hidden_size=A.decoder_hidden_size="d_model";break;case"musicgen_decoder":A.num_encoder_layers=A.num_decoder_layers="num_hidden_layers",A.num_encoder_heads=A.num_decoder_heads="num_attention_heads",A.encoder_hidden_size=A.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const me=Te(V.decoder),ce="num_decoder_layers"in me,D=(0,O.pick)(V,["model_type","is_encoder_decoder"]);return ce?(D.num_decoder_layers=me.num_decoder_layers,D.num_decoder_heads=me.num_decoder_heads,D.decoder_hidden_size=me.decoder_hidden_size,D.num_encoder_layers=me.num_encoder_layers,D.num_encoder_heads=me.num_encoder_heads,D.encoder_hidden_size=me.encoder_hidden_size):(D.num_layers=me.num_layers,D.num_heads=me.num_heads,D.hidden_size=me.hidden_size),D}const ne={...ee,...(0,O.pick)(V,["model_type","multi_query","is_encoder_decoder"])};for(const me in A)ne[me]=V[A[me]];return ne}function Ce(V,{prefix:A="past_key_values"}={}){const ee={},ne=V.normalized_config,me=1;if(ne.is_encoder_decoder&&"num_encoder_heads"in ne&&"num_decoder_heads"in ne){const ce=ne.encoder_dim_kv??ne.encoder_hidden_size/ne.num_encoder_heads,D=ne.decoder_dim_kv??ne.decoder_hidden_size/ne.num_decoder_heads,H=[me,ne.num_encoder_heads,0,ce],te=[me,ne.num_decoder_heads,0,D];for(let se=0;se{var k;N.r(Se),N.d(Se,{apis:()=>D,env:()=>I});var O=N("?569f"),fe=N("?3f59"),ye=N("?154a");const Te="3.0.0-alpha.16",Ce=typeof self<"u",j=Ce&&self.constructor.name==="DedicatedWorkerGlobalScope",$=Ce&&"caches"in self,V=typeof navigator<"u"&&"gpu"in navigator,A=typeof navigator<"u"&&"ml"in navigator,ee=typeof process<"u",ne=ee&&((k=process==null?void 0:process.release)==null?void 0:k.name)==="node",me=!B(O),ce=!B(fe),D=Object.freeze({IS_BROWSER_ENV:Ce,IS_WEBWORKER_ENV:j,IS_WEB_CACHE_AVAILABLE:$,IS_WEBGPU_AVAILABLE:V,IS_WEBNN_AVAILABLE:A,IS_PROCESS_AVAILABLE:ee,IS_NODE_ENV:ne,IS_FS_AVAILABLE:me,IS_PATH_AVAILABLE:ce}),H=me&&ce,te=H?fe.dirname(fe.dirname(ye.fileURLToPath(self.location.href))):"./",se=H?fe.join(te,"/.cache/"):null,X="/models/",R=H?fe.join(te,X):X,I={version:Te,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ce,localModelPath:R,useFS:me,useBrowserCache:$,useFSCache:me,cacheDir:se,useCustomCache:!1,customCache:null};function B(ue){return Object.keys(ue).length===0}},"./src/generation/configuration_utils.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{GenerationConfig:()=>fe});var O=N("./src/utils/core.js");class fe{constructor(Te){xe(this,"max_length",20);xe(this,"max_new_tokens",null);xe(this,"min_length",0);xe(this,"min_new_tokens",null);xe(this,"early_stopping",!1);xe(this,"max_time",null);xe(this,"do_sample",!1);xe(this,"num_beams",1);xe(this,"num_beam_groups",1);xe(this,"penalty_alpha",null);xe(this,"use_cache",!0);xe(this,"temperature",1);xe(this,"top_k",50);xe(this,"top_p",1);xe(this,"typical_p",1);xe(this,"epsilon_cutoff",0);xe(this,"eta_cutoff",0);xe(this,"diversity_penalty",0);xe(this,"repetition_penalty",1);xe(this,"encoder_repetition_penalty",1);xe(this,"length_penalty",1);xe(this,"no_repeat_ngram_size",0);xe(this,"bad_words_ids",null);xe(this,"force_words_ids",null);xe(this,"renormalize_logits",!1);xe(this,"constraints",null);xe(this,"forced_bos_token_id",null);xe(this,"forced_eos_token_id",null);xe(this,"remove_invalid_values",!1);xe(this,"exponential_decay_length_penalty",null);xe(this,"suppress_tokens",null);xe(this,"begin_suppress_tokens",null);xe(this,"forced_decoder_ids",null);xe(this,"guidance_scale",null);xe(this,"num_return_sequences",1);xe(this,"output_attentions",!1);xe(this,"output_hidden_states",!1);xe(this,"output_scores",!1);xe(this,"return_dict_in_generate",!1);xe(this,"pad_token_id",null);xe(this,"bos_token_id",null);xe(this,"eos_token_id",null);xe(this,"encoder_no_repeat_ngram_size",0);xe(this,"decoder_start_token_id",null);xe(this,"generation_kwargs",{});Object.assign(this,(0,O.pick)(Te,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{ClassifierFreeGuidanceLogitsProcessor:()=>H,ForcedBOSTokenLogitsProcessor:()=>j,ForcedEOSTokenLogitsProcessor:()=>$,LogitsProcessor:()=>ye,LogitsProcessorList:()=>Ce,LogitsWarper:()=>Te,MinLengthLogitsProcessor:()=>me,MinNewTokensLengthLogitsProcessor:()=>ce,NoBadWordsLogitsProcessor:()=>D,NoRepeatNGramLogitsProcessor:()=>ee,RepetitionPenaltyLogitsProcessor:()=>ne,SuppressTokensAtBeginLogitsProcessor:()=>V,TemperatureLogitsWarper:()=>te,TopKLogitsWarper:()=>X,TopPLogitsWarper:()=>se,WhisperTimeStampLogitsProcessor:()=>A});var O=N("./src/utils/generic.js");N("./src/utils/tensor.js");var fe=N("./src/utils/maths.js");class ye extends O.Callable{_call(I,B){throw Error("`_call` should be implemented in a subclass")}}class Te extends O.Callable{_call(I,B){throw Error("`_call` should be implemented in a subclass")}}class Ce extends O.Callable{constructor(){super(),this.processors=[]}push(I){this.processors.push(I)}extend(I){this.processors.push(...I)}_call(I,B){let k=B;for(const ue of this.processors)k=ue(I,k);return k}[Symbol.iterator](){return this.processors.values()}}class j extends ye{constructor(I){super(),this.bos_token_id=I}_call(I,B){for(let k=0;k=1&&ve[ve.length-1]>=this.timestamp_begin,Ie=ve.length<2||ve[ve.length-2]>=this.timestamp_begin;if(Ee&&(Ie?ue.subarray(this.timestamp_begin).fill(-1/0):ue.subarray(0,this.eos_token_id).fill(-1/0)),I[k].length===this.begin_index&&this.max_initial_timestamp_index!==null){const dt=this.timestamp_begin+this.max_initial_timestamp_index;ue.subarray(dt+1).fill(-1/0)}const Ae=(0,fe.log_softmax)(ue),tt=Math.log(Ae.subarray(this.timestamp_begin).map(Math.exp).reduce((dt,ge)=>dt+ge)),Xe=(0,fe.max)(Ae.subarray(0,this.timestamp_begin))[0];tt>Xe&&ue.subarray(0,this.timestamp_begin).fill(-1/0)}return B}}class ee extends ye{constructor(I){super(),this.no_repeat_ngram_size=I}getNgrams(I){const B=I.length,k=[];for(let ve=0;ve1 to use the classifier free guidance processor, got guidance scale ${I}.`);this.guidance_scale=I}_call(I,B){if(B.dims[0]!==2*I.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 ${B.dims[0]} for the logits and ${I.length} for the input ids.`);const k=I.length,ue=B.slice([0,k],null),ve=B.slice([k,B.dims[0]],null);for(let Ee=0;Ee1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${I}`);if(!Number.isInteger(k)||k<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${k}`);this.top_p=I,this.filter_value=B,this.min_tokens_to_keep=k}}class X extends Te{constructor(I,{filter_value:B=-1/0,min_tokens_to_keep:k=1}={}){if(super(),!Number.isInteger(I)||I<0)throw new Error(`\`top_k\` must be a positive integer, but is ${I}`);this.top_k=Math.max(I,k),this.filter_value=B}}},"./src/generation/logits_sampler.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{LogitsSampler:()=>Te});var O=N("./src/utils/generic.js"),fe=N("./src/utils/tensor.js"),ye=N("./src/utils/maths.js");N("./src/generation/configuration_utils.js");class Te extends O.Callable{constructor(A){super(),this.generation_config=A}async _call(A){return this.sample(A)}async sample(A){throw Error("sample should be implemented in subclasses.")}getLogits(A,ee){let ne=A.dims.at(-1),me=A.data;if(ee===-1)me=me.slice(-ne);else{let ce=ee*ne;me=me.slice(ce,ce+ne)}return me}randomSelect(A){let ee=0;for(let me=0;me1)return new $(A);if(A.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${A.num_return_sequences}.`);return new Ce(A)}}class Ce extends Te{async sample(A){const ee=(0,ye.max)(A.data)[1];return[[BigInt(ee),0]]}}class j extends Te{async sample(A){let ee=A.dims.at(-1);this.generation_config.top_k>0&&(ee=Math.min(this.generation_config.top_k,ee));const[ne,me]=await(0,fe.topk)(A,ee),ce=(0,ye.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},()=>{const D=this.randomSelect(ce);return[me.data[D],Math.log(ce[D])]})}}class $ extends Te{async sample(A){let ee=A.dims.at(-1);this.generation_config.top_k>0&&(ee=Math.min(this.generation_config.top_k,ee));const[ne,me]=await(0,fe.topk)(A,ee),ce=(0,ye.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},(D,H)=>[me.data[H],Math.log(ce[H])])}}},"./src/generation/stopping_criteria.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{EosTokenCriteria:()=>Ce,InterruptableStoppingCriteria:()=>j,MaxLengthCriteria:()=>Te,StoppingCriteria:()=>fe,StoppingCriteriaList:()=>ye});var O=N("./src/utils/generic.js");class fe extends O.Callable{_call(V,A){throw Error("StoppingCriteria needs to be subclassed")}}class ye extends O.Callable{constructor(){super(),this.criteria=[]}push(V){this.criteria.push(V)}extend(V){V instanceof ye?V=V.criteria:V instanceof fe&&(V=[V]),this.criteria.push(...V)}_call(V,A){const ee=new Array(V.length).fill(!1);for(const ne of this.criteria){const me=ne(V,A);for(let ce=0;ceA.length>=this.max_length)}}class Ce extends fe{constructor(V){super(),Array.isArray(V)||(V=[V]),this.eos_token_id=V}_call(V,A){return V.map(ee=>{const ne=ee.at(-1);return this.eos_token_id.some(me=>ne==me)})}}class j extends fe{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(V,A){return new Array(V.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{BaseStreamer:()=>Te,TextStreamer:()=>j,WhisperTextStreamer:()=>$});var O=N("./src/utils/core.js"),fe=N("./src/tokenizers.js"),ye=N("./src/env.js");class Te{put(A){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Ce=ye.apis.IS_PROCESS_AVAILABLE?V=>process.stdout.write(V):V=>console.log(V);class j extends Te{constructor(A,{skip_prompt:ee=!1,callback_function:ne=null,token_callback_function:me=null,decode_kwargs:ce={},...D}={}){super(),this.tokenizer=A,this.skip_prompt=ee,this.callback_function=ne??Ce,this.token_callback_function=me,this.decode_kwargs={...ce,...D},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(A){var ce;if(A.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 ee=A[0];(ce=this.token_callback_function)==null||ce.call(this,ee),this.token_cache=(0,O.mergeArrays)(this.token_cache,ee);const ne=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let me;ne.endsWith(` +`)?(me=ne.slice(this.print_len),this.token_cache=[],this.print_len=0):ne.length>0&&(0,fe.is_chinese_char)(ne.charCodeAt(ne.length-1))?(me=ne.slice(this.print_len),this.print_len+=me.length):(me=ne.slice(this.print_len,ne.lastIndexOf(" ")+1),this.print_len+=me.length),this.on_finalized_text(me,!1)}end(){let A;this.token_cache.length>0?(A=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):A="",this.next_tokens_are_prompt=!0,this.on_finalized_text(A,!0)}on_finalized_text(A,ee){var ne,me;A.length>0&&((ne=this.callback_function)==null||ne.call(this,A)),ee&&this.callback_function===Ce&&ye.apis.IS_PROCESS_AVAILABLE&&((me=this.callback_function)==null||me.call(this,` +`))}}class $ extends j{constructor(A,{skip_prompt:ee=!1,callback_function:ne=null,token_callback_function:me=null,on_chunk_start:ce=null,on_chunk_end:D=null,on_finalize:H=null,time_precision:te=.02,skip_special_tokens:se=!0,decode_kwargs:X={}}={}){super(A,{skip_prompt:ee,callback_function:ne,token_callback_function:me,decode_kwargs:{skip_special_tokens:se,...X}}),this.timestamp_begin=A.timestamp_begin,this.on_chunk_start=ce,this.on_chunk_end=D,this.on_finalize=H,this.time_precision=te,this.waiting_for_timestamp=!1}put(A){var ne,me;if(A.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const ee=A[0];if(ee.length===1){const ce=Number(ee[0])-this.timestamp_begin;if(ce>=0){const D=ce*this.time_precision;this.waiting_for_timestamp?(ne=this.on_chunk_end)==null||ne.call(this,D):(me=this.on_chunk_start)==null||me.call(this,D),this.waiting_for_timestamp=!this.waiting_for_timestamp,A=[[]]}}return super.put(A)}end(){var A;super.end(),(A=this.on_finalize)==null||A.call(this)}}},"./src/models.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{ASTForAudioClassification:()=>Js,ASTModel:()=>jt,ASTPreTrainedModel:()=>Sn,AlbertForMaskedLM:()=>Xt,AlbertForQuestionAnswering:()=>hs,AlbertForSequenceClassification:()=>ps,AlbertModel:()=>ts,AlbertPreTrainedModel:()=>Vn,AutoModel:()=>ja,AutoModelForAudioClassification:()=>nd,AutoModelForAudioFrameClassification:()=>id,AutoModelForCTC:()=>rd,AutoModelForCausalLM:()=>jd,AutoModelForDepthEstimation:()=>Ua,AutoModelForDocumentQuestionAnswering:()=>Ud,AutoModelForImageClassification:()=>Qu,AutoModelForImageFeatureExtraction:()=>Ga,AutoModelForImageMatting:()=>Ns,AutoModelForImageSegmentation:()=>Vd,AutoModelForImageToImage:()=>Va,AutoModelForMaskGeneration:()=>td,AutoModelForMaskedLM:()=>Hu,AutoModelForNormalEstimation:()=>Wa,AutoModelForObjectDetection:()=>Ju,AutoModelForQuestionAnswering:()=>Ku,AutoModelForSemanticSegmentation:()=>Yu,AutoModelForSeq2SeqLM:()=>Nd,AutoModelForSequenceClassification:()=>Vu,AutoModelForSpeechSeq2Seq:()=>Wu,AutoModelForTextToSpectrogram:()=>Gu,AutoModelForTextToWaveform:()=>qu,AutoModelForTokenClassification:()=>Uu,AutoModelForUniversalSegmentation:()=>Zu,AutoModelForVision2Seq:()=>Xu,AutoModelForXVector:()=>sd,AutoModelForZeroShotObjectDetection:()=>ed,BartForConditionalGeneration:()=>_,BartForSequenceClassification:()=>P,BartModel:()=>be,BartPretrainedModel:()=>vn,BaseModelOutput:()=>ct,BeitForImageClassification:()=>al,BeitModel:()=>il,BeitPreTrainedModel:()=>Yi,BertForMaskedLM:()=>je,BertForQuestionAnswering:()=>Le,BertForSequenceClassification:()=>st,BertForTokenClassification:()=>Pt,BertModel:()=>lt,BertPreTrainedModel:()=>nt,BlenderbotForConditionalGeneration:()=>zt,BlenderbotModel:()=>Mt,BlenderbotPreTrainedModel:()=>xt,BlenderbotSmallForConditionalGeneration:()=>ir,BlenderbotSmallModel:()=>zr,BlenderbotSmallPreTrainedModel:()=>er,BloomForCausalLM:()=>Do,BloomModel:()=>zo,BloomPreTrainedModel:()=>Oo,CLIPModel:()=>no,CLIPPreTrainedModel:()=>ns,CLIPSegForImageSegmentation:()=>po,CLIPSegModel:()=>co,CLIPSegPreTrainedModel:()=>xi,CLIPTextModel:()=>fd,CLIPTextModelWithProjection:()=>Ln,CLIPVisionModel:()=>md,CLIPVisionModelWithProjection:()=>so,CamembertForMaskedLM:()=>cr,CamembertForQuestionAnswering:()=>Br,CamembertForSequenceClassification:()=>xr,CamembertForTokenClassification:()=>Yr,CamembertModel:()=>Ot,CamembertPreTrainedModel:()=>bt,CausalLMOutput:()=>Jn,CausalLMOutputWithPast:()=>Gd,ChineseCLIPModel:()=>uo,ChineseCLIPPreTrainedModel:()=>lo,ClapAudioModelWithProjection:()=>cu,ClapModel:()=>uu,ClapPreTrainedModel:()=>hi,ClapTextModelWithProjection:()=>du,CodeGenForCausalLM:()=>Mo,CodeGenModel:()=>bo,CodeGenPreTrainedModel:()=>kn,CohereForCausalLM:()=>So,CohereModel:()=>To,CoherePreTrainedModel:()=>Ii,ConvBertForMaskedLM:()=>v,ConvBertForQuestionAnswering:()=>Y,ConvBertForSequenceClassification:()=>q,ConvBertForTokenClassification:()=>C,ConvBertModel:()=>kt,ConvBertPreTrainedModel:()=>vt,ConvNextForImageClassification:()=>Yn,ConvNextModel:()=>Qn,ConvNextPreTrainedModel:()=>Fl,ConvNextV2ForImageClassification:()=>Zn,ConvNextV2Model:()=>pa,ConvNextV2PreTrainedModel:()=>Un,DPTForDepthEstimation:()=>vl,DPTModel:()=>Ml,DPTPreTrainedModel:()=>ua,DebertaForMaskedLM:()=>U,DebertaForQuestionAnswering:()=>rt,DebertaForSequenceClassification:()=>_e,DebertaForTokenClassification:()=>Pe,DebertaModel:()=>at,DebertaPreTrainedModel:()=>Kr,DebertaV2ForMaskedLM:()=>gt,DebertaV2ForQuestionAnswering:()=>mt,DebertaV2ForSequenceClassification:()=>ft,DebertaV2ForTokenClassification:()=>St,DebertaV2Model:()=>Je,DebertaV2PreTrainedModel:()=>we,DecisionTransformerModel:()=>Cu,DecisionTransformerPreTrainedModel:()=>Su,DeiTForImageClassification:()=>ml,DeiTModel:()=>fl,DeiTPreTrainedModel:()=>ri,DepthAnythingForDepthEstimation:()=>Tl,DepthAnythingPreTrainedModel:()=>xl,DetrForObjectDetection:()=>ll,DetrForSegmentation:()=>Zi,DetrModel:()=>ol,DetrObjectDetectionOutput:()=>Ji,DetrPreTrainedModel:()=>ti,DetrSegmentationOutput:()=>ul,Dinov2ForImageClassification:()=>si,Dinov2Model:()=>ha,Dinov2PreTrainedModel:()=>un,DistilBertForMaskedLM:()=>et,DistilBertForQuestionAnswering:()=>Me,DistilBertForSequenceClassification:()=>Rt,DistilBertForTokenClassification:()=>Gt,DistilBertModel:()=>Nt,DistilBertPreTrainedModel:()=>Ft,DonutSwinModel:()=>Il,DonutSwinPreTrainedModel:()=>Al,EfficientNetForImageClassification:()=>gu,EfficientNetModel:()=>_u,EfficientNetPreTrainedModel:()=>Ea,ElectraForMaskedLM:()=>Ye,ElectraForQuestionAnswering:()=>Tt,ElectraForSequenceClassification:()=>Bt,ElectraForTokenClassification:()=>ht,ElectraModel:()=>Qe,ElectraPreTrainedModel:()=>he,EsmForMaskedLM:()=>gr,EsmForSequenceClassification:()=>Lr,EsmForTokenClassification:()=>mr,EsmModel:()=>Ht,EsmPreTrainedModel:()=>ot,FalconForCausalLM:()=>lu,FalconModel:()=>Ed,FalconPreTrainedModel:()=>Ta,FastViTForImageClassification:()=>Xo,FastViTModel:()=>Ko,FastViTPreTrainedModel:()=>Hi,Florence2ForConditionalGeneration:()=>vi,Florence2PreTrainedModel:()=>ro,GLPNForDepthEstimation:()=>Pl,GLPNModel:()=>kl,GLPNPreTrainedModel:()=>ca,GPT2LMHeadModel:()=>In,GPT2Model:()=>ho,GPT2PreTrainedModel:()=>Ti,GPTBigCodeForCausalLM:()=>Pi,GPTBigCodeModel:()=>ei,GPTBigCodePreTrainedModel:()=>ki,GPTJForCausalLM:()=>Fn,GPTJModel:()=>_d,GPTJPreTrainedModel:()=>$i,GPTNeoForCausalLM:()=>go,GPTNeoModel:()=>_o,GPTNeoPreTrainedModel:()=>Ci,GPTNeoXForCausalLM:()=>yo,GPTNeoXModel:()=>wo,GPTNeoXPreTrainedModel:()=>Ei,Gemma2ForCausalLM:()=>$o,Gemma2Model:()=>Eo,Gemma2PreTrainedModel:()=>Oi,GemmaForCausalLM:()=>On,GemmaModel:()=>Co,GemmaPreTrainedModel:()=>Fi,GroupViTModel:()=>Ho,GroupViTPreTrainedModel:()=>qo,HieraForImageClassification:()=>gl,HieraModel:()=>_l,HieraPreTrainedModel:()=>sa,HubertForCTC:()=>ba,HubertForSequenceClassification:()=>xd,HubertModel:()=>Ql,HubertPreTrainedModel:()=>vd,ImageMattingOutput:()=>ad,JAISLMHeadModel:()=>mo,JAISModel:()=>fo,JAISPreTrainedModel:()=>Si,LlamaForCausalLM:()=>xo,LlamaModel:()=>vo,LlamaPreTrainedModel:()=>Ai,LlavaForConditionalGeneration:()=>_s,LlavaPreTrainedModel:()=>to,LongT5ForConditionalGeneration:()=>ks,LongT5Model:()=>$s,LongT5PreTrainedModel:()=>fs,M2M100ForConditionalGeneration:()=>Nl,M2M100Model:()=>Rl,M2M100PreTrainedModel:()=>zs,MBartForCausalLM:()=>wt,MBartForConditionalGeneration:()=>pe,MBartForSequenceClassification:()=>De,MBartModel:()=>ie,MBartPreTrainedModel:()=>K,MPNetForMaskedLM:()=>vs,MPNetForQuestionAnswering:()=>Ss,MPNetForSequenceClassification:()=>xs,MPNetForTokenClassification:()=>Ts,MPNetModel:()=>Ys,MPNetPreTrainedModel:()=>jn,MT5ForConditionalGeneration:()=>Gr,MT5Model:()=>Ps,MT5PreTrainedModel:()=>ms,MarianMTModel:()=>ma,MarianModel:()=>Ll,MarianPreTrainedModel:()=>Os,MaskFormerForInstanceSegmentation:()=>$l,MaskFormerModel:()=>yd,MaskFormerPreTrainedModel:()=>da,MaskedLMOutput:()=>dn,MistralForCausalLM:()=>su,MistralModel:()=>nu,MistralPreTrainedModel:()=>xa,MobileBertForMaskedLM:()=>En,MobileBertForQuestionAnswering:()=>Hn,MobileBertForSequenceClassification:()=>Rr,MobileBertModel:()=>Tr,MobileBertPreTrainedModel:()=>yr,MobileNetV1ForImageClassification:()=>Pd,MobileNetV1Model:()=>bu,MobileNetV1PreTrainedModel:()=>ka,MobileNetV2ForImageClassification:()=>Ad,MobileNetV2Model:()=>Mu,MobileNetV2PreTrainedModel:()=>Pa,MobileNetV3ForImageClassification:()=>xu,MobileNetV3Model:()=>vu,MobileNetV3PreTrainedModel:()=>Aa,MobileNetV4ForImageClassification:()=>Tu,MobileNetV4Model:()=>Id,MobileNetV4PreTrainedModel:()=>Ia,MobileViTForImageClassification:()=>Jo,MobileViTModel:()=>Zo,MobileViTPreTrainedModel:()=>Ki,MobileViTV2ForImageClassification:()=>tl,MobileViTV2Model:()=>el,MobileViTV2PreTrainedModel:()=>Xi,ModelOutput:()=>He,Moondream1ForConditionalGeneration:()=>ar,MptForCausalLM:()=>As,MptModel:()=>Bo,MptPreTrainedModel:()=>Vi,MusicgenForCausalLM:()=>yu,MusicgenForConditionalGeneration:()=>$a,MusicgenModel:()=>kd,MusicgenPreTrainedModel:()=>wu,NomicBertModel:()=>ke,NomicBertPreTrainedModel:()=>re,OPTForCausalLM:()=>Wi,OPTModel:()=>Lo,OPTPreTrainedModel:()=>Ui,OpenELMForCausalLM:()=>Po,OpenELMModel:()=>ko,OpenELMPreTrainedModel:()=>zi,OwlViTForObjectDetection:()=>rl,OwlViTModel:()=>Is,OwlViTPreTrainedModel:()=>Qi,Owlv2ForObjectDetection:()=>sl,Owlv2Model:()=>nl,Owlv2PreTrainedModel:()=>Fs,Phi3ForCausalLM:()=>ji,Phi3Model:()=>Fo,Phi3PreTrainedModel:()=>Ni,PhiForCausalLM:()=>Ri,PhiModel:()=>Li,PhiPreTrainedModel:()=>Bi,PreTrainedModel:()=>J,PretrainedMixin:()=>Dr,PvtForImageClassification:()=>jo,PvtModel:()=>gd,PvtPreTrainedModel:()=>qi,PyAnnoteForAudioFrameClassification:()=>Wl,PyAnnoteModel:()=>Ul,PyAnnotePreTrainedModel:()=>oi,QuestionAnsweringModelOutput:()=>hn,Qwen2ForCausalLM:()=>Io,Qwen2Model:()=>Ao,Qwen2PreTrainedModel:()=>Di,RTDetrForObjectDetection:()=>cl,RTDetrModel:()=>dl,RTDetrObjectDetectionOutput:()=>pl,RTDetrPreTrainedModel:()=>ea,ResNetForImageClassification:()=>wl,ResNetModel:()=>aa,ResNetPreTrainedModel:()=>ia,RoFormerForMaskedLM:()=>We,RoFormerForQuestionAnswering:()=>yt,RoFormerForSequenceClassification:()=>Ke,RoFormerForTokenClassification:()=>ut,RoFormerModel:()=>qe,RoFormerPreTrainedModel:()=>Ve,RobertaForMaskedLM:()=>mn,RobertaForQuestionAnswering:()=>$n,RobertaForSequenceClassification:()=>ln,RobertaForTokenClassification:()=>Oe,RobertaModel:()=>pr,RobertaPreTrainedModel:()=>qt,SamImageSegmentationOutput:()=>Bl,SamModel:()=>fa,SamPreTrainedModel:()=>ai,SapiensForDepthEstimation:()=>Cl,SapiensForNormalEstimation:()=>El,SapiensForSemanticSegmentation:()=>Sl,SapiensPreTrainedModel:()=>ni,SegformerForImageClassification:()=>hu,SegformerForSemanticSegmentation:()=>fu,SegformerModel:()=>pu,SegformerPreTrainedModel:()=>as,Seq2SeqLMOutput:()=>Wd,SequenceClassifierOutput:()=>or,SiglipModel:()=>io,SiglipPreTrainedModel:()=>ss,SiglipTextModel:()=>ao,SiglipVisionModel:()=>oo,SpeechT5ForSpeechToText:()=>Jl,SpeechT5ForTextToSpeech:()=>va,SpeechT5HifiGan:()=>eu,SpeechT5Model:()=>Cd,SpeechT5PreTrainedModel:()=>pi,SqueezeBertForMaskedLM:()=>cs,SqueezeBertForQuestionAnswering:()=>Xn,SqueezeBertForSequenceClassification:()=>Bn,SqueezeBertModel:()=>Zs,SqueezeBertPreTrainedModel:()=>Kn,StableLmForCausalLM:()=>Ca,StableLmModel:()=>mu,StableLmPreTrainedModel:()=>Sa,Starcoder2ForCausalLM:()=>ou,Starcoder2Model:()=>au,Starcoder2PreTrainedModel:()=>iu,Swin2SRForImageSuperResolution:()=>zn,Swin2SRModel:()=>bl,Swin2SRPreTrainedModel:()=>la,SwinForImageClassification:()=>wd,SwinModel:()=>yl,SwinPreTrainedModel:()=>oa,T5ForConditionalGeneration:()=>Es,T5Model:()=>Cs,T5PreTrainedModel:()=>rs,TableTransformerForObjectDetection:()=>hl,TableTransformerModel:()=>ra,TableTransformerObjectDetectionOutput:()=>na,TableTransformerPreTrainedModel:()=>ta,TokenClassifierOutput:()=>en,TrOCRForCausalLM:()=>ru,TrOCRPreTrainedModel:()=>tu,UniSpeechForCTC:()=>Md,UniSpeechForSequenceClassification:()=>ga,UniSpeechModel:()=>ql,UniSpeechPreTrainedModel:()=>li,UniSpeechSatForAudioFrameClassification:()=>ui,UniSpeechSatForCTC:()=>Kl,UniSpeechSatForSequenceClassification:()=>Xl,UniSpeechSatModel:()=>Hl,UniSpeechSatPreTrainedModel:()=>Bs,ViTForImageClassification:()=>No,ViTMAEModel:()=>Uo,ViTMAEPreTrainedModel:()=>Vo,ViTMSNForImageClassification:()=>Er,ViTMSNModel:()=>Go,ViTMSNPreTrainedModel:()=>Wo,ViTModel:()=>Ro,ViTPreTrainedModel:()=>Gi,VisionEncoderDecoderModel:()=>Mi,VitMatteForImageMatting:()=>Yo,VitMattePreTrainedModel:()=>Qo,VitsModel:()=>Ls,VitsModelOutput:()=>Ha,VitsPreTrainedModel:()=>$d,Wav2Vec2BertForCTC:()=>wa,Wav2Vec2BertForSequenceClassification:()=>ya,Wav2Vec2BertModel:()=>ci,Wav2Vec2BertPreTrainedModel:()=>di,Wav2Vec2ForAudioFrameClassification:()=>Vl,Wav2Vec2ForCTC:()=>_a,Wav2Vec2ForSequenceClassification:()=>Ds,Wav2Vec2Model:()=>jl,Wav2Vec2PreTrainedModel:()=>is,WavLMForAudioFrameClassification:()=>Sd,WavLMForCTC:()=>Td,WavLMForSequenceClassification:()=>Zl,WavLMForXVector:()=>Ma,WavLMModel:()=>Yl,WavLMPreTrainedModel:()=>gs,WeSpeakerResNetModel:()=>bd,WeSpeakerResNetPreTrainedModel:()=>Gl,WhisperForConditionalGeneration:()=>bi,WhisperModel:()=>Wt,WhisperPreTrainedModel:()=>Ze,XLMForQuestionAnswering:()=>pn,XLMForSequenceClassification:()=>Qt,XLMForTokenClassification:()=>Tn,XLMModel:()=>sn,XLMPreTrainedModel:()=>Sr,XLMRobertaForMaskedLM:()=>It,XLMRobertaForQuestionAnswering:()=>Xr,XLMRobertaForSequenceClassification:()=>br,XLMRobertaForTokenClassification:()=>Nr,XLMRobertaModel:()=>Cr,XLMRobertaPreTrainedModel:()=>Ar,XLMWithLMHeadModel:()=>xn,XVectorOutput:()=>qa,YolosForObjectDetection:()=>zl,YolosModel:()=>Ol,YolosObjectDetectionOutput:()=>Dl,YolosPreTrainedModel:()=>ii});var O=N("./src/configs.js"),fe=N("./src/backends/onnx.js"),ye=N("./src/utils/dtypes.js"),Te=N("./src/utils/generic.js"),Ce=N("./src/utils/core.js"),j=N("./src/utils/hub.js"),$=N("./src/generation/logits_process.js"),V=N("./src/generation/configuration_utils.js"),A=N("./src/utils/tensor.js"),ee=N("./src/utils/maths.js"),ne=N("./src/generation/stopping_criteria.js"),me=N("./src/generation/logits_sampler.js"),ce=N("./src/env.js"),D=N("./src/models/whisper/generation_whisper.js"),H=N("./src/models/whisper/common_whisper.js");const te={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},se=new Map,X=new Map,R=new Map;async function I(f,m,S){var kr;const Z=((kr=S.config)==null?void 0:kr["transformers.js_config"])??{};let Fe=S.device??Z.device;Fe&&typeof Fe!="string"&&(Fe.hasOwnProperty(m)?Fe=Fe[m]:(console.warn(`device not specified for "${m}". Using the default device.`),Fe=null));const ze=Fe??(ce.apis.IS_NODE_ENV?"cpu":"wasm"),pt=(0,fe.deviceToExecutionProviders)(ze);let Ct=S.dtype??Z.dtype;typeof Ct!="string"&&(Ct&&Ct.hasOwnProperty(m)?Ct=Ct[m]:(Ct=ye.DEFAULT_DEVICE_DTYPE_MAPPING[ze]??ye.DATA_TYPES.fp32,console.warn(`dtype not specified for "${m}". Using the default dtype (${Ct}) for this device (${ze}).`)));const Ut=Ct;if(ye.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ut)){if(Ut===ye.DATA_TYPES.fp16&&ze==="webgpu"&&!await(0,ye.isWebGpuFp16Supported)())throw new Error(`The device (${ze}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Ut}. Should be one of: ${Object.keys(ye.DATA_TYPES).join(", ")}`);const sr=ye.DEFAULT_DTYPE_SUFFIX_MAPPING[Ut],Ir=`${S.subfolder??""}/${m}${sr}.onnx`,ur={...S.session_options};ur.executionProviders??(ur.executionProviders=pt);const hr=Z.free_dimension_overrides;hr?ur.freeDimensionOverrides??(ur.freeDimensionOverrides=hr):ze.startsWith("webnn")&&!ur.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 wr=(0,j.getModelFile)(f,Ir,!0,S);let $r=[];if(S.use_external_data_format&&(S.use_external_data_format===!0||typeof S.use_external_data_format=="object"&&S.use_external_data_format.hasOwnProperty(m)&&S.use_external_data_format[m]===!0)){if(ce.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const _r=`${m}${sr}.onnx_data`,tn=`${S.subfolder??""}/${_r}`;$r.push(new Promise(async(rn,wn)=>{const cn=await(0,j.getModelFile)(f,tn,!0,S);rn({path:_r,data:cn})}))}else ur.externalData!==void 0&&($r=ur.externalData.map(async _r=>{if(typeof _r.data=="string"){const tn=await(0,j.getModelFile)(f,_r.data,!0,S);return{..._r,data:tn}}return _r}));if($r.length>0&&(ur.externalData=await Promise.all($r)),ze==="webgpu"){const _r=(0,O.getKeyValueShapes)(S.config,{prefix:"present"});if(Object.keys(_r).length>0&&!(0,fe.isONNXProxy)()){const tn={};for(const rn in _r)rn.includes("encoder")||(tn[rn]="gpu-buffer");ur.preferredOutputLocation=tn}}return{buffer:await wr,session_options:ur}}async function B(f,m,S){return Object.fromEntries(await Promise.all(Object.keys(m).map(async Z=>{const{buffer:Fe,session_options:ze}=await I(f,m[Z],S),pt=await(0,fe.createInferenceSession)(Fe,ze);return[Z,pt]})))}function k(f,m){const S=Object.create(null),Z=[];for(const pt of f.inputNames){const Ct=m[pt];if(!(Ct instanceof A.Tensor)){Z.push(pt);continue}S[pt]=(0,fe.isONNXProxy)()?Ct.clone():Ct}if(Z.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Z.join(", ")}.`);const Fe=Object.keys(m).length,ze=f.inputNames.length;if(Fe>ze){let pt=Object.keys(m).filter(Ct=>!f.inputNames.includes(Ct));console.warn(`WARNING: Too many inputs were provided (${Fe} > ${ze}). The following inputs will be ignored: "${pt.join(", ")}".`)}return S}async function ue(f,m){const S=k(f,m);try{const Z=Object.fromEntries(Object.entries(S).map(([ze,pt])=>[ze,pt.ort_tensor]));let Fe=await f.run(Z);return Fe=ve(Fe),Fe}catch(Z){throw console.error(`An error occurred during model execution: "${Z}".`),console.error("Inputs given to model:",S),Z}}function ve(f){for(let m in f)(0,fe.isONNXTensor)(f[m])?f[m]=new A.Tensor(f[m]):typeof f[m]=="object"&&ve(f[m]);return f}function Ee(f){if(f instanceof A.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(m=>m.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 A.Tensor("int64",BigInt64Array.from(f.flat().map(m=>BigInt(m))),[f.length,f[0].length])}else return new A.Tensor("int64",BigInt64Array.from(f.map(m=>BigInt(m))),[1,f.length])}function Ie(f){return new A.Tensor("bool",[f],[1])}async function Ae(f,m){let{encoder_outputs:S,input_ids:Z,decoder_input_ids:Fe,...ze}=m;if(!S){const Ct=(0,Ce.pick)(m,f.sessions.model.inputNames);S=(await tt(f,Ct)).last_hidden_state}return ze.input_ids=Fe,ze.encoder_hidden_states=S,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(ze.encoder_attention_mask=m.attention_mask),await Xe(f,ze,!0)}async function tt(f,m){const S=f.sessions.model,Z=(0,Ce.pick)(m,S.inputNames);if(S.inputNames.includes("inputs_embeds")&&!Z.inputs_embeds){if(!m.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Z.inputs_embeds=await f.encode_text({input_ids:m.input_ids})}return S.inputNames.includes("token_type_ids")&&!Z.token_type_ids&&(Z.token_type_ids=new A.Tensor("int64",new BigInt64Array(Z.input_ids.data.length),Z.input_ids.dims)),await ue(S,Z)}async function Xe(f,m,S=!1){const Z=f.sessions[S?"decoder_model_merged":"model"],{past_key_values:Fe,...ze}=m;Z.inputNames.includes("use_cache_branch")&&(ze.use_cache_branch=Ie(!!Fe)),Z.inputNames.includes("position_ids")&&ze.attention_mask&&!ze.position_ids&&(ze.position_ids=ge(ze,Fe)),f.addPastKeyValues(ze,Fe);const pt=(0,Ce.pick)(ze,Z.inputNames);return await ue(Z,pt)}async function dt(f,{input_ids:m=null,attention_mask:S=null,pixel_values:Z=null,position_ids:Fe=null,inputs_embeds:ze=null,past_key_values:pt=null,generation_config:Ct=null,logits_processor:Ut=null,...sr}){if(!ze){if(ze=await f.encode_text({input_ids:m}),Z&&m.dims[1]!==1){const ur=await f.encode_image({pixel_values:Z});({inputs_embeds:ze,attention_mask:S}=f._merge_input_ids_with_image_features({image_features:ur,inputs_embeds:ze,input_ids:m,attention_mask:S}))}else if(pt&&Z&&m.dims[1]===1){const ur=m.dims[1],hr=Object.values(pt)[0].dims.at(-2);S=(0,A.cat)([(0,A.ones)([m.dims[0],hr]),S.slice(null,[S.dims[1]-ur,S.dims[1]])],1)}}return await Xe(f,{inputs_embeds:ze,past_key_values:pt,attention_mask:S,position_ids:Fe,generation_config:Ct,logits_processor:Ut},!0)}function ge(f,m=null){const{input_ids:S,inputs_embeds:Z,attention_mask:Fe}=f,[ze,pt]=Fe.dims,Ct=new BigInt64Array(Fe.data.length);for(let sr=0;srze.dims[1])){if(FeCt==f.config.image_token_index)){const Ct=f.config.num_image_tokens;if(!Ct)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ut=ze.dims[1]-(Fe-Ct);S.input_ids=ze.slice(null,[-Ut,null]),S.attention_mask=(0,A.ones)([1,Fe+Ut])}}}return S}function de(f,m,S,Z){return S.past_key_values&&(m=m.map(Fe=>[Fe.at(-1)])),{...S,decoder_input_ids:Ee(m)}}function $e(f,...m){return f.config.is_encoder_decoder?de(f,...m):W(f,...m)}class J extends Te.Callable{constructor(S,Z){super();xe(this,"main_input_name","input_ids");xe(this,"forward_params",["input_ids","attention_mask"]);this.config=S,this.sessions=Z;const Fe=R.get(this.constructor),ze=se.get(Fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,ze){case te.DecoderOnly:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=W;break;case te.Seq2Seq:case te.Vision2Seq:case te.Musicgen:this.can_generate=!0,this._forward=Ae,this._prepare_inputs_for_generation=de;break;case te.EncoderDecoder:this._forward=Ae;break;case te.ImageTextToText:this.can_generate=!0,this._forward=dt,this._prepare_inputs_for_generation=$e;break;default:this._forward=tt;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var Z;const S=[];for(const Fe of Object.values(this.sessions))(Z=Fe==null?void 0:Fe.handler)!=null&&Z.dispose&&S.push(Fe.handler.dispose());return await Promise.all(S)}static async from_pretrained(S,{progress_callback:Z=null,config:Fe=null,cache_dir:ze=null,local_files_only:pt=!1,revision:Ct="main",model_file_name:Ut=null,subfolder:sr="onnx",device:Ir=null,dtype:ur=null,use_external_data_format:hr=null,session_options:wr={}}={}){let $r={progress_callback:Z,config:Fe,cache_dir:ze,local_files_only:pt,revision:Ct,model_file_name:Ut,subfolder:sr,device:Ir,dtype:ur,use_external_data_format:hr,session_options:wr};const Fr=R.get(this),kr=se.get(Fr);Fe=$r.config=await O.AutoConfig.from_pretrained(S,$r);let _r;if(kr===te.DecoderOnly)_r=await Promise.all([B(S,{model:$r.model_file_name??"model"},$r),(0,j.getModelJSON)(S,"generation_config.json",!1,$r)]);else if(kr===te.Seq2Seq||kr===te.Vision2Seq)_r=await Promise.all([B(S,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},$r),(0,j.getModelJSON)(S,"generation_config.json",!1,$r)]);else if(kr===te.MaskGeneration)_r=await Promise.all([B(S,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},$r)]);else if(kr===te.EncoderDecoder)_r=await Promise.all([B(S,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},$r)]);else if(kr===te.ImageTextToText){const tn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Fe.is_encoder_decoder&&(tn.model="encoder_model"),_r=await Promise.all([B(S,tn,$r),(0,j.getModelJSON)(S,"generation_config.json",!1,$r)])}else kr===te.Musicgen?_r=await Promise.all([B(S,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},$r),(0,j.getModelJSON)(S,"generation_config.json",!1,$r)]):(kr!==te.EncoderOnly&&console.warn(`Model type for '${Fr??(Fe==null?void 0:Fe.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),_r=await Promise.all([B(S,{model:$r.model_file_name??"model"},$r)]));return new this(Fe,..._r)}async _call(S){return await this.forward(S)}async forward(S){return await this._forward(this,S)}_get_logits_warper(S){const Z=new $.LogitsProcessorList;return S.temperature!==null&&S.temperature!==1&&Z.push(new $.TemperatureLogitsWarper(S.temperature)),S.top_k!==null&&S.top_k!==0&&Z.push(new $.TopKLogitsWarper(S.top_k)),S.top_p!==null&&S.top_p<1&&Z.push(new $.TopPLogitsWarper(S.top_p)),Z}_get_logits_processor(S,Z,Fe=null){const ze=new $.LogitsProcessorList;if(S.repetition_penalty!==null&&S.repetition_penalty!==1&&ze.push(new $.RepetitionPenaltyLogitsProcessor(S.repetition_penalty)),S.no_repeat_ngram_size!==null&&S.no_repeat_ngram_size>0&&ze.push(new $.NoRepeatNGramLogitsProcessor(S.no_repeat_ngram_size)),S.bad_words_ids!==null&&ze.push(new $.NoBadWordsLogitsProcessor(S.bad_words_ids,S.eos_token_id)),S.min_length!==null&&S.eos_token_id!==null&&S.min_length>0&&ze.push(new $.MinLengthLogitsProcessor(S.min_length,S.eos_token_id)),S.min_new_tokens!==null&&S.eos_token_id!==null&&S.min_new_tokens>0&&ze.push(new $.MinNewTokensLengthLogitsProcessor(Z,S.min_new_tokens,S.eos_token_id)),S.forced_bos_token_id!==null&&ze.push(new $.ForcedBOSTokenLogitsProcessor(S.forced_bos_token_id)),S.forced_eos_token_id!==null&&ze.push(new $.ForcedEOSTokenLogitsProcessor(S.max_length,S.forced_eos_token_id)),S.begin_suppress_tokens!==null){const pt=Z>1||S.forced_bos_token_id===null?Z:Z+1;ze.push(new $.SuppressTokensAtBeginLogitsProcessor(S.begin_suppress_tokens,pt))}return S.guidance_scale!==null&&S.guidance_scale>1&&ze.push(new $.ClassifierFreeGuidanceLogitsProcessor(S.guidance_scale)),Fe!==null&&ze.extend(Fe),ze}_prepare_generation_config(S,Z,Fe=V.GenerationConfig){const ze={...this.config};for(const Ct of["decoder","generator","text_config"])Ct in ze&&Object.assign(ze,ze[Ct]);const pt=new Fe(ze);return"generation_config"in this&&Object.assign(pt,this.generation_config),S&&Object.assign(pt,S),Z&&Object.assign(pt,(0,Ce.pick)(Z,Object.getOwnPropertyNames(pt))),pt}_get_stopping_criteria(S,Z=null){const Fe=new ne.StoppingCriteriaList;return S.max_length!==null&&Fe.push(new ne.MaxLengthCriteria(S.max_length,this.config.max_position_embeddings??null)),S.eos_token_id!==null&&Fe.push(new ne.EosTokenCriteria(S.eos_token_id)),Z&&Fe.extend(Z),Fe}_validate_model_class(){if(!this.can_generate){const S=[za,Da,Oa,Fa],Z=R.get(this.constructor),Fe=new Set,ze=this.config.model_type;for(const Ct of S){const Ut=Ct.get(ze);Ut&&Fe.add(Ut[0])}let pt=`The current model class (${Z}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Fe.size>0&&(pt+=` Please use the following class instead: ${[...Fe].join(", ")}`),Error(pt)}}prepare_inputs_for_generation(...S){return this._prepare_inputs_for_generation(this,...S)}_update_model_kwargs_for_generation({generated_input_ids:S,outputs:Z,model_inputs:Fe,is_encoder_decoder:ze}){return Fe.past_key_values=this.getPastKeyValues(Z,Fe.past_key_values),Fe.input_ids=new A.Tensor("int64",S.flat(),[S.length,1]),ze||(Fe.attention_mask=(0,A.cat)([Fe.attention_mask,(0,A.ones)([Fe.attention_mask.dims[0],1])],1)),Fe.position_ids=null,Fe}_prepare_model_inputs({inputs:S,bos_token_id:Z,model_kwargs:Fe}){const ze=(0,Ce.pick)(Fe,this.forward_params),pt=this.main_input_name;if(pt in ze){if(S)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else ze[pt]=S;return{inputs_tensor:ze[pt],model_inputs:ze,model_input_name:pt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:S,model_inputs:Z,model_input_name:Fe,generation_config:ze}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Z.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Ct,pixel_values:Ut,attention_mask:sr,...Ir}=Z,ur=await this._prepare_inputs_embeds(Z);Z={...Ir,...(0,Ce.pick)(ur,["inputs_embeds","attention_mask"])}}let{last_hidden_state:pt}=await tt(this,Z);if(ze.guidance_scale!==null&&ze.guidance_scale>1)pt=(0,A.cat)([pt,(0,A.full_like)(pt,0)],0),"attention_mask"in Z&&(Z.attention_mask=(0,A.cat)([Z.attention_mask,(0,A.zeros_like)(Z.attention_mask)],0));else if(Z.decoder_input_ids){const Ct=Ee(Z.decoder_input_ids).dims[0];if(Ct!==pt.dims[0]){if(pt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${pt.dims[0]}) than the decoder inputs (${Ct}).`);pt=(0,A.cat)(Array.from({length:Ct},()=>pt),0)}}return Z.encoder_outputs=pt,Z}_prepare_decoder_input_ids_for_generation({batch_size:S,model_input_name:Z,model_kwargs:Fe,decoder_start_token_id:ze,bos_token_id:pt,generation_config:Ct}){let{decoder_input_ids:Ut,...sr}=Fe;if(Ut)Array.isArray(Ut[0])||(Ut=Array.from({length:S},()=>Ut));else if(ze??(ze=pt),this.config.model_type==="musicgen")Ut=Array.from({length:S*this.config.decoder.num_codebooks},()=>[ze]);else if(Array.isArray(ze)){if(ze.length!==S)throw new Error(`\`decoder_start_token_id\` expcted to have length ${S} but got ${ze.length}`);Ut=ze}else Ut=Array.from({length:S},()=>[ze]);return Ut=Ee(Ut),Fe.decoder_attention_mask=(0,A.ones_like)(Ut),{input_ids:Ut,model_inputs:sr}}async generate({inputs:S=null,generation_config:Z=null,logits_processor:Fe=null,stopping_criteria:ze=null,streamer:pt=null,...Ct}){this._validate_model_class(),Z=this._prepare_generation_config(Z,Ct);let{inputs_tensor:Ut,model_inputs:sr,model_input_name:Ir}=this._prepare_model_inputs({inputs:S,model_kwargs:Ct});const ur=this.config.is_encoder_decoder;ur&&("encoder_outputs"in sr||(sr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ut,model_inputs:sr,model_input_name:Ir,generation_config:Z})));let hr;ur?{input_ids:hr,model_inputs:sr}=this._prepare_decoder_input_ids_for_generation({batch_size:sr[Ir].dims.at(0),model_input_name:Ir,model_kwargs:sr,decoder_start_token_id:Z.decoder_start_token_id,bos_token_id:Z.bos_token_id,generation_config:Z}):hr=sr[Ir];let wr=hr.dims.at(-1);Z.max_new_tokens!==null&&(Z.max_length=wr+Z.max_new_tokens);const $r=this._get_logits_processor(Z,wr,Fe),Fr=this._get_stopping_criteria(Z,ze),kr=sr[Ir].dims.at(0),_r=me.LogitsSampler.getSampler(Z),tn=new Array(kr).fill(0),rn=hr.tolist();pt&&pt.put(rn);let wn,cn={};for(;;){if(sr=this.prepare_inputs_for_generation(rn,sr,Z),wn=await this.forward(sr),Z.output_attentions&&Z.return_dict_in_generate){const Rn=this.getAttentions(wn);for(const ys in Rn)ys in cn||(cn[ys]=[]),cn[ys].push(Rn[ys])}const ws=wn.logits.slice(null,-1,null),js=$r(rn,ws),Ka=[];for(let Rn=0;RnRn))break;sr=this._update_model_kwargs_for_generation({generated_input_ids:Ka,outputs:wn,model_inputs:sr,is_encoder_decoder:ur})}pt&&pt.end();const an=this.getPastKeyValues(wn,sr.past_key_values,!0),yn=new A.Tensor("int64",rn.flat(),[rn.length,rn[0].length]);if(Z.return_dict_in_generate)return{sequences:yn,past_key_values:an,...cn};for(const ws of Object.values(wn))ws.location==="gpu-buffer"&&ws.dispose();return yn}getPastKeyValues(S,Z,Fe=!1){const ze=Object.create(null);for(const pt in S)if(pt.startsWith("present")){const Ct=pt.replace("present","past_key_values"),Ut=pt.includes("encoder");if(Ut&&Z?ze[Ct]=Z[Ct]:ze[Ct]=S[pt],Z&&(!Ut||Fe)){const sr=Z[Ct];sr.location==="gpu-buffer"&&sr.dispose()}}return ze}getAttentions(S){const Z={};for(const Fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const ze in S)ze.startsWith(Fe)&&(Fe in Z||(Z[Fe]=[]),Z[Fe].push(S[ze]));return Z}addPastKeyValues(S,Z){if(Z)Object.assign(S,Z);else{const Fe=this.custom_config.kv_cache_dtype??"float32",ze=Fe==="float16"?new Uint16Array:[],pt=(0,O.getKeyValueShapes)(this.config);for(const Ct in pt)S[Ct]=new A.Tensor(Fe,ze,pt[Ct])}}async encode_image({pixel_values:S}){const Z=(await ue(this.sessions.vision_encoder,{pixel_values:S})).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 (${Z.dims[1]}).`),this.config.num_image_tokens=Z.dims[1]),Z}async encode_text({input_ids:S}){return(await ue(this.sessions.embed_tokens,{input_ids:S})).inputs_embeds}}class He{}class ct extends He{constructor({last_hidden_state:m,hidden_states:S=null,attentions:Z=null}){super(),this.last_hidden_state=m,this.hidden_states=S,this.attentions=Z}}class nt extends J{}class lt extends nt{}class je extends nt{async _call(m){return new dn(await super._call(m))}}class st extends nt{async _call(m){return new or(await super._call(m))}}class Pt extends nt{async _call(m){return new en(await super._call(m))}}class Le extends nt{async _call(m){return new hn(await super._call(m))}}class re extends J{}class ke extends re{}class Ve extends J{}class qe extends Ve{}class We extends Ve{async _call(m){return new dn(await super._call(m))}}class Ke extends Ve{async _call(m){return new or(await super._call(m))}}class ut extends Ve{async _call(m){return new en(await super._call(m))}}class yt extends Ve{async _call(m){return new hn(await super._call(m))}}class vt extends J{}class kt extends vt{}class v extends vt{async _call(m){return new dn(await super._call(m))}}class q extends vt{async _call(m){return new or(await super._call(m))}}class C extends vt{async _call(m){return new en(await super._call(m))}}class Y extends vt{async _call(m){return new hn(await super._call(m))}}class he extends J{}class Qe extends he{}class Ye extends he{async _call(m){return new dn(await super._call(m))}}class Bt extends he{async _call(m){return new or(await super._call(m))}}class ht extends he{async _call(m){return new en(await super._call(m))}}class Tt extends he{async _call(m){return new hn(await super._call(m))}}class bt extends J{}class Ot extends bt{}class cr extends bt{async _call(m){return new dn(await super._call(m))}}class xr extends bt{async _call(m){return new or(await super._call(m))}}class Yr extends bt{async _call(m){return new en(await super._call(m))}}class Br extends bt{async _call(m){return new hn(await super._call(m))}}class Kr extends J{}class at extends Kr{}class U extends Kr{async _call(m){return new dn(await super._call(m))}}class _e extends Kr{async _call(m){return new or(await super._call(m))}}class Pe extends Kr{async _call(m){return new en(await super._call(m))}}class rt extends Kr{async _call(m){return new hn(await super._call(m))}}class we extends J{}class Je extends we{}class gt extends we{async _call(m){return new dn(await super._call(m))}}class ft extends we{async _call(m){return new or(await super._call(m))}}class St extends we{async _call(m){return new en(await super._call(m))}}class mt extends we{async _call(m){return new hn(await super._call(m))}}class Ft extends J{}class Nt extends Ft{}class Rt extends Ft{async _call(m){return new or(await super._call(m))}}class Gt extends Ft{async _call(m){return new en(await super._call(m))}}class Me extends Ft{async _call(m){return new hn(await super._call(m))}}class et extends Ft{async _call(m){return new dn(await super._call(m))}}class ot extends J{}class Ht extends ot{}class gr extends ot{async _call(m){return new dn(await super._call(m))}}class Lr extends ot{async _call(m){return new or(await super._call(m))}}class mr extends ot{async _call(m){return new en(await super._call(m))}}class yr extends J{}class Tr extends yr{}class En extends yr{async _call(m){return new dn(await super._call(m))}}class Rr extends yr{async _call(m){return new or(await super._call(m))}}class Hn extends yr{async _call(m){return new hn(await super._call(m))}}class jn extends J{}class Ys extends jn{}class vs extends jn{async _call(m){return new dn(await super._call(m))}}class xs extends jn{async _call(m){return new or(await super._call(m))}}class Ts extends jn{async _call(m){return new en(await super._call(m))}}class Ss extends jn{async _call(m){return new hn(await super._call(m))}}class Kn extends J{}class Zs extends Kn{}class cs extends Kn{async _call(m){return new dn(await super._call(m))}}class Bn extends Kn{async _call(m){return new or(await super._call(m))}}class Xn extends Kn{async _call(m){return new hn(await super._call(m))}}class Vn extends J{}class ts extends Vn{}class ps extends Vn{async _call(m){return new or(await super._call(m))}}class hs extends Vn{async _call(m){return new hn(await super._call(m))}}class Xt extends Vn{async _call(m){return new dn(await super._call(m))}}class rs extends J{constructor(S,Z,Fe){super(S,Z);xe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Cs extends rs{}class Es extends rs{}class fs extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class $s extends fs{}class ks extends fs{}class ms extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class Ps extends ms{}class Gr extends ms{}class vn extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class be extends vn{}class _ extends vn{}class P extends vn{async _call(m){return new or(await super._call(m))}}class K extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class ie extends K{}class pe extends K{}class De extends K{async _call(m){return new or(await super._call(m))}}class wt extends K{}class xt extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class Mt extends xt{}class zt extends xt{}class er extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class zr extends er{}class ir extends er{}class qt extends J{}class pr extends qt{}class mn extends qt{async _call(m){return new dn(await super._call(m))}}class ln extends qt{async _call(m){return new or(await super._call(m))}}class Oe extends qt{async _call(m){return new en(await super._call(m))}}class $n extends qt{async _call(m){return new hn(await super._call(m))}}class Sr extends J{}class sn extends Sr{}class xn extends Sr{async _call(m){return new dn(await super._call(m))}}class Qt extends Sr{async _call(m){return new or(await super._call(m))}}class Tn extends Sr{async _call(m){return new en(await super._call(m))}}class pn extends Sr{async _call(m){return new hn(await super._call(m))}}class Ar extends J{}class Cr extends Ar{}class It extends Ar{async _call(m){return new dn(await super._call(m))}}class br extends Ar{async _call(m){return new or(await super._call(m))}}class Nr extends Ar{async _call(m){return new en(await super._call(m))}}class Xr extends Ar{async _call(m){return new hn(await super._call(m))}}class Sn extends J{}class jt extends Sn{}class Js extends Sn{}class Ze extends J{constructor(S,Z,Fe){super(S,Z);xe(this,"requires_attention_mask",!1);xe(this,"main_input_name","input_features");xe(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Wt extends Ze{}class bi extends Ze{_prepare_generation_config(m,S){return super._prepare_generation_config(m,S,D.WhisperGenerationConfig)}_retrieve_init_tokens(m){const S=[m.decoder_start_token_id];let Z=m.language;const Fe=m.task;if(m.is_multilingual){Z||(console.warn("No language specified - defaulting to English (en)."),Z="en");const pt=`<|${(0,H.whisper_language_to_code)(Z)}|>`;S.push(m.lang_to_id[pt]),S.push(m.task_to_id[Fe??"transcribe"])}else if(Z||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!m.return_timestamps&&m.no_timestamps_token_id&&S.at(-1)!==m.no_timestamps_token_id?S.push(m.no_timestamps_token_id):m.return_timestamps&&S.at(-1)===m.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),S.pop()),S.filter(ze=>ze!=null)}async generate({inputs:m=null,generation_config:S=null,logits_processor:Z=null,stopping_criteria:Fe=null,...ze}){S=this._prepare_generation_config(S,ze);const pt=ze.decoder_input_ids??this._retrieve_init_tokens(S);if(S.return_timestamps&&(Z??(Z=new $.LogitsProcessorList),Z.push(new $.WhisperTimeStampLogitsProcessor(S,pt))),S.begin_suppress_tokens&&(Z??(Z=new $.LogitsProcessorList),Z.push(new $.SuppressTokensAtBeginLogitsProcessor(S.begin_suppress_tokens,pt.length))),S.return_token_timestamps){if(!S.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.");S.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),S.output_attentions=!0,S.return_dict_in_generate=!0}const Ct=await super.generate({inputs:m,generation_config:S,logits_processor:Z,decoder_input_ids:pt,...ze});return S.return_token_timestamps&&(Ct.token_timestamps=this._extract_token_timestamps(Ct,S.alignment_heads,S.num_frames)),Ct}_extract_token_timestamps(m,S,Z=null,Fe=.02){if(!m.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`.");Z==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 ze=this.config.median_filter_width;ze===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),ze=7);const pt=m.cross_attentions,Ct=Array.from({length:this.config.decoder_layers},(Fr,kr)=>(0,A.cat)(pt.map(_r=>_r[kr]),2)),Ut=(0,A.stack)(S.map(([Fr,kr])=>{if(Fr>=Ct.length)throw new Error(`Layer index ${Fr} is out of bounds for cross attentions (length ${Ct.length}).`);return Z?Ct[Fr].slice(null,kr,null,[0,Z]):Ct[Fr].slice(null,kr)})).transpose(1,0,2,3),[sr,Ir]=(0,A.std_mean)(Ut,-2,0,!0),ur=Ut.clone();for(let Fr=0;Fr_r[yn+1]-_r[yn]),wn=(0,Ce.mergeArrays)([1],rn).map(an=>!!an),cn=[];for(let an=0;anhr.findIndex(wr=>wr==ze)),Ut=Ct.every(hr=>hr===-1),sr=Ct.every(hr=>hr!==-1);if(!Ut&&!sr)throw new Error("Every input should contain either 0 or 1 image token.");if(Ut)return{inputs_embeds:m,attention_mask:Fe};const Ir=[],ur=[];for(let hr=0;hrze*pt,1);m.input_labels=new A.Tensor("int64",new BigInt64Array(Fe).fill(1n),Z)}const S={image_embeddings:m.image_embeddings,image_positional_embeddings:m.image_positional_embeddings};return m.input_points&&(S.input_points=m.input_points),m.input_labels&&(S.input_labels=m.input_labels),m.input_boxes&&(S.input_boxes=m.input_boxes),await ue(this.sessions.prompt_encoder_mask_decoder,S)}async _call(m){return new Bl(await super._call(m))}}class Bl extends He{constructor({iou_scores:m,pred_masks:S}){super(),this.iou_scores=m,this.pred_masks=S}}class Os extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class Ll extends Os{}class ma extends Os{}class zs extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class Rl extends zs{}class Nl extends zs{}class is extends J{}class jl extends is{}class _a extends is{async _call(m){return new Jn(await super._call(m))}}class Ds extends is{async _call(m){return new or(await super._call(m))}}class Vl extends is{async _call(m){return new en(await super._call(m))}}class oi extends J{}class Ul extends oi{}class Wl extends oi{async _call(m){return new en(await super._call(m))}}class Gl extends J{}class bd extends Gl{}class li extends J{}class ql extends li{}class Md extends li{async _call(m){return new Jn(await super._call(m))}}class ga extends li{async _call(m){return new or(await super._call(m))}}class Bs extends J{}class Hl extends Bs{}class Kl extends Bs{async _call(m){return new Jn(await super._call(m))}}class Xl extends Bs{async _call(m){return new or(await super._call(m))}}class ui extends Bs{async _call(m){return new en(await super._call(m))}}class di extends J{}class ci extends di{}class wa extends di{async _call(m){return new Jn(await super._call(m))}}class ya extends di{async _call(m){return new or(await super._call(m))}}class vd extends J{}class Ql extends is{}class ba extends is{async _call(m){return new Jn(await super._call(m))}}class xd extends is{async _call(m){return new or(await super._call(m))}}class gs extends J{}class Yl extends gs{}class Td extends gs{async _call(m){return new Jn(await super._call(m))}}class Zl extends gs{async _call(m){return new or(await super._call(m))}}class Ma extends gs{async _call(m){return new qa(await super._call(m))}}class Sd extends gs{async _call(m){return new en(await super._call(m))}}class pi extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class Cd extends pi{}class Jl extends pi{}class va extends pi{async generate_speech(m,S,{threshold:Z=.5,minlenratio:Fe=0,maxlenratio:ze=20,vocoder:pt=null}={}){const Ct={input_ids:m},{encoder_outputs:Ut,encoder_attention_mask:sr}=await tt(this,Ct),Ir=Ut.dims[1]/this.config.reduction_factor,ur=Math.floor(Ir*ze),hr=Math.floor(Ir*Fe),wr=this.config.num_mel_bins;let $r=[],Fr=null,kr=null,_r=0;for(;;){++_r;const wn=Ie(!!kr);let cn;kr?cn=kr.output_sequence_out:cn=new A.Tensor("float32",new Float32Array(wr),[1,1,wr]);let an={use_cache_branch:wn,output_sequence:cn,encoder_attention_mask:sr,speaker_embeddings:S,encoder_hidden_states:Ut};this.addPastKeyValues(an,Fr),kr=await ue(this.sessions.decoder_model_merged,an),Fr=this.getPastKeyValues(kr,Fr);const{prob:yn,spectrum:ws}=kr;if($r.push(ws),_r>=hr&&(Array.from(yn.data).filter(js=>js>=Z).length>0||_r>=ur))break}const tn=(0,A.cat)($r),{waveform:rn}=await ue(pt.sessions.model,{spectrogram:tn});return{spectrogram:tn,waveform:rn}}}class eu extends J{constructor(){super(...arguments);xe(this,"main_input_name","spectrogram")}}class tu extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class ru extends tu{}class xa extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class nu extends xa{}class su extends xa{}class iu extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class au extends iu{}class ou extends iu{}class Ta extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class Ed extends Ta{}class lu extends Ta{}class hi extends J{}class uu extends hi{}class du extends hi{static async from_pretrained(m,S={}){return S.model_file_name??(S.model_file_name="text_model"),super.from_pretrained(m,S)}}class cu extends hi{static async from_pretrained(m,S={}){return S.model_file_name??(S.model_file_name="audio_model"),super.from_pretrained(m,S)}}class $d extends J{}class Ls extends $d{async _call(m){return new Ha(await super._call(m))}}class as extends J{}class pu extends as{}class hu extends as{}class fu extends as{}class Sa extends J{constructor(m,S,Z){super(m,S),this.generation_config=Z}}class mu extends Sa{}class Ca extends Sa{}class Ea extends J{}class _u extends Ea{}class gu extends Ea{async _call(m){return new or(await super._call(m))}}class wu extends J{}class kd extends wu{}class yu extends wu{}class $a extends J{constructor(S,Z,Fe){super(S,Z);xe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}_apply_and_filter_by_delay_pattern_mask(S){const[Z,Fe]=S.dims,ze=this.config.decoder.num_codebooks,pt=Fe-ze;let Ct=0;for(let Ir=0;Ir0&&wr<=pt&&(S.data[Ct++]=S.data[Ir])}const Ut=Math.floor(Z/ze),sr=Ct/(Ut*ze);return new A.Tensor(S.type,S.data.slice(0,Ct),[Ut,ze,sr])}prepare_inputs_for_generation(S,Z,Fe){let ze=structuredClone(S);for(let Ct=0;Ct=Ut&&(ze[Ct][Ut]=BigInt(this.config.decoder.pad_token_id));return Fe.guidance_scale!==null&&Fe.guidance_scale>1&&(ze=ze.concat(ze)),super.prepare_inputs_for_generation(ze,Z,Fe)}async generate(S){const Z=await super.generate(S),Fe=this._apply_and_filter_by_delay_pattern_mask(Z).unsqueeze_(0),{audio_values:ze}=await ue(this.sessions.encodec_decode,{audio_codes:Fe});return ze}}class ka extends J{}class bu extends ka{}class Pd extends ka{async _call(m){return new or(await super._call(m))}}class Pa extends J{}class Mu extends Pa{}class Ad extends Pa{async _call(m){return new or(await super._call(m))}}class Aa extends J{}class vu extends Aa{}class xu extends Aa{async _call(m){return new or(await super._call(m))}}class Ia extends J{}class Id extends Ia{}class Tu extends Ia{async _call(m){return new or(await super._call(m))}}class Su extends J{}class Cu extends Su{}class Dr{static async from_pretrained(m,{progress_callback:S=null,config:Z=null,cache_dir:Fe=null,local_files_only:ze=!1,revision:pt="main",model_file_name:Ct=null,subfolder:Ut="onnx",device:sr=null,dtype:Ir=null,use_external_data_format:ur=null,session_options:hr={}}={}){const wr={progress_callback:S,config:Z,cache_dir:Fe,local_files_only:ze,revision:pt,model_file_name:Ct,subfolder:Ut,device:sr,dtype:Ir,use_external_data_format:ur,session_options:hr};if(wr.config=await O.AutoConfig.from_pretrained(m,wr),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const $r of this.MODEL_CLASS_MAPPINGS){const Fr=$r.get(wr.config.model_type);if(Fr)return await Fr[1].from_pretrained(m,wr)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${wr.config.model_type}", attempting to construct from base class.`),await J.from_pretrained(m,wr);throw Error(`Unsupported model type: ${wr.config.model_type}`)}}xe(Dr,"MODEL_CLASS_MAPPINGS",null),xe(Dr,"BASE_IF_FAIL",!1);const yc=new Map([["bert",["BertModel",lt]],["nomic_bert",["NomicBertModel",ke]],["roformer",["RoFormerModel",qe]],["electra",["ElectraModel",Qe]],["esm",["EsmModel",Ht]],["convbert",["ConvBertModel",kt]],["camembert",["CamembertModel",Ot]],["deberta",["DebertaModel",at]],["deberta-v2",["DebertaV2Model",Je]],["mpnet",["MPNetModel",Ys]],["albert",["AlbertModel",ts]],["distilbert",["DistilBertModel",Nt]],["roberta",["RobertaModel",pr]],["xlm",["XLMModel",sn]],["xlm-roberta",["XLMRobertaModel",Cr]],["clap",["ClapModel",uu]],["clip",["CLIPModel",no]],["clipseg",["CLIPSegModel",co]],["chinese_clip",["ChineseCLIPModel",uo]],["siglip",["SiglipModel",io]],["mobilebert",["MobileBertModel",Tr]],["squeezebert",["SqueezeBertModel",Zs]],["wav2vec2",["Wav2Vec2Model",jl]],["wav2vec2-bert",["Wav2Vec2BertModel",ci]],["unispeech",["UniSpeechModel",ql]],["unispeech-sat",["UniSpeechSatModel",Hl]],["hubert",["HubertModel",Ql]],["wavlm",["WavLMModel",Yl]],["audio-spectrogram-transformer",["ASTModel",jt]],["vits",["VitsModel",Ls]],["pyannote",["PyAnnoteModel",Ul]],["wespeaker-resnet",["WeSpeakerResNetModel",bd]],["detr",["DetrModel",ol]],["rt_detr",["RTDetrModel",dl]],["table-transformer",["TableTransformerModel",ra]],["vit",["ViTModel",Ro]],["pvt",["PvtModel",gd]],["vit_msn",["ViTMSNModel",Go]],["vit_mae",["ViTMAEModel",Uo]],["groupvit",["GroupViTModel",Ho]],["fastvit",["FastViTModel",Ko]],["mobilevit",["MobileViTModel",Zo]],["mobilevitv2",["MobileViTV2Model",el]],["owlvit",["OwlViTModel",Is]],["owlv2",["Owlv2Model",nl]],["beit",["BeitModel",il]],["deit",["DeiTModel",fl]],["hiera",["HieraModel",_l]],["convnext",["ConvNextModel",Qn]],["convnextv2",["ConvNextV2Model",pa]],["dinov2",["Dinov2Model",ha]],["resnet",["ResNetModel",aa]],["swin",["SwinModel",yl]],["swin2sr",["Swin2SRModel",bl]],["donut-swin",["DonutSwinModel",Il]],["yolos",["YolosModel",Ol]],["dpt",["DPTModel",Ml]],["glpn",["GLPNModel",kl]],["hifigan",["SpeechT5HifiGan",eu]],["efficientnet",["EfficientNetModel",_u]],["decision_transformer",["DecisionTransformerModel",Cu]],["mobilenet_v1",["MobileNetV1Model",bu]],["mobilenet_v2",["MobileNetV2Model",Mu]],["mobilenet_v3",["MobileNetV3Model",vu]],["mobilenet_v4",["MobileNetV4Model",Id]],["maskformer",["MaskFormerModel",yd]]]),Fd=new Map([["t5",["T5Model",Cs]],["longt5",["LongT5Model",$s]],["mt5",["MT5Model",Ps]],["bart",["BartModel",be]],["mbart",["MBartModel",ie]],["marian",["MarianModel",Ll]],["whisper",["WhisperModel",Wt]],["m2m_100",["M2M100Model",Rl]],["blenderbot",["BlenderbotModel",Mt]],["blenderbot-small",["BlenderbotSmallModel",zr]]]),Od=new Map([["bloom",["BloomModel",zo]],["jais",["JAISModel",fo]],["gpt2",["GPT2Model",ho]],["gptj",["GPTJModel",_d]],["gpt_bigcode",["GPTBigCodeModel",ei]],["gpt_neo",["GPTNeoModel",_o]],["gpt_neox",["GPTNeoXModel",wo]],["codegen",["CodeGenModel",bo]],["llama",["LlamaModel",vo]],["cohere",["CohereModel",To]],["gemma",["GemmaModel",Co]],["gemma2",["Gemma2Model",Eo]],["openelm",["OpenELMModel",ko]],["qwen2",["Qwen2Model",Ao]],["phi",["PhiModel",Li]],["phi3",["Phi3Model",Fo]],["mpt",["MptModel",Bo]],["opt",["OPTModel",Lo]],["mistral",["MistralModel",nu]],["starcoder2",["Starcoder2Model",au]],["falcon",["FalconModel",Ed]],["stablelm",["StableLmModel",mu]]]),Fa=new Map([["speecht5",["SpeechT5ForSpeechToText",Jl]],["whisper",["WhisperForConditionalGeneration",bi]]]),Eu=new Map([["speecht5",["SpeechT5ForTextToSpeech",va]]]),zd=new Map([["vits",["VitsModel",Ls]],["musicgen",["MusicgenForConditionalGeneration",$a]]]),$u=new Map([["bert",["BertForSequenceClassification",st]],["roformer",["RoFormerForSequenceClassification",Ke]],["electra",["ElectraForSequenceClassification",Bt]],["esm",["EsmForSequenceClassification",Lr]],["convbert",["ConvBertForSequenceClassification",q]],["camembert",["CamembertForSequenceClassification",xr]],["deberta",["DebertaForSequenceClassification",_e]],["deberta-v2",["DebertaV2ForSequenceClassification",ft]],["mpnet",["MPNetForSequenceClassification",xs]],["albert",["AlbertForSequenceClassification",ps]],["distilbert",["DistilBertForSequenceClassification",Rt]],["roberta",["RobertaForSequenceClassification",ln]],["xlm",["XLMForSequenceClassification",Qt]],["xlm-roberta",["XLMRobertaForSequenceClassification",br]],["bart",["BartForSequenceClassification",P]],["mbart",["MBartForSequenceClassification",De]],["mobilebert",["MobileBertForSequenceClassification",Rr]],["squeezebert",["SqueezeBertForSequenceClassification",Bn]]]),ku=new Map([["bert",["BertForTokenClassification",Pt]],["roformer",["RoFormerForTokenClassification",ut]],["electra",["ElectraForTokenClassification",ht]],["esm",["EsmForTokenClassification",mr]],["convbert",["ConvBertForTokenClassification",C]],["camembert",["CamembertForTokenClassification",Yr]],["deberta",["DebertaForTokenClassification",Pe]],["deberta-v2",["DebertaV2ForTokenClassification",St]],["mpnet",["MPNetForTokenClassification",Ts]],["distilbert",["DistilBertForTokenClassification",Gt]],["roberta",["RobertaForTokenClassification",Oe]],["xlm",["XLMForTokenClassification",Tn]],["xlm-roberta",["XLMRobertaForTokenClassification",Nr]]]),Oa=new Map([["t5",["T5ForConditionalGeneration",Es]],["longt5",["LongT5ForConditionalGeneration",ks]],["mt5",["MT5ForConditionalGeneration",Gr]],["bart",["BartForConditionalGeneration",_]],["mbart",["MBartForConditionalGeneration",pe]],["marian",["MarianMTModel",ma]],["m2m_100",["M2M100ForConditionalGeneration",Nl]],["blenderbot",["BlenderbotForConditionalGeneration",zt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ir]]]),za=new Map([["bloom",["BloomForCausalLM",Do]],["gpt2",["GPT2LMHeadModel",In]],["jais",["JAISLMHeadModel",mo]],["gptj",["GPTJForCausalLM",Fn]],["gpt_bigcode",["GPTBigCodeForCausalLM",Pi]],["gpt_neo",["GPTNeoForCausalLM",go]],["gpt_neox",["GPTNeoXForCausalLM",yo]],["codegen",["CodeGenForCausalLM",Mo]],["llama",["LlamaForCausalLM",xo]],["cohere",["CohereForCausalLM",So]],["gemma",["GemmaForCausalLM",On]],["gemma2",["Gemma2ForCausalLM",$o]],["openelm",["OpenELMForCausalLM",Po]],["qwen2",["Qwen2ForCausalLM",Io]],["phi",["PhiForCausalLM",Ri]],["phi3",["Phi3ForCausalLM",ji]],["mpt",["MptForCausalLM",As]],["opt",["OPTForCausalLM",Wi]],["mbart",["MBartForCausalLM",wt]],["mistral",["MistralForCausalLM",su]],["starcoder2",["Starcoder2ForCausalLM",ou]],["falcon",["FalconForCausalLM",lu]],["trocr",["TrOCRForCausalLM",ru]],["stablelm",["StableLmForCausalLM",Ca]]]),Dd=new Map([["bert",["BertForMaskedLM",je]],["roformer",["RoFormerForMaskedLM",We]],["electra",["ElectraForMaskedLM",Ye]],["esm",["EsmForMaskedLM",gr]],["convbert",["ConvBertForMaskedLM",v]],["camembert",["CamembertForMaskedLM",cr]],["deberta",["DebertaForMaskedLM",U]],["deberta-v2",["DebertaV2ForMaskedLM",gt]],["mpnet",["MPNetForMaskedLM",vs]],["albert",["AlbertForMaskedLM",Xt]],["distilbert",["DistilBertForMaskedLM",et]],["roberta",["RobertaForMaskedLM",mn]],["xlm",["XLMWithLMHeadModel",xn]],["xlm-roberta",["XLMRobertaForMaskedLM",It]],["mobilebert",["MobileBertForMaskedLM",En]],["squeezebert",["SqueezeBertForMaskedLM",cs]]]),_n=new Map([["bert",["BertForQuestionAnswering",Le]],["roformer",["RoFormerForQuestionAnswering",yt]],["electra",["ElectraForQuestionAnswering",Tt]],["convbert",["ConvBertForQuestionAnswering",Y]],["camembert",["CamembertForQuestionAnswering",Br]],["deberta",["DebertaForQuestionAnswering",rt]],["deberta-v2",["DebertaV2ForQuestionAnswering",mt]],["mpnet",["MPNetForQuestionAnswering",Ss]],["albert",["AlbertForQuestionAnswering",hs]],["distilbert",["DistilBertForQuestionAnswering",Me]],["roberta",["RobertaForQuestionAnswering",$n]],["xlm",["XLMForQuestionAnswering",pn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Xr]],["mobilebert",["MobileBertForQuestionAnswering",Hn]],["squeezebert",["SqueezeBertForQuestionAnswering",Xn]]]),Da=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Mi]]]),Bd=new Map([["llava",["LlavaForConditionalGeneration",_s]],["moondream1",["Moondream1ForConditionalGeneration",ar]],["florence2",["Florence2ForConditionalGeneration",vi]]]),Pu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Mi]]]),Au=new Map([["vit",["ViTForImageClassification",No]],["pvt",["PvtForImageClassification",jo]],["vit_msn",["ViTMSNForImageClassification",Er]],["fastvit",["FastViTForImageClassification",Xo]],["mobilevit",["MobileViTForImageClassification",Jo]],["mobilevitv2",["MobileViTV2ForImageClassification",tl]],["beit",["BeitForImageClassification",al]],["deit",["DeiTForImageClassification",ml]],["hiera",["HieraForImageClassification",gl]],["convnext",["ConvNextForImageClassification",Yn]],["convnextv2",["ConvNextV2ForImageClassification",Zn]],["dinov2",["Dinov2ForImageClassification",si]],["resnet",["ResNetForImageClassification",wl]],["swin",["SwinForImageClassification",wd]],["segformer",["SegformerForImageClassification",hu]],["efficientnet",["EfficientNetForImageClassification",gu]],["mobilenet_v1",["MobileNetV1ForImageClassification",Pd]],["mobilenet_v2",["MobileNetV2ForImageClassification",Ad]],["mobilenet_v3",["MobileNetV3ForImageClassification",xu]],["mobilenet_v4",["MobileNetV4ForImageClassification",Tu]]]),Rs=new Map([["detr",["DetrForObjectDetection",ll]],["rt_detr",["RTDetrForObjectDetection",cl]],["table-transformer",["TableTransformerForObjectDetection",hl]],["yolos",["YolosForObjectDetection",zl]]]),Iu=new Map([["owlvit",["OwlViTForObjectDetection",rl]],["owlv2",["Owlv2ForObjectDetection",sl]]]),Fu=new Map([["detr",["DetrForSegmentation",Zi]],["clipseg",["CLIPSegForImageSegmentation",po]]]),Ba=new Map([["segformer",["SegformerForSemanticSegmentation",fu]],["sapiens",["SapiensForSemanticSegmentation",Sl]]]),Ou=new Map([["detr",["DetrForSegmentation",Zi]],["maskformer",["MaskFormerForInstanceSegmentation",$l]]]),zu=new Map([["sam",["SamModel",fa]]]),La=new Map([["wav2vec2",["Wav2Vec2ForCTC",_a]],["wav2vec2-bert",["Wav2Vec2BertForCTC",wa]],["unispeech",["UniSpeechForCTC",Md]],["unispeech-sat",["UniSpeechSatForCTC",Kl]],["wavlm",["WavLMForCTC",Td]],["hubert",["HubertForCTC",ba]]]),Du=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Ds]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",ya]],["unispeech",["UniSpeechForSequenceClassification",ga]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Xl]],["wavlm",["WavLMForSequenceClassification",Zl]],["hubert",["HubertForSequenceClassification",xd]],["audio-spectrogram-transformer",["ASTForAudioClassification",Js]]]),Bu=new Map([["wavlm",["WavLMForXVector",Ma]]]),Lu=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",ui]],["wavlm",["WavLMForAudioFrameClassification",Sd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Vl]],["pyannote",["PyAnnoteForAudioFrameClassification",Wl]]]),Ra=new Map([["vitmatte",["VitMatteForImageMatting",Yo]]]),Ru=new Map([["swin2sr",["Swin2SRForImageSuperResolution",zn]]]),Nu=new Map([["dpt",["DPTForDepthEstimation",vl]],["depth_anything",["DepthAnythingForDepthEstimation",Tl]],["glpn",["GLPNForDepthEstimation",Pl]],["sapiens",["SapiensForDepthEstimation",Cl]]]),Na=new Map([["sapiens",["SapiensForNormalEstimation",El]]]),ju=new Map([["clip",["CLIPVisionModelWithProjection",so]],["siglip",["SiglipVisionModel",oo]]]),Ld=[[yc,te.EncoderOnly],[Fd,te.EncoderDecoder],[Od,te.DecoderOnly],[$u,te.EncoderOnly],[ku,te.EncoderOnly],[Oa,te.Seq2Seq],[Fa,te.Seq2Seq],[za,te.DecoderOnly],[Dd,te.EncoderOnly],[_n,te.EncoderOnly],[Da,te.Vision2Seq],[Bd,te.ImageTextToText],[Au,te.EncoderOnly],[Fu,te.EncoderOnly],[Ou,te.EncoderOnly],[Ba,te.EncoderOnly],[Ra,te.EncoderOnly],[Ru,te.EncoderOnly],[Nu,te.EncoderOnly],[Na,te.EncoderOnly],[Rs,te.EncoderOnly],[Iu,te.EncoderOnly],[zu,te.MaskGeneration],[La,te.EncoderOnly],[Du,te.EncoderOnly],[Eu,te.Seq2Seq],[zd,te.EncoderOnly],[Bu,te.EncoderOnly],[Lu,te.EncoderOnly],[ju,te.EncoderOnly]];for(const[f,m]of Ld)for(const[S,Z]of f.values())se.set(S,m),R.set(Z,S),X.set(S,Z);const Rd=[["MusicgenForConditionalGeneration",$a,te.Musicgen],["CLIPTextModelWithProjection",Ln,te.EncoderOnly],["SiglipTextModel",ao,te.EncoderOnly],["ClapTextModelWithProjection",du,te.EncoderOnly],["ClapAudioModelWithProjection",cu,te.EncoderOnly]];for(const[f,m,S]of Rd)se.set(f,S),R.set(m,f),X.set(f,m);class ja extends Dr{}xe(ja,"MODEL_CLASS_MAPPINGS",Ld.map(m=>m[0])),xe(ja,"BASE_IF_FAIL",!0);class Vu extends Dr{}xe(Vu,"MODEL_CLASS_MAPPINGS",[$u]);class Uu extends Dr{}xe(Uu,"MODEL_CLASS_MAPPINGS",[ku]);class Nd extends Dr{}xe(Nd,"MODEL_CLASS_MAPPINGS",[Oa]);class Wu extends Dr{}xe(Wu,"MODEL_CLASS_MAPPINGS",[Fa]);class Gu extends Dr{}xe(Gu,"MODEL_CLASS_MAPPINGS",[Eu]);class qu extends Dr{}xe(qu,"MODEL_CLASS_MAPPINGS",[zd]);class jd extends Dr{}xe(jd,"MODEL_CLASS_MAPPINGS",[za]);class Hu extends Dr{}xe(Hu,"MODEL_CLASS_MAPPINGS",[Dd]);class Ku extends Dr{}xe(Ku,"MODEL_CLASS_MAPPINGS",[_n]);class Xu extends Dr{}xe(Xu,"MODEL_CLASS_MAPPINGS",[Da]);class Qu extends Dr{}xe(Qu,"MODEL_CLASS_MAPPINGS",[Au]);class Vd extends Dr{}xe(Vd,"MODEL_CLASS_MAPPINGS",[Fu]);class Yu extends Dr{}xe(Yu,"MODEL_CLASS_MAPPINGS",[Ba]);class Zu extends Dr{}xe(Zu,"MODEL_CLASS_MAPPINGS",[Ou]);class Ju extends Dr{}xe(Ju,"MODEL_CLASS_MAPPINGS",[Rs]);class ed extends Dr{}xe(ed,"MODEL_CLASS_MAPPINGS",[Iu]);class td extends Dr{}xe(td,"MODEL_CLASS_MAPPINGS",[zu]);class rd extends Dr{}xe(rd,"MODEL_CLASS_MAPPINGS",[La]);class nd extends Dr{}xe(nd,"MODEL_CLASS_MAPPINGS",[Du]);class sd extends Dr{}xe(sd,"MODEL_CLASS_MAPPINGS",[Bu]);class id extends Dr{}xe(id,"MODEL_CLASS_MAPPINGS",[Lu]);class Ud extends Dr{}xe(Ud,"MODEL_CLASS_MAPPINGS",[Pu]);class Ns extends Dr{}xe(Ns,"MODEL_CLASS_MAPPINGS",[Ra]);class Va extends Dr{}xe(Va,"MODEL_CLASS_MAPPINGS",[Ru]);class Ua extends Dr{}xe(Ua,"MODEL_CLASS_MAPPINGS",[Nu]);class Wa extends Dr{}xe(Wa,"MODEL_CLASS_MAPPINGS",[Na]);class Ga extends Dr{}xe(Ga,"MODEL_CLASS_MAPPINGS",[ju]);class Wd extends He{constructor({logits:m,past_key_values:S,encoder_outputs:Z,decoder_attentions:Fe=null,cross_attentions:ze=null}){super(),this.logits=m,this.past_key_values=S,this.encoder_outputs=Z,this.decoder_attentions=Fe,this.cross_attentions=ze}}class or extends He{constructor({logits:m}){super(),this.logits=m}}class qa extends He{constructor({logits:m,embeddings:S}){super(),this.logits=m,this.embeddings=S}}class en extends He{constructor({logits:m}){super(),this.logits=m}}class dn extends He{constructor({logits:m}){super(),this.logits=m}}class hn extends He{constructor({start_logits:m,end_logits:S}){super(),this.start_logits=m,this.end_logits=S}}class Jn extends He{constructor({logits:m}){super(),this.logits=m}}class Gd extends He{constructor({logits:m,past_key_values:S}){super(),this.logits=m,this.past_key_values=S}}class ad extends He{constructor({alphas:m}){super(),this.alphas=m}}class Ha extends He{constructor({waveform:m,spectrogram:S}){super(),this.waveform=m,this.spectrogram=S}}},"./src/models/whisper/common_whisper.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{WHISPER_LANGUAGE_MAPPING:()=>fe,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>ye,whisper_language_to_code:()=>Te});const O=[["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"]],fe=new Map(O),ye=new Map([...O.map(([Ce,j])=>[j,Ce]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Te(Ce){Ce=Ce.toLowerCase();let j=ye.get(Ce);if(j===void 0)if(fe.has(Ce))j=Ce;else{const V=Ce.length===2?fe.keys():fe.values();throw new Error(`Language "${Ce}" is not supported. Must be one of: ${JSON.stringify(V)}`)}return j}},"./src/models/whisper/generation_whisper.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{WhisperGenerationConfig:()=>fe});var O=N("./src/generation/configuration_utils.js");class fe extends O.GenerationConfig{constructor(){super(...arguments);xe(this,"return_timestamps",null);xe(this,"return_token_timestamps",null);xe(this,"num_frames",null);xe(this,"alignment_heads",null);xe(this,"task",null);xe(this,"language",null);xe(this,"no_timestamps_token_id",null);xe(this,"prompt_ids",null);xe(this,"is_multilingual",null);xe(this,"lang_to_id",null);xe(this,"task_to_id",null);xe(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{TensorOpRegistry:()=>Te});var O=N("./src/backends/onnx.js"),fe=N("./src/utils/tensor.js");const ye=async(Ce,j,$)=>{const V=await(0,O.createInferenceSession)(new Uint8Array(Ce),j);return async A=>{const ee=Object.fromEntries(Object.entries(A).map(([me,ce])=>[me,ce.ort_tensor])),ne=await V.run(ee);return Array.isArray($)?$.map(me=>new fe.Tensor(ne[me])):new fe.Tensor(ne[$])}};class Te{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=ye([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=ye([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=ye([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=ye([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=ye([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=ye([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}}xe(Te,"session_options",{})},"./src/pipelines.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{AudioClassificationPipeline:()=>Ie,AutomaticSpeechRecognitionPipeline:()=>tt,DepthEstimationPipeline:()=>nt,DocumentQuestionAnsweringPipeline:()=>J,FeatureExtractionPipeline:()=>ve,FillMaskPipeline:()=>se,ImageClassificationPipeline:()=>dt,ImageFeatureExtractionPipeline:()=>Ee,ImageSegmentationPipeline:()=>ge,ImageToImagePipeline:()=>ct,ImageToTextPipeline:()=>Xe,ObjectDetectionPipeline:()=>de,Pipeline:()=>ce,QuestionAnsweringPipeline:()=>te,SummarizationPipeline:()=>R,Text2TextGenerationPipeline:()=>X,TextClassificationPipeline:()=>D,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>He,TokenClassificationPipeline:()=>H,TranslationPipeline:()=>I,ZeroShotAudioClassificationPipeline:()=>Ae,ZeroShotClassificationPipeline:()=>ue,ZeroShotImageClassificationPipeline:()=>W,ZeroShotObjectDetectionPipeline:()=>$e,pipeline:()=>st});var O=N("./src/tokenizers.js"),fe=N("./src/models.js"),ye=N("./src/processors.js"),Te=N("./src/utils/generic.js"),Ce=N("./src/utils/core.js"),j=N("./src/utils/maths.js"),$=N("./src/utils/audio.js"),V=N("./src/utils/tensor.js"),A=N("./src/utils/image.js");async function ee(Le){return Array.isArray(Le)||(Le=[Le]),await Promise.all(Le.map(re=>A.RawImage.read(re)))}async function ne(Le,re){return Array.isArray(Le)||(Le=[Le]),await Promise.all(Le.map(ke=>typeof ke=="string"||ke instanceof URL?(0,$.read_audio)(ke,re):ke instanceof Float64Array?new Float32Array(ke):ke))}function me(Le,re){re&&(Le=Le.map(Ke=>Ke|0));const[ke,Ve,qe,We]=Le;return{xmin:ke,ymin:Ve,xmax:qe,ymax:We}}class ce extends Te.Callable{constructor({task:re,model:ke,tokenizer:Ve=null,processor:qe=null}){super(),this.task=re,this.model=ke,this.tokenizer=Ve,this.processor=qe}async dispose(){await this.model.dispose()}}class D extends ce{constructor(re){super(re)}async _call(re,{top_k:ke=1}={}){const Ve=this.tokenizer(re,{padding:!0,truncation:!0}),qe=await this.model(Ve),We=this.model.config.problem_type==="multi_label_classification"?yt=>yt.sigmoid():yt=>new V.Tensor("float32",(0,j.softmax)(yt.data),yt.dims),Ke=this.model.config.id2label,ut=[];for(const yt of qe.logits){const vt=We(yt),kt=await(0,V.topk)(vt,ke),v=kt[0].tolist(),C=kt[1].tolist().map((Y,he)=>({label:Ke?Ke[Y]:`LABEL_${Y}`,score:v[he]}));ke===1?ut.push(...C):ut.push(C)}return Array.isArray(re)||ke===1?ut:ut[0]}}class H extends ce{constructor(re){super(re)}async _call(re,{ignore_labels:ke=["O"]}={}){const Ve=Array.isArray(re),qe=this.tokenizer(Ve?re:[re],{padding:!0,truncation:!0}),Ke=(await this.model(qe)).logits,ut=this.model.config.id2label,yt=[];for(let vt=0;vtht==this.tokenizer.sep_token_id);yt[v].map((ht,Tt)=>ht==1&&(Tt===0||Tt>C&&vt.findIndex(bt=>bt==q[Tt])===-1));const Y=We[v].tolist(),he=Ke[v].tolist();for(let ht=1;htTt==q[ht])!==-1)&&(Y[ht]=-1/0,he[ht]=-1/0);const Qe=(0,j.softmax)(Y).map((ht,Tt)=>[ht,Tt]),Ye=(0,j.softmax)(he).map((ht,Tt)=>[ht,Tt]);Qe[0][0]=0,Ye[0][0]=0;const Bt=(0,Ce.product)(Qe,Ye).filter(ht=>ht[0][1]<=ht[1][1]).map(ht=>[ht[0][1],ht[1][1],ht[0][0]*ht[1][0]]).sort((ht,Tt)=>Tt[2]-ht[2]);for(let ht=0;htY==this.tokenizer.mask_token_id);if(vt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const kt=qe[ut][vt],v=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(kt.data),kt.dims),ke),q=v[0].tolist(),C=v[1].tolist();We.push(C.map((Y,he)=>{const Qe=yt.slice();return Qe[vt]=Y,{score:q[he],token:Number(Y),token_str:this.tokenizer.model.vocab[Y],sequence:this.tokenizer.decode(Qe,{skip_special_tokens:!0})}}))}return Array.isArray(re)?We:We[0]}}class X extends ce{constructor(ke){super(ke);xe(this,"_key","generated_text")}async _call(ke,Ve={}){Array.isArray(ke)||(ke=[ke]),this.model.config.prefix&&(ke=ke.map(vt=>this.model.config.prefix+vt));const qe=this.model.config.task_specific_params;qe&&qe[this.task]&&qe[this.task].prefix&&(ke=ke.map(vt=>qe[this.task].prefix+vt));const We=this.tokenizer,Ke={padding:!0,truncation:!0};let ut;this instanceof I&&"_build_translation_inputs"in We?ut=We._build_translation_inputs(ke,Ke,Ve):ut=We(ke,Ke);const yt=await this.model.generate({...ut,...Ve});return We.batch_decode(yt,{skip_special_tokens:!0}).map(vt=>({[this._key]:vt}))}}class R extends X{constructor(ke){super(ke);xe(this,"_key","summary_text")}}class I extends X{constructor(ke){super(ke);xe(this,"_key","translation_text")}}function B(Le){return Array.isArray(Le)&&Le.every(re=>"role"in re&&"content"in re)}class k extends ce{constructor(re){super(re)}async _call(re,ke={}){let Ve=!1,qe=!1,We;if(typeof re=="string")We=re=[re];else if(Array.isArray(re)&&re.every(C=>typeof C=="string"))Ve=!0,We=re;else{if(B(re))re=[re];else if(Array.isArray(re)&&re.every(B))Ve=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");qe=!0,We=re.map(C=>this.tokenizer.apply_chat_template(C,{tokenize:!1,add_generation_prompt:!0}))}const Ke=ke.add_special_tokens??!1,ut=qe?!1:ke.return_full_text??!0;this.tokenizer.padding_side="left";const yt=this.tokenizer(We,{add_special_tokens:Ke,padding:!0,truncation:!0}),vt=await this.model.generate({...yt,...ke}),kt=this.tokenizer.batch_decode(vt,{skip_special_tokens:!0});let v;!ut&&yt.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(yt.input_ids,{skip_special_tokens:!0}).map(C=>C.length));const q=Array.from({length:re.length},C=>[]);for(let C=0;C[ke.toLowerCase(),Ve])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(re,ke,{hypothesis_template:Ve="This example is {}.",multi_label:qe=!1}={}){const We=Array.isArray(re);We||(re=[re]),Array.isArray(ke)||(ke=[ke]);const Ke=ke.map(vt=>Ve.replace("{}",vt)),ut=qe||ke.length===1,yt=[];for(const vt of re){const kt=[];for(const C of Ke){const Y=this.tokenizer(vt,{text_pair:C,padding:!0,truncation:!0}),he=await this.model(Y);ut?kt.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):kt.push(he.logits.data[this.entailment_id])}const q=(ut?kt.map(C=>(0,j.softmax)(C)[1]):(0,j.softmax)(kt)).map((C,Y)=>[C,Y]).sort((C,Y)=>Y[0]-C[0]);yt.push({sequence:vt,labels:q.map(C=>ke[C[1]]),scores:q.map(C=>C[0])})}return We?yt:yt[0]}}class ve extends ce{constructor(re){super(re)}async _call(re,{pooling:ke="none",normalize:Ve=!1,quantize:qe=!1,precision:We="binary"}={}){const Ke=this.tokenizer(re,{padding:!0,truncation:!0}),ut=await this.model(Ke);let yt=ut.last_hidden_state??ut.logits??ut.token_embeddings;if(ke!=="none")if(ke==="mean")yt=(0,V.mean_pooling)(yt,Ke.attention_mask);else if(ke==="cls")yt=yt.slice(null,0);else throw Error(`Pooling method '${ke}' not supported.`);return Ve&&(yt=yt.normalize(2,-1)),qe&&(yt=(0,V.quantize_embeddings)(yt,We)),yt}}class Ee extends ce{constructor(re){super(re)}async _call(re,{pool:ke=null}={}){const Ve=await ee(re),{pixel_values:qe}=await this.processor(Ve),We=await this.model({pixel_values:qe});let Ke;if(ke){if(!("pooler_output"in We))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ke=We.pooler_output}else Ke=We.last_hidden_state??We.logits??We.image_embeds;return Ke}}class Ie extends ce{constructor(re){super(re)}async _call(re,{top_k:ke=5}={}){const Ve=this.processor.feature_extractor.config.sampling_rate,qe=await ne(re,Ve),We=this.model.config.id2label,Ke=[];for(const ut of qe){const yt=await this.processor(ut),kt=(await this.model(yt)).logits[0],v=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(kt.data),kt.dims),ke),q=v[0].tolist(),Y=v[1].tolist().map((he,Qe)=>({label:We?We[he]:`LABEL_${he}`,score:q[Qe]}));Ke.push(Y)}return Array.isArray(re)?Ke:Ke[0]}}class Ae extends ce{constructor(re){super(re)}async _call(re,ke,{hypothesis_template:Ve="This is a sound of {}."}={}){const qe=!Array.isArray(re);qe&&(re=[re]);const We=ke.map(kt=>Ve.replace("{}",kt)),Ke=this.tokenizer(We,{padding:!0,truncation:!0}),ut=this.processor.feature_extractor.config.sampling_rate,yt=await ne(re,ut),vt=[];for(const kt of yt){const v=await this.processor(kt),q=await this.model({...Ke,...v}),C=(0,j.softmax)(q.logits_per_audio.data);vt.push([...C].map((Y,he)=>({score:Y,label:ke[he]})))}return qe?vt[0]:vt}}class tt extends ce{constructor(re){super(re)}async _call(re,ke={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(re,ke);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(re,ke);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(re,ke){ke.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ke.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ve=!Array.isArray(re);Ve&&(re=[re]);const qe=this.processor.feature_extractor.config.sampling_rate,We=await ne(re,qe),Ke=[];for(const ut of We){const yt=await this.processor(ut),kt=(await this.model(yt)).logits[0],v=[];for(const C of kt)v.push((0,j.max)(C.data)[1]);const q=this.tokenizer.decode(v);Ke.push({text:q})}return Ve?Ke[0]:Ke}async _call_whisper(re,ke){const Ve=ke.return_timestamps??!1,qe=ke.chunk_length_s??0,We=ke.force_full_sequences??!1;let Ke=ke.stride_length_s??null;const ut={...ke};Ve==="word"&&(ut.return_token_timestamps=!0,ut.return_timestamps=!1);const yt=!Array.isArray(re);yt&&(re=[re]);const vt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,kt=this.processor.feature_extractor.config.hop_length,v=this.processor.feature_extractor.config.sampling_rate,q=await ne(re,v),C=[];for(const Y of q){let he=[];if(qe>0){if(Ke===null)Ke=qe/6;else if(qe<=Ke)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Bt=v*qe,ht=v*Ke,Tt=Bt-2*ht;let bt=0;for(;;){const Ot=bt+Bt,cr=Y.subarray(bt,Ot),xr=await this.processor(cr),Yr=bt===0,Br=Ot>=Y.length;if(he.push({stride:[cr.length,Yr?0:ht,Br?0:ht],input_features:xr.input_features,is_last:Br}),Br)break;bt+=Tt}}else he=[{stride:[Y.length,0,0],input_features:(await this.processor(Y)).input_features,is_last:!0}];for(const Bt of he){ut.num_frames=Math.floor(Bt.stride[0]/kt);const ht=await this.model.generate({inputs:Bt.input_features,...ut});Ve==="word"?(Bt.tokens=ht.sequences.tolist()[0],Bt.token_timestamps=ht.token_timestamps.tolist()[0].map(Tt=>(0,j.round)(Tt,2))):Bt.tokens=ht[0].tolist(),Bt.stride=Bt.stride.map(Tt=>Tt/v)}const[Qe,Ye]=this.tokenizer._decode_asr(he,{time_precision:vt,return_timestamps:Ve,force_full_sequences:We});C.push({text:Qe,...Ye})}return yt?C[0]:C}}class Xe extends ce{constructor(re){super(re)}async _call(re,ke={}){const Ve=Array.isArray(re),qe=await ee(re),{pixel_values:We}=await this.processor(qe),Ke=[];for(const ut of We){ut.dims=[1,...ut.dims];const yt=await this.model.generate({inputs:ut,...ke}),vt=this.tokenizer.batch_decode(yt,{skip_special_tokens:!0}).map(kt=>({generated_text:kt.trim()}));Ke.push(vt)}return Ve?Ke:Ke[0]}}class dt extends ce{constructor(re){super(re)}async _call(re,{top_k:ke=5}={}){const Ve=await ee(re),{pixel_values:qe}=await this.processor(Ve),We=await this.model({pixel_values:qe}),Ke=this.model.config.id2label,ut=[];for(const yt of We.logits){const vt=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(yt.data),yt.dims),ke),kt=vt[0].tolist(),q=vt[1].tolist().map((C,Y)=>({label:Ke?Ke[C]:`LABEL_${C}`,score:kt[Y]}));ut.push(q)}return Array.isArray(re)?ut:ut[0]}}class ge extends ce{constructor(re){super(re),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(re,{threshold:ke=.5,mask_threshold:Ve=.5,overlap_mask_area_threshold:qe=.8,label_ids_to_fuse:We=null,target_sizes:Ke=null,subtask:ut=null}={}){if(Array.isArray(re)&&re.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const vt=await ee(re),kt=vt.map(Ye=>[Ye.height,Ye.width]),{pixel_values:v,pixel_mask:q}=await this.processor(vt),C=await this.model({pixel_values:v,pixel_mask:q});let Y=null;if(ut!==null)Y=this.subtasks_mapping[ut];else for(let[Ye,Bt]of Object.entries(this.subtasks_mapping))if(Bt in this.processor.feature_extractor){Y=this.processor.feature_extractor[Bt].bind(this.processor.feature_extractor),ut=Ye;break}const he=this.model.config.id2label,Qe=[];if(ut==="panoptic"||ut==="instance"){const Ye=Y(C,ke,Ve,qe,We,Ke??kt)[0],Bt=Ye.segmentation;for(const ht of Ye.segments_info){const Tt=new Uint8ClampedArray(Bt.data.length);for(let Ot=0;OtVe.replace("{}",q)),ut=this.tokenizer(Ke,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:yt}=await this.processor(We),vt=await this.model({...ut,pixel_values:yt}),kt=this.model.config.model_type==="siglip"?q=>q.sigmoid().data:q=>(0,j.softmax)(q.data),v=[];for(const q of vt.logits_per_image){const Y=[...kt(q)].map((he,Qe)=>({score:he,label:ke[Qe]}));Y.sort((he,Qe)=>Qe.score-he.score),v.push(Y)}return qe?v:v[0]}}class de extends ce{constructor(re){super(re)}async _call(re,{threshold:ke=.9,percentage:Ve=!1}={}){const qe=Array.isArray(re);if(qe&&re.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const We=await ee(re),Ke=Ve?null:We.map(C=>[C.height,C.width]),{pixel_values:ut,pixel_mask:yt}=await this.processor(We),vt=await this.model({pixel_values:ut,pixel_mask:yt}),kt=this.processor.feature_extractor.post_process_object_detection(vt,ke,Ke),v=this.model.config.id2label,q=kt.map(C=>C.boxes.map((Y,he)=>({score:C.scores[he],label:v[C.classes[he]],box:me(Y,!Ve)})));return qe?q:q[0]}}class $e extends ce{constructor(re){super(re)}async _call(re,ke,{threshold:Ve=.1,top_k:qe=null,percentage:We=!1}={}){const Ke=Array.isArray(re),ut=await ee(re),yt=this.tokenizer(ke,{padding:!0,truncation:!0}),vt=await this.processor(ut),kt=[];for(let v=0;v({score:Qe.scores[ht],label:ke[Qe.classes[ht]],box:me(Bt,!We)})).sort((Bt,ht)=>ht.score-Bt.score);qe!==null&&(Ye=Ye.slice(0,qe)),kt.push(Ye)}return Ke?kt:kt[0]}}class J extends ce{constructor(re){super(re)}async _call(re,ke,Ve={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class He extends ce{constructor(ke){super(ke);xe(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ke.vocoder??null}async _call(ke,{speaker_embeddings:Ve=null}={}){return this.processor?this._call_text_to_spectrogram(ke,{speaker_embeddings:Ve}):this._call_text_to_waveform(ke)}async _call_text_to_waveform(ke){const Ve=this.tokenizer(ke,{padding:!0,truncation:!0}),{waveform:qe}=await this.model(Ve),We=this.model.config.sampling_rate;return{audio:qe.data,sampling_rate:We}}async _call_text_to_spectrogram(ke,{speaker_embeddings:Ve}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await fe.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ve=="string"||Ve instanceof URL)&&(Ve=new Float32Array(await(await fetch(Ve)).arrayBuffer())),Ve instanceof Float32Array)Ve=new V.Tensor("float32",Ve,[1,Ve.length]);else if(!(Ve instanceof V.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:qe}=this.tokenizer(ke,{padding:!0,truncation:!0}),{waveform:We}=await this.model.generate_speech(qe,Ve,{vocoder:this.vocoder}),Ke=this.processor.feature_extractor.config.sampling_rate;return{audio:We.data,sampling_rate:Ke}}}class ct extends ce{constructor(re){super(re)}async _call(re){const ke=await ee(re),Ve=await this.processor(ke),qe=await this.model(Ve),We=[];for(const Ke of qe.reconstruction){const ut=Ke.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");We.push(A.RawImage.fromTensor(ut))}return We.length>1?We:We[0]}}class nt extends ce{constructor(re){super(re)}async _call(re){const ke=await ee(re),Ve=await this.processor(ke),{predicted_depth:qe}=await this.model(Ve),We=[];for(let Ke=0;Ke1?We:We[0]}}const lt=Object.freeze({"text-classification":{tokenizer:O.AutoTokenizer,pipeline:D,model:fe.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:O.AutoTokenizer,pipeline:H,model:fe.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:O.AutoTokenizer,pipeline:te,model:fe.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:O.AutoTokenizer,pipeline:se,model:fe.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:O.AutoTokenizer,pipeline:R,model:fe.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:O.AutoTokenizer,pipeline:I,model:fe.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:O.AutoTokenizer,pipeline:X,model:fe.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:O.AutoTokenizer,pipeline:k,model:fe.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:O.AutoTokenizer,pipeline:ue,model:fe.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Ie,model:fe.AutoModelForAudioClassification,processor:ye.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:O.AutoTokenizer,pipeline:Ae,model:fe.AutoModel,processor:ye.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:O.AutoTokenizer,pipeline:tt,model:[fe.AutoModelForSpeechSeq2Seq,fe.AutoModelForCTC],processor:ye.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:O.AutoTokenizer,pipeline:He,model:[fe.AutoModelForTextToWaveform,fe.AutoModelForTextToSpectrogram],processor:[ye.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:O.AutoTokenizer,pipeline:Xe,model:fe.AutoModelForVision2Seq,processor:ye.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:dt,model:fe.AutoModelForImageClassification,processor:ye.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ge,model:[fe.AutoModelForImageSegmentation,fe.AutoModelForSemanticSegmentation,fe.AutoModelForUniversalSegmentation],processor:ye.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:O.AutoTokenizer,pipeline:W,model:fe.AutoModel,processor:ye.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:de,model:fe.AutoModelForObjectDetection,processor:ye.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:O.AutoTokenizer,pipeline:$e,model:fe.AutoModelForZeroShotObjectDetection,processor:ye.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:O.AutoTokenizer,pipeline:J,model:fe.AutoModelForDocumentQuestionAnswering,processor:ye.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ct,model:fe.AutoModelForImageToImage,processor:ye.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:nt,model:fe.AutoModelForDepthEstimation,processor:ye.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:O.AutoTokenizer,pipeline:ve,model:fe.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:ye.AutoProcessor,pipeline:Ee,model:[fe.AutoModelForImageFeatureExtraction,fe.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),je=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function st(Le,re=null,{progress_callback:ke=null,config:Ve=null,cache_dir:qe=null,local_files_only:We=!1,revision:Ke="main",device:ut=null,dtype:yt=null,model_file_name:vt=null,session_options:kt={}}={}){Le=je[Le]??Le;const v=lt[Le.split("_",1)[0]];if(!v)throw Error(`Unsupported pipeline: ${Le}. Must be one of [${Object.keys(lt)}]`);re||(re=v.default.model,console.log(`No model specified. Using default model: "${re}".`));const q={progress_callback:ke,config:Ve,cache_dir:qe,local_files_only:We,revision:Ke,device:ut,dtype:yt,model_file_name:vt,session_options:kt},C=new Map([["tokenizer",v.tokenizer],["model",v.model],["processor",v.processor]]),Y=await Pt(C,re,q);Y.task=Le,(0,Ce.dispatchCallback)(ke,{status:"ready",task:Le,model:re});const he=v.pipeline;return new he(Y)}async function Pt(Le,re,ke){const Ve=Object.create(null),qe=[];for(const[We,Ke]of Le.entries()){if(!Ke)continue;let ut;Array.isArray(Ke)?ut=new Promise(async(yt,vt)=>{var v,q;let kt;for(const C of Ke){if(C===null){yt(null);return}try{yt(await C.from_pretrained(re,ke));return}catch(Y){if((v=Y.message)!=null&&v.includes("Unsupported model type"))kt=Y;else if((q=Y.message)!=null&&q.includes("Could not locate file"))kt=Y;else{vt(Y);return}}}vt(kt)}):ut=Ke.from_pretrained(re,ke),Ve[We]=ut,qe.push(ut)}await Promise.all(qe);for(const[We,Ke]of Object.entries(Ve))Ve[We]=await Ke;return Ve}},"./src/processors.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{ASTFeatureExtractor:()=>Y,AutoProcessor:()=>Kr,BeitFeatureExtractor:()=>ke,BitImageProcessor:()=>ve,CLIPFeatureExtractor:()=>Ie,CLIPImageProcessor:()=>Ae,ChineseCLIPFeatureExtractor:()=>tt,ClapFeatureExtractor:()=>he,ConvNextFeatureExtractor:()=>dt,ConvNextImageProcessor:()=>ge,DPTFeatureExtractor:()=>k,DPTImageProcessor:()=>ue,DeiTFeatureExtractor:()=>re,DetrFeatureExtractor:()=>We,DonutFeatureExtractor:()=>Ve,EfficientNetImageProcessor:()=>$e,FeatureExtractor:()=>se,Florence2Processor:()=>Br,GLPNFeatureExtractor:()=>Ee,ImageFeatureExtractor:()=>X,MaskFormerFeatureExtractor:()=>Ke,MobileNetV1FeatureExtractor:()=>J,MobileNetV2FeatureExtractor:()=>He,MobileNetV3FeatureExtractor:()=>ct,MobileNetV4FeatureExtractor:()=>nt,MobileViTFeatureExtractor:()=>lt,MobileViTImageProcessor:()=>je,NougatImageProcessor:()=>qe,OwlViTFeatureExtractor:()=>st,OwlViTProcessor:()=>Yr,Owlv2ImageProcessor:()=>Pt,Processor:()=>ht,PvtImageProcessor:()=>B,PyAnnoteFeatureExtractor:()=>Qe,PyAnnoteProcessor:()=>cr,RTDetrImageProcessor:()=>Le,SamImageProcessor:()=>yt,SamProcessor:()=>Tt,SapiensFeatureExtractor:()=>R,SeamlessM4TFeatureExtractor:()=>C,SegformerFeatureExtractor:()=>I,SiglipImageProcessor:()=>Xe,SpeechT5FeatureExtractor:()=>Bt,SpeechT5Processor:()=>xr,Swin2SRImageProcessor:()=>vt,ViTFeatureExtractor:()=>W,ViTImageProcessor:()=>de,VitMatteImageProcessor:()=>kt,Wav2Vec2FeatureExtractor:()=>q,Wav2Vec2ProcessorWithLM:()=>Ot,WeSpeakerFeatureExtractor:()=>Ye,WhisperFeatureExtractor:()=>v,WhisperProcessor:()=>bt,YolosFeatureExtractor:()=>ut});var O=N("./src/utils/generic.js"),fe=N("./src/utils/core.js"),ye=N("./src/utils/hub.js"),Te=N("./src/utils/maths.js"),Ce=N("./src/utils/tensor.js");N("./src/utils/image.js");var j=N("./src/utils/audio.js");function $([at,U,_e,Pe]){return[at-_e/2,U-Pe/2,at+_e/2,U+Pe/2]}function V(at,U=.5,_e=null,Pe=!1){const rt=at.logits,we=at.pred_boxes,[Je,gt,ft]=rt.dims;if(_e!==null&&_e.length!==Je)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let St=[];for(let mt=0;mtU&&ot.push(gr)}else{let gr=(0,Te.max)(et.data)[1];if(gr===ft-1||(Ht=(0,Te.softmax)(et.data),Ht[gr]mr*Ft[(yr+1)%2])),Nt.boxes.push(Lr),Nt.classes.push(gr),Nt.scores.push(Ht[gr])}}St.push(Nt)}return St}function A(at,U=null){const _e=at.logits,Pe=_e.dims[0];if(U!==null&&U.length!==Pe)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const rt=[];for(let we=0;weFt[ot]&&(Ft[ot]=et[ot],Nt[ot]=Me)}const Rt=new Array(gt.dims[0]);for(let Me=0;MeMe!==void 0);rt.push({segmentation:mt,labels:Gt})}return rt}function ee(at,U,_e,Pe){const rt=[],we=[],Je=[];for(let gt=0;gt_e&&(rt.push(St),we.push(Nt),Je.push(mt))}return[rt,we,Je]}function ne(at,U,_e,Pe=.5,rt=.8){const we=[];let Je=0,gt=0;const ft=U[_e].data;for(let mt=0;mt=Pe&&++gt;let St=Je>0&>>0;return St&&(St=Je/gt>rt),[St,we]}function me(at,U,_e,Pe,rt,we=null,Je=null){const[gt,ft]=Je??at[0].dims,St=new Ce.Tensor("int32",new Int32Array(gt*ft),[gt,ft]),mt=[];if(Je!==null)for(let Me=0;MeNt[Ht]&&(Ft[Ht]=Me,Nt[Ht]=ot[Ht])}let Rt=0;const Gt=St.data;for(let Me=0;Me<_e.length;++Me){const et=_e[Me],[ot,Ht]=ne(Ft,at,Me,Pe,rt);if(ot){++Rt;for(const gr of Ht)Gt[gr]=Rt;mt.push({id:Rt,label_id:et,score:U[Me]})}}return[St,mt]}function ce(at,U=.5,_e=.5,Pe=.8,rt=null,we=null){rt===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),rt=new Set);const Je=at.class_queries_logits??at.logits,ft=(at.masks_queries_logits??at.pred_masks).sigmoid();let[St,mt,Ft]=Je.dims;if(Ft-=1,we!==null&&we.length!==St)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Nt=[];for(let Rt=0;RtPe&&(we=Math.floor(rt)*U),we<_e&&(we=Math.ceil(rt)*U),we}function te([at,U],_e){return[Math.max(Math.floor(at/_e),1)*_e,Math.max(Math.floor(U/_e),1)*_e]}class se extends O.Callable{constructor(U){super(),this.config=U}}class X extends se{constructor(U){super(U),this.image_mean=this.config.image_mean??this.config.mean,this.image_std=this.config.image_std??this.config.std,this.resample=this.config.resample??2,this.do_rescale=this.config.do_rescale??!0,this.rescale_factor=this.config.rescale_factor??.00392156862745098,this.do_normalize=this.config.do_normalize,this.do_resize=this.config.do_resize,this.do_thumbnail=this.config.do_thumbnail,this.size=this.config.size,this.size_divisibility=this.config.size_divisibility??this.config.size_divisor,this.do_center_crop=this.config.do_center_crop,this.crop_size=this.config.crop_size,this.do_convert_rgb=this.config.do_convert_rgb??!0,this.do_crop_margin=this.config.do_crop_margin,this.pad_size=this.config.pad_size,this.do_pad=this.config.do_pad,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=this.config.do_flip_channel_order??!1}async thumbnail(U,_e,Pe=2){const rt=U.height,we=U.width,Je=_e.height,gt=_e.width;let ft=Math.min(rt,Je),St=Math.min(we,gt);return ft===rt&&St===we?U:(rt>we?St=Math.floor(we*ft/rt):we>rt&&(ft=Math.floor(rt*St/we)),await U.resize(St,ft,{resample:Pe}))}async crop_margin(U,_e=200){const Pe=U.clone().grayscale(),rt=(0,Te.min)(Pe.data)[0],Je=(0,Te.max)(Pe.data)[0]-rt;if(Je===0)return U;const gt=_e/255;let ft=Pe.width,St=Pe.height,mt=0,Ft=0;const Nt=Pe.data;for(let Rt=0;Rtthis.preprocess(we)));return{pixel_values:(0,Ce.stack)(Pe.map(we=>we.pixel_values),0),original_sizes:Pe.map(we=>we.original_size),reshaped_input_sizes:Pe.map(we=>we.reshaped_input_size)}}}class R extends X{post_process_semantic_segmentation(...U){return A(...U)}}class I extends X{post_process_semantic_segmentation(...U){return A(...U)}}class B extends X{}class k extends X{}class ue extends k{}class ve extends X{}class Ee extends X{}class Ie extends X{}class Ae extends Ie{}class tt extends X{}class Xe extends X{}class dt extends X{constructor(U){super(U),this.crop_pct=this.config.crop_pct??.875}async resize(U){var Pe;const _e=(Pe=this.size)==null?void 0:Pe.shortest_edge;if(_e===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(_e<384){const rt=Math.floor(_e/this.crop_pct),[we,Je]=this.get_resize_output_image_size(U,{shortest_edge:rt});U=await U.resize(we,Je,{resample:this.resample}),U=await U.center_crop(_e,_e)}else U=await U.resize(_e,_e,{resample:this.resample});return U}}class ge extends dt{}class W extends X{}class de extends X{}class $e extends X{constructor(U){super(U),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(_e=>_e*_e))}}class J extends X{}class He extends X{}class ct extends X{}class nt extends X{}class lt extends X{}class je extends lt{}class st extends X{post_process_object_detection(...U){return V(...U)}}class Pt extends st{}class Le extends X{post_process_object_detection(...U){return V(...U)}}class re extends X{}class ke extends X{}class Ve extends X{pad_image(U,_e,Pe,rt={}){const[we,Je,gt]=_e;let ft=this.image_mean;Array.isArray(this.image_mean)||(ft=new Array(gt).fill(ft));let St=this.image_std;Array.isArray(St)||(St=new Array(gt).fill(ft));const mt=ft.map((Ft,Nt)=>-Ft/St[Nt]);return super.pad_image(U,_e,Pe,{center:!0,constant_values:mt,...rt})}}class qe extends Ve{}class We extends X{async _call(U){const _e=await super._call(U),Pe=[_e.pixel_values.dims[0],64,64],rt=(0,Ce.full)(Pe,1n);return{..._e,pixel_mask:rt}}post_process_object_detection(...U){return V(...U)}post_process_panoptic_segmentation(...U){return ce(...U)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class Ke extends X{post_process_panoptic_segmentation(...U){return ce(...U)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class ut extends X{post_process_object_detection(...U){return V(...U)}}class yt extends X{reshape_input_points(U,_e,Pe,rt=!1){U=structuredClone(U);let we=(0,fe.calculateDimensions)(U);if(we.length===3)rt||(we=[1,...we]),U=[U];else if(we.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 Je=0;Jert!==_e.dims[we]))throw Error(`The first ${Pe.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Ce.Tensor("int64",U.flat(1/0).map(BigInt),Pe)}async _call(U,{input_points:_e=null,input_labels:Pe=null,input_boxes:rt=null}={}){const we=await super._call(U);if(_e&&(we.input_points=this.reshape_input_points(_e,we.original_sizes,we.reshaped_input_sizes)),Pe){if(!we.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");we.input_labels=this.add_input_labels(Pe,we.input_points)}return rt&&(we.input_boxes=this.reshape_input_points(rt,we.original_sizes,we.reshaped_input_sizes,!0)),we}async post_process_masks(U,_e,Pe,{mask_threshold:rt=0,binarize:we=!0,pad_size:Je=null}={}){const gt=[];Je=Je??this.pad_size;const ft=[Je.height,Je.width];for(let St=0;St<_e.length;++St){const mt=_e[St],Ft=Pe[St];let Nt=await(0,Ce.interpolate_4d)(U[St],{mode:"bilinear",size:ft});if(Nt=Nt.slice(null,null,[0,Ft[0]],[0,Ft[1]]),Nt=await(0,Ce.interpolate_4d)(Nt,{mode:"bilinear",size:mt}),we){const Rt=Nt.data,Gt=new Uint8Array(Rt.length);for(let Me=0;Mert&&(Gt[Me]=1);Nt=new Ce.Tensor("bool",Gt,Nt.dims)}gt.push(Nt)}return gt}generate_crop_boxes(U,_e,{crop_n_layers:Pe=0,overlap_ratio:rt=.3413333333333333,points_per_crop:we=32,crop_n_points_downscale_factor:Je=1}={}){}}class vt extends X{pad_image(U,_e,Pe,rt={}){const[we,Je,gt]=_e;return super.pad_image(U,_e,{width:Je+(Pe-Je%Pe)%Pe,height:we+(Pe-we%Pe)%Pe},{mode:"symmetric",center:!1,constant_values:-1,...rt})}}class kt extends X{async _call(U,_e){Array.isArray(U)||(U=[U]),Array.isArray(_e)||(_e=[_e]);const Pe=await Promise.all(U.map(Je=>this.preprocess(Je))),rt=await Promise.all(_e.map(Je=>this.preprocess(Je,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,Ce.stack)(Pe.map((Je,gt)=>(0,Ce.cat)([Je.pixel_values,rt[gt].pixel_values],0)),0),original_sizes:Pe.map(Je=>Je.original_size),reshaped_input_sizes:Pe.map(Je=>Je.reshaped_input_size)}}}class v extends se{constructor(U){var _e;super(U),(_e=this.config).mel_filters??(_e.mel_filters=(0,j.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,j.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(U){const _e=await(0,j.spectrogram)(U,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}),Pe=_e.data,rt=(0,Te.max)(Pe)[0];for(let we=0;wethis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),_e=U.slice(0,this.config.n_samples)):(_e=new Float32Array(this.config.n_samples),_e.set(U)),{input_features:(await this._extract_fbank_features(_e)).unsqueeze_(0)}}}class q extends se{_zero_mean_unit_var_norm(U){const Pe=U.reduce((we,Je)=>we+Je,0)/U.length,rt=U.reduce((we,Je)=>we+(Je-Pe)**2,0)/U.length;return U.map(we=>(we-Pe)/Math.sqrt(rt+1e-7))}async _call(U){D(U,"Wav2Vec2FeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));let _e=U;this.config.do_normalize&&(_e=this._zero_mean_unit_var_norm(_e));const Pe=[1,_e.length];return{input_values:new Ce.Tensor("float32",_e,Pe),attention_mask:new Ce.Tensor("int64",new BigInt64Array(_e.length).fill(1n),Pe)}}}class C extends se{constructor(U){super(U);const _e=this.config.sampling_rate,Pe=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(_e/2),_e,null,"kaldi",!0);for(let rt=0;rtPe*32768),(0,j.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:_e,transpose:!0})}async _call(U,{padding:_e=!0,pad_to_multiple_of:Pe=2,do_normalize_per_mel_bins:rt=!0,return_attention_mask:we=!0}={}){D(U,"SeamlessM4TFeatureExtractor");let Je=await this._extract_fbank_features(U,this.config.max_length);if(rt){const[Gt,Me]=Je.dims,et=Je.data;for(let ot=0;ot0){const Ht=new Float32Array(Me*(Gt+ot));Ht.set(et),Ht.fill(this.config.padding_value,et.length);const gr=Gt+ot;Je=new Ce.Tensor(Je.type,Ht,[gr,Me]),we&&(gt=new Ce.Tensor("int64",new BigInt64Array(gr),[1,gr]),gt.data.fill(1n,0,Gt))}}const[ft,St]=Je.dims,mt=this.config.stride;if(ft%mt!==0)throw new Error(`The number of frames (${ft}) must be a multiple of the stride (${mt}).`);const Nt=Je.view(1,Math.floor(ft/mt),St*mt),Rt={input_features:Nt};if(we){const Gt=Nt.dims[1],Me=new BigInt64Array(Gt);if(gt){const et=gt.data;for(let ot=1,Ht=0;ot0)if(Pe==="rand_trunc"){const gt=Math.floor(Math.random()*(Je+1));U=U.subarray(gt,gt+_e),we=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Pe}" not implemented`);else{if(Je<0){let gt=new Float64Array(_e);if(gt.set(U),rt==="repeat")for(let ft=U.length;ft<_e;ft+=U.length)gt.set(U.subarray(0,Math.min(U.length,_e-ft)),ft);else if(rt==="repeatpad")for(let ft=U.length;ft<-Je;ft+=U.length)gt.set(U,ft);U=gt}if(Pe==="fusion")throw new Error(`Truncation strategy "${Pe}" not implemented`);we=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}return we.unsqueeze_(0)}async _extract_fbank_features(U,_e,Pe=null){return(0,j.spectrogram)(U,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:_e,log_mel:"dB",max_num_frames:Pe,do_pad:!1,transpose:!0})}async _call(U,{max_length:_e=null}={}){return D(U,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(U,_e??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}class Qe extends se{async _call(U){D(U,"PyAnnoteFeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));const _e=[1,1,U.length];return{input_values:new Ce.Tensor("float32",U,_e)}}samples_to_frames(U){return(U-this.config.offset)/this.config.step}post_process_speaker_diarization(U,_e){const Pe=_e/this.samples_to_frames(_e)/this.config.sampling_rate,rt=[];for(const we of U.tolist()){const Je=[];let gt=-1;for(let ft=0;ft({id:ft,start:St*Pe,end:mt*Pe,confidence:Ft/(mt-St)})))}return rt}}class Ye extends se{constructor(U){super(U);const _e=this.config.sampling_rate,Pe=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(_e/2),_e,null,"kaldi",!0);for(let rt=0;rt_e*32768),(0,j.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(U){D(U,"WeSpeakerFeatureExtractor");const _e=(await this._extract_fbank_features(U)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Pe=_e.mean(1).data,rt=_e.data,[we,Je,gt]=_e.dims;for(let ft=0;ft/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(U){typeof U=="string"&&(U=[U]);const _e=[];for(const Pe of U)if(this.task_prompts_without_inputs.has(Pe))_e.push(this.task_prompts_without_inputs.get(Pe));else{for(const[rt,we]of this.task_prompts_with_input)if(Pe.includes(rt)){_e.push(we.replaceAll("{input}",Pe).replaceAll(rt,""));break}_e.length!==U.length&&_e.push(Pe)}return _e}post_process_generation(U,_e,Pe){const rt=this.tasks_answer_post_processing_type.get(_e)??"pure_text";U=U.replaceAll("","").replaceAll("","");let we;switch(rt){case"pure_text":we=U;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Je=rt==="ocr"?"quad_boxes":"bboxes",gt=U.matchAll(this.regexes[Je]),ft=[],St=[];for(const[mt,Ft,...Nt]of gt)ft.push(Ft?Ft.trim():ft.at(-1)??""),St.push(Nt.map((Rt,Gt)=>(Number(Rt)+.5)/this.size_per_bin*Pe[Gt%2]));we={labels:ft,[Je]:St};break;default:throw new Error(`Task "${_e}" (of type "${rt}") not yet implemented.`)}return{[_e]:we}}}class Kr{static async from_pretrained(U,{progress_callback:_e=null,config:Pe=null,cache_dir:rt=null,local_files_only:we=!1,revision:Je="main"}={}){let gt=Pe??await(0,ye.getModelJSON)(U,"preprocessor_config.json",!0,{progress_callback:_e,config:Pe,cache_dir:rt,local_files_only:we,revision:Je}),ft=gt.feature_extractor_type??gt.image_processor_type,St=this.FEATURE_EXTRACTOR_CLASS_MAPPING[ft];if(!St)if(gt.size!==void 0)console.warn(`Feature extractor type "${ft}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),St=X;else throw new Error(`Unknown Feature Extractor type: ${ft}`);let mt=this.PROCESSOR_CLASS_MAPPING[gt.processor_class]??ht,Ft=new St(gt);return new mt(Ft)}}xe(Kr,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:X,WhisperFeatureExtractor:v,ViTFeatureExtractor:W,MobileViTFeatureExtractor:lt,MobileViTImageProcessor:je,MobileNetV1FeatureExtractor:J,MobileNetV2FeatureExtractor:He,MobileNetV3FeatureExtractor:ct,MobileNetV4FeatureExtractor:nt,OwlViTFeatureExtractor:st,Owlv2ImageProcessor:Pt,CLIPFeatureExtractor:Ie,CLIPImageProcessor:Ae,Florence2Processor:Br,ChineseCLIPFeatureExtractor:tt,SiglipImageProcessor:Xe,ConvNextFeatureExtractor:dt,ConvNextImageProcessor:ge,SegformerFeatureExtractor:I,SapiensFeatureExtractor:R,BitImageProcessor:ve,DPTImageProcessor:ue,DPTFeatureExtractor:k,PvtImageProcessor:B,GLPNFeatureExtractor:Ee,BeitFeatureExtractor:ke,DeiTFeatureExtractor:re,DetrFeatureExtractor:We,RTDetrImageProcessor:Le,MaskFormerFeatureExtractor:Ke,YolosFeatureExtractor:ut,DonutFeatureExtractor:Ve,NougatImageProcessor:qe,EfficientNetImageProcessor:$e,ViTImageProcessor:de,VitMatteImageProcessor:kt,SamImageProcessor:yt,Swin2SRImageProcessor:vt,Wav2Vec2FeatureExtractor:q,SeamlessM4TFeatureExtractor:C,SpeechT5FeatureExtractor:Bt,ASTFeatureExtractor:Y,ClapFeatureExtractor:he,PyAnnoteFeatureExtractor:Qe,WeSpeakerFeatureExtractor:Ye}),xe(Kr,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:bt,Wav2Vec2ProcessorWithLM:Ot,PyAnnoteProcessor:cr,SamProcessor:Tt,SpeechT5Processor:xr,OwlViTProcessor:Yr,Florence2Processor:Br})},"./src/tokenizers.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{AlbertTokenizer:()=>gt,AutoTokenizer:()=>vn,BartTokenizer:()=>mr,BertTokenizer:()=>Je,BlenderbotSmallTokenizer:()=>$s,BlenderbotTokenizer:()=>fs,BloomTokenizer:()=>Rr,CLIPTokenizer:()=>Xt,CamembertTokenizer:()=>et,CodeGenTokenizer:()=>hs,CodeLlamaTokenizer:()=>Ys,CohereTokenizer:()=>Gr,ConvBertTokenizer:()=>Rt,DebertaTokenizer:()=>mt,DebertaV2Tokenizer:()=>Ft,DistilBertTokenizer:()=>Me,ElectraTokenizer:()=>Ht,EsmTokenizer:()=>Kn,FalconTokenizer:()=>Ts,GPT2Tokenizer:()=>Lr,GPTNeoXTokenizer:()=>Ss,GemmaTokenizer:()=>cs,Grok1Tokenizer:()=>Bn,HerbertTokenizer:()=>Nt,LlamaTokenizer:()=>jn,M2M100Tokenizer:()=>ts,MBart50Tokenizer:()=>Tr,MBartTokenizer:()=>yr,MPNetTokenizer:()=>xs,MarianTokenizer:()=>Cs,MobileBertTokenizer:()=>ft,NllbTokenizer:()=>Vn,NougatTokenizer:()=>ms,PreTrainedTokenizer:()=>we,Qwen2Tokenizer:()=>Zs,RoFormerTokenizer:()=>Gt,RobertaTokenizer:()=>En,SiglipTokenizer:()=>rs,SpeechT5Tokenizer:()=>ks,SqueezeBertTokenizer:()=>St,T5Tokenizer:()=>gr,TokenizerModel:()=>Ee,VitsTokenizer:()=>Ps,Wav2Vec2CTCTokenizer:()=>Es,WhisperTokenizer:()=>ps,XLMRobertaTokenizer:()=>vs,XLMTokenizer:()=>ot,is_chinese_char:()=>X});var O=N("./src/utils/generic.js"),fe=N("./src/utils/core.js"),ye=N("./src/utils/hub.js"),Te=N("./src/utils/maths.js"),Ce=N("./src/utils/tensor.js"),j=N("./src/utils/data-structures.js"),$=N("./node_modules/@huggingface/jinja/dist/index.js"),V=N("./src/models/whisper/common_whisper.js"),A=N("./src/utils/constants.js");async function ee(be,_){const P=await Promise.all([(0,ye.getModelJSON)(be,"tokenizer.json",!0,_),(0,ye.getModelJSON)(be,"tokenizer_config.json",!0,_)]);return _.legacy!==null&&(P[1].legacy=_.legacy),P}function ne(be,_){const P=[];let K=0;for(const ie of be.matchAll(_)){const pe=ie[0];K0&&P.push(pe),K=ie.index+pe.length}return K=19968&&be<=40959||be>=13312&&be<=19903||be>=131072&&be<=173791||be>=173824&&be<=177983||be>=177984&&be<=178207||be>=178208&&be<=183983||be>=63744&&be<=64255||be>=194560&&be<=195103}function R(be,_,P){const K=[];let ie=0;for(;iethis.tokens_to_ids.get(P)??this.unk_token_id)}convert_ids_to_tokens(_){return _.map(P=>this.vocab[P]??this.unk_token)}}class Ie extends Ee{constructor(_){super(_),this.tokens_to_ids=ce(_.vocab),this.unk_token_id=this.tokens_to_ids.get(_.unk_token),this.unk_token=_.unk_token,this.max_input_chars_per_word=_.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[P,K]of this.tokens_to_ids)this.vocab[K]=P}encode(_){const P=[];for(const K of _){const ie=[...K];if(ie.length>this.max_input_chars_per_word){P.push(this.unk_token);continue}let pe=!1,De=0;const wt=[];for(;De0&&(zt=this.config.continuing_subword_prefix+zt),this.tokens_to_ids.has(zt)){Mt=zt;break}--xt}if(Mt===null){pe=!0;break}wt.push(Mt),De=xt}pe?P.push(this.unk_token):P.push(...wt)}return P}}class Ae extends Ee{constructor(_,P){super(_);const K=_.vocab.length;this.vocab=new Array(K),this.scores=new Array(K);for(let ie=0;ie[ie,pe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=P.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,Te.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new j.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(_){const P=_.chars,K=1;let ie=0;for(;ie{const be=[...Array.from({length:94},(ie,pe)=>pe+33),...Array.from({length:12},(ie,pe)=>pe+161),...Array.from({length:82},(ie,pe)=>pe+174)],_=be.slice();let P=0;for(let ie=0;ie<256;++ie)be.includes(ie)||(be.push(ie),_.push(256+P),P+=1);const K=_.map(ie=>String.fromCharCode(ie));return Object.fromEntries(be.map((ie,pe)=>[ie,K[pe]]))})(),Xe=(0,fe.reverseDictionary)(tt);class dt extends Ee{constructor(_){super(_),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=ce(_.vocab),this.unk_token_id=this.tokens_to_ids.get(_.unk_token),this.unk_token=_.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[P,K]of this.tokens_to_ids)this.vocab[K]=P;this.bpe_ranks=new Map(_.merges.map((P,K)=>[P,K])),this.merges=_.merges.map(P=>P.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=_.end_of_word_suffix,this.continuing_subword_suffix=_.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(_){if(_.length===0)return[];const P=this.cache.get(_);if(P!==void 0)return P;const K=Array.from(_);this.end_of_word_suffix&&(K[K.length-1]+=this.end_of_word_suffix);let ie=[];if(K.length>1){const pe=new j.PriorityQueue((xt,Mt)=>xt.score`<0x${wt.toString(16).toUpperCase().padStart(2,"0")}>`);De.every(wt=>this.tokens_to_ids.has(wt))?P.push(...De):P.push(this.unk_token)}else P.push(this.unk_token)}return P}}class ge extends Ee{constructor(_,P){super(_),this.tokens_to_ids=ce(P.target_lang?_.vocab[P.target_lang]:_.vocab),this.bos_token=P.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=P.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=P.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=P.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[K,ie]of this.tokens_to_ids)this.vocab[ie]=K}encode(_){return _}}class W extends O.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"BertNormalizer":return new Pt(_);case"Precompiled":return new Yr(_);case"Sequence":return new st(_);case"Replace":return new de(_);case"NFC":return new $e(_);case"NFKC":return new J(_);case"NFKD":return new He(_);case"Strip":return new ct(_);case"StripAccents":return new nt(_);case"Lowercase":return new lt(_);case"Prepend":return new je(_);default:throw new Error(`Unknown Normalizer type: ${_.type}`)}}normalize(_){throw Error("normalize should be implemented in subclass.")}_call(_){return this.normalize(_)}}class de extends W{normalize(_){const P=me(this.config.pattern);return P===null?_:_.replaceAll(P,this.config.content)}}class $e extends W{normalize(_){return _=_.normalize("NFC"),_}}class J extends W{normalize(_){return _=_.normalize("NFKC"),_}}class He extends W{normalize(_){return _=_.normalize("NFKD"),_}}class ct extends W{normalize(_){return this.config.strip_left&&this.config.strip_right?_=_.trim():(this.config.strip_left&&(_=_.trimStart()),this.config.strip_right&&(_=_.trimEnd())),_}}class nt extends W{normalize(_){return _=te(_),_}}class lt extends W{normalize(_){return _=_.toLowerCase(),_}}class je extends W{normalize(_){return _=this.config.prepend+_,_}}class st extends W{constructor(_){super(_),this.normalizers=_.normalizers.map(P=>W.fromConfig(P))}normalize(_){return this.normalizers.reduce((P,K)=>K.normalize(P),_)}}class Pt extends W{_tokenize_chinese_chars(_){const P=[];for(let K=0;K<_.length;++K){const ie=_[K],pe=ie.charCodeAt(0);X(pe)?(P.push(" "),P.push(ie),P.push(" ")):P.push(ie)}return P.join("")}stripAccents(_){return _.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control(_){switch(_){case" ":case` +`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(_)}}_clean_text(_){const P=[];for(const K of _){const ie=K.charCodeAt(0);ie===0||ie===65533||this._is_control(K)||(/^\s$/.test(K)?P.push(" "):P.push(K))}return P.join("")}normalize(_){return this.config.clean_text&&(_=this._clean_text(_)),this.config.handle_chinese_chars&&(_=this._tokenize_chinese_chars(_)),this.config.lowercase?(_=_.toLowerCase(),this.config.strip_accents!==!1&&(_=this.stripAccents(_))):this.config.strip_accents&&(_=this.stripAccents(_)),_}}class Le extends O.Callable{static fromConfig(_){if(_===null)return null;switch(_.type){case"BertPreTokenizer":return new re(_);case"Sequence":return new Br(_);case"Whitespace":return new Kr(_);case"WhitespaceSplit":return new at(_);case"Metaspace":return new cr(_);case"ByteLevel":return new ke(_);case"Split":return new Ve(_);case"Punctuation":return new qe(_);case"Digits":return new We(_);case"Replace":return new U(_);default:throw new Error(`Unknown PreTokenizer type: ${_.type}`)}}pre_tokenize_text(_,P){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(_,P){return(Array.isArray(_)?_.map(K=>this.pre_tokenize_text(K,P)):this.pre_tokenize_text(_,P)).flat()}_call(_,P){return this.pre_tokenize(_,P)}}class re extends Le{constructor(_){super(),this.pattern=new RegExp(`[^\\s${B}]+|[${B}]`,"gu")}pre_tokenize_text(_,P){return _.trim().match(this.pattern)||[]}}class ke extends Le{constructor(_){super(),this.config=_,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=tt,this.text_encoder=new TextEncoder}pre_tokenize_text(_,P){return this.add_prefix_space&&!_.startsWith(" ")&&(_=" "+_),(this.use_regex?_.match(this.pattern)||[]:[_]).map(ie=>Array.from(this.text_encoder.encode(ie),pe=>this.byte_encoder[pe]).join(""))}}class Ve extends Le{constructor(_){super(),this.config=_,this.pattern=me(this.config.pattern,this.config.invert)}pre_tokenize_text(_,P){return this.pattern===null?[]:this.config.invert?_.match(this.pattern)||[]:ne(_,this.pattern)}}class qe extends Le{constructor(_){super(),this.config=_,this.pattern=new RegExp(`[^${B}]+|[${B}]+`,"gu")}pre_tokenize_text(_,P){return _.match(this.pattern)||[]}}class We extends Le{constructor(_){super(),this.config=_;const P=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(P,"gu")}pre_tokenize_text(_,P){return _.match(this.pattern)||[]}}class Ke extends O.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"TemplateProcessing":return new vt(_);case"ByteLevel":return new kt(_);case"RobertaProcessing":return new yt(_);case"BertProcessing":return new ut(_);case"Sequence":return new v(_);default:throw new Error(`Unknown PostProcessor type: ${_.type}`)}}post_process(_,...P){throw Error("post_process should be implemented in subclass.")}_call(_,...P){return this.post_process(_,...P)}}class ut extends Ke{constructor(_){super(_),this.cls=_.cls[0],this.sep=_.sep[0]}post_process(_,P=null,{add_special_tokens:K=!0}={}){K&&(_=(0,fe.mergeArrays)([this.cls],_,[this.sep]));let ie=new Array(_.length).fill(0);if(P!==null){const pe=K&&this instanceof yt?[this.sep]:[],De=K?[this.sep]:[];_=(0,fe.mergeArrays)(_,pe,P,De),ie=(0,fe.mergeArrays)(ie,new Array(P.length+pe.length+De.length).fill(1))}return{tokens:_,token_type_ids:ie}}}class yt extends ut{}class vt extends Ke{constructor(_){super(_),this.single=_.single,this.pair=_.pair}post_process(_,P=null,{add_special_tokens:K=!0}={}){const ie=P===null?this.single:this.pair;let pe=[],De=[];for(const wt of ie)"SpecialToken"in wt?K&&(pe.push(wt.SpecialToken.id),De.push(wt.SpecialToken.type_id)):"Sequence"in wt&&(wt.Sequence.id==="A"?(pe=(0,fe.mergeArrays)(pe,_),De=(0,fe.mergeArrays)(De,new Array(_.length).fill(wt.Sequence.type_id))):wt.Sequence.id==="B"&&(pe=(0,fe.mergeArrays)(pe,P),De=(0,fe.mergeArrays)(De,new Array(P.length).fill(wt.Sequence.type_id))));return{tokens:pe,token_type_ids:De}}}class kt extends Ke{post_process(_,P=null){return P&&(_=(0,fe.mergeArrays)(_,P)),{tokens:_}}}class v extends Ke{constructor(_){super(_),this.processors=_.processors.map(P=>Ke.fromConfig(P))}post_process(_,P=null,K={}){let ie;for(const pe of this.processors)if(pe instanceof kt)_=pe.post_process(_).tokens,P&&(P=pe.post_process(P).tokens);else{const De=pe.post_process(_,P,K);_=De.tokens,ie=De.token_type_ids}return{tokens:_,token_type_ids:ie}}}class q extends O.Callable{constructor(_){super(),this.config=_,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=_.trim_offsets}static fromConfig(_){if(_===null)return null;switch(_.type){case"WordPiece":return new Ye(_);case"Metaspace":return new xr(_);case"ByteLevel":return new Bt(_);case"Replace":return new C(_);case"ByteFallback":return new Y(_);case"Fuse":return new he(_);case"Strip":return new Qe(_);case"Sequence":return new Tt(_);case"CTC":return new ht(_);case"BPEDecoder":return new bt(_);default:throw new Error(`Unknown Decoder type: ${_.type}`)}}_call(_){return this.decode(_)}decode(_){return this.decode_chain(_).join("")}decode_chain(_){throw Error("`decode_chain` should be implemented in subclass.")}}class C extends q{decode_chain(_){const P=me(this.config.pattern);return P===null?_:_.map(K=>K.replaceAll(P,this.config.content))}}class Y extends q{constructor(_){super(_),this.text_decoder=new TextDecoder}decode_chain(_){const P=[];let K=[];for(const ie of _){let pe=null;if(ie.length===6&&ie.startsWith("<0x")&&ie.endsWith(">")){const De=parseInt(ie.slice(3,5),16);isNaN(De)||(pe=De)}if(pe!==null)K.push(pe);else{if(K.length>0){const De=this.text_decoder.decode(Uint8Array.from(K));P.push(De),K=[]}P.push(ie)}}if(K.length>0){const ie=this.text_decoder.decode(Uint8Array.from(K));P.push(ie),K=[]}return P}}class he extends q{decode_chain(_){return[_.join("")]}}class Qe extends q{constructor(_){super(_),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(_){return _.map(P=>{let K=0;for(let pe=0;pe(K!==0&&(P.startsWith(this.config.prefix)?P=P.replace(this.config.prefix,""):P=" "+P),this.cleanup&&(P=H(P)),P))}}class Bt extends q{constructor(_){super(_),this.byte_decoder=Xe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(_){const P=_.join(""),K=new Uint8Array([...P].map(pe=>this.byte_decoder[pe]));return this.text_decoder.decode(K)}decode_chain(_){const P=[];let K=[];for(const ie of _)this.added_tokens.find(pe=>pe.content===ie)!==void 0?(K.length>0&&(P.push(this.convert_tokens_to_string(K)),K=[]),P.push(ie)):K.push(ie);return K.length>0&&P.push(this.convert_tokens_to_string(K)),P}}class ht extends q{constructor(_){super(_),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(_){if(_.length===0)return"";const P=[_[0]];for(let pe=1;pe<_.length;++pe)_[pe]!==P.at(-1)&&P.push(_[pe]);let ie=P.filter(pe=>pe!==this.pad_token).join("");return this.cleanup&&(ie=H(ie).replaceAll(this.word_delimiter_token," ").trim()),ie}decode_chain(_){return[this.convert_tokens_to_string(_)]}}class Tt extends q{constructor(_){super(_),this.decoders=_.decoders.map(P=>q.fromConfig(P))}decode_chain(_){return this.decoders.reduce((P,K)=>K.decode_chain(P),_)}}class bt extends q{constructor(_){super(_),this.suffix=this.config.suffix}decode_chain(_){return _.map((P,K)=>P.replaceAll(this.suffix,K===_.length-1?"":" "))}}class Ot extends q{decode_chain(_){let P="";for(let K=1;K<_.length;K+=2)P+=_[K];return[P]}}class cr extends Le{constructor(_){super(),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement,this.strRep=_.str_rep||this.replacement,this.prepend_scheme=_.prepend_scheme??"always"}pre_tokenize_text(_,{section_index:P=void 0}={}){let K=_.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!K.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&P===0)&&(K=this.strRep+K),[K]}}class xr extends q{constructor(_){super(_),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement}decode_chain(_){const P=[];for(let K=0;K<_.length;++K){let ie=_[K].replaceAll(this.replacement," ");this.addPrefixSpace&&K==0&&ie.startsWith(" ")&&(ie=ie.substring(1)),P.push(ie)}return P}}class Yr extends W{constructor(_){super(_),this.charsmap=_.precompiled_charsmap}normalize(_){return _=_.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),_=_.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),_.includes("~")?_=_.split("~").map(K=>K.normalize("NFKC")).join("~"):_=_.normalize("NFKC"),_}}class Br extends Le{constructor(_){super(),this.tokenizers=_.pretokenizers.map(P=>Le.fromConfig(P))}pre_tokenize_text(_,P){return this.tokenizers.reduce((K,ie)=>ie.pre_tokenize(K,P),[_])}}class Kr extends Le{constructor(_){super()}pre_tokenize_text(_,P){return _.match(/\w+|[^\w\s]+/g)||[]}}class at extends Le{constructor(_){super()}pre_tokenize_text(_,P){return I(_)}}class U extends Le{constructor(_){super(),this.config=_,this.pattern=me(this.config.pattern),this.content=this.config.content}pre_tokenize_text(_,P){return this.pattern===null?[_]:[_.replaceAll(this.pattern,this.config.content)]}}const _e=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Pe(be,_,P,K){for(const ie of Object.keys(be)){const pe=_-be[ie].length,De=P(ie),wt=new Array(pe).fill(De);be[ie]=K==="right"?(0,fe.mergeArrays)(be[ie],wt):(0,fe.mergeArrays)(wt,be[ie])}}function rt(be,_){for(const P of Object.keys(be))be[P].length=_}class we extends O.Callable{constructor(P,K){super();xe(this,"return_token_type_ids",!1);xe(this,"padding_side","right");this._tokenizer_config=K,this.normalizer=W.fromConfig(P.normalizer),this.pre_tokenizer=Le.fromConfig(P.pre_tokenizer),this.model=Ee.fromConfig(P.model,K),this.post_processor=Ke.fromConfig(P.post_processor),this.decoder=q.fromConfig(P.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ie of P.added_tokens){const pe=new ve(ie);this.added_tokens.push(pe),this.model.tokens_to_ids.set(pe.content,pe.id),this.model.vocab[pe.id]=pe.content,pe.special&&(this.special_tokens.push(pe.content),this.all_special_ids.push(pe.id))}if(this.additional_special_tokens=K.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((ie,pe)=>pe.content.length-ie.content.length).map(ie=>`${ie.lstrip?"\\s*":""}(${(0,fe.escapeRegExp)(ie.content)})${ie.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=K.model_max_length,this.remove_space=K.remove_space,this.clean_up_tokenization_spaces=K.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=K.do_lowercase_and_remove_accent??!1,K.padding_side&&(this.padding_side=K.padding_side),this.legacy=!1,this.chat_template=K.chat_template??null,Array.isArray(this.chat_template)){const ie=Object.create(null);for(const{name:pe,template:De}of this.chat_template){if(typeof pe!="string"||typeof De!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ie[pe]=De}this.chat_template=ie}this._compiled_template_cache=new Map}getToken(...P){for(const K of P){const ie=this._tokenizer_config[K];if(ie)if(typeof ie=="object"){if(ie.__type==="AddedToken")return ie.content;throw Error(`Unknown token: ${ie}`)}else return ie}return null}static async from_pretrained(P,{progress_callback:K=null,config:ie=null,cache_dir:pe=null,local_files_only:De=!1,revision:wt="main",legacy:xt=null}={}){const Mt=await ee(P,{progress_callback:K,config:ie,cache_dir:pe,local_files_only:De,revision:wt,legacy:xt});return new this(...Mt)}_call(P,{text_pair:K=null,add_special_tokens:ie=!0,padding:pe=!1,truncation:De=null,max_length:wt=null,return_tensor:xt=!0,return_token_type_ids:Mt=null}={}){const zt=Array.isArray(P);let er;if(zt){if(P.length===0)throw Error("text array must be non-empty");if(K!==null){if(Array.isArray(K)){if(P.length!==K.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");er=P.map((ir,qt)=>this._encode_plus(ir,{text_pair:K[qt],add_special_tokens:ie,return_token_type_ids:Mt}))}else er=P.map(ir=>this._encode_plus(ir,{add_special_tokens:ie,return_token_type_ids:Mt}))}else{if(P==null)throw Error("text may not be null or undefined");if(Array.isArray(K))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");er=[this._encode_plus(P,{text_pair:K,add_special_tokens:ie,return_token_type_ids:Mt})]}if(wt===null?pe==="max_length"?wt=this.model_max_length:wt=(0,Te.max)(er.map(ir=>ir.input_ids.length))[0]:De||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."),wt=Math.min(wt,this.model_max_length??1/0),pe||De)for(let ir=0;irwt?De&&rt(er[ir],wt):pe&&Pe(er[ir],wt,qt=>qt==="input_ids"?this.pad_token_id:0,this.padding_side));const zr={};if(xt){if(!(pe&&De)&&er.some(qt=>{var pr;for(const mn of Object.keys(qt))if(qt[mn].length!==((pr=er[0][mn])==null?void 0:pr.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 ir=[er.length,er[0].input_ids.length];for(const qt of Object.keys(er[0]))zr[qt]=new Ce.Tensor("int64",BigInt64Array.from(er.flatMap(pr=>pr[qt]).map(BigInt)),ir)}else{for(const ir of Object.keys(er[0]))zr[ir]=er.map(qt=>qt[ir]);if(!zt)for(const ir of Object.keys(zr))zr[ir]=zr[ir][0]}return zr}_encode_text(P){return P===null?null:(this.added_tokens_regex?P.split(this.added_tokens_regex).filter(pe=>pe):[P]).map((pe,De)=>{if(this.added_tokens.find(xt=>xt.content===pe)!==void 0)return pe;{if(this.remove_space===!0&&(pe=pe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(pe=se(pe)),this.normalizer!==null&&(pe=this.normalizer(pe)),pe.length===0)return[];const xt=this.pre_tokenizer!==null?this.pre_tokenizer(pe,{section_index:De}):[pe];return this.model(xt)}}).flat()}_encode_plus(P,{text_pair:K=null,add_special_tokens:ie=!0,return_token_type_ids:pe=null}={}){const{tokens:De,token_type_ids:wt}=this._tokenize_helper(P,{pair:K,add_special_tokens:ie}),xt=this.model.convert_tokens_to_ids(De),Mt={input_ids:xt,attention_mask:new Array(xt.length).fill(1)};return(pe??this.return_token_type_ids)&&wt&&(Mt.token_type_ids=wt),Mt}_tokenize_helper(P,{pair:K=null,add_special_tokens:ie=!1}={}){const pe=this._encode_text(P),De=this._encode_text(K);return this.post_processor?this.post_processor(pe,De,{add_special_tokens:ie}):{tokens:(0,fe.mergeArrays)(pe??[],De??[])}}tokenize(P,{pair:K=null,add_special_tokens:ie=!1}={}){return this._tokenize_helper(P,{pair:K,add_special_tokens:ie}).tokens}encode(P,{text_pair:K=null,add_special_tokens:ie=!0,return_token_type_ids:pe=null}={}){return this._encode_plus(P,{text_pair:K,add_special_tokens:ie,return_token_type_ids:pe}).input_ids}batch_decode(P,K={}){return P instanceof Ce.Tensor&&(P=P.tolist()),P.map(ie=>this.decode(ie,K))}decode(P,K={}){if(P instanceof Ce.Tensor&&(P=D(P)),!Array.isArray(P)||P.length===0||!(0,fe.isIntegralNumber)(P[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(P,K)}decode_single(P,{skip_special_tokens:K=!1,clean_up_tokenization_spaces:ie=null}){let pe=this.model.convert_ids_to_tokens(P);K&&(pe=pe.filter(wt=>!this.special_tokens.includes(wt)));let De=this.decoder?this.decoder(pe):pe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(De=De.replaceAll(this.decoder.end_of_word_suffix," "),K&&(De=De.trim())),(ie??this.clean_up_tokenization_spaces)&&(De=H(De)),De}get_chat_template({chat_template:P=null,tools:K=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ie=this.chat_template;if(P!==null&&Object.hasOwn(ie,P))P=ie[P];else if(P===null)if(K!==null&&"tool_use"in ie)P=ie.tool_use;else if("default"in ie)P=ie.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(ie).sort()}.`)}else if(P===null)if(this.chat_template)P=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 P}apply_chat_template(P,{tools:K=null,documents:ie=null,chat_template:pe=null,add_generation_prompt:De=!1,tokenize:wt=!0,padding:xt=!1,truncation:Mt=!1,max_length:zt=null,return_tensor:er=!0,return_dict:zr=!1,tokenizer_kwargs:ir={},...qt}={}){if(pe=this.get_chat_template({chat_template:pe,tools:K}),typeof pe!="string")throw Error(`chat_template must be a string, but got ${typeof pe}`);let pr=this._compiled_template_cache.get(pe);pr===void 0&&(pr=new $.Template(pe),this._compiled_template_cache.set(pe,pr));const mn=Object.create(null);for(const Oe of _e){const $n=this.getToken(Oe);$n&&(mn[Oe]=$n)}const ln=pr.render({messages:P,add_generation_prompt:De,tools:K,documents:ie,...mn,...qt});if(wt){const Oe=this._call(ln,{add_special_tokens:!1,padding:xt,truncation:Mt,max_length:zt,return_tensor:er,...ir});return zr?Oe:Oe.input_ids}return ln}}class Je extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class gt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class ft extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class St extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class mt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Ft extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Nt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Rt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Gt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Me extends we{}class et extends we{}class ot extends we{constructor(P,K){super(P,K);xe(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 Ht extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class gr extends we{}class Lr extends we{}class mr extends we{}class yr extends we{constructor(_,P){super(_,P),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)),this.lang_to_token=K=>K}_build_translation_inputs(_,P,K){return Xn(this,_,P,K)}}class Tr extends yr{}class En extends we{}class Rr extends we{constructor(_,P){var pe,De;const K=".,!?…。,、।۔،",ie=(De=(pe=_.pre_tokenizer)==null?void 0:pe.pretokenizers[0])==null?void 0:De.pattern;ie&&ie.Regex===` ?[^(\\s|[${K}])]+`&&(ie.Regex=` ?[^\\s${K}]+`),super(_,P)}}const Hn="▁";class jn extends we{constructor(P,K){super(P,K);xe(this,"padding_side","left");this.legacy=K.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new cr({replacement:Hn,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(P){if(P===null)return null;if(this.legacy||P.length===0)return super._encode_text(P);let K=super._encode_text(Hn+P.replaceAll(Hn," "));return K.length>1&&K[0]===Hn&&this.special_tokens.includes(K[1])&&(K=K.slice(1)),K}}class Ys extends we{}class vs extends we{}class xs extends we{}class Ts extends we{}class Ss extends we{}class Kn extends we{}class Zs extends we{}class cs extends we{}class Bn extends we{}function Xn(be,_,P,K){if(!("language_codes"in be)||!Array.isArray(be.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in be)||!(be.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in be)||typeof be.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ie=K.src_lang,pe=K.tgt_lang;if(!be.language_codes.includes(pe))throw new Error(`Target language code "${pe}" is not valid. Must be one of: {${be.language_codes.join(", ")}}`);if(ie!==void 0){if(!be.language_codes.includes(ie))throw new Error(`Source language code "${ie}" is not valid. Must be one of: {${be.language_codes.join(", ")}}`);for(const De of be.post_processor.config.single)if("SpecialToken"in De&&be.languageRegex.test(De.SpecialToken.id)){De.SpecialToken.id=be.lang_to_token(ie);break}}return K.forced_bos_token_id=be.model.convert_tokens_to_ids([be.lang_to_token(pe)])[0],be._call(_,P)}class Vn extends we{constructor(_,P){super(_,P),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)),this.lang_to_token=K=>K}_build_translation_inputs(_,P,K){return Xn(this,_,P,K)}}class ts extends we{constructor(_,P){super(_,P),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)).map(K=>K.slice(2,-2)),this.lang_to_token=K=>`__${K}__`}_build_translation_inputs(_,P,K){return Xn(this,_,P,K)}}class ps extends we{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(_,{return_timestamps:P=!1,return_language:K=!1,time_precision:ie=null,force_full_sequences:pe=!0}={}){if(ie===null)throw Error("Must specify time_precision");let De=null;const wt=P==="word";function xt(){return{language:De,timestamp:[null,null],text:""}}const Mt=[];let zt=xt(),er=0;const zr=this.timestamp_begin;let ir=[],qt=[],pr=!1,mn=null;const ln=new Set(this.all_special_ids);for(const Sr of _){const sn=Sr.tokens,xn=wt?Sr.token_timestamps:null;let Qt=null,Tn=zr;if("stride"in Sr){const[Cr,It,br]=Sr.stride;if(er-=It,mn=Cr-br,It&&(Tn=It/ie+zr),br)for(let Nr=sn.length-1;Nr>=0;--Nr){const Xr=Number(sn[Nr]);if(Xr>=zr){if(Qt!==null&&(Xr-zr)*ie=zr){const br=(It-zr)*ie+er,Nr=(0,Te.round)(br,2);if(Qt!==null&&It>=Qt)pr=!0;else if(pr||ir.length>0&&It0?(ir.push(pn),wt&&qt.push(Ar)):ir.every(Cr=>Cr.length===0)&&(zt=xt(),ir=[],pn=[],qt=[],Ar=[])}if(ir.length>0){if(pe&&P)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[Sr,sn]=this.findLongestCommonSequence(ir,qt),xn=this.decode(Sr);zt.text=xn,wt&&(zt.words=this.collateWordTimestamps(Sr,sn,De)),Mt.push(zt)}let Oe=Object.create(null);const $n=Mt.map(Sr=>Sr.text).join("");if(P||K){for(let Sr=0;Sr0;let wt=De?[]:null,xt=De?P[0]:null;for(let Mt=1;Mt<_.length;++Mt){const zt=_[Mt];let er=0,zr=[ie,ie,0,0];const ir=zt.length;for(let Sr=1;SrNr===Ar[Xr]&&xt[sn+Xr]<=P[Mt][Tn+Xr]).length:Cr=Qt.filter((Nr,Xr)=>Nr===Ar[Xr]).length;const It=Sr/1e4,br=Cr/Sr+It;Cr>1&&br>er&&(er=br,zr=[sn,xn,Tn,pn])}const[qt,pr,mn,ln]=zr,Oe=Math.floor((pr+qt)/2),$n=Math.floor((ln+mn)/2);pe.push(...K.slice(0,Oe)),K=zt.slice($n),ie=K.length,De&&(wt.push(...xt.slice(0,Oe)),xt=P[Mt].slice($n))}return pe.push(...K),De?(wt.push(...xt),[pe,wt]):[pe,[]]}collateWordTimestamps(_,P,K){const[ie,pe,De]=this.combineTokensIntoWords(_,K),wt=[];for(let xt=0;xt=ie){const wt=((De-ie)*K).toFixed(2);pe.push(`<|${wt}|>`),pe.push([])}else pe[pe.length-1].push(De);return pe=pe.map(De=>typeof De=="string"?De:super.decode(De,P)),pe.join("")}splitTokensOnUnicode(_){const P=this.decode(_,{decode_with_timestamps:!0}),K="�",ie=[],pe=[],De=[];let wt=[],xt=[],Mt=0;for(let zt=0;zt<_.length;++zt){const er=_[zt];wt.push(er),xt.push(zt);const zr=this.decode(wt,{decode_with_timestamps:!0});(!zr.includes(K)||P[Mt+zr.indexOf(K)]===K)&&(ie.push(zr),pe.push(wt),De.push(xt),wt=[],xt=[],Mt+=zr.length)}return[ie,pe,De]}splitTokensOnSpaces(_){const[P,K,ie]=this.splitTokensOnUnicode(_),pe=[],De=[],wt=[],xt=new RegExp(`^[${B}]$`,"gu");for(let Mt=0;Mt=this.model.tokens_to_ids.get("<|endoftext|>"),qt=zt.startsWith(" "),pr=zt.trim(),mn=xt.test(pr);if(ir||qt||mn||pe.length===0)pe.push(zt),De.push(er),wt.push(zr);else{const ln=pe.length-1;pe[ln]+=zt,De[ln].push(...er),wt[ln].push(...zr)}}return[pe,De,wt]}mergePunctuations(_,P,K,ie,pe){const De=structuredClone(_),wt=structuredClone(P),xt=structuredClone(K);let Mt=De.length-2,zt=De.length-1;for(;Mt>=0;)De[Mt].startsWith(" ")&&ie.includes(De[Mt].trim())?(De[zt]=De[Mt]+De[zt],wt[zt]=(0,fe.mergeArrays)(wt[Mt],wt[zt]),xt[zt]=(0,fe.mergeArrays)(xt[Mt],xt[zt]),De[Mt]="",wt[Mt]=[],xt[Mt]=[]):zt=Mt,--Mt;for(Mt=0,zt=1;zter),wt.filter(er=>er.length>0),xt.filter(er=>er.length>0)]}get_decoder_prompt_ids({language:_=null,task:P=null,no_timestamps:K=!0}={}){const ie=[];if(_){const pe=(0,V.whisper_language_to_code)(_),De=this.model.tokens_to_ids.get(`<|${pe}|>`);if(De===void 0)throw new Error(`Unable to find language "${pe}" in model vocabulary. Please report this issue at ${A.GITHUB_ISSUE_URL}.`);ie.push(De)}else ie.push(null);if(P){if(P=P.toLowerCase(),P!=="transcribe"&&P!=="translate")throw new Error(`Task "${P}" is not supported. Must be one of: ["transcribe", "translate"]`);const pe=this.model.tokens_to_ids.get(`<|${P}|>`);if(pe===void 0)throw new Error(`Unable to find task "${P}" in model vocabulary. Please report this issue at ${A.GITHUB_ISSUE_URL}.`);ie.push(pe)}else ie.push(null);if(K){const pe=this.model.tokens_to_ids.get("<|notimestamps|>");if(pe===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${A.GITHUB_ISSUE_URL}.`);ie.push(pe)}return ie.map((pe,De)=>[De+1,pe]).filter(pe=>pe[1]!==null)}}class hs extends we{}class Xt extends we{}class rs extends we{}class Cs extends we{constructor(_,P){super(_,P),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(K=>this.languageRegex.test(K)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(_){if(_===null)return null;const[P,...K]=_.trim().split(this.languageRegex);if(K.length===0)return super._encode_text(P);if(K.length===2){const[ie,pe]=K;return this.supported_language_codes.includes(ie)||console.warn(`Unsupported language code "${ie}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,fe.mergeArrays)([ie],super._encode_text(pe))}}}class Es extends we{}class fs extends we{}class $s extends we{}class ks extends we{}class ms extends we{}class Ps extends we{constructor(_,P){super(_,P),this.decoder=new Ot({})}}class Gr extends we{}class vn{static async from_pretrained(_,{progress_callback:P=null,config:K=null,cache_dir:ie=null,local_files_only:pe=!1,revision:De="main",legacy:wt=null}={}){var zr;const[xt,Mt]=await ee(_,{progress_callback:P,config:K,cache_dir:ie,local_files_only:pe,revision:De,legacy:wt}),zt=((zr=Mt.tokenizer_class)==null?void 0:zr.replace(/Fast$/,""))??"PreTrainedTokenizer";let er=this.TOKENIZER_CLASS_MAPPING[zt];return er||(console.warn(`Unknown tokenizer class "${zt}", attempting to construct from base class.`),er=we),new er(xt,Mt)}}xe(vn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:gr,DistilBertTokenizer:Me,CamembertTokenizer:et,DebertaTokenizer:mt,DebertaV2Tokenizer:Ft,BertTokenizer:Je,HerbertTokenizer:Nt,ConvBertTokenizer:Rt,RoFormerTokenizer:Gt,XLMTokenizer:ot,ElectraTokenizer:Ht,MobileBertTokenizer:ft,SqueezeBertTokenizer:St,AlbertTokenizer:gt,GPT2Tokenizer:Lr,BartTokenizer:mr,MBartTokenizer:yr,MBart50Tokenizer:Tr,RobertaTokenizer:En,WhisperTokenizer:ps,CodeGenTokenizer:hs,CLIPTokenizer:Xt,SiglipTokenizer:rs,MarianTokenizer:Cs,BloomTokenizer:Rr,NllbTokenizer:Vn,M2M100Tokenizer:ts,LlamaTokenizer:jn,CodeLlamaTokenizer:Ys,XLMRobertaTokenizer:vs,MPNetTokenizer:xs,FalconTokenizer:Ts,GPTNeoXTokenizer:Ss,EsmTokenizer:Kn,Wav2Vec2CTCTokenizer:Es,BlenderbotTokenizer:fs,BlenderbotSmallTokenizer:$s,SpeechT5Tokenizer:ks,NougatTokenizer:ms,VitsTokenizer:Ps,Qwen2Tokenizer:Zs,GemmaTokenizer:cs,Grok1Tokenizer:Bn,CohereTokenizer:Gr,PreTrainedTokenizer:we})},"./src/utils/audio.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{hamming:()=>V,hanning:()=>$,mel_filter_bank:()=>H,read_audio:()=>Ce,spectrogram:()=>I,window_function:()=>B});var O=N("./src/utils/hub.js"),fe=N("./src/utils/maths.js"),ye=N("./src/utils/core.js"),Te=N("./src/utils/tensor.js");async function Ce(k,ue){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 ve=await(await(0,O.getFile)(k)).arrayBuffer(),Ee=new AudioContext({sampleRate:ue});typeof ue>"u"&&console.warn(`No sampling rate provided, using default of ${Ee.sampleRate}Hz.`);const Ie=await Ee.decodeAudioData(ve);let Ae;if(Ie.numberOfChannels===2){const tt=Math.sqrt(2),Xe=Ie.getChannelData(0),dt=Ie.getChannelData(1);Ae=new Float32Array(Xe.length);for(let ge=0;ge2595*Math.log10(1+k/700),kaldi:k=>1127*Math.log(1+k/700),slaney:(k,ue=1e3,ve=15,Ee=27/Math.log(6.4))=>k>=ue?ve+Math.log(k/ue)*Ee:3*k/200};function ee(k,ue="htk"){const ve=A[ue];if(!ve)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?ve(k):k.map(Ee=>ve(Ee))}const ne={htk:k=>700*(10**(k/2595)-1),kaldi:k=>700*(Math.exp(k/1127)-1),slaney:(k,ue=1e3,ve=15,Ee=Math.log(6.4)/27)=>k>=ve?ue*Math.exp(Ee*(k-ve)):200*k/3};function me(k,ue="htk"){const ve=ne[ue];if(!ve)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?ve(k):k.map(Ee=>ve(Ee))}function ce(k,ue){const ve=Float64Array.from({length:ue.length-1},(tt,Xe)=>ue[Xe+1]-ue[Xe]),Ee=Array.from({length:k.length},()=>new Array(ue.length));for(let tt=0;ttnew Array(k.length));for(let tt=0;ttk+Ee*Ae)}function H(k,ue,ve,Ee,Ie,Ae=null,tt="htk",Xe=!1){if(Ae!==null&&Ae!=="slaney")throw new Error('norm must be one of null or "slaney"');const dt=ee(ve,tt),ge=ee(Ee,tt),W=D(dt,ge,ue+2);let de=me(W,tt),$e;if(Xe){const He=Ie/(k*2);$e=ee(Float64Array.from({length:k},(ct,nt)=>nt*He),tt),de=W}else $e=D(0,Math.floor(Ie/2),k);const J=ce($e,de);if(Ae!==null&&Ae==="slaney")for(let He=0;HeIe)throw Error(`frame_length (${ve}) may not be larger than fft_length (${Ie})`);if(Le!==ve)throw new Error(`Length of the window (${Le}) must equal frame_length (${ve})`);if(Ee<=0)throw new Error("hop_length must be greater than zero");if(Ae===null&&W!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(tt){if(Xe!=="reflect")throw new Error(`pad_mode="${Xe}" not implemented yet.`);const q=Math.floor((Ie-1)/2)+1;k=te(k,q,q)}let re=Math.floor(1+Math.floor((k.length-ve)/Ee));lt!==null&&rere?st&&(qe=je):qe=Ve=je);const We=new fe.FFT(Ie),Ke=new Float64Array(Ie),ut=new Float64Array(We.outputBufferSize),yt=new Float32Array(ke*qe);for(let q=0;q=1;--he)Ke[he]-=ge*Ke[he-1];Ke[0]*=1-ge}for(let he=0;heMath.pow(Xe,.85));break;default:throw new Error(`Unknown window type ${ue}.`)}if(ve&&(tt=tt.subarray(0,k)),Ee===null)return tt;if(k>Ee)throw new Error(`Length of the window (${k}) may not be larger than frame_length (${Ee})`);return tt}},"./src/utils/constants.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{GITHUB_ISSUE_URL:()=>O});const O="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{calculateDimensions:()=>j,calculateReflectOffset:()=>ee,dispatchCallback:()=>O,escapeRegExp:()=>ye,isIntegralNumber:()=>Ce,isTypedArray:()=>Te,len:()=>me,mergeArrays:()=>V,pick:()=>ne,pop:()=>$,product:()=>A,reverseDictionary:()=>fe});function O(ce,D){ce&&ce(D)}function fe(ce){return Object.fromEntries(Object.entries(ce).map(([D,H])=>[H,D]))}function ye(ce){return ce.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Te(ce){var D,H,te;return((te=(H=(D=ce==null?void 0:ce.prototype)==null?void 0:D.__proto__)==null?void 0:H.constructor)==null?void 0:te.name)==="TypedArray"}function Ce(ce){return Number.isInteger(ce)||typeof ce=="bigint"}function j(ce){const D=[];let H=ce;for(;Array.isArray(H);)D.push(H.length),H=H[0];return D}function $(ce,D,H=void 0){const te=ce[D];if(te!==void 0)return delete ce[D],te;if(H===void 0)throw Error(`Key ${D} does not exist in object.`);return H}function V(...ce){return Array.prototype.concat.apply([],ce)}function A(...ce){return ce.reduce((D,H)=>D.flatMap(te=>H.map(se=>[te,se])))}function ee(ce,D){return Math.abs((ce+D)%(2*D)-D)}function ne(ce,D){return Object.assign({},...D.map(H=>{if(ce[H]!==void 0)return{[H]:ce[H]}}))}function me(ce){let D=0;for(const H of ce)++D;return D}},"./src/utils/data-structures.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{CharTrie:()=>fe,PriorityQueue:()=>O,TokenLattice:()=>Te});class O{constructor($=(A,ee)=>A>ee,V=1/0){this._heap=[],this._comparator=$,this._maxSize=V}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...$){return this.extend($)}extend($){for(const V of $)if(this.size0&&this._swap(0,V),this._heap.pop(),this._siftDown(),$}replace($){const V=this.peek();return this._heap[0]=$,this._siftDown(),V}_parent($){return($+1>>>1)-1}_left($){return($<<1)+1}_right($){return $+1<<1}_greater($,V){return this._comparator(this._heap[$],this._heap[V])}_swap($,V){const A=this._heap[$];this._heap[$]=this._heap[V],this._heap[V]=A}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom($){for(;$>0&&this._greater($,this._parent($));)this._swap($,this._parent($)),$=this._parent($)}_siftDown(){let $=0;for(;this._left($)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const ee=new Ce(this.bosTokenId,0,0,0,0),ne=new Ce(this.eosTokenId,1,this.len,0,0);this.nodes.push(ee.clone()),this.nodes.push(ne.clone()),this.beginNodes[this.len].push(ne),this.endNodes[0].push(ee)}insert($,V,A,ee){const ne=this.nodes.length,me=new Ce(ee,ne,$,V,A);this.beginNodes[$].push(me),this.endNodes[$+V].push(me),this.nodes.push(me)}viterbi(){const $=this.len;let V=0;for(;V<=$;){if(this.beginNodes[V].length==0)return[];for(let ce of this.beginNodes[V]){ce.prev=null;let D=0,H=null;for(let te of this.endNodes[V]){const se=te.backtraceScore+ce.score;(H===null||se>D)&&(H=te.clone(),D=se)}if(H!==null)ce.prev=H,ce.backtraceScore=D;else return[]}++V}const A=[],ne=this.beginNodes[$][0].prev;if(ne===null)return[];let me=ne.clone();for(;me.prev!==null;)A.push(me.clone()),me=me.clone().prev.clone();return A.reverse(),A}piece($){return this.chars.slice($.pos,$.pos+$.length).join("")}tokens(){return this.viterbi().map(V=>this.piece(V))}tokenIds(){return this.viterbi().map(V=>V.tokenId)}}class Ce{constructor($,V,A,ee,ne){this.tokenId=$,this.nodeId=V,this.pos=A,this.length=ee,this.score=ne,this.prev=null,this.backtraceScore=0}clone(){const $=new Ce(this.tokenId,this.nodeId,this.pos,this.length,this.score);return $.prev=this.prev,$.backtraceScore=this.backtraceScore,$}}},"./src/utils/devices.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{DEVICE_TYPES:()=>O});const O=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":(Et,Se,N)=>{N.r(Se),N.d(Se,{DATA_TYPES:()=>Te,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Ce,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>j,isWebGpuFp16Supported:()=>ye});var O=N("./src/env.js"),fe=N("./src/utils/devices.js");const ye=function(){let $;return async function(){if($===void 0)if(!O.apis.IS_WEBGPU_AVAILABLE)$=!1;else try{$=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{$=!1}return $}}(),Te=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Ce=Object.freeze({[fe.DEVICE_TYPES.wasm]:Te.q8}),j=Object.freeze({[Te.fp32]:"",[Te.fp16]:"_fp16",[Te.int8]:"_int8",[Te.uint8]:"_uint8",[Te.q8]:"_quantized",[Te.q4]:"_q4",[Te.q4f16]:"_q4f16",[Te.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{Callable:()=>O});const O=class{constructor(){let fe=function(...ye){return fe._call(...ye)};return Object.setPrototypeOf(fe,new.target.prototype)}_call(...fe){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{getFile:()=>V,getModelFile:()=>ce,getModelJSON:()=>D});var O=N("?7a2c"),fe=N("?a42a"),ye=N("./src/env.js"),Te=N("./src/utils/core.js");const Ce={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 j{constructor(X){if(this.filePath=X,this.headers=new Headers,this.exists=O.existsSync(X),this.exists){this.status=200,this.statusText="OK";let R=O.statSync(X);this.headers.set("content-length",R.size.toString()),this.updateContentType();let I=this;this.body=new ReadableStream({start(B){I.arrayBuffer().then(k=>{B.enqueue(new Uint8Array(k)),B.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const X=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Ce[X]??"application/octet-stream")}clone(){let X=new j(this.filePath);return X.exists=this.exists,X.status=this.status,X.statusText=this.statusText,X.headers=new Headers(this.headers),X}async arrayBuffer(){return(await O.promises.readFile(this.filePath)).buffer}async blob(){const X=await O.promises.readFile(this.filePath);return new Blob([X],{type:this.headers.get("content-type")})}async text(){return await O.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function $(se,X=null,R=null){let I;try{I=new URL(se)}catch{return!1}return!(X&&!X.includes(I.protocol)||R&&!R.includes(I.hostname))}async function V(se){var X;if(ye.env.useFS&&!$(se,["http:","https:","blob:"]))return new j(se);if(typeof process<"u"&&((X=process==null?void 0:process.release)==null?void 0:X.name)==="node"){const R=!!(Cn!=null&&Cn.TESTING_REMOTELY),I=ye.env.version,B=new Headers;if(B.set("User-Agent",`transformers.js/${I}; is_ci/${R};`),$(se,["http:","https:"],["huggingface.co","hf.co"])){const ue=(Cn==null?void 0:Cn.HF_TOKEN)??(Cn==null?void 0:Cn.HF_ACCESS_TOKEN);ue&&B.set("Authorization",`Bearer ${ue}`)}return fetch(se,{headers:B})}else return fetch(se)}const A={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 ee(se,X,R){if(!R)return null;const I=A[se]??`Error (${se}) occurred while trying to load file`;throw Error(`${I}: "${X}".`)}class ne{constructor(X){this.path=X}async match(X){let R=fe.join(this.path,X),I=new j(R);if(I.exists)return I}async put(X,R){const I=Buffer.from(await R.arrayBuffer());let B=fe.join(this.path,X);try{await O.promises.mkdir(fe.dirname(B),{recursive:!0}),await O.promises.writeFile(B,I)}catch(k){console.warn("An error occurred while writing the file to cache:",k)}}}async function me(se,...X){for(let R of X)try{let I=await se.match(R);if(I)return I}catch{continue}}async function ce(se,X,R=!0,I={}){if(!ye.env.allowLocalModels){if(I.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(!ye.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,Te.dispatchCallback)(I.progress_callback,{status:"initiate",name:se,file:X});let B;if(!B&&ye.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{B=await caches.open("transformers-cache")}catch($e){console.warn("An error occurred while opening the browser cache:",$e)}}if(!B&&ye.env.useFSCache&&(B=new ne(I.cache_dir??ye.env.cacheDir)),!B&&ye.env.useCustomCache){if(!ye.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ye.env.customCache.match||!ye.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");B=ye.env.customCache}const k=I.revision??"main";let ue=te(se,X),ve=te(ye.env.localModelPath,ue),Ee=te(ye.env.remoteHost,ye.env.remotePathTemplate.replaceAll("{model}",se).replaceAll("{revision}",encodeURIComponent(k)),X),Ie=k==="main"?ue:te(se,k,X),Ae,tt=B instanceof ne?Ie:Ee,Xe=!1,dt;B&&(dt=await me(B,ve,tt));const ge=dt!==void 0;if(dt===void 0){if(ye.env.allowLocalModels)if($(ue,["http:","https:"])){if(I.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ue}.`);if(!ye.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ue}.`)}else try{dt=await V(ve),Ae=ve}catch(J){console.warn(`Unable to load from local path "${ve}": "${J}"`)}if(dt===void 0||dt.status===404){if(I.local_files_only||!ye.env.allowRemoteModels){if(R)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ve}".`);return null}if(dt=await V(Ee),dt.status!==200)return ee(dt.status,Ee,R);Ae=tt}Xe=B&&typeof Response<"u"&&dt instanceof Response&&dt.status===200}(0,Te.dispatchCallback)(I.progress_callback,{status:"download",name:se,file:X});const W={status:"progress",name:se,file:X};let de;return I.progress_callback?ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(de=new Uint8Array(await dt.arrayBuffer()),(0,Te.dispatchCallback)(I.progress_callback,{...W,progress:100,loaded:de.length,total:de.length})):de=await H(dt,$e=>{(0,Te.dispatchCallback)(I.progress_callback,{...W,...$e})}):de=new Uint8Array(await dt.arrayBuffer()),Xe&&Ae&&await B.match(Ae)===void 0&&await B.put(Ae,new Response(de,{headers:dt.headers})).catch($e=>{console.warn(`Unable to add response to browser cache: ${$e}.`)}),(0,Te.dispatchCallback)(I.progress_callback,{status:"done",name:se,file:X}),de}async function D(se,X,R=!0,I={}){let B=await ce(se,X,R,I);if(B===null)return{};let ue=new TextDecoder("utf-8").decode(B);return JSON.parse(ue)}async function H(se,X){const R=se.headers.get("Content-Length");R===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let I=parseInt(R??"0"),B=new Uint8Array(I),k=0;const ue=se.body.getReader();async function ve(){const{done:Ee,value:Ie}=await ue.read();if(Ee)return;let Ae=k+Ie.length;if(Ae>I){I=Ae;let Xe=new Uint8Array(I);Xe.set(B),B=Xe}B.set(Ie,k),k=Ae;const tt=k/I*100;return X({progress:tt,loaded:k,total:I}),ve()}return await ve(),B}function te(...se){return se=se.map((X,R)=>(R&&(X=X.replace(new RegExp("^/"),"")),R!==se.length-1&&(X=X.replace(new RegExp("/$"),"")),X)),se.join("/")}},"./src/utils/image.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{RawImage:()=>me});var O=N("./src/utils/hub.js"),fe=N("./src/env.js"),ye=N("./src/utils/tensor.js"),Te=N("?2b25");const Ce=typeof self<"u",j=Ce&&self.constructor.name==="DedicatedWorkerGlobalScope";let $,V,A;if(Ce)$=(ce,D)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ce,D)},A=self.createImageBitmap,V=self.ImageData;else if(Te)A=async ce=>{const H=(await ce.metadata()).channels,{data:te,info:se}=await ce.rotate().raw().toBuffer({resolveWithObject:!0}),X=new me(new Uint8ClampedArray(te),se.width,se.height,se.channels);return H!==void 0&&H!==se.channels&&X.convert(H),X};else throw new Error("Unable to load image processing library.");const ee={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},ne=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class me{constructor(D,H,te,se){this.data=D,this.width=H,this.height=te,this.channels=se}get size(){return[this.width,this.height]}static async read(D){if(D instanceof me)return D;if(typeof D=="string"||D instanceof URL)return await this.fromURL(D);throw new Error(`Unsupported input type: ${typeof D}`)}static fromCanvas(D){if(!Ce)throw new Error("fromCanvas() is only supported in browser environments.");const te=D.getContext("2d").getImageData(0,0,D.width,D.height).data;return new me(te,D.width,D.height,4)}static async fromURL(D){const H=await(0,O.getFile)(D);if(H.status!==200)throw new Error(`Unable to read image from "${D}" (${H.status} ${H.statusText})`);const te=await H.blob();return this.fromBlob(te)}static async fromBlob(D){if(Ce){const H=await A(D),te=$(H.width,H.height).getContext("2d");return te.drawImage(H,0,0),new this(te.getImageData(0,0,H.width,H.height).data,H.width,H.height,4)}else{const H=Te(await D.arrayBuffer());return await A(H)}}static fromTensor(D,H="CHW"){if(D.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${D.dims.length} dimensions.`);if(H==="CHW")D=D.transpose(1,2,0);else if(H!=="HWC")throw new Error(`Unsupported channel format: ${H}`);if(!(D.data instanceof Uint8ClampedArray||D.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${D.type}`);switch(D.dims[2]){case 1:case 2:case 3:case 4:return new me(D.data,D.dims[1],D.dims[0],D.dims[2]);default:throw new Error(`Unsupported number of channels: ${D.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const D=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let H=0,te=0;H=0?B=te:ue=-te,se>=0?k=se:ve=-se,I.drawImage(R,B,k,D,H,ue,ve,D,H),new me(I.getImageData(0,0,D,H).data,D,H,4).convert(X)}else{let X=this.toSharp();if(te>=0&&se>=0)X=X.extract({left:Math.floor(te),top:Math.floor(se),width:D,height:H});else if(te<=0&&se<=0){const R=Math.floor(-se),I=Math.floor(-te);X=X.extend({top:R,left:I,right:D-this.width-I,bottom:H-this.height-R})}else{let R=[0,0],I=0;se<0?(R[0]=Math.floor(-se),R[1]=H-this.height-R[0]):I=Math.floor(se);let B=[0,0],k=0;te<0?(B[0]=Math.floor(-te),B[1]=D-this.width-B[0]):k=Math.floor(te),X=X.extend({top:R[0],bottom:R[1],left:B[0],right:B[1]}).extract({left:k,top:I,width:D,height:H})}return await A(X)}}async toBlob(D="image/png",H=1){if(!Ce)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:D,quality:H})}toTensor(D="CHW"){let H=new ye.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(D!=="HWC")if(D==="CHW")H=H.permute(2,0,1);else throw new Error(`Unsupported channel format: ${D}`);return H}toCanvas(){if(!Ce)throw new Error("toCanvas() is only supported in browser environments.");const D=this.clone().rgba(),H=$(D.width,D.height),te=new V(D.data,D.width,D.height);return H.getContext("2d").putImageData(te,0,0),H}_update(D,H,te,se=null){return this.data=D,this.width=H,this.height=te,se!==null&&(this.channels=se),this}clone(){return new me(this.data.slice(),this.width,this.height,this.channels)}convert(D){if(this.channels===D)return this;switch(D){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(D){if(Ce){if(j)throw new Error("Unable to save an image from a Web Worker.");const H=D.split(".").pop().toLowerCase(),te=ne.get(H)??"image/png",se=await this.toBlob(te),X=URL.createObjectURL(se),R=document.createElement("a");R.href=X,R.download=D,R.click(),R.remove()}else{if(fe.env.useFS)return await this.toSharp().toFile(D);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Ce)throw new Error("toSharp() is only supported in server-side environments.");return Te(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{FFT:()=>ce,bankers_round:()=>te,cos_sim:()=>j,dot:()=>Ce,dynamic_time_warping:()=>se,interpolate_data:()=>O,log_softmax:()=>Te,magnitude:()=>$,max:()=>A,medianFilter:()=>D,min:()=>V,permute_data:()=>fe,round:()=>H,softmax:()=>ye});function O(X,[R,I,B],[k,ue],ve="bilinear",Ee=!1){const Ie=ue/B,Ae=k/I,tt=new X.constructor(k*ue*R),Xe=I*B,dt=k*ue;for(let ge=0;ge=0;--Ee)k[Ee]=Ie,B[Ee]=R[I[Ee]],Ie*=B[Ee];const ue=I.map((Ee,Ie)=>k[I.indexOf(Ie)]),ve=new X.constructor(X.length);for(let Ee=0;Ee=0;--Ae)Ie+=tt%R[Ae]*ue[Ae],tt=Math.floor(tt/R[Ae]);ve[Ie]=X[Ee]}return[ve,B]}function ye(X){const R=A(X)[0],I=X.map(ue=>Math.exp(ue-R)),B=I.reduce((ue,ve)=>ue+ve,0);return I.map(ue=>ue/B)}function Te(X){const R=A(X)[0];let I=0;for(let ue=0;ueue-R-B)}function Ce(X,R){let I=0;for(let B=0;BR+I*I,0))}function V(X){if(X.length===0)throw Error("Array must not be empty");let R=X[0],I=0;for(let B=1;BR&&(R=X[B],I=B);return[Number(R),I]}function ee(X){return X>0&&(X&X-1)===0}class ne{constructor(R){if(this.size=R|0,this.size<=1||!ee(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=R<<1,this.table=new Float64Array(this.size*2);for(let B=0;BB;B<<=1)++I;this._width=I%2===0?I-1:I,this._bitrev=new Int32Array(1<>>k&3)<>>1);for(let k=0;k>>1]=R[k];return B}toComplexArray(R,I){const B=I||this.createComplexArray();for(let k=0;k>>1],B[k+1]=0;return B}transform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._transform4(R,I,1)}realTransform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._realTransform4(R,I,1)}inverseTransform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._transform4(R,I,-1);for(let B=0;B>=2;ve>=2;ve>>=2){Ee=k/ve<<1;const dt=Ee>>>2;for(Ie=0;Ie>>1,ve>>>1)}else for(Ie=0,Ae=0;Ie>>1,ve>>>1,B)}const Xe=this.table;for(ve>>=2;ve>=2;ve>>=2){Ee=k/ve<<1;const ge=Ee>>>1,W=ge>>>1,de=W>>>1;for(Ie=0;Ie>>1;for(let ge=2;ge>1;++tt){const Xe=(tt+1-R)**2/2,dt=Math.sqrt(Ie**2+Ae**2)**Xe,ge=Xe*Math.atan2(Ae,Ie),W=2*tt;ue[W]=dt*Math.cos(ge),ue[W+1]=dt*Math.sin(ge),ve[W]=ue[W],ve[W+1]=-ue[W+1]}this._slicedChirpBuffer=ue.subarray(I,B),this._f=new ne(k>>1),this._f.transform(this._chirpBuffer,ve)}_transform(R,I,B){const k=this._buffer1,ue=this._buffer2,ve=this._outBuffer1,Ee=this._outBuffer2,Ie=this._chirpBuffer,Ae=this._slicedChirpBuffer,tt=this._a;if(B)for(let Xe=0;Xe>1,W=I[ge];k[Xe]=W*Ae[Xe],k[dt]=W*Ae[dt]}else for(let Xe=0;Xe=X.length&&(Ie=2*(X.length-1)-Ie),B[ve++]=X[Ie]}B.sort(),I[ue]=B[k]}return I}function H(X,R){const I=Math.pow(10,R);return Math.round(X*I)/I}function te(X){const R=Math.round(X);return Math.abs(X)%1===.5?R%2===0?R:R-1:R}function se(X){const R=X.length,I=X[0].length,B=[R+1,I+1],k=Array.from({length:B[0]},()=>Array(B[1]).fill(1/0));k[0][0]=0;const ue=Array.from({length:B[0]},()=>Array(B[1]).fill(-1));for(let tt=1;tt0||Ee>0;)switch(Ie.push(ve-1),Ae.push(Ee-1),ue[ve][Ee]){case 0:--ve,--Ee;break;case 1:--ve;break;case 2:--Ee;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ve}, ${Ee}]. Please file a bug report.`)}return Ie.reverse(),Ae.reverse(),[Ie,Ae]}},"./src/utils/tensor.js":(Et,Se,N)=>{N.r(Se),N.d(Se,{Tensor:()=>Ce,cat:()=>X,full:()=>ve,full_like:()=>Ee,interpolate:()=>V,interpolate_4d:()=>A,layer_norm:()=>D,matmul:()=>ee,mean:()=>B,mean_pooling:()=>ce,ones:()=>Ie,ones_like:()=>Ae,permute:()=>$,quantize_embeddings:()=>dt,rfft:()=>ne,stack:()=>R,std_mean:()=>I,topk:()=>me,zeros:()=>tt,zeros_like:()=>Xe});var O=N("./src/utils/maths.js"),fe=N("./src/backends/onnx.js"),ye=N("./src/ops/registry.js");const Te=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 Ce{constructor(...W){xe(this,"ort_tensor");return(0,fe.isONNXTensor)(W[0])?this.ort_tensor=W[0]:this.ort_tensor=new fe.Tensor(W[0],W[1],W[2]),new Proxy(this,{get:(de,$e)=>{if(typeof $e=="string"){let J=Number($e);if(Number.isInteger(J))return de._getitem(J)}return de[$e]},set:(de,$e,J)=>de[$e]=J})}get dims(){return this.ort_tensor.dims}set dims(W){this.ort_tensor.dims=W}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[W,...de]=this.dims;if(de.length>0){const $e=de.reduce((J,He)=>J*He);for(let J=0;J0){const J=$e.reduce((He,ct)=>He*ct);return this._subarray(W,J,$e)}else return new Ce(this.type,[this.data[W]],$e)}indexOf(W){const de=this.data;for(let $e=0;$eLe)throw new Error(`Invalid slice: ${st}`);const re=[Math.max(Pt,0),Math.min(Le,this.dims[je])];$e.push(re),de.push(re[1]-re[0])}else throw new Error(`Invalid slice: ${st}`)}const J=$e.map(([je,st])=>st-je),He=J.reduce((je,st)=>je*st),ct=this.data,nt=new ct.constructor(He),lt=this.stride();for(let je=0;je=0;--Pt){const re=J[Pt];st+=(Le%re+$e[Pt][0])*lt[Pt],Le=Math.floor(Le/re)}nt[je]=ct[st]}return new Ce(this.type,nt,de)}permute(...W){return $(this,W)}transpose(...W){return this.permute(...W)}sum(W=null,de=!1){return this.norm(1,W,de)}norm(W="fro",de=null,$e=!1){if(W==="fro")W=2;else if(typeof W=="string")throw Error(`Unsupported norm: ${W}`);const J=this.data;if(de===null){let nt=J.reduce((lt,je)=>lt+je**W,0)**(1/W);return new Ce(this.type,[nt],[])}de=se(de,this.dims.length);const He=this.dims.slice();He[de]=1;const ct=new J.constructor(J.length/this.dims[de]);for(let nt=0;nt=0;--je){const Le=this.dims[je];if(je!==de){const re=st%Le;lt+=re*Pt,Pt*=He[je]}st=Math.floor(st/Le)}ct[lt]+=J[nt]**W}if(W!==1)for(let nt=0;nt=0;--lt){const Pt=this.dims[lt];if(lt!==de){const Le=je%Pt;nt+=Le*st,st*=this.dims[lt]}je=Math.floor(je/Pt)}J[ct]/=He[nt]}return this}normalize(W=2,de=1){return this.clone().normalize_(W,de)}stride(){return k(this.dims)}squeeze(W=null){return new Ce(this.type,this.data,H(this.dims,W))}squeeze_(W=null){return this.dims=H(this.dims,W),this}unsqueeze(W=null){return new Ce(this.type,this.data,te(this.dims,W))}unsqueeze_(W=null){return this.dims=te(this.dims,W),this}flatten_(W=0,de=-1){de=(de+this.dims.length)%this.dims.length;let $e=this.dims.slice(0,W),J=this.dims.slice(W,de+1),He=this.dims.slice(de+1);return this.dims=[...$e,J.reduce((ct,nt)=>ct*nt,1),...He],this}flatten(W=0,de=-1){return this.clone().flatten_(W,de)}view(...W){let de=-1;for(let J=0;Jnt!==de?He*ct:He,1);W[de]=$e.length/J}return new Ce(this.type,$e,W)}neg_(){const W=this.data;for(let de=0;deHe*ct);if(de!==$e)throw Error(`cannot reshape array of size ${de} into shape (${W})`);let J=ge;for(let He=W.length-1;He>=0;He--)J=J.reduce((ct,nt)=>{let lt=ct[ct.length-1];return lt.lengthde!==1):typeof W=="number"?ge[W]===1&&ge.splice(W,1):Array.isArray(W)&&(ge=ge.filter((de,$e)=>de!==1||!W.includes($e))),ge}function te(ge,W){return W=se(W,ge.length+1),ge=ge.slice(),ge.splice(W,0,1),ge}function se(ge,W,de=null,$e=!0){if($e&&(ge<-W||ge>=W))throw new Error(`IndexError: index ${ge} is out of bounds for dimension${de===null?"":" "+de} with size ${W}`);return ge<0&&(ge=(ge%W+W)%W),ge}function X(ge,W=0){W=se(W,ge[0].dims.length);const de=ge[0].dims.slice();de[W]=ge.reduce((ct,nt)=>ct+nt.dims[W],0);const $e=de.reduce((ct,nt)=>ct*nt,1),J=new ge[0].data.constructor($e),He=ge[0].type;if(W===0){let ct=0;for(const nt of ge){const lt=nt.data;J.set(lt,ct),ct+=lt.length}}else{let ct=0;for(let nt=0;nt=0;--Le){const Ve=je[Le];let qe=re%Ve;Le===W&&(qe+=ct),Pt+=qe*ke,ke*=de[Le],re=Math.floor(re/Ve)}J[Pt]=lt[st]}ct+=je[W]}}return new Ce(He,J,de)}function R(ge,W=0){return X(ge.map(de=>de.unsqueeze(W)),W)}function I(ge,W=null,de=1,$e=!1){const J=ge.data,He=ge.dims;if(W===null){const Le=J.reduce((qe,We)=>qe+We,0)/J.length,re=Math.sqrt(J.reduce((qe,We)=>qe+(We-Le)**2,0)/(J.length-de)),ke=new Ce(ge.type,[Le],[]);return[new Ce(ge.type,[re],[]),ke]}W=se(W,He.length);const ct=B(ge,W,$e),nt=ct.data,lt=He.slice();lt[W]=1;const je=new J.constructor(J.length/He[W]);for(let Pt=0;Pt=0;--re){const qe=He[re];if(re!==W){const We=ke%qe;Le+=We*Ve,Ve*=lt[re]}ke=Math.floor(ke/qe)}je[Le]+=(J[Pt]-nt[Le])**2}for(let Pt=0;Ptlt+je,0);return new Ce(ge.type,[nt/$e.length],[])}const J=ge.dims;W=se(W,J.length);const He=J.slice();He[W]=1;const ct=new $e.constructor($e.length/J[W]);for(let nt=0;nt<$e.length;++nt){let lt=0;for(let je=J.length-1,st=nt,Pt=1;je>=0;--je){const Le=J[je];if(je!==W){const re=st%Le;lt+=re*Pt,Pt*=He[je]}st=Math.floor(st/Le)}ct[lt]+=$e[nt]}if(J[W]!==1)for(let nt=0;nt=0;--de)W[de]=$e,$e*=ge[de];return W}function ue(ge,W,de,$e){const J=ge.reduce((He,ct)=>He*ct,1);return new Ce(de,new $e(J).fill(W),ge)}function ve(ge,W){let de,$e;if(typeof W=="number")de="float32",$e=Float32Array;else if(typeof W=="bigint")de="int64",$e=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof W}`);return ue(ge,W,de,$e)}function Ee(ge,W){return ve(ge.dims,W)}function Ie(ge){return ue(ge,1n,"int64",BigInt64Array)}function Ae(ge){return Ie(ge.dims)}function tt(ge){return ue(ge,0n,"int64",BigInt64Array)}function Xe(ge){return tt(ge.dims)}function dt(ge,W){if(ge.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ge.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(W))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=W==="binary",$e=de?"int8":"uint8",J=de?Int8Array:Uint8Array,He=ge.data,ct=new J(He.length/8);for(let nt=0;nt0?1:0,je=Math.floor(nt/8),st=nt%8;ct[je]|=lt<<7-st,de&&st===0&&(ct[je]-=128)}return new Ce($e,ct,[ge.dims[0],ge.dims[1]/8])}}},Qs={};function qr(Et){var Se=Qs[Et];if(Se!==void 0)return Se.exports;var N=Qs[Et]={exports:{}};return es[Et](N,N.exports,qr),N.exports}qr.m=es,(()=>{var Et=Object.getPrototypeOf?N=>Object.getPrototypeOf(N):N=>N.__proto__,Se;qr.t=function(N,O){if(O&1&&(N=this(N)),O&8||typeof N=="object"&&N&&(O&4&&N.__esModule||O&16&&typeof N.then=="function"))return N;var fe=Object.create(null);qr.r(fe);var ye={};Se=Se||[null,Et({}),Et([]),Et(Et)];for(var Te=O&2&&N;typeof Te=="object"&&!~Se.indexOf(Te);Te=Et(Te))Object.getOwnPropertyNames(Te).forEach(Ce=>ye[Ce]=()=>N[Ce]);return ye.default=()=>N,qr.d(fe,ye),fe}})(),qr.d=(Et,Se)=>{for(var N in Se)qr.o(Se,N)&&!qr.o(Et,N)&&Object.defineProperty(Et,N,{enumerable:!0,get:Se[N]})},qr.o=(Et,Se)=>Object.prototype.hasOwnProperty.call(Et,Se),qr.r=Et=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Et,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Et,"__esModule",{value:!0})},(()=>{var Et;if(typeof self.location.href=="string"&&(Et=self.location.href),!Et)throw new Error("Automatic publicPath is not supported in this browser");Et=Et.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),qr.p=Et})(),qr.b=new URL("./",self.location.href);var c={};/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/qr.r(c),qr.d(c,{ASTFeatureExtractor:()=>Jt.ASTFeatureExtractor,ASTForAudioClassification:()=>b.ASTForAudioClassification,ASTModel:()=>b.ASTModel,ASTPreTrainedModel:()=>b.ASTPreTrainedModel,AlbertForMaskedLM:()=>b.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>b.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>b.AlbertForSequenceClassification,AlbertModel:()=>b.AlbertModel,AlbertPreTrainedModel:()=>b.AlbertPreTrainedModel,AlbertTokenizer:()=>nr.AlbertTokenizer,AudioClassificationPipeline:()=>Hr.AudioClassificationPipeline,AutoConfig:()=>mc.AutoConfig,AutoModel:()=>b.AutoModel,AutoModelForAudioClassification:()=>b.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>b.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>b.AutoModelForCTC,AutoModelForCausalLM:()=>b.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>b.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>b.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>b.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>b.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>b.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>b.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>b.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>b.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>b.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>b.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>b.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>b.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>b.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>b.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>b.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>b.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>b.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>b.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>b.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>b.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>b.AutoModelForVision2Seq,AutoModelForXVector:()=>b.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>b.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Jt.AutoProcessor,AutoTokenizer:()=>nr.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>Hr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>b.BartForConditionalGeneration,BartForSequenceClassification:()=>b.BartForSequenceClassification,BartModel:()=>b.BartModel,BartPretrainedModel:()=>b.BartPretrainedModel,BartTokenizer:()=>nr.BartTokenizer,BaseModelOutput:()=>b.BaseModelOutput,BaseStreamer:()=>_c.BaseStreamer,BeitFeatureExtractor:()=>Jt.BeitFeatureExtractor,BeitForImageClassification:()=>b.BeitForImageClassification,BeitModel:()=>b.BeitModel,BeitPreTrainedModel:()=>b.BeitPreTrainedModel,BertForMaskedLM:()=>b.BertForMaskedLM,BertForQuestionAnswering:()=>b.BertForQuestionAnswering,BertForSequenceClassification:()=>b.BertForSequenceClassification,BertForTokenClassification:()=>b.BertForTokenClassification,BertModel:()=>b.BertModel,BertPreTrainedModel:()=>b.BertPreTrainedModel,BertTokenizer:()=>nr.BertTokenizer,BitImageProcessor:()=>Jt.BitImageProcessor,BlenderbotForConditionalGeneration:()=>b.BlenderbotForConditionalGeneration,BlenderbotModel:()=>b.BlenderbotModel,BlenderbotPreTrainedModel:()=>b.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>b.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>b.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>b.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>nr.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>nr.BlenderbotTokenizer,BloomForCausalLM:()=>b.BloomForCausalLM,BloomModel:()=>b.BloomModel,BloomPreTrainedModel:()=>b.BloomPreTrainedModel,BloomTokenizer:()=>nr.BloomTokenizer,CLIPFeatureExtractor:()=>Jt.CLIPFeatureExtractor,CLIPImageProcessor:()=>Jt.CLIPImageProcessor,CLIPModel:()=>b.CLIPModel,CLIPPreTrainedModel:()=>b.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>b.CLIPSegForImageSegmentation,CLIPSegModel:()=>b.CLIPSegModel,CLIPSegPreTrainedModel:()=>b.CLIPSegPreTrainedModel,CLIPTextModel:()=>b.CLIPTextModel,CLIPTextModelWithProjection:()=>b.CLIPTextModelWithProjection,CLIPTokenizer:()=>nr.CLIPTokenizer,CLIPVisionModel:()=>b.CLIPVisionModel,CLIPVisionModelWithProjection:()=>b.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>b.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>b.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>b.CamembertForSequenceClassification,CamembertForTokenClassification:()=>b.CamembertForTokenClassification,CamembertModel:()=>b.CamembertModel,CamembertPreTrainedModel:()=>b.CamembertPreTrainedModel,CamembertTokenizer:()=>nr.CamembertTokenizer,CausalLMOutput:()=>b.CausalLMOutput,CausalLMOutputWithPast:()=>b.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Jt.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>b.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>b.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>b.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Jt.ClapFeatureExtractor,ClapModel:()=>b.ClapModel,ClapPreTrainedModel:()=>b.ClapPreTrainedModel,ClapTextModelWithProjection:()=>b.ClapTextModelWithProjection,CodeGenForCausalLM:()=>b.CodeGenForCausalLM,CodeGenModel:()=>b.CodeGenModel,CodeGenPreTrainedModel:()=>b.CodeGenPreTrainedModel,CodeGenTokenizer:()=>nr.CodeGenTokenizer,CodeLlamaTokenizer:()=>nr.CodeLlamaTokenizer,CohereForCausalLM:()=>b.CohereForCausalLM,CohereModel:()=>b.CohereModel,CoherePreTrainedModel:()=>b.CoherePreTrainedModel,CohereTokenizer:()=>nr.CohereTokenizer,ConvBertForMaskedLM:()=>b.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>b.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>b.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>b.ConvBertForTokenClassification,ConvBertModel:()=>b.ConvBertModel,ConvBertPreTrainedModel:()=>b.ConvBertPreTrainedModel,ConvBertTokenizer:()=>nr.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Jt.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>b.ConvNextForImageClassification,ConvNextImageProcessor:()=>Jt.ConvNextImageProcessor,ConvNextModel:()=>b.ConvNextModel,ConvNextPreTrainedModel:()=>b.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>b.ConvNextV2ForImageClassification,ConvNextV2Model:()=>b.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>b.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Jt.DPTFeatureExtractor,DPTForDepthEstimation:()=>b.DPTForDepthEstimation,DPTImageProcessor:()=>Jt.DPTImageProcessor,DPTModel:()=>b.DPTModel,DPTPreTrainedModel:()=>b.DPTPreTrainedModel,DebertaForMaskedLM:()=>b.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>b.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>b.DebertaForSequenceClassification,DebertaForTokenClassification:()=>b.DebertaForTokenClassification,DebertaModel:()=>b.DebertaModel,DebertaPreTrainedModel:()=>b.DebertaPreTrainedModel,DebertaTokenizer:()=>nr.DebertaTokenizer,DebertaV2ForMaskedLM:()=>b.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>b.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>b.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>b.DebertaV2ForTokenClassification,DebertaV2Model:()=>b.DebertaV2Model,DebertaV2PreTrainedModel:()=>b.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>nr.DebertaV2Tokenizer,DecisionTransformerModel:()=>b.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>b.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>Jt.DeiTFeatureExtractor,DeiTForImageClassification:()=>b.DeiTForImageClassification,DeiTModel:()=>b.DeiTModel,DeiTPreTrainedModel:()=>b.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>b.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>b.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>Hr.DepthEstimationPipeline,DetrFeatureExtractor:()=>Jt.DetrFeatureExtractor,DetrForObjectDetection:()=>b.DetrForObjectDetection,DetrForSegmentation:()=>b.DetrForSegmentation,DetrModel:()=>b.DetrModel,DetrObjectDetectionOutput:()=>b.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>b.DetrPreTrainedModel,DetrSegmentationOutput:()=>b.DetrSegmentationOutput,Dinov2ForImageClassification:()=>b.Dinov2ForImageClassification,Dinov2Model:()=>b.Dinov2Model,Dinov2PreTrainedModel:()=>b.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>b.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>b.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>b.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>b.DistilBertForTokenClassification,DistilBertModel:()=>b.DistilBertModel,DistilBertPreTrainedModel:()=>b.DistilBertPreTrainedModel,DistilBertTokenizer:()=>nr.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>Hr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Jt.DonutFeatureExtractor,DonutSwinModel:()=>b.DonutSwinModel,DonutSwinPreTrainedModel:()=>b.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>b.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Jt.EfficientNetImageProcessor,EfficientNetModel:()=>b.EfficientNetModel,EfficientNetPreTrainedModel:()=>b.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>b.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>b.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>b.ElectraForSequenceClassification,ElectraForTokenClassification:()=>b.ElectraForTokenClassification,ElectraModel:()=>b.ElectraModel,ElectraPreTrainedModel:()=>b.ElectraPreTrainedModel,ElectraTokenizer:()=>nr.ElectraTokenizer,EosTokenCriteria:()=>eo.EosTokenCriteria,EsmForMaskedLM:()=>b.EsmForMaskedLM,EsmForSequenceClassification:()=>b.EsmForSequenceClassification,EsmForTokenClassification:()=>b.EsmForTokenClassification,EsmModel:()=>b.EsmModel,EsmPreTrainedModel:()=>b.EsmPreTrainedModel,EsmTokenizer:()=>nr.EsmTokenizer,FFT:()=>An.FFT,FalconForCausalLM:()=>b.FalconForCausalLM,FalconModel:()=>b.FalconModel,FalconPreTrainedModel:()=>b.FalconPreTrainedModel,FalconTokenizer:()=>nr.FalconTokenizer,FastViTForImageClassification:()=>b.FastViTForImageClassification,FastViTModel:()=>b.FastViTModel,FastViTPreTrainedModel:()=>b.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>Hr.FeatureExtractionPipeline,FeatureExtractor:()=>Jt.FeatureExtractor,FillMaskPipeline:()=>Hr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>b.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>b.Florence2PreTrainedModel,Florence2Processor:()=>Jt.Florence2Processor,GLPNFeatureExtractor:()=>Jt.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>b.GLPNForDepthEstimation,GLPNModel:()=>b.GLPNModel,GLPNPreTrainedModel:()=>b.GLPNPreTrainedModel,GPT2LMHeadModel:()=>b.GPT2LMHeadModel,GPT2Model:()=>b.GPT2Model,GPT2PreTrainedModel:()=>b.GPT2PreTrainedModel,GPT2Tokenizer:()=>nr.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>b.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>b.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>b.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>b.GPTJForCausalLM,GPTJModel:()=>b.GPTJModel,GPTJPreTrainedModel:()=>b.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>b.GPTNeoForCausalLM,GPTNeoModel:()=>b.GPTNeoModel,GPTNeoPreTrainedModel:()=>b.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>b.GPTNeoXForCausalLM,GPTNeoXModel:()=>b.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>b.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>nr.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>b.Gemma2ForCausalLM,Gemma2Model:()=>b.Gemma2Model,Gemma2PreTrainedModel:()=>b.Gemma2PreTrainedModel,GemmaForCausalLM:()=>b.GemmaForCausalLM,GemmaModel:()=>b.GemmaModel,GemmaPreTrainedModel:()=>b.GemmaPreTrainedModel,GemmaTokenizer:()=>nr.GemmaTokenizer,Grok1Tokenizer:()=>nr.Grok1Tokenizer,GroupViTModel:()=>b.GroupViTModel,GroupViTPreTrainedModel:()=>b.GroupViTPreTrainedModel,HerbertTokenizer:()=>nr.HerbertTokenizer,HieraForImageClassification:()=>b.HieraForImageClassification,HieraModel:()=>b.HieraModel,HieraPreTrainedModel:()=>b.HieraPreTrainedModel,HubertForCTC:()=>b.HubertForCTC,HubertForSequenceClassification:()=>b.HubertForSequenceClassification,HubertModel:()=>b.HubertModel,HubertPreTrainedModel:()=>b.HubertPreTrainedModel,ImageClassificationPipeline:()=>Hr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>Hr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Jt.ImageFeatureExtractor,ImageMattingOutput:()=>b.ImageMattingOutput,ImageSegmentationPipeline:()=>Hr.ImageSegmentationPipeline,ImageToImagePipeline:()=>Hr.ImageToImagePipeline,ImageToTextPipeline:()=>Hr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>eo.InterruptableStoppingCriteria,JAISLMHeadModel:()=>b.JAISLMHeadModel,JAISModel:()=>b.JAISModel,JAISPreTrainedModel:()=>b.JAISPreTrainedModel,LlamaForCausalLM:()=>b.LlamaForCausalLM,LlamaModel:()=>b.LlamaModel,LlamaPreTrainedModel:()=>b.LlamaPreTrainedModel,LlamaTokenizer:()=>nr.LlamaTokenizer,LlavaForConditionalGeneration:()=>b.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>b.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>b.LongT5ForConditionalGeneration,LongT5Model:()=>b.LongT5Model,LongT5PreTrainedModel:()=>b.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>b.M2M100ForConditionalGeneration,M2M100Model:()=>b.M2M100Model,M2M100PreTrainedModel:()=>b.M2M100PreTrainedModel,M2M100Tokenizer:()=>nr.M2M100Tokenizer,MBart50Tokenizer:()=>nr.MBart50Tokenizer,MBartForCausalLM:()=>b.MBartForCausalLM,MBartForConditionalGeneration:()=>b.MBartForConditionalGeneration,MBartForSequenceClassification:()=>b.MBartForSequenceClassification,MBartModel:()=>b.MBartModel,MBartPreTrainedModel:()=>b.MBartPreTrainedModel,MBartTokenizer:()=>nr.MBartTokenizer,MPNetForMaskedLM:()=>b.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>b.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>b.MPNetForSequenceClassification,MPNetForTokenClassification:()=>b.MPNetForTokenClassification,MPNetModel:()=>b.MPNetModel,MPNetPreTrainedModel:()=>b.MPNetPreTrainedModel,MPNetTokenizer:()=>nr.MPNetTokenizer,MT5ForConditionalGeneration:()=>b.MT5ForConditionalGeneration,MT5Model:()=>b.MT5Model,MT5PreTrainedModel:()=>b.MT5PreTrainedModel,MarianMTModel:()=>b.MarianMTModel,MarianModel:()=>b.MarianModel,MarianPreTrainedModel:()=>b.MarianPreTrainedModel,MarianTokenizer:()=>nr.MarianTokenizer,MaskFormerFeatureExtractor:()=>Jt.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>b.MaskFormerForInstanceSegmentation,MaskFormerModel:()=>b.MaskFormerModel,MaskFormerPreTrainedModel:()=>b.MaskFormerPreTrainedModel,MaskedLMOutput:()=>b.MaskedLMOutput,MaxLengthCriteria:()=>eo.MaxLengthCriteria,MistralForCausalLM:()=>b.MistralForCausalLM,MistralModel:()=>b.MistralModel,MistralPreTrainedModel:()=>b.MistralPreTrainedModel,MobileBertForMaskedLM:()=>b.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>b.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>b.MobileBertForSequenceClassification,MobileBertModel:()=>b.MobileBertModel,MobileBertPreTrainedModel:()=>b.MobileBertPreTrainedModel,MobileBertTokenizer:()=>nr.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>Jt.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>b.MobileNetV1ForImageClassification,MobileNetV1Model:()=>b.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>b.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Jt.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>b.MobileNetV2ForImageClassification,MobileNetV2Model:()=>b.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>b.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Jt.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>b.MobileNetV3ForImageClassification,MobileNetV3Model:()=>b.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>b.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Jt.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>b.MobileNetV4ForImageClassification,MobileNetV4Model:()=>b.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>b.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Jt.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>b.MobileViTForImageClassification,MobileViTImageProcessor:()=>Jt.MobileViTImageProcessor,MobileViTModel:()=>b.MobileViTModel,MobileViTPreTrainedModel:()=>b.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>b.MobileViTV2ForImageClassification,MobileViTV2Model:()=>b.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>b.MobileViTV2PreTrainedModel,ModelOutput:()=>b.ModelOutput,Moondream1ForConditionalGeneration:()=>b.Moondream1ForConditionalGeneration,MptForCausalLM:()=>b.MptForCausalLM,MptModel:()=>b.MptModel,MptPreTrainedModel:()=>b.MptPreTrainedModel,MusicgenForCausalLM:()=>b.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>b.MusicgenForConditionalGeneration,MusicgenModel:()=>b.MusicgenModel,MusicgenPreTrainedModel:()=>b.MusicgenPreTrainedModel,NllbTokenizer:()=>nr.NllbTokenizer,NomicBertModel:()=>b.NomicBertModel,NomicBertPreTrainedModel:()=>b.NomicBertPreTrainedModel,NougatImageProcessor:()=>Jt.NougatImageProcessor,NougatTokenizer:()=>nr.NougatTokenizer,OPTForCausalLM:()=>b.OPTForCausalLM,OPTModel:()=>b.OPTModel,OPTPreTrainedModel:()=>b.OPTPreTrainedModel,ObjectDetectionPipeline:()=>Hr.ObjectDetectionPipeline,OpenELMForCausalLM:()=>b.OpenELMForCausalLM,OpenELMModel:()=>b.OpenELMModel,OpenELMPreTrainedModel:()=>b.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Jt.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>b.OwlViTForObjectDetection,OwlViTModel:()=>b.OwlViTModel,OwlViTPreTrainedModel:()=>b.OwlViTPreTrainedModel,OwlViTProcessor:()=>Jt.OwlViTProcessor,Owlv2ForObjectDetection:()=>b.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Jt.Owlv2ImageProcessor,Owlv2Model:()=>b.Owlv2Model,Owlv2PreTrainedModel:()=>b.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>b.Phi3ForCausalLM,Phi3Model:()=>b.Phi3Model,Phi3PreTrainedModel:()=>b.Phi3PreTrainedModel,PhiForCausalLM:()=>b.PhiForCausalLM,PhiModel:()=>b.PhiModel,PhiPreTrainedModel:()=>b.PhiPreTrainedModel,Pipeline:()=>Hr.Pipeline,PreTrainedModel:()=>b.PreTrainedModel,PreTrainedTokenizer:()=>nr.PreTrainedTokenizer,PretrainedConfig:()=>mc.PretrainedConfig,PretrainedMixin:()=>b.PretrainedMixin,Processor:()=>Jt.Processor,PvtForImageClassification:()=>b.PvtForImageClassification,PvtImageProcessor:()=>Jt.PvtImageProcessor,PvtModel:()=>b.PvtModel,PvtPreTrainedModel:()=>b.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>Jt.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>b.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>b.PyAnnoteModel,PyAnnotePreTrainedModel:()=>b.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Jt.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>b.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>Hr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>b.Qwen2ForCausalLM,Qwen2Model:()=>b.Qwen2Model,Qwen2PreTrainedModel:()=>b.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>nr.Qwen2Tokenizer,RTDetrForObjectDetection:()=>b.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Jt.RTDetrImageProcessor,RTDetrModel:()=>b.RTDetrModel,RTDetrObjectDetectionOutput:()=>b.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>b.RTDetrPreTrainedModel,RawImage:()=>xf.RawImage,ResNetForImageClassification:()=>b.ResNetForImageClassification,ResNetModel:()=>b.ResNetModel,ResNetPreTrainedModel:()=>b.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>b.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>b.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>b.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>b.RoFormerForTokenClassification,RoFormerModel:()=>b.RoFormerModel,RoFormerPreTrainedModel:()=>b.RoFormerPreTrainedModel,RoFormerTokenizer:()=>nr.RoFormerTokenizer,RobertaForMaskedLM:()=>b.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>b.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>b.RobertaForSequenceClassification,RobertaForTokenClassification:()=>b.RobertaForTokenClassification,RobertaModel:()=>b.RobertaModel,RobertaPreTrainedModel:()=>b.RobertaPreTrainedModel,RobertaTokenizer:()=>nr.RobertaTokenizer,SamImageProcessor:()=>Jt.SamImageProcessor,SamImageSegmentationOutput:()=>b.SamImageSegmentationOutput,SamModel:()=>b.SamModel,SamPreTrainedModel:()=>b.SamPreTrainedModel,SamProcessor:()=>Jt.SamProcessor,SapiensFeatureExtractor:()=>Jt.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>b.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>b.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>b.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>b.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Jt.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Jt.SegformerFeatureExtractor,SegformerForImageClassification:()=>b.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>b.SegformerForSemanticSegmentation,SegformerModel:()=>b.SegformerModel,SegformerPreTrainedModel:()=>b.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>b.Seq2SeqLMOutput,SequenceClassifierOutput:()=>b.SequenceClassifierOutput,SiglipImageProcessor:()=>Jt.SiglipImageProcessor,SiglipModel:()=>b.SiglipModel,SiglipPreTrainedModel:()=>b.SiglipPreTrainedModel,SiglipTextModel:()=>b.SiglipTextModel,SiglipTokenizer:()=>nr.SiglipTokenizer,SiglipVisionModel:()=>b.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Jt.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>b.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>b.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>b.SpeechT5HifiGan,SpeechT5Model:()=>b.SpeechT5Model,SpeechT5PreTrainedModel:()=>b.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Jt.SpeechT5Processor,SpeechT5Tokenizer:()=>nr.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>b.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>b.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>b.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>b.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>b.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>nr.SqueezeBertTokenizer,StableLmForCausalLM:()=>b.StableLmForCausalLM,StableLmModel:()=>b.StableLmModel,StableLmPreTrainedModel:()=>b.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>b.Starcoder2ForCausalLM,Starcoder2Model:()=>b.Starcoder2Model,Starcoder2PreTrainedModel:()=>b.Starcoder2PreTrainedModel,StoppingCriteria:()=>eo.StoppingCriteria,StoppingCriteriaList:()=>eo.StoppingCriteriaList,SummarizationPipeline:()=>Hr.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>b.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Jt.Swin2SRImageProcessor,Swin2SRModel:()=>b.Swin2SRModel,Swin2SRPreTrainedModel:()=>b.Swin2SRPreTrainedModel,SwinForImageClassification:()=>b.SwinForImageClassification,SwinModel:()=>b.SwinModel,SwinPreTrainedModel:()=>b.SwinPreTrainedModel,T5ForConditionalGeneration:()=>b.T5ForConditionalGeneration,T5Model:()=>b.T5Model,T5PreTrainedModel:()=>b.T5PreTrainedModel,T5Tokenizer:()=>nr.T5Tokenizer,TableTransformerForObjectDetection:()=>b.TableTransformerForObjectDetection,TableTransformerModel:()=>b.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>b.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>b.TableTransformerPreTrainedModel,Tensor:()=>on.Tensor,Text2TextGenerationPipeline:()=>Hr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>Hr.TextClassificationPipeline,TextGenerationPipeline:()=>Hr.TextGenerationPipeline,TextStreamer:()=>_c.TextStreamer,TextToAudioPipeline:()=>Hr.TextToAudioPipeline,TokenClassificationPipeline:()=>Hr.TokenClassificationPipeline,TokenClassifierOutput:()=>b.TokenClassifierOutput,TokenizerModel:()=>nr.TokenizerModel,TrOCRForCausalLM:()=>b.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>b.TrOCRPreTrainedModel,TranslationPipeline:()=>Hr.TranslationPipeline,UniSpeechForCTC:()=>b.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>b.UniSpeechForSequenceClassification,UniSpeechModel:()=>b.UniSpeechModel,UniSpeechPreTrainedModel:()=>b.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>b.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>b.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>b.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>b.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>b.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>Jt.ViTFeatureExtractor,ViTForImageClassification:()=>b.ViTForImageClassification,ViTImageProcessor:()=>Jt.ViTImageProcessor,ViTMAEModel:()=>b.ViTMAEModel,ViTMAEPreTrainedModel:()=>b.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>b.ViTMSNForImageClassification,ViTMSNModel:()=>b.ViTMSNModel,ViTMSNPreTrainedModel:()=>b.ViTMSNPreTrainedModel,ViTModel:()=>b.ViTModel,ViTPreTrainedModel:()=>b.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>b.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>b.VitMatteForImageMatting,VitMatteImageProcessor:()=>Jt.VitMatteImageProcessor,VitMattePreTrainedModel:()=>b.VitMattePreTrainedModel,VitsModel:()=>b.VitsModel,VitsModelOutput:()=>b.VitsModelOutput,VitsPreTrainedModel:()=>b.VitsPreTrainedModel,VitsTokenizer:()=>nr.VitsTokenizer,Wav2Vec2BertForCTC:()=>b.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>b.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>b.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>b.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>nr.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Jt.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>b.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>b.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>b.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>b.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>b.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Jt.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>b.WavLMForAudioFrameClassification,WavLMForCTC:()=>b.WavLMForCTC,WavLMForSequenceClassification:()=>b.WavLMForSequenceClassification,WavLMForXVector:()=>b.WavLMForXVector,WavLMModel:()=>b.WavLMModel,WavLMPreTrainedModel:()=>b.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Jt.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>b.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>b.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Jt.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>b.WhisperForConditionalGeneration,WhisperModel:()=>b.WhisperModel,WhisperPreTrainedModel:()=>b.WhisperPreTrainedModel,WhisperProcessor:()=>Jt.WhisperProcessor,WhisperTextStreamer:()=>_c.WhisperTextStreamer,WhisperTokenizer:()=>nr.WhisperTokenizer,XLMForQuestionAnswering:()=>b.XLMForQuestionAnswering,XLMForSequenceClassification:()=>b.XLMForSequenceClassification,XLMForTokenClassification:()=>b.XLMForTokenClassification,XLMModel:()=>b.XLMModel,XLMPreTrainedModel:()=>b.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>b.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>b.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>b.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>b.XLMRobertaForTokenClassification,XLMRobertaModel:()=>b.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>b.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>nr.XLMRobertaTokenizer,XLMTokenizer:()=>nr.XLMTokenizer,XLMWithLMHeadModel:()=>b.XLMWithLMHeadModel,XVectorOutput:()=>b.XVectorOutput,YolosFeatureExtractor:()=>Jt.YolosFeatureExtractor,YolosForObjectDetection:()=>b.YolosForObjectDetection,YolosModel:()=>b.YolosModel,YolosObjectDetectionOutput:()=>b.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>b.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>Hr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>Hr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>Hr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>Hr.ZeroShotObjectDetectionPipeline,bankers_round:()=>An.bankers_round,cat:()=>on.cat,cos_sim:()=>An.cos_sim,dot:()=>An.dot,dynamic_time_warping:()=>An.dynamic_time_warping,env:()=>vf.env,full:()=>on.full,full_like:()=>on.full_like,getKeyValueShapes:()=>mc.getKeyValueShapes,hamming:()=>yi.hamming,hanning:()=>yi.hanning,interpolate:()=>on.interpolate,interpolate_4d:()=>on.interpolate_4d,interpolate_data:()=>An.interpolate_data,is_chinese_char:()=>nr.is_chinese_char,layer_norm:()=>on.layer_norm,log_softmax:()=>An.log_softmax,magnitude:()=>An.magnitude,matmul:()=>on.matmul,max:()=>An.max,mean:()=>on.mean,mean_pooling:()=>on.mean_pooling,medianFilter:()=>An.medianFilter,mel_filter_bank:()=>yi.mel_filter_bank,min:()=>An.min,ones:()=>on.ones,ones_like:()=>on.ones_like,permute:()=>on.permute,permute_data:()=>An.permute_data,pipeline:()=>Hr.pipeline,quantize_embeddings:()=>on.quantize_embeddings,read_audio:()=>yi.read_audio,rfft:()=>on.rfft,round:()=>An.round,softmax:()=>An.softmax,spectrogram:()=>yi.spectrogram,stack:()=>on.stack,std_mean:()=>on.std_mean,topk:()=>on.topk,window_function:()=>yi.window_function,zeros:()=>on.zeros,zeros_like:()=>on.zeros_like});var vf=qr("./src/env.js"),Hr=qr("./src/pipelines.js"),b=qr("./src/models.js"),nr=qr("./src/tokenizers.js"),Jt=qr("./src/processors.js"),mc=qr("./src/configs.js"),yi=qr("./src/utils/audio.js"),xf=qr("./src/utils/image.js"),on=qr("./src/utils/tensor.js"),An=qr("./src/utils/maths.js"),_c=qr("./src/generation/streamers.js"),eo=qr("./src/generation/stopping_criteria.js");c.ASTFeatureExtractor,c.ASTForAudioClassification,c.ASTModel,c.ASTPreTrainedModel,c.AlbertForMaskedLM,c.AlbertForQuestionAnswering,c.AlbertForSequenceClassification,c.AlbertModel,c.AlbertPreTrainedModel,c.AlbertTokenizer,c.AudioClassificationPipeline,c.AutoConfig,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC;var Tf=c.AutoModelForCausalLM;c.AutoModelForDepthEstimation,c.AutoModelForDocumentQuestionAnswering,c.AutoModelForImageClassification,c.AutoModelForImageFeatureExtraction,c.AutoModelForImageMatting,c.AutoModelForImageSegmentation,c.AutoModelForImageToImage,c.AutoModelForMaskGeneration,c.AutoModelForMaskedLM,c.AutoModelForNormalEstimation,c.AutoModelForObjectDetection,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation,c.AutoModelForVision2Seq,c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection,c.AutoProcessor;var Sf=c.AutoTokenizer;c.AutomaticSpeechRecognitionPipeline,c.BartForConditionalGeneration,c.BartForSequenceClassification,c.BartModel,c.BartPretrainedModel,c.BartTokenizer,c.BaseModelOutput,c.BaseStreamer,c.BeitFeatureExtractor,c.BeitForImageClassification,c.BeitModel,c.BeitPreTrainedModel,c.BertForMaskedLM,c.BertForQuestionAnswering,c.BertForSequenceClassification,c.BertForTokenClassification,c.BertModel,c.BertPreTrainedModel,c.BertTokenizer,c.BitImageProcessor,c.BlenderbotForConditionalGeneration,c.BlenderbotModel,c.BlenderbotPreTrainedModel,c.BlenderbotSmallForConditionalGeneration,c.BlenderbotSmallModel,c.BlenderbotSmallPreTrainedModel,c.BlenderbotSmallTokenizer,c.BlenderbotTokenizer,c.BloomForCausalLM,c.BloomModel,c.BloomPreTrainedModel,c.BloomTokenizer,c.CLIPFeatureExtractor,c.CLIPImageProcessor,c.CLIPModel,c.CLIPPreTrainedModel,c.CLIPSegForImageSegmentation,c.CLIPSegModel,c.CLIPSegPreTrainedModel,c.CLIPTextModel,c.CLIPTextModelWithProjection,c.CLIPTokenizer,c.CLIPVisionModel,c.CLIPVisionModelWithProjection,c.CamembertForMaskedLM,c.CamembertForQuestionAnswering,c.CamembertForSequenceClassification,c.CamembertForTokenClassification,c.CamembertModel,c.CamembertPreTrainedModel,c.CamembertTokenizer,c.CausalLMOutput,c.CausalLMOutputWithPast,c.ChineseCLIPFeatureExtractor,c.ChineseCLIPModel,c.ChineseCLIPPreTrainedModel,c.ClapAudioModelWithProjection,c.ClapFeatureExtractor,c.ClapModel,c.ClapPreTrainedModel,c.ClapTextModelWithProjection,c.CodeGenForCausalLM,c.CodeGenModel,c.CodeGenPreTrainedModel,c.CodeGenTokenizer,c.CodeLlamaTokenizer,c.CohereForCausalLM,c.CohereModel,c.CoherePreTrainedModel,c.CohereTokenizer,c.ConvBertForMaskedLM,c.ConvBertForQuestionAnswering,c.ConvBertForSequenceClassification,c.ConvBertForTokenClassification,c.ConvBertModel,c.ConvBertPreTrainedModel,c.ConvBertTokenizer,c.ConvNextFeatureExtractor,c.ConvNextForImageClassification,c.ConvNextImageProcessor,c.ConvNextModel,c.ConvNextPreTrainedModel,c.ConvNextV2ForImageClassification,c.ConvNextV2Model,c.ConvNextV2PreTrainedModel,c.DPTFeatureExtractor,c.DPTForDepthEstimation,c.DPTImageProcessor,c.DPTModel,c.DPTPreTrainedModel,c.DebertaForMaskedLM,c.DebertaForQuestionAnswering,c.DebertaForSequenceClassification,c.DebertaForTokenClassification,c.DebertaModel,c.DebertaPreTrainedModel,c.DebertaTokenizer,c.DebertaV2ForMaskedLM,c.DebertaV2ForQuestionAnswering,c.DebertaV2ForSequenceClassification,c.DebertaV2ForTokenClassification,c.DebertaV2Model,c.DebertaV2PreTrainedModel,c.DebertaV2Tokenizer,c.DecisionTransformerModel,c.DecisionTransformerPreTrainedModel,c.DeiTFeatureExtractor,c.DeiTForImageClassification,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrModel,c.DetrObjectDetectionOutput,c.DetrPreTrainedModel,c.DetrSegmentationOutput,c.Dinov2ForImageClassification,c.Dinov2Model,c.Dinov2PreTrainedModel,c.DistilBertForMaskedLM,c.DistilBertForQuestionAnswering,c.DistilBertForSequenceClassification,c.DistilBertForTokenClassification,c.DistilBertModel,c.DistilBertPreTrainedModel,c.DistilBertTokenizer,c.DocumentQuestionAnsweringPipeline,c.DonutFeatureExtractor,c.DonutSwinModel,c.DonutSwinPreTrainedModel,c.EfficientNetForImageClassification,c.EfficientNetImageProcessor,c.EfficientNetModel,c.EfficientNetPreTrainedModel,c.ElectraForMaskedLM,c.ElectraForQuestionAnswering,c.ElectraForSequenceClassification,c.ElectraForTokenClassification,c.ElectraModel,c.ElectraPreTrainedModel,c.ElectraTokenizer,c.EosTokenCriteria,c.EsmForMaskedLM,c.EsmForSequenceClassification,c.EsmForTokenClassification,c.EsmModel,c.EsmPreTrainedModel,c.EsmTokenizer,c.FFT,c.FalconForCausalLM,c.FalconModel,c.FalconPreTrainedModel,c.FalconTokenizer,c.FastViTForImageClassification,c.FastViTModel,c.FastViTPreTrainedModel,c.FeatureExtractionPipeline,c.FeatureExtractor,c.FillMaskPipeline,c.Florence2ForConditionalGeneration,c.Florence2PreTrainedModel,c.Florence2Processor,c.GLPNFeatureExtractor,c.GLPNForDepthEstimation,c.GLPNModel,c.GLPNPreTrainedModel,c.GPT2LMHeadModel,c.GPT2Model,c.GPT2PreTrainedModel,c.GPT2Tokenizer,c.GPTBigCodeForCausalLM,c.GPTBigCodeModel,c.GPTBigCodePreTrainedModel,c.GPTJForCausalLM,c.GPTJModel,c.GPTJPreTrainedModel,c.GPTNeoForCausalLM,c.GPTNeoModel,c.GPTNeoPreTrainedModel,c.GPTNeoXForCausalLM,c.GPTNeoXModel,c.GPTNeoXPreTrainedModel,c.GPTNeoXTokenizer,c.Gemma2ForCausalLM,c.Gemma2Model,c.Gemma2PreTrainedModel,c.GemmaForCausalLM,c.GemmaModel,c.GemmaPreTrainedModel,c.GemmaTokenizer,c.Grok1Tokenizer,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline;var Cf=c.InterruptableStoppingCriteria;c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaPreTrainedModel,c.LongT5ForConditionalGeneration,c.LongT5Model,c.LongT5PreTrainedModel,c.M2M100ForConditionalGeneration,c.M2M100Model,c.M2M100PreTrainedModel,c.M2M100Tokenizer,c.MBart50Tokenizer,c.MBartForCausalLM,c.MBartForConditionalGeneration,c.MBartForSequenceClassification,c.MBartModel,c.MBartPreTrainedModel,c.MBartTokenizer,c.MPNetForMaskedLM,c.MPNetForQuestionAnswering,c.MPNetForSequenceClassification,c.MPNetForTokenClassification,c.MPNetModel,c.MPNetPreTrainedModel,c.MPNetTokenizer,c.MT5ForConditionalGeneration,c.MT5Model,c.MT5PreTrainedModel,c.MarianMTModel,c.MarianModel,c.MarianPreTrainedModel,c.MarianTokenizer,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4Model,c.MobileNetV4PreTrainedModel,c.MobileViTFeatureExtractor,c.MobileViTForImageClassification,c.MobileViTImageProcessor,c.MobileViTModel,c.MobileViTPreTrainedModel,c.MobileViTV2ForImageClassification,c.MobileViTV2Model,c.MobileViTV2PreTrainedModel,c.ModelOutput,c.Moondream1ForConditionalGeneration,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.PhiForCausalLM,c.PhiModel,c.PhiPreTrainedModel,c.Pipeline,c.PreTrainedModel,c.PreTrainedTokenizer,c.PretrainedConfig,c.PretrainedMixin,c.Processor,c.PvtForImageClassification,c.PvtImageProcessor,c.PvtModel,c.PvtPreTrainedModel,c.PyAnnoteFeatureExtractor,c.PyAnnoteForAudioFrameClassification,c.PyAnnoteModel,c.PyAnnotePreTrainedModel,c.PyAnnoteProcessor,c.QuestionAnsweringModelOutput,c.QuestionAnsweringPipeline,c.Qwen2ForCausalLM,c.Qwen2Model,c.Qwen2PreTrainedModel,c.Qwen2Tokenizer,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel,c.RawImage,c.ResNetForImageClassification,c.ResNetModel,c.ResNetPreTrainedModel,c.RoFormerForMaskedLM,c.RoFormerForQuestionAnswering,c.RoFormerForSequenceClassification,c.RoFormerForTokenClassification,c.RoFormerModel,c.RoFormerPreTrainedModel,c.RoFormerTokenizer,c.RobertaForMaskedLM,c.RobertaForQuestionAnswering,c.RobertaForSequenceClassification,c.RobertaForTokenClassification,c.RobertaModel,c.RobertaPreTrainedModel,c.RobertaTokenizer,c.SamImageProcessor,c.SamImageSegmentationOutput,c.SamModel,c.SamPreTrainedModel,c.SamProcessor,c.SapiensFeatureExtractor,c.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerModel,c.SegformerPreTrainedModel,c.Seq2SeqLMOutput,c.SequenceClassifierOutput,c.SiglipImageProcessor,c.SiglipModel,c.SiglipPreTrainedModel,c.SiglipTextModel,c.SiglipTokenizer,c.SiglipVisionModel,c.SpeechT5FeatureExtractor,c.SpeechT5ForSpeechToText,c.SpeechT5ForTextToSpeech,c.SpeechT5HifiGan,c.SpeechT5Model,c.SpeechT5PreTrainedModel,c.SpeechT5Processor,c.SpeechT5Tokenizer,c.SqueezeBertForMaskedLM,c.SqueezeBertForQuestionAnswering,c.SqueezeBertForSequenceClassification,c.SqueezeBertModel,c.SqueezeBertPreTrainedModel,c.SqueezeBertTokenizer,c.StableLmForCausalLM,c.StableLmModel,c.StableLmPreTrainedModel,c.Starcoder2ForCausalLM,c.Starcoder2Model,c.Starcoder2PreTrainedModel,c.StoppingCriteria,c.StoppingCriteriaList,c.SummarizationPipeline,c.Swin2SRForImageSuperResolution,c.Swin2SRImageProcessor,c.Swin2SRModel,c.Swin2SRPreTrainedModel,c.SwinForImageClassification,c.SwinModel,c.SwinPreTrainedModel,c.T5ForConditionalGeneration,c.T5Model,c.T5PreTrainedModel,c.T5Tokenizer,c.TableTransformerForObjectDetection,c.TableTransformerModel,c.TableTransformerObjectDetectionOutput,c.TableTransformerPreTrainedModel,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline;var Ef=c.TextStreamer;c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TrOCRForCausalLM,c.TrOCRPreTrainedModel,c.TranslationPipeline,c.UniSpeechForCTC,c.UniSpeechForSequenceClassification,c.UniSpeechModel,c.UniSpeechPreTrainedModel,c.UniSpeechSatForAudioFrameClassification,c.UniSpeechSatForCTC,c.UniSpeechSatForSequenceClassification,c.UniSpeechSatModel,c.UniSpeechSatPreTrainedModel,c.ViTFeatureExtractor,c.ViTForImageClassification,c.ViTImageProcessor,c.ViTMAEModel,c.ViTMAEPreTrainedModel,c.ViTMSNForImageClassification,c.ViTMSNModel,c.ViTMSNPreTrainedModel,c.ViTModel,c.ViTPreTrainedModel,c.VisionEncoderDecoderModel,c.VitMatteForImageMatting,c.VitMatteImageProcessor,c.VitMattePreTrainedModel,c.VitsModel,c.VitsModelOutput,c.VitsPreTrainedModel,c.VitsTokenizer,c.Wav2Vec2BertForCTC,c.Wav2Vec2BertForSequenceClassification,c.Wav2Vec2BertModel,c.Wav2Vec2BertPreTrainedModel,c.Wav2Vec2CTCTokenizer,c.Wav2Vec2FeatureExtractor,c.Wav2Vec2ForAudioFrameClassification,c.Wav2Vec2ForCTC,c.Wav2Vec2ForSequenceClassification,c.Wav2Vec2Model,c.Wav2Vec2PreTrainedModel,c.Wav2Vec2ProcessorWithLM,c.WavLMForAudioFrameClassification,c.WavLMForCTC,c.WavLMForSequenceClassification,c.WavLMForXVector,c.WavLMModel,c.WavLMPreTrainedModel,c.WeSpeakerFeatureExtractor,c.WeSpeakerResNetModel,c.WeSpeakerResNetPreTrainedModel,c.WhisperFeatureExtractor,c.WhisperForConditionalGeneration,c.WhisperModel,c.WhisperPreTrainedModel,c.WhisperProcessor,c.WhisperTextStreamer,c.WhisperTokenizer,c.XLMForQuestionAnswering,c.XLMForSequenceClassification,c.XLMForTokenClassification,c.XLMModel,c.XLMPreTrainedModel,c.XLMRobertaForMaskedLM,c.XLMRobertaForQuestionAnswering,c.XLMRobertaForSequenceClassification,c.XLMRobertaForTokenClassification,c.XLMRobertaModel,c.XLMRobertaPreTrainedModel,c.XLMRobertaTokenizer,c.XLMTokenizer,c.XLMWithLMHeadModel,c.XVectorOutput,c.YolosFeatureExtractor,c.YolosForObjectDetection,c.YolosModel,c.YolosObjectDetectionOutput,c.YolosPreTrainedModel,c.ZeroShotAudioClassificationPipeline,c.ZeroShotClassificationPipeline,c.ZeroShotImageClassificationPipeline,c.ZeroShotObjectDetectionPipeline,c.bankers_round,c.cat,c.cos_sim,c.dot,c.dynamic_time_warping,c.env,c.full,c.full_like,c.getKeyValueShapes,c.hamming,c.hanning,c.interpolate,c.interpolate_4d,c.interpolate_data,c.is_chinese_char,c.layer_norm,c.log_softmax,c.magnitude,c.matmul,c.max,c.mean,c.mean_pooling,c.medianFilter,c.mel_filter_bank,c.min,c.ones,c.ones_like,c.permute,c.permute_data,c.pipeline,c.quantize_embeddings,c.read_audio,c.rfft,c.round,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;class gc{static async getInstance(Se=null){return this.tokenizer??(this.tokenizer=Sf.from_pretrained(this.model_id,{progress_callback:Se})),this.model??(this.model=Tf.from_pretrained(this.model_id,{dtype:"q4",device:"webgpu",progress_callback:Se})),Promise.all([this.tokenizer,this.model])}}xe(gc,"model_id","onnx-community/Llama-3.2-1B-Instruct");const hd=new Cf;let wc=null;async function $f(Et){const[Se,N]=await gc.getInstance(),O=Se.apply_chat_template(Et,{add_generation_prompt:!0,return_dict:!0});let fe,ye=0,Te;const Ce=()=>{fe??(fe=performance.now()),ye++>0&&(Te=ye/(performance.now()-fe)*1e3)},j=ne=>{self.postMessage({status:"update",output:ne,tps:Te,numTokens:ye})},$=new Ef(Se,{skip_prompt:!0,skip_special_tokens:!0,callback_function:j,token_callback_function:Ce});self.postMessage({status:"start"});const{past_key_values:V,sequences:A}=await N.generate({...O,past_key_values:wc,max_new_tokens:1024,streamer:$,stopping_criteria:hd,return_dict_in_generate:!0});wc=V;const ee=Se.batch_decode(A,{skip_special_tokens:!0});self.postMessage({status:"complete",output:ee})}async function kf(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(Et){self.postMessage({status:"error",data:Et.toString()})}}async function Pf(){self.postMessage({status:"loading",data:"Loading model..."});const[Et,Se]=await gc.getInstance(O=>{self.postMessage(O)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const N=Et("a");await Se.generate({...N,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async Et=>{const{type:Se,data:N}=Et.data;switch(Se){case"check":kf();break;case"load":Pf();break;case"generate":hd.reset(),$f(N);break;case"interrupt":hd.interrupt();break;case"reset":wc=null,hd.reset();break}})})();