var p_=Object.defineProperty;var h_=(Cn,rs,Qs)=>rs in Cn?p_(Cn,rs,{enumerable:!0,configurable:!0,writable:!0,value:Qs}):Cn[rs]=Qs;var ve=(Cn,rs,Qs)=>h_(Cn,typeof rs!="symbol"?rs+"":rs,Qs);(function(){"use strict";var Cn={},rs={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Dt,Ee,V)=>{Dt.exports=V.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{Environment:()=>Ve,Interpreter:()=>ut,Template:()=>xt,parse:()=>xe,tokenize:()=>B});var F=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"}),ce=Object.freeze({set:F.Set,for:F.For,in:F.In,is:F.Is,if:F.If,else:F.Else,endif:F.EndIf,elif:F.ElseIf,endfor:F.EndFor,and:F.And,or:F.Or,not:F.Not,"not in":F.NotIn,macro:F.Macro,endmacro:F.EndMacro,true:F.BooleanLiteral,false:F.BooleanLiteral,True:F.BooleanLiteral,False:F.BooleanLiteral}),we=class{constructor(v,H){this.value=v,this.type=H}};function ye(v){return/\w/.test(v)}function Te(v){return/[0-9]/.test(v)}var L=[["{%",F.OpenStatement],["%}",F.CloseStatement],["{{",F.OpenExpression],["}}",F.CloseExpression],["(",F.OpenParen],[")",F.CloseParen],["{",F.OpenCurlyBracket],["}",F.CloseCurlyBracket],["[",F.OpenSquareBracket],["]",F.CloseSquareBracket],[",",F.Comma],[".",F.Dot],[":",F.Colon],["|",F.Pipe],["<=",F.ComparisonBinaryOperator],[">=",F.ComparisonBinaryOperator],["==",F.ComparisonBinaryOperator],["!=",F.ComparisonBinaryOperator],["<",F.ComparisonBinaryOperator],[">",F.ComparisonBinaryOperator],["+",F.AdditiveBinaryOperator],["-",F.AdditiveBinaryOperator],["*",F.MultiplicativeBinaryOperator],["/",F.MultiplicativeBinaryOperator],["%",F.MultiplicativeBinaryOperator],["=",F.Equals]],P=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function D(v,H={}){return v.endsWith(` `)&&(v=v.slice(0,-1)),v=v.replace(/{#.*?#}/gs,"{##}"),H.lstrip_blocks&&(v=v.replace(/^[ \t]*({[#%])/gm,"$1")),H.trim_blocks&&(v=v.replace(/([#%]})\n/g,"$1")),v.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function B(v,H={}){var Je,Nt,yt;const $=[],Y=D(v,H);let he=0;const nt=bt=>{let zt="";for(;bt(Y[he]);){if(Y[he]==="\\"){if(++he,he>=Y.length)throw new SyntaxError("Unexpected end of input");const Pt=Y[he++],dr=P.get(Pt);if(dr===void 0)throw new SyntaxError(`Unexpected escaped character: ${Pt}`);zt+=dr;continue}if(zt+=Y[he++],he>=Y.length)throw new SyntaxError("Unexpected end of input")}return zt};e:for(;he0){$.push(new we(Pt,F.Text));continue}}nt(Pt=>/\s/.test(Pt));const zt=Y[he];if(zt==="-"||zt==="+"){const Pt=(Nt=$.at(-1))==null?void 0:Nt.type;if(Pt===F.Text||Pt===void 0)throw new SyntaxError(`Unexpected character: ${zt}`);switch(Pt){case F.Identifier:case F.NumericLiteral:case F.BooleanLiteral:case F.StringLiteral:case F.CloseParen:case F.CloseSquareBracket:break;default:{++he;const dr=nt(Te);$.push(new we(`${zt}${dr}`,dr.length>0?F.NumericLiteral:F.UnaryOperator));continue}}}for(const[Pt,dr]of L)if(Y.slice(he,he+Pt.length)===Pt){$.push(new we(Pt,dr)),he+=Pt.length;continue e}if(zt==="'"||zt==='"'){++he;const Pt=nt(dr=>dr!==zt);$.push(new we(Pt,F.StringLiteral)),++he;continue}if(Te(zt)){const Pt=nt(Te);$.push(new we(Pt,F.NumericLiteral));continue}if(ye(zt)){const Pt=nt(ye),dr=Object.hasOwn(ce,Pt)?ce[Pt]:F.Identifier;dr===F.In&&((yt=$.at(-1))==null?void 0:yt.type)===F.Not?($.pop(),$.push(new we("not in",F.NotIn))):$.push(new we(Pt,dr));continue}throw new SyntaxError(`Unexpected character: ${zt}`)}return $}var q=class{constructor(){ve(this,"type","Statement")}},re=class extends q{constructor(H){super();ve(this,"type","Program");this.body=H}},fe=class extends q{constructor(H,$,Y){super();ve(this,"type","If");this.test=H,this.body=$,this.alternate=Y}},le=class extends q{constructor(H,$,Y,he){super();ve(this,"type","For");this.loopvar=H,this.iterable=$,this.body=Y,this.defaultBlock=he}},O=class extends q{constructor(H,$){super();ve(this,"type","Set");this.assignee=H,this.value=$}},J=class extends q{constructor(H,$,Y){super();ve(this,"type","Macro");this.name=H,this.args=$,this.body=Y}},pe=class extends q{constructor(){super(...arguments);ve(this,"type","Expression")}},X=class extends pe{constructor(H,$,Y){super();ve(this,"type","MemberExpression");this.object=H,this.property=$,this.computed=Y}},K=class extends pe{constructor(H,$){super();ve(this,"type","CallExpression");this.callee=H,this.args=$}},j=class extends pe{constructor(H){super();ve(this,"type","Identifier");this.value=H}},k=class extends pe{constructor(H){super();ve(this,"type","Literal");this.value=H}},N=class extends k{constructor(){super(...arguments);ve(this,"type","NumericLiteral")}},E=class extends k{constructor(){super(...arguments);ve(this,"type","StringLiteral")}},ue=class extends k{constructor(){super(...arguments);ve(this,"type","BooleanLiteral")}},be=class extends k{constructor(){super(...arguments);ve(this,"type","ArrayLiteral")}},Ce=class extends k{constructor(){super(...arguments);ve(this,"type","TupleLiteral")}},De=class extends k{constructor(){super(...arguments);ve(this,"type","ObjectLiteral")}},ze=class extends pe{constructor(H,$,Y){super();ve(this,"type","BinaryExpression");this.operator=H,this.left=$,this.right=Y}},it=class extends pe{constructor(H,$){super();ve(this,"type","FilterExpression");this.operand=H,this.filter=$}},rt=class extends pe{constructor(H,$){super();ve(this,"type","SelectExpression");this.iterable=H,this.test=$}},lt=class extends pe{constructor(H,$,Y){super();ve(this,"type","TestExpression");this.operand=H,this.negate=$,this.test=Y}},me=class extends pe{constructor(H,$){super();ve(this,"type","UnaryExpression");this.operator=H,this.argument=$}},W=class extends pe{constructor(H=void 0,$=void 0,Y=void 0){super();ve(this,"type","SliceExpression");this.start=H,this.stop=$,this.step=Y}},de=class extends pe{constructor(H,$){super();ve(this,"type","KeywordArgumentExpression");this.key=H,this.value=$}};function xe(v){const H=new re([]);let $=0;function Y(Fe,Oe){const ct=v[$++];if(!ct||ct.type!==Fe)throw new Error(`Parser Error: ${Oe}. ${ct.type} !== ${Fe}.`);return ct}function he(){switch(v[$].type){case F.Text:return Nt();case F.OpenStatement:return yt();case F.OpenExpression:return bt();default:throw new SyntaxError(`Unexpected token type: ${v[$].type}`)}}function nt(...Fe){return $+Fe.length<=v.length&&Fe.some((Oe,ct)=>Oe!==v[$+ct].type)}function Je(...Fe){return $+Fe.length<=v.length&&Fe.every((Oe,ct)=>Oe===v[$+ct].type)}function Nt(){return new E(Y(F.Text,"Expected text token").value)}function yt(){Y(F.OpenStatement,"Expected opening statement token");let Fe;switch(v[$].type){case F.Set:++$,Fe=zt(),Y(F.CloseStatement,"Expected closing statement token");break;case F.If:++$,Fe=Pt(),Y(F.OpenStatement,"Expected {% token"),Y(F.EndIf,"Expected endif token"),Y(F.CloseStatement,"Expected %} token");break;case F.Macro:++$,Fe=dr(),Y(F.OpenStatement,"Expected {% token"),Y(F.EndMacro,"Expected endmacro token"),Y(F.CloseStatement,"Expected %} token");break;case F.For:++$,Fe=Yr(),Y(F.OpenStatement,"Expected {% token"),Y(F.EndFor,"Expected endfor token"),Y(F.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${v[$].type}`)}return Fe}function bt(){Y(F.OpenExpression,"Expected opening expression token");const Fe=Rr();return Y(F.CloseExpression,"Expected closing expression token"),Fe}function zt(){const Fe=Rr();if(Je(F.Equals)){++$;const Oe=zt();return new O(Fe,Oe)}return Fe}function Pt(){var Ut,sr,br,Nr,mr,kr,gr,$n;const Fe=Rr();Y(F.CloseStatement,"Expected closing statement token");const Oe=[],ct=[];for(;!(((Ut=v[$])==null?void 0:Ut.type)===F.OpenStatement&&(((sr=v[$+1])==null?void 0:sr.type)===F.ElseIf||((br=v[$+1])==null?void 0:br.type)===F.Else||((Nr=v[$+1])==null?void 0:Nr.type)===F.EndIf));)Oe.push(he());if(((mr=v[$])==null?void 0:mr.type)===F.OpenStatement&&((kr=v[$+1])==null?void 0:kr.type)!==F.EndIf)if(++$,Je(F.ElseIf))Y(F.ElseIf,"Expected elseif token"),ct.push(Pt());else for(Y(F.Else,"Expected else token"),Y(F.CloseStatement,"Expected closing statement token");!(((gr=v[$])==null?void 0:gr.type)===F.OpenStatement&&(($n=v[$+1])==null?void 0:$n.type)===F.EndIf);)ct.push(he());return new fe(Fe,Oe,ct)}function dr(){const Fe=Ft();if(Fe.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Oe=tt();Y(F.CloseStatement,"Expected closing statement token");const ct=[];for(;nt(F.OpenStatement,F.EndMacro);)ct.push(he());return new J(Fe,Oe,ct)}function Cr(Fe=!1){const Oe=Fe?Ft:Rr,ct=[Oe()],Ut=Je(F.Comma);for(;Ut&&(++$,ct.push(Oe()),!!Je(F.Comma)););return Ut?new Ce(ct):ct[0]}function Yr(){const Fe=Cr(!0);if(!(Fe instanceof j||Fe instanceof Ce))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Fe.type} instead`);Y(F.In,"Expected `in` keyword following loop variable");const Oe=Rr();Y(F.CloseStatement,"Expected closing statement token");const ct=[];for(;nt(F.OpenStatement,F.EndFor)&&nt(F.OpenStatement,F.Else);)ct.push(he());const Ut=[];if(Je(F.OpenStatement,F.Else))for(++$,++$,Y(F.CloseStatement,"Expected closing statement token");nt(F.OpenStatement,F.EndFor);)Ut.push(he());return new le(Fe,Oe,ct,Ut)}function Rr(){return Jr()}function Jr(){const Fe=bn();if(Je(F.If)){++$;const Oe=bn();if(Je(F.Else)){++$;const ct=bn();return new fe(Oe,[Fe],[ct])}else return new rt(Fe,Oe)}return Fe}function bn(){let Fe=at();for(;Je(F.Or);){const Oe=v[$];++$;const ct=at();Fe=new ze(Oe,Fe,ct)}return Fe}function at(){let Fe=G();for(;Je(F.And);){const Oe=v[$];++$;const ct=G();Fe=new ze(Oe,Fe,ct)}return Fe}function G(){let Fe;for(;Je(F.Not);){const Oe=v[$];++$;const ct=G();Fe=new me(Oe,ct)}return Fe??ge()}function ge(){let Fe=Ie();for(;Je(F.ComparisonBinaryOperator)||Je(F.In)||Je(F.NotIn);){const Oe=v[$];++$;const ct=Ie();Fe=new ze(Oe,Fe,ct)}return Fe}function Ie(){let Fe=ft();for(;Je(F.AdditiveBinaryOperator);){const Oe=v[$];++$;const ct=ft();Fe=new ze(Oe,Fe,ct)}return Fe}function Se(){const Fe=Ct();return Je(F.OpenParen)?Ne(Fe):Fe}function Ne(Fe){let Oe=new K(Fe,tt());return Je(F.OpenParen)&&(Oe=Ne(Oe)),Oe}function tt(){Y(F.OpenParen,"Expected opening parenthesis for arguments list");const Fe=wt();return Y(F.CloseParen,"Expected closing parenthesis for arguments list"),Fe}function wt(){const Fe=[];for(;!Je(F.CloseParen);){let Oe=Rr();if(Je(F.Equals)){if(++$,!(Oe instanceof j))throw new SyntaxError("Expected identifier for keyword argument");const ct=Rr();Oe=new de(Oe,ct)}Fe.push(Oe),Je(F.Comma)&&++$}return Fe}function mt(){const Fe=[];let Oe=!1;for(;!Je(F.CloseSquareBracket);)Je(F.Colon)?(Fe.push(void 0),++$,Oe=!0):(Fe.push(Rr()),Je(F.Colon)&&(++$,Oe=!0));if(Fe.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Oe){if(Fe.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new W(...Fe)}return Fe[0]}function Ct(){let Fe=Ft();for(;Je(F.Dot)||Je(F.OpenSquareBracket);){const Oe=v[$];++$;let ct;const Ut=Oe.type!==F.Dot;if(Ut)ct=mt(),Y(F.CloseSquareBracket,"Expected closing square bracket");else if(ct=Ft(),ct.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Fe=new X(Fe,ct,Ut)}return Fe}function ft(){let Fe=Lt();for(;Je(F.MultiplicativeBinaryOperator);){const Oe=v[$];++$;const ct=Lt();Fe=new ze(Oe,Fe,ct)}return Fe}function Lt(){let Fe=jt();for(;Je(F.Is);){++$;const Oe=Je(F.Not);Oe&&++$;let ct=Ft();if(ct instanceof ue&&(ct=new j(ct.value.toString())),!(ct instanceof j))throw new SyntaxError("Expected identifier for the test");Fe=new lt(Fe,Oe,ct)}return Fe}function jt(){let Fe=Se();for(;Je(F.Pipe);){++$;let Oe=Ft();if(!(Oe instanceof j))throw new SyntaxError("Expected identifier for the filter");Je(F.OpenParen)&&(Oe=Ne(Oe)),Fe=new it(Fe,Oe)}return Fe}function Ft(){const Fe=v[$];switch(Fe.type){case F.NumericLiteral:return++$,new N(Number(Fe.value));case F.StringLiteral:return++$,new E(Fe.value);case F.BooleanLiteral:return++$,new ue(Fe.value.toLowerCase()==="true");case F.Identifier:return++$,new j(Fe.value);case F.OpenParen:{++$;const Oe=Cr();if(v[$].type!==F.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${v[$].type} instead`);return++$,Oe}case F.OpenSquareBracket:{++$;const Oe=[];for(;!Je(F.CloseSquareBracket);)Oe.push(Rr()),Je(F.Comma)&&++$;return++$,new be(Oe)}case F.OpenCurlyBracket:{++$;const Oe=new Map;for(;!Je(F.CloseCurlyBracket);){const ct=Rr();Y(F.Colon,"Expected colon between key and value in object literal");const Ut=Rr();Oe.set(ct,Ut),Je(F.Comma)&&++$}return++$,new De(Oe)}default:throw new SyntaxError(`Unexpected token: ${Fe.type}`)}}for(;$=0?(H=(H??(H=0))<0?Math.max(v.length+H,0):Math.min(H,v.length),$=($??($=v.length))<0?Math.max(v.length+$,0):Math.min($,v.length)):(H=(H??(H=v.length-1))<0?Math.max(v.length+H,-1):Math.min(H,v.length-1),$=($??($=-1))<-1?Math.max(v.length+$,-1):Math.min($,v.length-1));const nt=[];for(let Je=H;he*JeH.toUpperCase())}var Ze=class{constructor(v=void 0){ve(this,"type","RuntimeValue");ve(this,"value");ve(this,"builtins",new Map);this.value=v}__bool__(){return new ht(!!this.value)}},dt=class extends Ze{constructor(){super(...arguments);ve(this,"type","NumericValue")}},Re=class extends Ze{constructor(){super(...arguments);ve(this,"type","StringValue");ve(this,"builtins",new Map([["upper",new Ke(()=>new Re(this.value.toUpperCase()))],["lower",new Ke(()=>new Re(this.value.toLowerCase()))],["strip",new Ke(()=>new Re(this.value.trim()))],["title",new Ke(()=>new Re(se(this.value)))],["length",new dt(this.value.length)]]))}},ht=class extends Ze{constructor(){super(...arguments);ve(this,"type","BooleanValue")}},Mt=class extends Ze{constructor(){super(...arguments);ve(this,"type","ObjectValue");ve(this,"builtins",new Map([["get",new Ke(([H,$])=>{if(!(H instanceof Re))throw new Error(`Object key must be a string: got ${H.type}`);return this.value.get(H.value)??$??new et})],["items",new Ke(()=>new Z(Array.from(this.value.entries()).map(([H,$])=>new Z([new Re(H),$]))))]]))}__bool__(){return new ht(this.value.size>0)}},Xe=class extends Mt{constructor(){super(...arguments);ve(this,"type","KeywordArgumentsValue")}},Z=class extends Ze{constructor(){super(...arguments);ve(this,"type","ArrayValue");ve(this,"builtins",new Map([["length",new dt(this.value.length)]]))}__bool__(){return new ht(this.value.length>0)}},Ae=class extends Z{constructor(){super(...arguments);ve(this,"type","TupleValue")}},Ke=class extends Ze{constructor(){super(...arguments);ve(this,"type","FunctionValue")}},et=class extends Ze{constructor(){super(...arguments);ve(this,"type","NullValue")}},je=class extends Ze{constructor(){super(...arguments);ve(this,"type","UndefinedValue")}},Ve=class{constructor(v){ve(this,"variables",new Map([["namespace",new Ke(v=>{if(v.length===0)return new Mt(new Map);if(v.length!==1||!(v[0]instanceof Mt))throw new Error("`namespace` expects either zero arguments or a single object argument");return v[0]})]]));ve(this,"tests",new Map([["boolean",v=>v.type==="BooleanValue"],["callable",v=>v instanceof Ke],["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 Z||v instanceof Re],["lower",v=>{const H=v.value;return v.type==="StringValue"&&H===H.toLowerCase()}],["upper",v=>{const H=v.value;return v.type==="StringValue"&&H===H.toUpperCase()}],["none",v=>v.type==="NullValue"],["defined",v=>v.type!=="UndefinedValue"],["undefined",v=>v.type==="UndefinedValue"],["equalto",(v,H)=>v.value===H.value],["eq",(v,H)=>v.value===H.value]]));this.parent=v}set(v,H){return this.declareVariable(v,_t(H))}declareVariable(v,H){if(this.variables.has(v))throw new SyntaxError(`Variable already declared: ${v}`);return this.variables.set(v,H),H}setVariable(v,H){return this.variables.set(v,H),H}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 je}catch{return new je}}},ut=class{constructor(v){ve(this,"global");this.global=v??new Ve}run(v){return this.evaluate(v,this.global)}evaluateBinaryExpression(v,H){const $=this.evaluate(v.left,H);switch(v.operator.value){case"and":return $.__bool__().value?this.evaluate(v.right,H):$;case"or":return $.__bool__().value?$:this.evaluate(v.right,H)}const Y=this.evaluate(v.right,H);switch(v.operator.value){case"==":return new ht($.value==Y.value);case"!=":return new ht($.value!=Y.value)}if($ instanceof je||Y instanceof je)throw new Error("Cannot perform operation on undefined values");if($ instanceof et||Y instanceof et)throw new Error("Cannot perform operation on null values");if($ instanceof dt&&Y instanceof dt)switch(v.operator.value){case"+":return new dt($.value+Y.value);case"-":return new dt($.value-Y.value);case"*":return new dt($.value*Y.value);case"/":return new dt($.value/Y.value);case"%":return new dt($.value%Y.value);case"<":return new ht($.value":return new ht($.value>Y.value);case">=":return new ht($.value>=Y.value);case"<=":return new ht($.value<=Y.value)}else if($ instanceof Z&&Y instanceof Z)switch(v.operator.value){case"+":return new Z($.value.concat(Y.value))}else if(Y instanceof Z){const he=Y.value.find(nt=>nt.value===$.value)!==void 0;switch(v.operator.value){case"in":return new ht(he);case"not in":return new ht(!he)}}if($ instanceof Re||Y instanceof Re)switch(v.operator.value){case"+":return new Re($.value.toString()+Y.value.toString())}if($ instanceof Re&&Y instanceof Re)switch(v.operator.value){case"in":return new ht(Y.value.includes($.value));case"not in":return new ht(!Y.value.includes($.value))}if($ instanceof Re&&Y instanceof Mt)switch(v.operator.value){case"in":return new ht(Y.value.has($.value));case"not in":return new ht(!Y.value.has($.value))}throw new SyntaxError(`Unknown operator "${v.operator.value}" between ${$.type} and ${Y.type}`)}evaluateArguments(v,H){const $=[],Y=new Map;for(const he of v)if(he.type==="KeywordArgumentExpression"){const nt=he;Y.set(nt.key.value,this.evaluate(nt.value,H))}else{if(Y.size>0)throw new Error("Positional arguments must come before keyword arguments");$.push(this.evaluate(he,H))}return[$,Y]}evaluateFilterExpression(v,H){const $=this.evaluate(v.operand,H);if(v.filter.type==="Identifier"){const Y=v.filter;if(Y.value==="tojson")return new Re(St($));if($ instanceof Z)switch(Y.value){case"list":return $;case"first":return $.value[0];case"last":return $.value[$.value.length-1];case"length":return new dt($.value.length);case"reverse":return new Z($.value.reverse());case"sort":return new Z($.value.sort((he,nt)=>{if(he.type!==nt.type)throw new Error(`Cannot compare different types: ${he.type} and ${nt.type}`);switch(he.type){case"NumericValue":return he.value-nt.value;case"StringValue":return he.value.localeCompare(nt.value);default:throw new Error(`Cannot compare type: ${he.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Y.value}`)}else if($ instanceof Re)switch(Y.value){case"length":return new dt($.value.length);case"upper":return new Re($.value.toUpperCase());case"lower":return new Re($.value.toLowerCase());case"title":return new Re(se($.value));case"capitalize":return new Re($.value.charAt(0).toUpperCase()+$.value.slice(1));case"trim":return new Re($.value.trim());case"indent":return new Re($.value.split(` `).map((he,nt)=>nt===0||he.length===0?he:" "+he).join(` `));case"string":return $;default:throw new Error(`Unknown StringValue filter: ${Y.value}`)}else if($ instanceof dt)switch(Y.value){case"abs":return new dt(Math.abs($.value));default:throw new Error(`Unknown NumericValue filter: ${Y.value}`)}else if($ instanceof Mt)switch(Y.value){case"items":return new Z(Array.from($.value.entries()).map(([he,nt])=>new Z([new Re(he),nt])));case"length":return new dt($.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Y.value}`)}throw new Error(`Cannot apply filter "${Y.value}" to type: ${$.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[,nt]=this.evaluateArguments(Y.args,H),Je=nt.get("indent")??new et;if(!(Je instanceof dt||Je instanceof et))throw new Error("If set, indent must be a number");return new Re(St($,Je.value))}if($ instanceof Z){switch(he){case"selectattr":{if($.value.some(zt=>!(zt instanceof Mt)))throw new Error("`selectattr` can only be applied to array of objects");if(Y.args.some(zt=>zt.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[nt,Je,Nt]=Y.args.map(zt=>this.evaluate(zt,H));let yt;if(Je){const zt=H.tests.get(Je.value);if(!zt)throw new Error(`Unknown test: ${Je.value}`);yt=zt}else yt=(...zt)=>zt[0].__bool__().value;const bt=$.value.filter(zt=>{const Pt=zt.value.get(nt.value);return Pt?yt(Pt,Nt):!1});return new Z(bt)}case"map":{const[,nt]=this.evaluateArguments(Y.args,H);if(nt.has("attribute")){const Je=nt.get("attribute");if(!(Je instanceof Re))throw new Error("attribute must be a string");const Nt=nt.get("default"),yt=$.value.map(bt=>{if(!(bt instanceof Mt))throw new Error("items in map must be an object");return bt.value.get(Je.value)??Nt??new je});return new Z(yt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${he}`)}else if($ instanceof Re){switch(he){case"indent":{const[nt,Je]=this.evaluateArguments(Y.args,H),Nt=nt.at(0)??Je.get("width")??new dt(4);if(!(Nt instanceof dt))throw new Error("width must be a number");const yt=nt.at(1)??Je.get("first")??new ht(!1),bt=nt.at(2)??Je.get("blank")??new ht(!1),zt=$.value.split(` `),Pt=" ".repeat(Nt.value),dr=zt.map((Cr,Yr)=>!yt.value&&Yr===0||!bt.value&&Cr.length===0?Cr:Pt+Cr);return new Re(dr.join(` `))}}throw new Error(`Unknown StringValue filter: ${he}`)}else throw new Error(`Cannot apply filter "${he}" to type: ${$.type}`)}throw new Error(`Unknown filter: ${v.filter.type}`)}evaluateTestExpression(v,H){const $=this.evaluate(v.operand,H),Y=H.tests.get(v.test.value);if(!Y)throw new Error(`Unknown test: ${v.test.value}`);const he=Y($);return new ht(v.negate?!he:he)}evaluateUnaryExpression(v,H){const $=this.evaluate(v.argument,H);switch(v.operator.value){case"not":return new ht(!$.value);default:throw new SyntaxError(`Unknown operator: ${v.operator.value}`)}}evalProgram(v,H){return this.evaluateBlock(v.body,H)}evaluateBlock(v,H){let $="";for(const Y of v){const he=this.evaluate(Y,H);he.type!=="NullValue"&&he.type!=="UndefinedValue"&&($+=he.value)}return new Re($)}evaluateIdentifier(v,H){return H.lookupVariable(v.value)}evaluateCallExpression(v,H){const[$,Y]=this.evaluateArguments(v.args,H);Y.size>0&&$.push(new Xe(Y));const he=this.evaluate(v.callee,H);if(he.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${he.type}`);return he.value($,H)}evaluateSliceExpression(v,H,$){if(!(v instanceof Z||v instanceof Re))throw new Error("Slice object must be an array or string");const Y=this.evaluate(H.start,$),he=this.evaluate(H.stop,$),nt=this.evaluate(H.step,$);if(!(Y instanceof dt||Y instanceof je))throw new Error("Slice start must be numeric or undefined");if(!(he instanceof dt||he instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(nt instanceof dt||nt instanceof je))throw new Error("Slice step must be numeric or undefined");return v instanceof Z?new Z(ot(v.value,Y.value,he.value,nt.value)):new Re(ot(Array.from(v.value),Y.value,he.value,nt.value).join(""))}evaluateMemberExpression(v,H){const $=this.evaluate(v.object,H);let Y;if(v.computed){if(v.property.type==="SliceExpression")return this.evaluateSliceExpression($,v.property,H);Y=this.evaluate(v.property,H)}else Y=new Re(v.property.value);let he;if($ instanceof Mt){if(!(Y instanceof Re))throw new Error(`Cannot access property with non-string: got ${Y.type}`);he=$.value.get(Y.value)??$.builtins.get(Y.value)}else if($ instanceof Z||$ instanceof Re)if(Y instanceof dt)he=$.value.at(Y.value),$ instanceof Re&&(he=new Re($.value.at(Y.value)));else if(Y instanceof Re)he=$.builtins.get(Y.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Y.type}`);else{if(!(Y instanceof Re))throw new Error(`Cannot access property with non-string: got ${Y.type}`);he=$.builtins.get(Y.value)}return he instanceof Ze?he:new je}evaluateSet(v,H){const $=this.evaluate(v.value,H);if(v.assignee.type==="Identifier"){const Y=v.assignee.value;H.setVariable(Y,$)}else if(v.assignee.type==="MemberExpression"){const Y=v.assignee,he=this.evaluate(Y.object,H);if(!(he instanceof Mt))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,$)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(v.assignee)}`);return new et}evaluateIf(v,H){const $=this.evaluate(v.test,H);return this.evaluateBlock($.__bool__().value?v.body:v.alternate,H)}evaluateFor(v,H){const $=new Ve(H);let Y,he;if(v.iterable.type==="SelectExpression"){const bt=v.iterable;he=this.evaluate(bt.iterable,$),Y=bt.test}else he=this.evaluate(v.iterable,$);if(!(he instanceof Z))throw new Error(`Expected iterable type in for loop: got ${he.type}`);const nt=[],Je=[];for(let bt=0;btCr.setVariable(v.loopvar.value,Pt);else if(v.loopvar.type==="TupleLiteral"){const Cr=v.loopvar;if(Pt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Pt.type}`);const Yr=Pt;if(Cr.value.length!==Yr.value.length)throw new Error(`Too ${Cr.value.length>Yr.value.length?"few":"many"} items to unpack`);dr=Rr=>{for(let Jr=0;Jr0?nt[bt-1]:new je],["nextitem",bt{var Je;const he=new Ve(Y);$=$.slice();let nt;((Je=$.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(nt=$.pop());for(let Nt=0;Ntthis.evaluate($,H)));case"TupleLiteral":return new Ae(v.value.map($=>this.evaluate($,H)));case"ObjectLiteral":{const $=new Map;for(const[Y,he]of v.value){const nt=this.evaluate(Y,H);if(!(nt instanceof Re))throw new Error(`Object keys must be strings: got ${nt.type}`);$.set(nt.value,this.evaluate(he,H))}return new Mt($)}case"Identifier":return this.evaluateIdentifier(v,H);case"CallExpression":return this.evaluateCallExpression(v,H);case"MemberExpression":return this.evaluateMemberExpression(v,H);case"UnaryExpression":return this.evaluateUnaryExpression(v,H);case"BinaryExpression":return this.evaluateBinaryExpression(v,H);case"FilterExpression":return this.evaluateFilterExpression(v,H);case"TestExpression":return this.evaluateTestExpression(v,H);default:throw new SyntaxError(`Unknown node type: ${v.type}`)}}};function _t(v){switch(typeof v){case"number":return new dt(v);case"string":return new Re(v);case"boolean":return new ht(v);case"undefined":return new je;case"object":return v===null?new et:Array.isArray(v)?new Z(v.map(_t)):new Mt(new Map(Object.entries(v).map(([H,$])=>[H,_t($)])));case"function":return new Ke((H,$)=>{const Y=v(...H.map(he=>he.value))??null;return _t(Y)});default:throw new Error(`Cannot convert to runtime value: ${v}`)}}function St(v,H,$){const Y=$??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=H?" ".repeat(H):"",nt=` `+he.repeat(Y),Je=nt+he;if(v.type==="ArrayValue"){const Nt=v.value.map(yt=>St(yt,H,Y+1));return H?`[${Je}${Nt.join(`,${Je}`)}${nt}]`:`[${Nt.join(", ")}]`}else{const Nt=Array.from(v.value.entries()).map(([yt,bt])=>{const zt=`"${yt}": ${St(bt,H,Y+1)}`;return H?`${Je}${zt}`:zt});return H?`{${Nt.join(",")}${nt}}`:`{${Nt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${v.type}`)}}var xt=class{constructor(v){ve(this,"parsed");const H=B(v,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=xe(H)}render(v){const H=new Ve;H.set("false",!1),H.set("true",!0),H.set("raise_exception",he=>{throw new Error(he)}),H.set("range",We);for(const[he,nt]of Object.entries(v))H.set(he,nt);return new ut(H).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{registerBackend:()=>we,resolveBackendAndExecutionProviders:()=>Te});const F=new Map,ce=[],we=(L,P,D)=>{if(P&&typeof P.init=="function"&&typeof P.createInferenceSessionHandler=="function"){const B=F.get(L);if(B===void 0)F.set(L,{backend:P,priority:D});else{if(B.priority>D)return;if(B.priority===D&&B.backend!==P)throw new Error(`cannot register backend "${L}" using priority ${D}`)}if(D>=0){const q=ce.indexOf(L);q!==-1&&ce.splice(q,1);for(let re=0;re{const P=F.get(L);if(!P)return"backend not found.";if(P.initialized)return P.backend;if(P.aborted)return P.error;{const D=!!P.initPromise;try{return D||(P.initPromise=P.backend.init(L)),await P.initPromise,P.initialized=!0,P.backend}catch(B){return D||(P.error=`${B}`,P.aborted=!0),P.error}finally{delete P.initPromise}}},Te=async L=>{const P=L.executionProviders||[],D=P.map(O=>typeof O=="string"?O:O.name),B=D.length===0?ce:D;let q;const re=[],fe=new Set;for(const O of B){const J=await ye(O);typeof J=="string"?re.push({name:O,err:J}):(q||(q=J),q===J&&fe.add(O))}if(!q)throw new Error(`no available backend found. ERR: ${re.map(O=>`[${O.name}] ${O.err}`).join(", ")}`);for(const{name:O,err:J}of re)D.includes(O)&&console.warn(`removing requested execution provider "${O}" from session options because it is not available: ${J}`);const le=P.filter(O=>fe.has(typeof O=="string"?O:O.name));return[q,new Proxy(L,{get:(O,J)=>J==="executionProviders"?le:Reflect.get(O,J)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{registerBackend:()=>F.registerBackend});var F=V("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{env:()=>we});var F=V("./node_modules/onnxruntime-common/dist/esm/version.js");let ce="warning";const we={wasm:{},webgl:{},webgpu:{},versions:{common:F.version},set logLevel(ye){if(ye!==void 0){if(typeof ye!="string"||["verbose","info","warning","error","fatal"].indexOf(ye)===-1)throw new Error(`Unsupported logging level: ${ye}`);ce=ye}},get logLevel(){return ce}};Object.defineProperty(we,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{env:()=>ce});var F=V("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const ce=F.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{InferenceSession:()=>we.InferenceSession,TRACE:()=>Te.TRACE,TRACE_FUNC_BEGIN:()=>Te.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Te.TRACE_FUNC_END,Tensor:()=>ye.Tensor,TrainingSession:()=>L.TrainingSession,env:()=>ce.env,registerBackend:()=>F.registerBackend});var F=V("./node_modules/onnxruntime-common/dist/esm/backend.js"),ce=V("./node_modules/onnxruntime-common/dist/esm/env.js"),we=V("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),ye=V("./node_modules/onnxruntime-common/dist/esm/tensor.js");V("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),V("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Te=V("./node_modules/onnxruntime-common/dist/esm/trace.js");V("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),V("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var L=V("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{InferenceSession:()=>ye});var F=V("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),ce=V("./node_modules/onnxruntime-common/dist/esm/tensor.js"),we=V("./node_modules/onnxruntime-common/dist/esm/trace.js");class ye{constructor(L){this.handler=L}async run(L,P,D){(0,we.TRACE_FUNC_BEGIN)();const B={};let q={};if(typeof L!="object"||L===null||L instanceof ce.Tensor||Array.isArray(L))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let re=!0;if(typeof P=="object"){if(P===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(P instanceof ce.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(P)){if(P.length===0)throw new TypeError("'fetches' cannot be an empty array.");re=!1;for(const O of P){if(typeof O!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(O)===-1)throw new RangeError(`'fetches' contains invalid output name: ${O}.`);B[O]=null}if(typeof D=="object"&&D!==null)q=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else{let O=!1;const J=Object.getOwnPropertyNames(P);for(const pe of this.outputNames)if(J.indexOf(pe)!==-1){const X=P[pe];(X===null||X instanceof ce.Tensor)&&(O=!0,re=!1,B[pe]=X)}if(O){if(typeof D=="object"&&D!==null)q=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else q=P}}else if(typeof P<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const O of this.inputNames)if(typeof L[O]>"u")throw new Error(`input '${O}' is missing in 'feeds'.`);if(re)for(const O of this.outputNames)B[O]=null;const fe=await this.handler.run(L,B,q),le={};for(const O in fe)if(Object.hasOwnProperty.call(fe,O)){const J=fe[O];J instanceof ce.Tensor?le[O]=J:le[O]=new ce.Tensor(J.type,J.data,J.dims)}return(0,we.TRACE_FUNC_END)(),le}async release(){return this.handler.dispose()}static async create(L,P,D,B){(0,we.TRACE_FUNC_BEGIN)();let q,re={};if(typeof L=="string"){if(q=L,typeof P=="object"&&P!==null)re=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(L instanceof Uint8Array){if(q=L,typeof P=="object"&&P!==null)re=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(L instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&L instanceof SharedArrayBuffer){const J=L;let pe=0,X=L.byteLength;if(typeof P=="object"&&P!==null)re=P;else if(typeof P=="number"){if(pe=P,!Number.isSafeInteger(pe))throw new RangeError("'byteOffset' must be an integer.");if(pe<0||pe>=J.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${J.byteLength}).`);if(X=L.byteLength-pe,typeof D=="number"){if(X=D,!Number.isSafeInteger(X))throw new RangeError("'byteLength' must be an integer.");if(X<=0||pe+X>J.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${J.byteLength-pe}].`);if(typeof B=="object"&&B!==null)re=B;else if(typeof B<"u")throw new TypeError("'options' must be an object.")}else if(typeof D<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof P<"u")throw new TypeError("'options' must be an object.");q=new Uint8Array(J,pe,X)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[fe,le]=await(0,F.resolveBackendAndExecutionProviders)(re),O=await fe.createInferenceSessionHandler(q,le);return(0,we.TRACE_FUNC_END)(),new ye(O)}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":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{InferenceSession:()=>ce});var F=V("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const ce=F.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Dt,Ee,V)=>{V.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Dt,Ee,V)=>{V.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{tensorToDataURL:()=>F,tensorToImageData:()=>ce});const F=(we,ye)=>{const Te=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Te.width=we.dims[3],Te.height=we.dims[2];const L=Te.getContext("2d");if(L!=null){let P,D;(ye==null?void 0:ye.tensorLayout)!==void 0&&ye.tensorLayout==="NHWC"?(P=we.dims[2],D=we.dims[3]):(P=we.dims[3],D=we.dims[2]);const B=(ye==null?void 0:ye.format)!==void 0?ye.format:"RGB",q=ye==null?void 0:ye.norm;let re,fe;q===void 0||q.mean===void 0?re=[255,255,255,255]:typeof q.mean=="number"?re=[q.mean,q.mean,q.mean,q.mean]:(re=[q.mean[0],q.mean[1],q.mean[2],0],q.mean[3]!==void 0&&(re[3]=q.mean[3])),q===void 0||q.bias===void 0?fe=[0,0,0,0]:typeof q.bias=="number"?fe=[q.bias,q.bias,q.bias,q.bias]:(fe=[q.bias[0],q.bias[1],q.bias[2],0],q.bias[3]!==void 0&&(fe[3]=q.bias[3]));const le=D*P;let O=0,J=le,pe=le*2,X=-1;B==="RGBA"?(O=0,J=le,pe=le*2,X=le*3):B==="RGB"?(O=0,J=le,pe=le*2):B==="RBG"&&(O=0,pe=le,J=le*2);for(let K=0;K{const Te=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let L;if(Te!=null){let P,D,B;(ye==null?void 0:ye.tensorLayout)!==void 0&&ye.tensorLayout==="NHWC"?(P=we.dims[2],D=we.dims[1],B=we.dims[3]):(P=we.dims[3],D=we.dims[2],B=we.dims[1]);const q=ye!==void 0&&ye.format!==void 0?ye.format:"RGB",re=ye==null?void 0:ye.norm;let fe,le;re===void 0||re.mean===void 0?fe=[255,255,255,255]:typeof re.mean=="number"?fe=[re.mean,re.mean,re.mean,re.mean]:(fe=[re.mean[0],re.mean[1],re.mean[2],255],re.mean[3]!==void 0&&(fe[3]=re.mean[3])),re===void 0||re.bias===void 0?le=[0,0,0,0]:typeof re.bias=="number"?le=[re.bias,re.bias,re.bias,re.bias]:(le=[re.bias[0],re.bias[1],re.bias[2],0],re.bias[3]!==void 0&&(le[3]=re.bias[3]));const O=D*P;if(ye!==void 0&&(ye.format!==void 0&&B===4&&ye.format!=="RGBA"||B===3&&ye.format!=="RGB"&&ye.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const J=4;let pe=0,X=1,K=2,j=3,k=0,N=O,E=O*2,ue=-1;q==="RGBA"?(k=0,N=O,E=O*2,ue=O*3):q==="RGB"?(k=0,N=O,E=O*2):q==="RBG"&&(k=0,E=O,N=O*2),L=Te.createImageData(P,D);for(let be=0;be{V.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{bufferToTensor:()=>ce,tensorFromGpuBuffer:()=>Te,tensorFromImage:()=>we,tensorFromPinnedBuffer:()=>L,tensorFromTexture:()=>ye});var F=V("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const ce=(P,D)=>{if(P===void 0)throw new Error("Image buffer must be defined");if(D.height===void 0||D.width===void 0)throw new Error("Image height and width must be defined");if(D.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:B,width:q}=D,re=D.norm??{mean:255,bias:0};let fe,le;typeof re.mean=="number"?fe=[re.mean,re.mean,re.mean,re.mean]:fe=[re.mean[0],re.mean[1],re.mean[2],re.mean[3]??255],typeof re.bias=="number"?le=[re.bias,re.bias,re.bias,re.bias]:le=[re.bias[0],re.bias[1],re.bias[2],re.bias[3]??0];const O=D.format!==void 0?D.format:"RGBA",J=D.tensorFormat!==void 0&&D.tensorFormat!==void 0?D.tensorFormat:"RGB",pe=B*q,X=J==="RGBA"?new Float32Array(pe*4):new Float32Array(pe*3);let K=4,j=0,k=1,N=2,E=3,ue=0,be=pe,Ce=pe*2,De=-1;O==="RGB"&&(K=3,j=0,k=1,N=2,E=-1),J==="RGBA"?De=pe*3:J==="RBG"?(ue=0,Ce=pe,be=pe*2):J==="BGR"&&(Ce=0,be=pe,ue=pe*2);for(let it=0;it{const B=typeof HTMLImageElement<"u"&&P instanceof HTMLImageElement,q=typeof ImageData<"u"&&P instanceof ImageData,re=typeof ImageBitmap<"u"&&P instanceof ImageBitmap,fe=typeof P=="string";let le,O=D??{};const J=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},pe=X=>X instanceof HTMLCanvasElement||X instanceof OffscreenCanvas?X.getContext("2d"):null;if(B){const X=J();X.width=P.width,X.height=P.height;const K=pe(X);if(K!=null){let j=P.height,k=P.width;if(D!==void 0&&D.resizedHeight!==void 0&&D.resizedWidth!==void 0&&(j=D.resizedHeight,k=D.resizedWidth),D!==void 0){if(O=D,D.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");O.tensorFormat="RGBA",O.height=j,O.width=k}else O.tensorFormat="RGBA",O.height=j,O.width=k;K.drawImage(P,0,0),le=K.getImageData(0,0,k,j).data}else throw new Error("Can not access image data")}else if(q){let X,K;if(D!==void 0&&D.resizedWidth!==void 0&&D.resizedHeight!==void 0?(X=D.resizedHeight,K=D.resizedWidth):(X=P.height,K=P.width),D!==void 0&&(O=D),O.format="RGBA",O.height=X,O.width=K,D!==void 0){const j=J();j.width=K,j.height=X;const k=pe(j);if(k!=null)k.putImageData(P,0,0),le=k.getImageData(0,0,K,X).data;else throw new Error("Can not access image data")}else le=P.data}else if(re){if(D===void 0)throw new Error("Please provide image config with format for Imagebitmap");const X=J();X.width=P.width,X.height=P.height;const K=pe(X);if(K!=null){const j=P.height,k=P.width;return K.drawImage(P,0,0,k,j),le=K.getImageData(0,0,k,j).data,O.height=j,O.width=k,ce(le,O)}else throw new Error("Can not access image data")}else{if(fe)return new Promise((X,K)=>{const j=J(),k=pe(j);if(!P||!k)return K();const N=new Image;N.crossOrigin="Anonymous",N.src=P,N.onload=()=>{j.width=N.width,j.height=N.height,k.drawImage(N,0,0,j.width,j.height);const E=k.getImageData(0,0,j.width,j.height);O.height=j.height,O.width=j.width,X(ce(E.data,O))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(le!==void 0)return ce(le,O);throw new Error("Input data provided is not supported - aborted tensor creation")},ye=(P,D)=>{const{width:B,height:q,download:re,dispose:fe}=D,le=[1,q,B,4];return new F.Tensor({location:"texture",type:"float32",texture:P,dims:le,download:re,dispose:fe})},Te=(P,D)=>{const{dataType:B,dims:q,download:re,dispose:fe}=D;return new F.Tensor({location:"gpu-buffer",type:B??"float32",gpuBuffer:P,dims:q,download:re,dispose:fe})},L=(P,D,B)=>new F.Tensor({location:"cpu-pinned",type:P,data:D,dims:B??[D.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Dt,Ee,V)=>{V.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>ce,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>F,checkTypedArray:()=>ye});const F=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),ce=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let we=!1;const ye=()=>{if(!we){we=!0;const Te=typeof BigInt64Array<"u"&&BigInt64Array.from,L=typeof BigUint64Array<"u"&&BigUint64Array.from,P=typeof Float16Array<"u"&&Float16Array.from;Te&&(F.set("int64",BigInt64Array),ce.set(BigInt64Array,"int64")),L&&(F.set("uint64",BigUint64Array),ce.set(BigUint64Array,"uint64")),P?(F.set("float16",Float16Array),ce.set(Float16Array,"float16")):F.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{Tensor:()=>Te});var F=V("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),ce=V("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),we=V("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),ye=V("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Te{constructor(P,D,B){(0,we.checkTypedArray)();let q,re;if(typeof P=="object"&&"location"in P)switch(this.dataLocation=P.location,q=P.type,re=P.dims,P.location){case"cpu-pinned":{const le=we.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(q);if(!le)throw new TypeError(`unsupported type "${q}" to create tensor from pinned buffer`);if(!(P.data instanceof le))throw new TypeError(`buffer should be of type ${le.name}`);this.cpuData=P.data;break}case"texture":{if(q!=="float32")throw new TypeError(`unsupported type "${q}" to create tensor from texture`);this.gpuTextureData=P.texture,this.downloader=P.download,this.disposer=P.dispose;break}case"gpu-buffer":{if(q!=="float32"&&q!=="float16"&&q!=="int32"&&q!=="int64"&&q!=="uint32"&&q!=="uint8"&&q!=="bool")throw new TypeError(`unsupported type "${q}" to create tensor from gpu buffer`);this.gpuBufferData=P.gpuBuffer,this.downloader=P.download,this.disposer=P.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let le,O;if(typeof P=="string")if(q=P,O=B,P==="string"){if(!Array.isArray(D))throw new TypeError("A string tensor's data must be a string array.");le=D}else{const J=we.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(P);if(J===void 0)throw new TypeError(`Unsupported tensor type: ${P}.`);if(Array.isArray(D)){if(P==="float16"&&J===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");P==="uint64"||P==="int64"?le=J.from(D,BigInt):le=J.from(D)}else if(D instanceof J)le=D;else throw new TypeError(`A ${q} tensor's data must be type of ${J}`)}else if(O=D,Array.isArray(P)){if(P.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const J=typeof P[0];if(J==="string")q="string",le=P;else if(J==="boolean")q="bool",le=Uint8Array.from(P);else throw new TypeError(`Invalid element type of data array: ${J}.`)}else{const J=we.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(P.constructor);if(J===void 0)throw new TypeError(`Unsupported type for tensor data: ${P.constructor}.`);q=J,le=P}if(O===void 0)O=[le.length];else if(!Array.isArray(O))throw new TypeError("A tensor's dims must be a number array");re=O,this.cpuData=le,this.dataLocation="cpu"}const fe=(0,ye.calculateSize)(re);if(this.cpuData&&fe!==this.cpuData.length)throw new Error(`Tensor's size(${fe}) does not match data length(${this.cpuData.length}).`);this.type=q,this.dims=re,this.size=fe}static async fromImage(P,D){return(0,ce.tensorFromImage)(P,D)}static fromTexture(P,D){return(0,ce.tensorFromTexture)(P,D)}static fromGpuBuffer(P,D){return(0,ce.tensorFromGpuBuffer)(P,D)}static fromPinnedBuffer(P,D,B){return(0,ce.tensorFromPinnedBuffer)(P,D,B)}toDataURL(P){return(0,F.tensorToDataURL)(this,P)}toImageData(P){return(0,F.tensorToImageData)(this,P)}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(P){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 D=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=D,P&&this.disposer&&(this.disposer(),this.disposer=void 0),D}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(P){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,ye.tensorReshape)(this,P)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{calculateSize:()=>ce,tensorReshape:()=>we});var F=V("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const ce=ye=>{let Te=1;for(let L=0;L{switch(ye.location){case"cpu":return new F.Tensor(ye.type,ye.data,Te);case"cpu-pinned":return new F.Tensor({location:"cpu-pinned",data:ye.data,type:ye.type,dims:Te});case"texture":return new F.Tensor({location:"texture",texture:ye.texture,type:ye.type,dims:Te});case"gpu-buffer":return new F.Tensor({location:"gpu-buffer",gpuBuffer:ye.gpuBuffer,type:ye.type,dims:Te});default:throw new Error(`tensorReshape: tensor location ${ye.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{Tensor:()=>ce});var F=V("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const ce=F.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{TRACE:()=>ce,TRACE_FUNC_BEGIN:()=>ye,TRACE_FUNC_END:()=>Te});var F=V("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const ce=(L,P)=>{(typeof F.env.trace>"u"?!F.env.wasm.trace:!F.env.trace)||console.timeStamp(`${L}::ORT::${P}`)},we=(L,P)=>{var q;const D=((q=new Error().stack)==null?void 0:q.split(/\r\n|\r|\n/g))||[];let B=!1;for(let re=0;re{(typeof F.env.trace>"u"?!F.env.wasm.trace:!F.env.trace)||we("BEGIN",L)},Te=L=>{(typeof F.env.trace>"u"?!F.env.wasm.trace:!F.env.trace)||we("END",L)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{TrainingSession:()=>ye});var F=V("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),ce=V("./node_modules/onnxruntime-common/dist/esm/tensor.js");const we="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class ye{constructor(L,P,D){this.handler=L,this.hasOptimizerModel=P,this.hasEvalModel=D}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(L,P){const D=L.evalModel||"",B=L.optimizerModel||"",q=P||{},[re,fe]=await(0,F.resolveBackendAndExecutionProviders)(q);if(re.createTrainingSessionHandler){const le=await re.createTrainingSessionHandler(L.checkpointState,L.trainModel,D,B,fe);return new ye(le,!!L.optimizerModel,!!L.evalModel)}else throw new Error(we)}typeNarrowingForRunStep(L,P,D,B,q){const re={};let fe={};if(typeof D!="object"||D===null||D instanceof ce.Tensor||Array.isArray(D))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let le=!0;if(typeof B=="object"){if(B===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(B instanceof ce.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(B)){if(B.length===0)throw new TypeError("'fetches' cannot be an empty array.");le=!1;for(const O of B){if(typeof O!="string")throw new TypeError("'fetches' must be a string array or an object.");if(P.indexOf(O)===-1)throw new RangeError(`'fetches' contains invalid output name: ${O}.`);re[O]=null}if(typeof q=="object"&&q!==null)fe=q;else if(typeof q<"u")throw new TypeError("'options' must be an object.")}else{let O=!1;const J=Object.getOwnPropertyNames(B);for(const pe of P)if(J.indexOf(pe)!==-1){const X=B[pe];(X===null||X instanceof ce.Tensor)&&(O=!0,le=!1,re[pe]=X)}if(O){if(typeof q=="object"&&q!==null)fe=q;else if(typeof q<"u")throw new TypeError("'options' must be an object.")}else fe=B}}else if(typeof B<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const O of L)if(typeof D[O]>"u")throw new Error(`input '${O}' is missing in 'feeds'.`);if(le)for(const O of P)re[O]=null;return[re,fe]}convertHandlerReturnTypeToMapOfTensors(L){const P={};for(const D in L)if(Object.hasOwnProperty.call(L,D)){const B=L[D];B instanceof ce.Tensor?P[D]=B:P[D]=new ce.Tensor(B.type,B.data,B.dims)}return P}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(L,P,D){const[B,q]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,L,P,D),re=await this.handler.runTrainStep(L,B,q);return this.convertHandlerReturnTypeToMapOfTensors(re)}async runOptimizerStep(L){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(L||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(L,P,D){if(this.hasEvalModel){const[B,q]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,L,P,D),re=await this.handler.runEvalStep(L,B,q);return this.convertHandlerReturnTypeToMapOfTensors(re)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(L=!0){return this.handler.getParametersSize(L)}async loadParametersBuffer(L,P=!0){const D=await this.getParametersSize(P);if(L.length!==4*D)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(L,P)}async getContiguousParameters(L=!0){return this.handler.getContiguousParameters(L)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{TrainingSession:()=>ce});var F=V("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const ce=F.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{version:()=>F});const F="1.19.2"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{InferenceSession:()=>xt,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>je,TRACE_FUNC_END:()=>Ve,Tensor:()=>Z,TrainingSession:()=>yt,default:()=>Kf,env:()=>E,registerBackend:()=>fe});/*! * ONNX Runtime Web v1.21.0-dev.20241024-d9ca84ef96 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var F=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyNames,ye=Object.prototype.hasOwnProperty,Te=(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')}),L=(e,t)=>()=>(e&&(t=e(e=0)),t),P=(e,t)=>{for(var r in t)F(e,r,{get:t[r],enumerable:!0})},D=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of we(t))!ye.call(e,i)&&i!==r&&F(e,i,{get:()=>t[i],enumerable:!(n=ce(t,i))||n.enumerable});return e},B=e=>D(F({},"__esModule",{value:!0}),e),q,re,fe,le,O,J=L(()=>{q=new Map,re=[],fe=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=q.get(e);if(n===void 0)q.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 i=re.indexOf(e);i!==-1&&re.splice(i,1);for(let a=0;a{let t=q.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}}},O=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?re:r,i,a=[],s=new Set;for(let d of n){let c=await le(d);typeof c=="string"?a.push({name:d,err:c}):(i||(i=c),i===c&&s.add(d))}if(!i)throw new Error(`no available backend found. ERR: ${a.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:c}of a)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${c}`);let u=t.filter(d=>s.has(typeof d=="string"?d:d.name));return[i,new Proxy(e,{get:(d,c)=>c==="executionProviders"?u:Reflect.get(d,c)})]}}),pe=L(()=>{J()}),X,K=L(()=>{X="1.20.0-dev.20241016-2b8fc5529b"}),j,k,N=L(()=>{K(),j="warning",k={wasm:{},webgl:{},webgpu:{},versions:{common:X},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}`);j=e}},get logLevel(){return j}},Object.defineProperty(k,"logLevel",{enumerable:!0})}),E,ue=L(()=>{N(),E=k}),be,Ce,De=L(()=>{be=(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 i,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let s=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,d,c;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?c=[0,0,0,0]:typeof u.bias=="number"?c=[u.bias,u.bias,u.bias,u.bias]:(c=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(c[3]=u.bias[3]));let g=a*i,m=0,l=g,T=g*2,x=-1;s==="RGBA"?(m=0,l=g,T=g*2,x=g*3):s==="RGB"?(m=0,l=g,T=g*2):s==="RBG"&&(m=0,T=g,l=g*2);for(let C=0;C{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let i,a,s;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[1],s=e.dims[3]):(i=e.dims[3],a=e.dims[2],s=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,c,g;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean=="number"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?g=[0,0,0,0]:typeof d.bias=="number"?g=[d.bias,d.bias,d.bias,d.bias]:(g=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(g[3]=d.bias[3]));let m=a*i;if(t!==void 0&&(t.format!==void 0&&s===4&&t.format!=="RGBA"||s===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,T=0,x=1,C=2,z=3,U=0,A=m,ee=m*2,te=-1;u==="RGBA"?(U=0,A=m,ee=m*2,te=m*3):u==="RGB"?(U=0,A=m,ee=m*2):u==="RBG"&&(U=0,ee=m,A=m*2),n=r.createImageData(i,a);for(let ie=0;ie{Xe(),ze=(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,i=t.norm??{mean:255,bias:0},a,s;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?s=[i.bias,i.bias,i.bias,i.bias]:s=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*n,g=d==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),m=4,l=0,T=1,x=2,C=3,z=0,U=c,A=c*2,ee=-1;u==="RGB"&&(m=3,l=0,T=1,x=2,C=-1),d==="RGBA"?ee=c*3:d==="RBG"?(z=0,A=c,U=c*2):d==="BGR"&&(A=0,U=c,z=c*2);for(let te=0;te{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",s,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")},c=g=>typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(r){let g=d();g.width=e.width,g.height=e.height;let m=c(g);if(m!=null){let l=e.height,T=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,T=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=T}else u.tensorFormat="RGBA",u.height=l,u.width=T;m.drawImage(e,0,0),s=m.getImageData(0,0,T,l).data}else throw new Error("Can not access image data")}else if(n){let g,m;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,m=t.resizedWidth):(g=e.height,m=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=g,u.width=m,t!==void 0){let l=d();l.width=m,l.height=g;let T=c(l);if(T!=null)T.putImageData(e,0,0),s=T.getImageData(0,0,m,g).data;else throw new Error("Can not access image data")}else s=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=d();g.width=e.width,g.height=e.height;let m=c(g);if(m!=null){let l=e.height,T=e.width;return m.drawImage(e,0,0,T,l),s=m.getImageData(0,0,T,l).data,u.height=l,u.width=T,ze(s,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((g,m)=>{let l=d(),T=c(l);if(!e||!T)return m();let x=new Image;x.crossOrigin="Anonymous",x.src=e,x.onload=()=>{l.width=x.width,l.height=x.height,T.drawImage(x,0,0,l.width,l.height);let C=T.getImageData(0,0,l.width,l.height);u.height=l.height,u.width=l.width,g(ze(C.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return ze(s,u);throw new Error("Input data provided is not supported - aborted tensor creation")},rt=(e,t)=>{let{width:r,height:n,download:i,dispose:a}=t,s=[1,n,r,4];return new Mt({location:"texture",type:"float32",texture:e,dims:s,download:i,dispose:a})},lt=(e,t)=>{let{dataType:r,dims:n,download:i,dispose:a}=t;return new Mt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:i,dispose:a})},me=(e,t)=>{let{dataType:r,dims:n,download:i,dispose:a}=t;return new Mt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:i,dispose:a})},W=(e,t,r)=>new Mt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),xe,We,ot,se,Ze=L(()=>{xe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),We=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ot=!1,se=()=>{if(!ot){ot=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(xe.set("int64",BigInt64Array),We.set(BigInt64Array,"int64")),t&&(xe.set("uint64",BigUint64Array),We.set(BigUint64Array,"uint64")),r?(xe.set("float16",Float16Array),We.set(Float16Array,"float16")):xe.set("float16",Uint16Array)}}}),dt,Re,ht=L(()=>{Xe(),dt=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Mt(e.type,e.data,t);case"cpu-pinned":return new Mt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Mt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Mt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Mt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Mt,Xe=L(()=>{De(),de(),Ze(),ht(),Mt=class{constructor(e,t,r){se();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let s=xe.get(n);if(!s)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof s))throw new TypeError(`buffer should be of type ${s.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,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.");s=t}else{let d=xe.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"?s=d.from(t,BigInt):s=d.from(t)}else if(t instanceof d)s=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")s=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${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",s=e;else if(d==="boolean")n="bool",s=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",s=Uint8Array.from(e);else{let d=We.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=d,s=e}if(u===void 0)u=[s.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");i=u,this.cpuData=s,this.dataLocation="cpu"}let a=dt(i);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=i,this.size=a}static async fromImage(e,t){return it(e,t)}static fromTexture(e,t){return rt(e,t)}static fromGpuBuffer(e,t){return lt(e,t)}static fromMLTensor(e,t){return me(e,t)}static fromPinnedBuffer(e,t,r){return W(e,t,r)}toDataURL(e){return be(this,e)}toImageData(e){return Ce(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Re(this,e)}}}),Z,Ae=L(()=>{Xe(),Z=Mt}),Ke,et,je,Ve,ut=L(()=>{N(),Ke=(e,t)=>{(typeof k.trace>"u"?!k.wasm.trace:!k.trace)||console.timeStamp(`${e}::ORT::${t}`)},et=(e,t)=>{var i;let r=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof k.trace>"u"?!k.wasm.trace:!k.trace)||et("BEGIN",e)},Ve=e=>{(typeof k.trace>"u"?!k.wasm.trace:!k.trace)||et("END",e)}}),_t,St=L(()=>{J(),Ae(),ut(),_t=class Ef{constructor(t){this.handler=t}async run(t,r,n){je();let i={},a={};if(typeof t!="object"||t===null||t instanceof Z||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Z)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.");s=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);i[c]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,g=Object.getOwnPropertyNames(r);for(let m of this.outputNames)if(g.indexOf(m)!==-1){let l=r[m];(l===null||l instanceof Z)&&(c=!0,s=!1,i[m]=l)}if(c){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 c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(s)for(let c of this.outputNames)i[c]=null;let u=await this.handler.run(t,i,a),d={};for(let c in u)if(Object.hasOwnProperty.call(u,c)){let g=u[c];g instanceof Z?d[c]=g:d[c]=new Z(g.type,g.data,g.dims)}return Ve(),d}async release(){return this.handler.dispose()}static async create(t,r,n,i){je();let a,s={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)s=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)s=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 g=t,m=0,l=t.byteLength;if(typeof r=="object"&&r!==null)s=r;else if(typeof r=="number"){if(m=r,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(l=t.byteLength-m,typeof n=="number"){if(l=n,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||m+l>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-m}].`);if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"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(g,m,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await O(s),c=await u.createInferenceSessionHandler(a,d);return Ve(),new Ef(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),xt,v=L(()=>{St(),xt=_t}),H=L(()=>{}),$=L(()=>{}),Y=L(()=>{}),he=L(()=>{}),nt,Je,Nt=L(()=>{J(),Ae(),nt="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Je=class kf{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||"",i=t.optimizerModel||"",a=r||{},[s,u]=await O(a);if(s.createTrainingSessionHandler){let d=await s.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,i,u);return new kf(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(nt)}typeNarrowingForRunStep(t,r,n,i,a){let s={},u={};if(typeof n!="object"||n===null||n instanceof Z||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 i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof Z)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let c of i){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);s[c]=null}if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,g=Object.getOwnPropertyNames(i);for(let m of r)if(g.indexOf(m)!==-1){let l=i[m];(l===null||l instanceof Z)&&(c=!0,d=!1,s[m]=l)}if(c){if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else u=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of t)if(typeof n[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(d)for(let c of r)s[c]=null;return[s,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let i=t[n];i instanceof Z?r[n]=i:r[n]=new Z(i.type,i.data,i.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[i,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),s=await this.handler.runTrainStep(t,i,a);return this.convertHandlerReturnTypeToMapOfTensors(s)}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[i,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),s=await this.handler.runEvalStep(t,i,a);return this.convertHandlerReturnTypeToMapOfTensors(s)}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()}}}),yt,bt=L(()=>{Nt(),yt=Je}),zt={};P(zt,{InferenceSession:()=>xt,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>je,TRACE_FUNC_END:()=>Ve,Tensor:()=>Z,TrainingSession:()=>yt,env:()=>E,registerBackend:()=>fe});var Pt=L(()=>{pe(),ue(),v(),Ae(),H(),$(),ut(),Y(),he(),bt()}),dr=L(()=>{}),Cr={};P(Cr,{default:()=>Jr});var Yr,Rr,Jr,bn=L(()=>{var e;Kp(),kr(),Ft(),Yr="ort-wasm-proxy-worker",Rr=((e=globalThis.self)==null?void 0:e.name)===Yr,Rr&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Nr(n.wasm).then(()=>{Ac(n).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})})},i=>{postMessage({type:r,err:i})});break;case"init-ep":{let{epName:i,env:a}=n;Ic(a,i).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})});break}case"copy-from":{let{buffer:i}=n,a=ec(i);postMessage({type:r,out:a});break}case"create":{let{model:i,options:a}=n;Fc(i,a).then(s=>{postMessage({type:r,out:s})},s=>{postMessage({type:r,err:s})});break}case"release":Oc(n),postMessage({type:r});break;case"run":{let{sessionId:i,inputIndices:a,inputs:s,outputIndices:u,options:d}=n;Dc(i,a,s,u,new Array(u.length).fill(null),d).then(c=>{c.some(g=>g[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:c},Bc([...s,...c]))},c=>{postMessage({type:r,err:c})});break}case"end-profiling":Lc(n),postMessage({type:r});break;default:}}catch(i){postMessage({type:r,err:i})}}),Jr=Rr?null:t=>new Worker(t??Ne,{type:"module",name:Yr})}),at={};P(at,{default:()=>Ie});var G,ge,Ie,Se=L(()=>{var e;ge=(G=self.location.href,async function(t={}){function r(){return hr.buffer!=Qt.buffer&&mn(),Qt}function n(){return hr.buffer!=Qt.buffer&&mn(),xr}function i(){return hr.buffer!=Qt.buffer&&mn(),qe}function a(){return hr.buffer!=Qt.buffer&&mn(),vt}function s(){return hr.buffer!=Qt.buffer&&mn(),rr}function u(){return hr.buffer!=Qt.buffer&&mn(),Br}function d(){return hr.buffer!=Qt.buffer&&mn(),sn}function c(){return hr.buffer!=Qt.buffer&&mn(),nc}var g,m,l=Object.assign({},t),T=new Promise((o,h)=>{g=o,m=h}),x=typeof window=="object",C=typeof importScripts=="function",z=C&&self.name=="em-pthread";l.mountExternalData=(o,h)=>{o.startsWith("./")&&(o=o.substring(2)),(l.Eb||(l.Eb=new Map)).set(o,h)},l.unmountExternalData=()=>{delete l.Eb};var U=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let A=()=>{let o=(w,M,S)=>(...ne)=>{let He=ps,st=M==null?void 0:M();ne=w(...ne);let At=M==null?void 0:M();return st!==At&&(w=At,S(st),M=S=null),ps!=He?new Promise((Rt,Zt)=>{sp={resolve:Rt,reject:Zt}}):ne},h=w=>async(...M)=>{var S;try{if(l.Fb)throw Error("Session already started");let ne=l.Fb={fc:M[0],errors:[]},He=await w(...M);if(l.Fb!==ne)throw Error("Session mismatch");(S=l.Gb)==null||S.flush();let st=ne.errors;if(0Rt),0l._OrtCreateSession,w=>l._OrtCreateSession=w),l._OrtRun=h(o(l._OrtRun,()=>l._OrtRun,w=>l._OrtRun=w)),l._OrtRunWithBinding=h(o(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,w=>l._OrtRunWithBinding=w)),l._OrtBindInput=o(l._OrtBindInput,()=>l._OrtBindInput,w=>l._OrtBindInput=w),A=void 0};l.jsepInit=(o,h)=>{if(A==null||A(),o==="webgpu"){[l.Gb,l.Ub,l.Yb,l.Nb,l.Xb,l.jb,l.Zb,l.bc,l.Vb,l.Wb,l.$b]=h;let w=l.Gb;l.jsepRegisterBuffer=(M,S,ne,He)=>w.registerBuffer(M,S,ne,He),l.jsepGetBuffer=M=>w.getBuffer(M),l.jsepCreateDownloader=(M,S,ne)=>w.createDownloader(M,S,ne),l.jsepOnCreateSession=M=>{w.onCreateSession(M)},l.jsepOnReleaseSession=M=>{w.onReleaseSession(M)},l.jsepOnRunStart=M=>w.onRunStart(M),l.cc=(M,S)=>{w.upload(M,S)}}else if(o==="webnn"){[l.Gb,l.ac,l.Ob,l.jsepEnsureTensor,l.dc,l.jsepDownloadTensor]=h,l.jsepReleaseTensorId=l.Ob;let w=l.Gb;l.jsepOnRunStart=M=>w.onRunStart(M),l.jsepRegisterMLContext=(M,S)=>{w.registerMLContext(M,S)},l.jsepOnReleaseSession=M=>{w.onReleaseSession(M)},l.jsepCreateMLTensorDownloader=(M,S)=>w.createMLTensorDownloader(M,S),l.jsepRegisterMLTensor=(M,S,ne)=>w.registerMLTensor(M,S,ne),l.qc=(M,S,ne,He,st)=>w.registerMLConstant(M,S,ne,He,st,l.Eb)}};var ee,te,ie=Object.assign({},l),ke="./this.program",Pe=(o,h)=>{throw h},Ye="";(x||C)&&(C?Ye=self.location.href:typeof document<"u"&&document.currentScript&&(Ye=document.currentScript.src),G&&(Ye=G),Ye=Ye.startsWith("blob:")?"":Ye.substr(0,Ye.replace(/[?#].*/,"").lastIndexOf("/")+1),C&&(te=o=>{var h=new XMLHttpRequest;return h.open("GET",o,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),ee=(o,h,w)=>{var M=new XMLHttpRequest;M.open("GET",o,!0),M.responseType="arraybuffer",M.onload=()=>{M.status==200||M.status==0&&M.response?h(M.response):w()},M.onerror=w,M.send(null)});var It,Bt=console.log.bind(console),ar=console.error.bind(console),nr=Bt,Ht=ar;if(Object.assign(l,ie),ie=null,z){let o=function(h){try{var w=h.data,M=w.cmd;if(M==="load"){let S=[];self.onmessage=ne=>S.push(ne),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ne of S)o(ne);self.onmessage=o};for(let ne of w.handlers)l[ne]&&!l[ne].proxy||(l[ne]=(...He)=>{postMessage({Mb:"callHandler",oc:ne,args:He})},ne=="print"&&(nr=l[ne]),ne=="printErr"&&(Ht=l[ne]));hr=w.wasmMemory,mn(),Er(w.wasmModule)}else if(M==="run"){lp(w.pthread_ptr,0,0,1,0,0),tp(w.pthread_ptr),Yf(),gh(),jr||(mf(),jr=!0);try{Zf(w.start_routine,w.arg)}catch(S){if(S!="unwind")throw S}}else M==="cancel"?io()&&mc(-1):w.target!=="setimmediate"&&(M==="checkMailbox"?jr&&ac():M&&(Ht(`worker: received unknown command ${M}`),Ht(w)))}catch(S){throw _f(),S}};var Er,jr=!1;Ht=function(...h){h=h.join(" "),console.error(h)},self.alert=function(...h){postMessage({Mb:"alert",text:h.join(" "),rc:io()})},l.instantiateWasm=(h,w)=>new Promise(M=>{Er=S=>{S=new WebAssembly.Instance(S,ph()),w(S),M()}}),self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=o}l.wasmBinary&&(It=l.wasmBinary);var hr,Ir,Gt,Qt,xr,qe,vt,rr,Br,sn,an,Ws,nc,Sn=!1;function mn(){var o=hr.buffer;l.HEAP8=Qt=new Int8Array(o),l.HEAP16=qe=new Int16Array(o),l.HEAPU8=xr=new Uint8Array(o),l.HEAPU16=vt=new Uint16Array(o),l.HEAP32=rr=new Int32Array(o),l.HEAPU32=Br=new Uint32Array(o),l.HEAPF32=sn=new Float32Array(o),l.HEAPF64=nc=new Float64Array(o),l.HEAP64=an=new BigInt64Array(o),l.HEAPU64=Ws=new BigUint64Array(o)}if(!z){if(!((hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof U))throw Ht("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");mn()}var wi=[],cn=[],vn=[],Un=0,Gs=null;function sc(){if(--Un==0&&Gs){var o=Gs;Gs=null,o()}}function ro(o){throw Ht(o="Aborted("+o+")"),Sn=!0,Gt=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),m(o),o}var Uc,lh=o=>o.startsWith("data:application/octet-stream;base64,"),uh=o=>o.startsWith("file://");function dh(o){if(o==Uc&&It)return new Uint8Array(It);if(te)return te(o);throw"both async and sync fetching of the wasm failed"}function ch(o,h,w){return function(M){if(!It&&(x||C)){if(typeof fetch=="function"&&!uh(M))return fetch(M,{credentials:"same-origin"}).then(S=>{if(!S.ok)throw`failed to load wasm binary file at '${M}'`;return S.arrayBuffer()}).catch(()=>dh(M));if(ee)return new Promise((S,ne)=>{ee(M,He=>S(new Uint8Array(He)),ne)})}return Promise.resolve().then(()=>dh(M))}(o).then(M=>WebAssembly.instantiate(M,h)).then(w,M=>{Ht(`failed to asynchronously prepare wasm: ${M}`),ro(M)})}function ph(){return{a:{O:Qf,Aa:Xf,b:em,aa:Mh,B:Th,qa:Ch,Y:Eh,_:kh,ra:Sh,oa:Ph,ha:Ah,na:Ih,L:Fh,Z:Oh,W:zh,pa:Dh,X:Lh,wa:tm,F:rm,Q:nm,P:im,E:om,u:lm,q:um,G:dm,A:gm,R:wm,ua:ym,ka:bm,U:Mm,ba:vm,H:xm,ja:tp,ta:Tm,t:Cm,x:km,n:Sm,l:Am,c:Jc,o:Im,j:zm,w:Dm,p:Lm,g:Bm,s:Rm,m:Nm,e:jm,k:Vm,i:Um,h:Wm,d:Gm,ea:qm,fa:Hm,ga:Km,ca:Yh,da:Zh,T:Xm,f:Qm,D:Ym,I:Zm,M:Jm,y:e_,sa:t_,V:r_,v:ef,z:n_,N:s_,S:i_,za:a_,ya:o_,la:nf,ma:sf,$:Kc,C:af,K:of,ia:lf,J:uf,a:hr,xa:Hc,va:pf,r:d_}}}var Wc={867364:(o,h,w,M,S)=>{if(l===void 0||!l.Eb)return 1;if((o=yn(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=l.Eb.get(o)))return 2;if(M>>>=0,(h>>>=0)+(w>>>=0)>o.byteLength)return 3;try{let ne=o.subarray(h,h+w);switch(S){case 0:n().set(ne,M>>>0);break;case 1:l.cc(M,ne);break;default:return 4}return 0}catch{return 4}},868047:(o,h,w)=>{l.dc(o,n().subarray(h>>>0,h+w>>>0))},868110:()=>l.ac(),868151:o=>{l.Ob(o)},868187:()=>{l.Vb()},868218:()=>{l.Wb()},868247:()=>{l.$b()},868272:o=>l.Ub(o),868305:o=>l.Yb(o),868337:(o,h,w)=>{l.Nb(o,h,w,!0)},868376:(o,h,w)=>{l.Nb(o,h,w)},868409:()=>typeof wasmOffsetConverter<"u",868466:o=>{l.jb("Abs",o,void 0)},868517:o=>{l.jb("Neg",o,void 0)},868568:o=>{l.jb("Floor",o,void 0)},868621:o=>{l.jb("Ceil",o,void 0)},868673:o=>{l.jb("Reciprocal",o,void 0)},868731:o=>{l.jb("Sqrt",o,void 0)},868783:o=>{l.jb("Exp",o,void 0)},868834:o=>{l.jb("Erf",o,void 0)},868885:o=>{l.jb("Sigmoid",o,void 0)},868940:(o,h,w)=>{l.jb("HardSigmoid",o,{alpha:h,beta:w})},869019:o=>{l.jb("Log",o,void 0)},869070:o=>{l.jb("Sin",o,void 0)},869121:o=>{l.jb("Cos",o,void 0)},869172:o=>{l.jb("Tan",o,void 0)},869223:o=>{l.jb("Asin",o,void 0)},869275:o=>{l.jb("Acos",o,void 0)},869327:o=>{l.jb("Atan",o,void 0)},869379:o=>{l.jb("Sinh",o,void 0)},869431:o=>{l.jb("Cosh",o,void 0)},869483:o=>{l.jb("Asinh",o,void 0)},869536:o=>{l.jb("Acosh",o,void 0)},869589:o=>{l.jb("Atanh",o,void 0)},869642:o=>{l.jb("Tanh",o,void 0)},869694:o=>{l.jb("Not",o,void 0)},869745:(o,h,w)=>{l.jb("Clip",o,{min:h,max:w})},869814:o=>{l.jb("Clip",o,void 0)},869866:(o,h)=>{l.jb("Elu",o,{alpha:h})},869924:o=>{l.jb("Gelu",o,void 0)},869976:o=>{l.jb("Relu",o,void 0)},870028:(o,h)=>{l.jb("LeakyRelu",o,{alpha:h})},870092:(o,h)=>{l.jb("ThresholdedRelu",o,{alpha:h})},870162:(o,h)=>{l.jb("Cast",o,{to:h})},870220:o=>{l.jb("Add",o,void 0)},870271:o=>{l.jb("Sub",o,void 0)},870322:o=>{l.jb("Mul",o,void 0)},870373:o=>{l.jb("Div",o,void 0)},870424:o=>{l.jb("Pow",o,void 0)},870475:o=>{l.jb("Equal",o,void 0)},870528:o=>{l.jb("Greater",o,void 0)},870583:o=>{l.jb("GreaterOrEqual",o,void 0)},870645:o=>{l.jb("Less",o,void 0)},870697:o=>{l.jb("LessOrEqual",o,void 0)},870756:(o,h,w,M,S)=>{l.jb("ReduceMean",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},870915:(o,h,w,M,S)=>{l.jb("ReduceMax",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871073:(o,h,w,M,S)=>{l.jb("ReduceMin",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871231:(o,h,w,M,S)=>{l.jb("ReduceProd",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871390:(o,h,w,M,S)=>{l.jb("ReduceSum",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871548:(o,h,w,M,S)=>{l.jb("ReduceL1",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871705:(o,h,w,M,S)=>{l.jb("ReduceL2",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871862:(o,h,w,M,S)=>{l.jb("ReduceLogSum",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},872023:(o,h,w,M,S)=>{l.jb("ReduceSumSquare",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},872187:(o,h,w,M,S)=>{l.jb("ReduceLogSumExp",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},872351:o=>{l.jb("Where",o,void 0)},872404:(o,h,w)=>{l.jb("Transpose",o,{perm:h?Array.from(s().subarray(h>>>0,w>>>0)):[]})},872512:(o,h,w,M)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:yn(w),format:M?"NHWC":"NCHW"})},872645:(o,h,w,M)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:yn(w),format:M?"NHWC":"NCHW"})},872778:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be,vr)=>{l.jb("ConvTranspose",o,{format:At?"NHWC":"NCHW",autoPad:h,dilations:[w],group:M,kernelShape:[S],pads:[ne,He],strides:[st],wIsConst:()=>!!r()[Rt>>>0],outputPadding:Zt?Array.from(s().subarray(Zt>>>0,Tr>>>0)):[],outputShape:Vr?Array.from(s().subarray(Vr>>>0,Be>>>0)):[],activation:yn(vr)})},873179:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be)=>{l.jb("ConvTranspose",o,{format:st?"NHWC":"NCHW",autoPad:h,dilations:Array.from(s().subarray(w>>>0,2+(w>>>0)>>>0)),group:M,kernelShape:Array.from(s().subarray(S>>>0,2+(S>>>0)>>>0)),pads:Array.from(s().subarray(ne>>>0,4+(ne>>>0)>>>0)),strides:Array.from(s().subarray(He>>>0,2+(He>>>0)>>>0)),wIsConst:()=>!!r()[At>>>0],outputPadding:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],outputShape:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[],activation:yn(Be)})},873744:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be,vr)=>{l.jb("ConvTranspose",o,{format:At?"NHWC":"NCHW",autoPad:h,dilations:[w],group:M,kernelShape:[S],pads:[ne,He],strides:[st],wIsConst:()=>!!r()[Rt>>>0],outputPadding:Zt?Array.from(s().subarray(Zt>>>0,Tr>>>0)):[],outputShape:Vr?Array.from(s().subarray(Vr>>>0,Be>>>0)):[],activation:yn(vr)})},874145:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be)=>{l.jb("ConvTranspose",o,{format:st?"NHWC":"NCHW",autoPad:h,dilations:Array.from(s().subarray(w>>>0,2+(w>>>0)>>>0)),group:M,kernelShape:Array.from(s().subarray(S>>>0,2+(S>>>0)>>>0)),pads:Array.from(s().subarray(ne>>>0,4+(ne>>>0)>>>0)),strides:Array.from(s().subarray(He>>>0,2+(He>>>0)>>>0)),wIsConst:()=>!!r()[At>>>0],outputPadding:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],outputShape:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[],activation:yn(Be)})},874710:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},874801:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:M,storage_order:S,dilations:ne?Array.from(s().subarray(ne>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,At>>>0)):[],pads:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],strides:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[]})},875216:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},875307:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:M,storage_order:S,dilations:ne?Array.from(s().subarray(ne>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,At>>>0)):[],pads:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],strides:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[]})},875722:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},875809:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:M,storage_order:S,dilations:ne?Array.from(s().subarray(ne>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,At>>>0)):[],pads:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],strides:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[]})},876220:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},876307:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:M,storage_order:S,dilations:ne?Array.from(s().subarray(ne>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,At>>>0)):[],pads:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],strides:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[]})},876718:(o,h,w,M,S)=>{l.jb("Gemm",o,{alpha:h,beta:w,transA:M,transB:S})},876822:o=>{l.jb("MatMul",o,void 0)},876876:(o,h,w,M)=>{l.jb("ArgMax",o,{keepDims:!!h,selectLastIndex:!!w,axis:M})},876984:(o,h,w,M)=>{l.jb("ArgMin",o,{keepDims:!!h,selectLastIndex:!!w,axis:M})},877092:(o,h)=>{l.jb("Softmax",o,{axis:h})},877155:(o,h)=>{l.jb("Concat",o,{axis:h})},877215:(o,h,w,M,S)=>{l.jb("Split",o,{axis:h,numOutputs:w,splitSizes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},877355:o=>{l.jb("Expand",o,void 0)},877409:(o,h)=>{l.jb("Gather",o,{axis:Number(h)})},877480:(o,h)=>{l.jb("GatherElements",o,{axis:Number(h)})},877559:(o,h,w,M,S,ne,He,st,At,Rt,Zt)=>{l.jb("Resize",o,{antialias:h,axes:w?Array.from(s().subarray(w>>>0,M>>>0)):[],coordinateTransformMode:yn(S),cubicCoeffA:ne,excludeOutside:He,extrapolationValue:st,keepAspectRatioPolicy:yn(At),mode:yn(Rt),nearestMode:yn(Zt)})},877905:(o,h,w,M,S,ne,He)=>{l.jb("Slice",o,{starts:h?Array.from(s().subarray(h>>>0,w>>>0)):[],ends:M?Array.from(s().subarray(M>>>0,S>>>0)):[],axes:ne?Array.from(s().subarray(ne>>>0,He>>>0)):[]})},878121:o=>{l.jb("Tile",o,void 0)},878173:(o,h,w)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:w?"NHWC":"NCHW"})},878287:(o,h,w)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:w?"NHWC":"NCHW"})},878401:o=>{l.jb("Range",o,void 0)},878454:(o,h)=>{l.jb("Einsum",o,{equation:yn(h)})},878535:(o,h,w,M,S)=>{l.jb("Pad",o,{mode:h,value:w,pads:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},878662:(o,h,w,M,S,ne)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:w,spatial:!!S,trainingMode:!!M,format:ne?"NHWC":"NCHW"})},878831:(o,h,w,M,S,ne)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:w,spatial:!!S,trainingMode:!!M,format:ne?"NHWC":"NCHW"})},879e3:(o,h,w)=>{l.jb("CumSum",o,{exclusive:Number(h),reverse:Number(w)})},879097:(o,h,w)=>{l.jb("DequantizeLinear",o,{axis:h,blockSize:w})},879187:(o,h,w,M,S,ne,He,st,At)=>{l.jb("Attention",o,{numHeads:h,isUnidirectional:w,maskFilterValue:M,scale:S,doRotary:ne,qkvHiddenSizes:He?Array.from(s().subarray(Number(st)>>>0,Number(st)+He>>>0)):[],pastPresentShareBuffer:!!At})},879459:o=>{l.jb("BiasAdd",o,void 0)},879514:o=>{l.jb("BiasSplitGelu",o,void 0)},879575:o=>{l.jb("FastGelu",o,void 0)},879631:(o,h,w,M,S,ne,He,st,At,Rt,Zt,Tr,Vr,Be,vr,rn)=>{l.jb("Conv",o,{format:Tr?"NHWC":"NCHW",auto_pad:h,dilations:w?Array.from(s().subarray(w>>>0,M>>>0)):[],group:S,kernel_shape:ne?Array.from(s().subarray(ne>>>0,He>>>0)):[],pads:st?Array.from(s().subarray(st>>>0,At>>>0)):[],strides:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],w_is_const:()=>!!r()[Vr>>>0],activation:yn(Be),activation_params:vr?Array.from(d().subarray(vr>>>0,rn>>>0)):[]})},880127:o=>{l.jb("Gelu",o,void 0)},880179:(o,h,w,M,S,ne,He,st,At)=>{l.jb("GroupQueryAttention",o,{numHeads:h,kvNumHeads:w,scale:M,softcap:S,doRotary:ne,rotaryInterleaved:He,smoothSoftmax:st,localWindowSize:At})},880396:(o,h,w,M)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:w,simplified:!!M})},880507:(o,h,w,M)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:w,simplified:!!M})},880618:(o,h,w,M,S,ne)=>{l.jb("MatMulNBits",o,{k:h,n:w,accuracyLevel:M,bits:S,blockSize:ne})},880745:(o,h,w,M,S,ne)=>{l.jb("MultiHeadAttention",o,{numHeads:h,isUnidirectional:w,maskFilterValue:M,scale:S,doRotary:ne})},880904:(o,h)=>{l.jb("QuickGelu",o,{alpha:h})},880968:(o,h,w,M,S)=>{l.jb("RotaryEmbedding",o,{interleaved:!!h,numHeads:w,rotaryEmbeddingDim:M,scale:S})},881107:(o,h,w)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!w})},881209:(o,h,w)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!w})},881311:(o,h,w,M)=>{l.jb("GatherBlockQuantized",o,{gatherAxis:h,quantizeAxis:w,blockSize:M})},881432:o=>{l.Zb(o)},881466:(o,h)=>l.bc(o,h,l.Fb.fc,l.Fb.errors)};function Xf(o,h,w){return qh(async()=>{await l.Xb(o,h,w)})}function Qf(){return typeof wasmOffsetConverter<"u"}function Gc(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var qc=o=>{o.terminate(),o.onmessage=()=>{}},hh=o=>{qs.length==0&&(yh(),wh(qs[0]));var h=qs.pop();if(!h)return 6;bi.push(h),ds[o.Ab]=h,h.Ab=o.Ab;var w={cmd:"run",start_routine:o.hc,arg:o.Qb,pthread_ptr:o.Ab};return h.postMessage(w,o.mc),0},yi=0,Zr=(o,h,...w)=>{for(var M=2*w.length,S=cp(),ne=dp(8*M),He=ne>>>3,st=0;st>>0]=At)}return o=gf(o,0,M,ne,h),_c(S),o};function Hc(o){if(z)return Zr(0,1,o);if(Gt=o,!(0{if(Gt=o,z)throw fh(o),"unwind";Hc(o)},qs=[],bi=[],mh=[],ds={},_h=o=>{var h=o.Ab;delete ds[h],qs.push(o),bi.splice(bi.indexOf(o),1),o.Ab=0,up(h)};function gh(){mh.forEach(o=>o())}var wh=o=>new Promise(h=>{o.onmessage=S=>{var ne=(S=S.data).cmd;if(S.targetThread&&S.targetThread!=io()){var He=ds[S.targetThread];He?He.postMessage(S,S.transferList):Ht(`Internal error! Worker sent a message "${ne}" to target pthread ${S.targetThread}, but that thread no longer exists!`)}else ne==="checkMailbox"?ac():ne==="spawnThread"?hh(S):ne==="cleanupThread"?_h(ds[S.thread]):ne==="killThread"?(S=S.thread,ne=ds[S],delete ds[S],qc(ne),up(S),bi.splice(bi.indexOf(ne),1),ne.Ab=0):ne==="cancelThread"?ds[S.thread].postMessage({cmd:"cancel"}):ne==="loaded"?(o.loaded=!0,h(o)):ne==="alert"?alert(`Thread ${S.threadId}: ${S.text}`):S.target==="setimmediate"?o.postMessage(S):ne==="callHandler"?l[S.handler](...S.args):ne&&Ht(`worker sent an unknown command ${ne}`)},o.onerror=S=>{throw Ht(`worker sent an error! ${S.filename}:${S.lineno}: ${S.message}`),S};var w,M=[];for(w of[])l.hasOwnProperty(w)&&M.push(w);o.postMessage({cmd:"load",handlers:M,wasmMemory:hr,wasmModule:Ir})});function yh(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});qs.push(o)}var ic=o=>{for(;0{var o=io(),h=u()[o+52>>>2>>>0];o=u()[o+56>>>2>>>0],yf(h,h-o),_c(h)},Zf=(o,h)=>{yi=0,o=bf(o,h),0>>=0);throw h>>>=0,w>>>=0,u()[M.Jb+16>>>2>>>0]=0,u()[M.Jb+4>>>2>>>0]=h,u()[M.Jb+8>>>2>>>0]=w,o}function bh(o,h,w,M){return z?Zr(2,1,o,h,w,M):Mh(o,h,w,M)}function Mh(o,h,w,M){if(o>>>=0,h>>>=0,w>>>=0,M>>>=0,U===void 0)return Ht("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var S=[];return z&&S.length===0?bh(o,h,w,M):(o={hc:w,Ab:o,Qb:M,mc:S},z?(o.Mb="spawnThread",postMessage(o,S),0):hh(o))}var vh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,xh=(o,h,w)=>{var M=(h>>>=0)+w;for(w=h;o[w]&&!(w>=M);)++w;if(16(S=(240&S)==224?(15&S)<<12|ne<<6|He:(7&S)<<18|ne<<12|He<<6|63&o[h++])?M+=String.fromCharCode(S):(S-=65536,M+=String.fromCharCode(55296|S>>10,56320|1023&S))}}else M+=String.fromCharCode(S)}return M},yn=(o,h)=>(o>>>=0)?xh(n(),o,h):"";function Th(o,h,w){return z?Zr(3,1,o,h,w):0}function Ch(o,h){if(z)return Zr(4,1,o,h)}var Xc=o=>{for(var h=0,w=0;w=M?h++:2047>=M?h+=2:55296<=M&&57343>=M?(h+=4,++w):h+=3}return h},$h=(o,h,w,M)=>{if(!(0>>=0;M=w+M-1;for(var ne=0;ne=He&&(He=65536+((1023&He)<<10)|1023&o.charCodeAt(++ne)),127>=He){if(w>=M)break;h[w++>>>0]=He}else{if(2047>=He){if(w+1>=M)break;h[w++>>>0]=192|He>>6}else{if(65535>=He){if(w+2>=M)break;h[w++>>>0]=224|He>>12}else{if(w+3>=M)break;h[w++>>>0]=240|He>>18,h[w++>>>0]=128|He>>12&63}h[w++>>>0]=128|He>>6&63}h[w++>>>0]=128|63&He}}return h[w>>>0]=0,w-S},no=(o,h,w)=>$h(o,n(),h,w);function Eh(o,h){if(z)return Zr(5,1,o,h)}function kh(o,h,w){if(z)return Zr(6,1,o,h,w)}function Sh(o,h,w){return z?Zr(7,1,o,h,w):0}function Ph(o,h){if(z)return Zr(8,1,o,h)}function Ah(o,h,w){if(z)return Zr(9,1,o,h,w)}function Ih(o,h,w,M){if(z)return Zr(10,1,o,h,w,M)}function Fh(o,h,w,M){if(z)return Zr(11,1,o,h,w,M)}function Oh(o,h,w,M){if(z)return Zr(12,1,o,h,w,M)}function zh(o){if(z)return Zr(13,1,o)}function Dh(o,h){if(z)return Zr(14,1,o,h)}function Lh(o,h,w){if(z)return Zr(15,1,o,h,w)}var Bh,Hs,tm=()=>{ro("")},cs=o=>{for(var h="";n()[o>>>0];)h+=Bh[n()[o++>>>0]];return h},Qc={},Yc={};function Ts(o,h,w={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(M,S,ne={}){var He=S.name;if(!M)throw new Hs(`type "${He}" must have a positive integer typeid pointer`);if(Yc.hasOwnProperty(M)){if(ne.Sb)return;throw new Hs(`Cannot register type '${He}' twice`)}Yc[M]=S,Qc.hasOwnProperty(M)&&(S=Qc[M],delete Qc[M],S.forEach(st=>st()))}(o,h,w)}var Rh=(o,h,w)=>{switch(h){case 1:return w?M=>r()[M>>>0]:M=>n()[M>>>0];case 2:return w?M=>i()[M>>>1>>>0]:M=>a()[M>>>1>>>0];case 4:return w?M=>s()[M>>>2>>>0]:M=>u()[M>>>2>>>0];case 8:return w?M=>an[M>>>3]:M=>Ws[M>>>3];default:throw new TypeError(`invalid integer width (${h}): ${o}`)}};function rm(o,h,w){w>>>=0,Ts(o>>>=0,{name:h=cs(h>>>0),fromWireType:M=>M,toWireType:function(M,S){if(typeof S!="bigint"&&typeof S!="number")throw S=S===null?"null":(M=typeof S)=="object"||M==="array"||M==="function"?S.toString():""+S,new TypeError(`Cannot convert "${S}" to ${this.name}`);return typeof S=="number"&&(S=BigInt(S)),S},argPackAdvance:Ks,readValueFromPointer:Rh(h,w,h.indexOf("u")==-1),Db:null})}var Ks=8;function nm(o,h,w,M){Ts(o>>>=0,{name:h=cs(h>>>0),fromWireType:function(S){return!!S},toWireType:function(S,ne){return ne?w:M},argPackAdvance:Ks,readValueFromPointer:function(S){return this.fromWireType(n()[S>>>0])},Db:null})}var Zc=[],Cs=[];function Jc(o){9<(o>>>=0)&&--Cs[o+1]==0&&(Cs[o]=void 0,Zc.push(o))}var Wn=o=>{if(!o)throw new Hs("Cannot use deleted val. handle = "+o);return Cs[o]},Gn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=Zc.pop()||Cs.length;return Cs[h]=o,Cs[h+1]=1,h}};function ep(o){return this.fromWireType(u()[o>>>2>>>0])}var sm={name:"emscripten::val",fromWireType:o=>{var h=Wn(o);return Jc(o),h},toWireType:(o,h)=>Gn(h),argPackAdvance:Ks,readValueFromPointer:ep,Db:null};function im(o){return Ts(o>>>0,sm)}var am=(o,h)=>{switch(h){case 4:return function(w){return this.fromWireType(d()[w>>>2>>>0])};case 8:return function(w){return this.fromWireType(c()[w>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${o}`)}};function om(o,h,w){w>>>=0,Ts(o>>>=0,{name:h=cs(h>>>0),fromWireType:M=>M,toWireType:(M,S)=>S,argPackAdvance:Ks,readValueFromPointer:am(h,w),Db:null})}function lm(o,h,w,M,S){if(o>>>=0,w>>>=0,h=cs(h>>>0),S===-1&&(S=4294967295),S=st=>st,M===0){var ne=32-8*w;S=st=>st<>>ne}var He=h.includes("unsigned")?function(st,At){return At>>>0}:function(st,At){return At};Ts(o,{name:h,fromWireType:S,toWireType:He,argPackAdvance:Ks,readValueFromPointer:Rh(h,w,M!==0),Db:null})}function um(o,h,w){function M(ne){var He=u()[ne>>>2>>>0];return ne=u()[ne+4>>>2>>>0],new S(r().buffer,ne,He)}var S=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];Ts(o>>>=0,{name:w=cs(w>>>0),fromWireType:M,argPackAdvance:Ks,readValueFromPointer:M},{Sb:!0})}function dm(o,h){o>>>=0;var w=(h=cs(h>>>0))==="std::string";Ts(o,{name:h,fromWireType:function(M){var S=u()[M>>>2>>>0],ne=M+4;if(w)for(var He=ne,st=0;st<=S;++st){var At=ne+st;if(st==S||n()[At>>>0]==0){if(He=yn(He,At-He),Rt===void 0)var Rt=He;else Rt+="\0",Rt+=He;He=At+1}}else{for(Rt=Array(S),st=0;st>>0]);Rt=Rt.join("")}return hs(M),Rt},toWireType:function(M,S){S instanceof ArrayBuffer&&(S=new Uint8Array(S));var ne=typeof S=="string";if(!(ne||S instanceof Uint8Array||S instanceof Uint8ClampedArray||S instanceof Int8Array))throw new Hs("Cannot pass non-string to std::string");var He=w&&ne?Xc(S):S.length,st=fc(4+He+1),At=st+4;if(u()[st>>>2>>>0]=He,w&&ne)no(S,At,He+1);else if(ne)for(ne=0;ne>>0]=Rt}else for(ne=0;ne>>0]=S[ne];return M!==null&&M.push(hs,st),st},argPackAdvance:Ks,readValueFromPointer:ep,Db(M){hs(M)}})}var Nh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,cm=(o,h)=>{for(var w=o>>1,M=w+h/2;!(w>=M)&&a()[w>>>0];)++w;if(32<(w<<=1)-o&&Nh)return Nh.decode(n().slice(o,w));for(w="",M=0;!(M>=h/2);++M){var S=i()[o+2*M>>>1>>>0];if(S==0)break;w+=String.fromCharCode(S)}return w},pm=(o,h,w)=>{if(w??(w=2147483647),2>w)return 0;var M=h;w=(w-=2)<2*o.length?w/2:o.length;for(var S=0;S>>1>>>0]=ne,h+=2}return i()[h>>>1>>>0]=0,h-M},hm=o=>2*o.length,fm=(o,h)=>{for(var w=0,M="";!(w>=h/4);){var S=s()[o+4*w>>>2>>>0];if(S==0)break;++w,65536<=S?(S-=65536,M+=String.fromCharCode(55296|S>>10,56320|1023&S)):M+=String.fromCharCode(S)}return M},mm=(o,h,w)=>{if(h>>>=0,w??(w=2147483647),4>w)return 0;var M=h;w=M+w-4;for(var S=0;S=ne&&(ne=65536+((1023&ne)<<10)|1023&o.charCodeAt(++S)),s()[h>>>2>>>0]=ne,(h+=4)+4>w)break}return s()[h>>>2>>>0]=0,h-M},_m=o=>{for(var h=0,w=0;w=M&&++w,h+=4}return h};function gm(o,h,w){if(o>>>=0,h>>>=0,w=cs(w>>>=0),h===2)var M=cm,S=pm,ne=hm,He=st=>a()[st>>>1>>>0];else h===4&&(M=fm,S=mm,ne=_m,He=st=>u()[st>>>2>>>0]);Ts(o,{name:w,fromWireType:st=>{for(var At,Rt=u()[st>>>2>>>0],Zt=st+4,Tr=0;Tr<=Rt;++Tr){var Vr=st+4+Tr*h;Tr!=Rt&&He(Vr)!=0||(Zt=M(Zt,Vr-Zt),At===void 0?At=Zt:(At+="\0",At+=Zt),Zt=Vr+h)}return hs(st),At},toWireType:(st,At)=>{if(typeof At!="string")throw new Hs(`Cannot pass non-string to C++ string type ${w}`);var Rt=ne(At),Zt=fc(4+Rt+h);return u()[Zt>>>2>>>0]=Rt/h,S(At,Zt+4,Rt+h),st!==null&&st.push(hs,Zt),Zt},argPackAdvance:Ks,readValueFromPointer:ep,Db(st){hs(st)}})}function wm(o,h){Ts(o>>>=0,{Tb:!0,name:h=cs(h>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var ym=()=>1;function bm(o){lp(o>>>0,!C,1,!x,131072,!1),gh()}var jh=o=>{if(!Sn)try{if(o(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(s(),o>>>2,o).value.then(ac),o+=128,Atomics.store(s(),o>>>2,1))}var ac=()=>{var o=io();o&&(tp(o),jh(wf))};function Mm(o,h){(o>>>=0)==h>>>0?setTimeout(ac):z?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=ds[o])&&o.postMessage({cmd:"checkMailbox"})}var rp=[];function vm(o,h,w,M,S){for(h>>>=0,M/=2,rp.length=M,w=S>>>0>>>3,S=0;S>>0];return(h?Wc[h]:c_[o])(...rp)}function xm(o){o>>>=0,z?postMessage({cmd:"cleanupThread",thread:o}):_h(ds[o])}function Tm(o){}var np=(o,h)=>{var w=Yc[o];if(w===void 0)throw o=ff(o),w=cs(o),hs(o),new Hs(`${h} has unknown type ${w}`);return w},Vh=(o,h,w)=>{var M=[];return o=o.toWireType(M,w),M.length&&(u()[h>>>2>>>0]=Gn(M)),o};function Cm(o,h,w){return h>>>=0,w>>>=0,o=Wn(o>>>0),h=np(h,"emval::as"),Vh(h,w,o)}var oc=o=>{try{o()}catch(h){ro(h)}},Xs=0,ps=null,Uh=0,lc=[],Wh={},Gh={},$m=0,sp=null,Em=[];function qh(o){return function(h){if(!Sn){if(Xs===0){var w=!1,M=!1;h((S=0)=>{if(!Sn&&(Uh=S,w=!0,M)){Xs=2,oc(()=>xf(ps)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),S=!1;try{var ne=function(){var At=s()[ps+8>>>2>>>0];return At=Xt[Gh[At]],--yi,At()}()}catch(At){ne=At,S=!0}var He=!1;if(!ps){var st=sp;st&&(sp=null,(S?st.reject:st.resolve)(ne),He=!0)}if(S&&!He)throw ne}}),M=!0,w||(Xs=1,ps=function(){var S=fc(65548),ne=S+12;u()[S>>>2>>>0]=ne,u()[S+4>>>2>>>0]=ne+65536,ne=lc[0];var He=Wh[ne];return He===void 0&&(He=$m++,Wh[ne]=He,Gh[He]=ne),ne=He,s()[S+8>>>2>>>0]=ne,S}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),oc(()=>Mf(ps)))}else Xs===2?(Xs=0,oc(Tf),hs(ps),ps=null,Em.forEach(jh)):ro(`invalid state: ${Xs}`);return Uh}}(h=>{o().then(h)})}function km(o){return o>>>=0,qh(()=>(o=Wn(o)).then(Gn))}var uc=[];function Sm(o,h,w,M){return w>>>=0,M>>>=0,(o=uc[o>>>0])(null,h=Wn(h>>>0),w,M)}var Pm={},dc=o=>{var h=Pm[o];return h===void 0?cs(o):h};function Am(o,h,w,M,S){return w>>>=0,M>>>=0,S>>>=0,(o=uc[o>>>0])(h=Wn(h>>>0),h[w=dc(w)],M,S)}var Hh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Im(o){return(o>>>=0)==0?Gn(Hh()):(o=dc(o),Gn(Hh()[o]))}var Fm=o=>{var h=uc.length;return uc.push(o),h},Om=(o,h)=>{for(var w=Array(o),M=0;M>>2>>>0],"parameter "+M);return w},Kh=(o,h)=>Object.defineProperty(h,"name",{value:o});function zm(o,h,w){var M=(h=Om(o,h>>>0)).shift();o--;var S=`return function (obj, func, destructorsRef, args) { `,ne=0,He=[];w===0&&He.push("obj");for(var st=["retType"],At=[M],Rt=0;RtZt.name).join(", ")}) => ${M.name}>`,Fm(Kh(w,o))}function Dm(o){return o=dc(o>>>0),Gn(l[o])}function Lm(o,h){return h>>>=0,o=Wn(o>>>0),h=Wn(h),Gn(o[h])}function Bm(o){9<(o>>>=0)&&(Cs[o+1]+=1)}function Rm(){return Gn([])}function Nm(o){o=Wn(o>>>0);for(var h=Array(o.length),w=0;w>>0))}function Vm(){return Gn({})}function Um(o){for(var h=Wn(o>>>=0);h.length;){var w=h.pop();h.pop()(w)}Jc(o)}function Wm(o,h,w){h>>>=0,w>>>=0,o=Wn(o>>>0),h=Wn(h),w=Wn(w),o[h]=w}function Gm(o,h){return h>>>=0,o=(o=np(o>>>0,"_emval_take_value")).readValueFromPointer(h),Gn(o)}function qm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),s()[h>>>2>>>0]=o.getUTCSeconds(),s()[h+4>>>2>>>0]=o.getUTCMinutes(),s()[h+8>>>2>>>0]=o.getUTCHours(),s()[h+12>>>2>>>0]=o.getUTCDate(),s()[h+16>>>2>>>0]=o.getUTCMonth(),s()[h+20>>>2>>>0]=o.getUTCFullYear()-1900,s()[h+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,s()[h+28>>>2>>>0]=o}var so=o=>o%4==0&&(o%100!=0||o%400==0),Xh=[0,31,60,91,121,152,182,213,244,274,305,335],Qh=[0,31,59,90,120,151,181,212,243,273,304,334];function Hm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),s()[h>>>2>>>0]=o.getSeconds(),s()[h+4>>>2>>>0]=o.getMinutes(),s()[h+8>>>2>>>0]=o.getHours(),s()[h+12>>>2>>>0]=o.getDate(),s()[h+16>>>2>>>0]=o.getMonth(),s()[h+20>>>2>>>0]=o.getFullYear()-1900,s()[h+24>>>2>>>0]=o.getDay();var w=(so(o.getFullYear())?Xh:Qh)[o.getMonth()]+o.getDate()-1|0;s()[h+28>>>2>>>0]=w,s()[h+36>>>2>>>0]=-60*o.getTimezoneOffset(),w=new Date(o.getFullYear(),6,1).getTimezoneOffset();var M=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(w!=M&&o.getTimezoneOffset()==Math.min(M,w)),s()[h+32>>>2>>>0]=o}function Km(o){o>>>=0;var h=new Date(s()[o+20>>>2>>>0]+1900,s()[o+16>>>2>>>0],s()[o+12>>>2>>>0],s()[o+8>>>2>>>0],s()[o+4>>>2>>>0],s()[o>>>2>>>0],0),w=s()[o+32>>>2>>>0],M=h.getTimezoneOffset(),S=new Date(h.getFullYear(),6,1).getTimezoneOffset(),ne=new Date(h.getFullYear(),0,1).getTimezoneOffset(),He=Math.min(ne,S);return 0>w?s()[o+32>>>2>>>0]=+(S!=ne&&He==M):0>>2>>>0]=h.getDay(),w=(so(h.getFullYear())?Xh:Qh)[h.getMonth()]+h.getDate()-1|0,s()[o+28>>>2>>>0]=w,s()[o>>>2>>>0]=h.getSeconds(),s()[o+4>>>2>>>0]=h.getMinutes(),s()[o+8>>>2>>>0]=h.getHours(),s()[o+12>>>2>>>0]=h.getDate(),s()[o+16>>>2>>>0]=h.getMonth(),s()[o+20>>>2>>>0]=h.getYear(),o=h.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Yh(o,h,w,M,S,ne,He){return z?Zr(16,1,o,h,w,M,S,ne,He):-52}function Zh(o,h,w,M,S,ne){if(z)return Zr(17,1,o,h,w,M,S,ne)}function Xm(o,h,w,M){o>>>=0,h>>>=0,w>>>=0,M>>>=0;var S=new Date().getFullYear(),ne=new Date(S,0,1),He=new Date(S,6,1);S=ne.getTimezoneOffset();var st=He.getTimezoneOffset(),At=Math.max(S,st);u()[o>>>2>>>0]=60*At,s()[h>>>2>>>0]=+(S!=st),ne=(o=Rt=>Rt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ne),He=o(He),st{ip.length=0;for(var w;w=n()[o++>>>0];){var M=w!=105;h+=(M&=w!=112)&&h%8?4:0,ip.push(w==112?u()[h>>>2>>>0]:w==106?an[h>>>3]:w==105?s()[h>>>2>>>0]:c()[h>>>3>>>0]),h+=M?8:4}return ip};function Qm(o,h,w){return o>>>=0,h=Jh(h>>>0,w>>>0),Wc[o](...h)}function Ym(o,h,w){return o>>>=0,h=Jh(h>>>0,w>>>0),Wc[o](...h)}var Zm=()=>{},Jm=()=>Date.now();function e_(o,h){return Ht(yn(o>>>0,h>>>0))}var ef,t_=()=>{throw yi+=1,"unwind"};function r_(){return 4294901760}ef=()=>performance.timeOrigin+performance.now();var n_=()=>navigator.hardwareConcurrency;function s_(){return ro("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function i_(o){o>>>=0;var h=n().length;if(o<=h||4294901760=w;w*=2){var M=h*(1+.2/w);M=Math.min(M,o+100663296);var S=Math;M=Math.max(o,M);e:{S=(S.min.call(S,4294901760,M+(65536-M%65536)%65536)-hr.buffer.byteLength+65535)/65536;try{hr.grow(S),mn();var ne=1;break e}catch{}ne=void 0}if(ne)return!0}return!1}var cc=()=>(ro("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),yd={},tf=o=>{o.forEach(h=>{cc()})};function a_(){var o=Error().stack.toString().split(` `);return o[0]=="Error"&&o.shift(),tf(o),yd.Pb=cc(),yd.ec=o,yd.Pb}function o_(o,h,w){if(o>>>=0,h>>>=0,yd.Pb==o)var M=yd.ec;else(M=Error().stack.toString().split(` `))[0]=="Error"&&M.shift(),tf(M);for(var S=3;M[S]&&cc()!=o;)++S;for(o=0;o>>2>>>0]=cc();return o}var ap,op={},rf=()=>{if(!ap){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",_:ke};for(o in op)op[o]===void 0?delete h[o]:h[o]=op[o];var w=[];for(o in h)w.push(`${o}=${h[o]}`);ap=w}return ap};function nf(o,h){if(z)return Zr(18,1,o,h);o>>>=0,h>>>=0;var w=0;return rf().forEach((M,S)=>{var ne=h+w;for(S=u()[o+4*S>>>2>>>0]=ne,ne=0;ne>>0]=M.charCodeAt(ne);r()[S>>>0]=0,w+=M.length+1}),0}function sf(o,h){if(z)return Zr(19,1,o,h);o>>>=0,h>>>=0;var w=rf();u()[o>>>2>>>0]=w.length;var M=0;return w.forEach(S=>M+=S.length+1),u()[h>>>2>>>0]=M,0}function af(o){return z?Zr(20,1,o):52}function of(o,h,w,M){return z?Zr(21,1,o,h,w,M):52}function lf(o,h,w,M){return z?Zr(22,1,o,h,w,M):70}var l_=[null,[],[]];function uf(o,h,w,M){if(z)return Zr(23,1,o,h,w,M);h>>>=0,w>>>=0,M>>>=0;for(var S=0,ne=0;ne>>2>>>0],st=u()[h+4>>>2>>>0];h+=8;for(var At=0;At>>0],Zt=l_[o];Rt===0||Rt===10?((o===1?nr:Ht)(xh(Zt,0)),Zt.length=0):Zt.push(Rt)}S+=st}return u()[M>>>2>>>0]=S,0}var df=[31,29,31,30,31,30,31,31,30,31,30,31],cf=[31,28,31,30,31,30,31,31,30,31,30,31],u_=(o,h)=>{r().set(o,h>>>0)};function pf(o,h,w,M){function S(Be,vr,rn){for(Be=typeof Be=="number"?Be.toString():Be||"";Be.length$f?-1:0<$f?1:0}var Mi;return(Mi=rn(Be.getFullYear()-vr.getFullYear()))===0&&(Mi=rn(Be.getMonth()-vr.getMonth()))===0&&(Mi=rn(Be.getDate()-vr.getDate())),Mi}function st(Be){switch(Be.getDay()){case 0:return new Date(Be.getFullYear()-1,11,29);case 1:return Be;case 2:return new Date(Be.getFullYear(),0,3);case 3:return new Date(Be.getFullYear(),0,2);case 4:return new Date(Be.getFullYear(),0,1);case 5:return new Date(Be.getFullYear()-1,11,31);case 6:return new Date(Be.getFullYear()-1,11,30)}}function At(Be){var vr=Be.Bb;for(Be=new Date(new Date(Be.Cb+1900,0,1).getTime());0Mi-Be.getDate())){Be.setDate(Be.getDate()+vr);break}vr-=Mi-Be.getDate()+1,Be.setDate(1),11>rn?Be.setMonth(rn+1):(Be.setMonth(0),Be.setFullYear(Be.getFullYear()+1))}return rn=new Date(Be.getFullYear()+1,0,4),vr=st(new Date(Be.getFullYear(),0,4)),rn=st(rn),0>=He(vr,Be)?0>=He(rn,Be)?Be.getFullYear()+1:Be.getFullYear():Be.getFullYear()-1}o>>>=0,h>>>=0,w>>>=0,M>>>=0;var Rt=u()[M+40>>>2>>>0];for(var Zt in M={kc:s()[M>>>2>>>0],jc:s()[M+4>>>2>>>0],Hb:s()[M+8>>>2>>>0],Lb:s()[M+12>>>2>>>0],Ib:s()[M+16>>>2>>>0],Cb:s()[M+20>>>2>>>0],ub:s()[M+24>>>2>>>0],Bb:s()[M+28>>>2>>>0],sc:s()[M+32>>>2>>>0],ic:s()[M+36>>>2>>>0],lc:Rt?yn(Rt):""},w=yn(w),Rt={"%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"})w=w.replace(new RegExp(Zt,"g"),Rt[Zt]);var Tr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Vr="January February March April May June July August September October November December".split(" ");for(Zt in Rt={"%a":Be=>Tr[Be.ub].substring(0,3),"%A":Be=>Tr[Be.ub],"%b":Be=>Vr[Be.Ib].substring(0,3),"%B":Be=>Vr[Be.Ib],"%C":Be=>ne((Be.Cb+1900)/100|0,2),"%d":Be=>ne(Be.Lb,2),"%e":Be=>S(Be.Lb,2," "),"%g":Be=>At(Be).toString().substring(2),"%G":At,"%H":Be=>ne(Be.Hb,2),"%I":Be=>((Be=Be.Hb)==0?Be=12:12{for(var vr=0,rn=0;rn<=Be.Ib-1;vr+=(so(Be.Cb+1900)?df:cf)[rn++]);return ne(Be.Lb+vr,3)},"%m":Be=>ne(Be.Ib+1,2),"%M":Be=>ne(Be.jc,2),"%n":()=>` `,"%p":Be=>0<=Be.Hb&&12>Be.Hb?"AM":"PM","%S":Be=>ne(Be.kc,2),"%t":()=>" ","%u":Be=>Be.ub||7,"%U":Be=>ne(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&&((rn=(Be.ub+371-Be.Bb)%7)==4||rn==3&&so(Be.Cb)||(vr=1));else{vr=52;var rn=(Be.ub+7-Be.Bb-1)%7;(rn==4||rn==5&&so(Be.Cb%400-1))&&vr++}return ne(vr,2)},"%w":Be=>Be.ub,"%W":Be=>ne(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.ic);return Be=Math.abs(Be)/60,(vr?"+":"-")+("0000"+(Be/60*100+Be%60)).slice(-4)},"%Z":Be=>Be.lc,"%%":()=>"%"},w=w.replace(/%%/g,"\0\0"),Rt)w.includes(Zt)&&(w=w.replace(new RegExp(Zt,"g"),Rt[Zt](M)));return Zt=function(Be){var vr=Array(Xc(Be)+1);return $h(Be,vr,0,vr.length),vr}(w=w.replace(/\0\0/g,"%")),Zt.length>h?0:(u_(Zt,o),Zt.length-1)}function d_(o,h,w,M){return pf(o>>>0,h>>>0,w>>>0,M>>>0)}z||function(){for(var o=l.numThreads-1;o--;)yh();wi.unshift(()=>{Un++,function(h){z?h():Promise.all(qs.map(wh)).then(h)}(()=>sc())})}();for(var hf=Array(256),pc=0;256>pc;++pc)hf[pc]=String.fromCharCode(pc);Bh=hf,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"}},Cs.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>Cs.length/2-5-Zc.length;var c_=[Hc,fh,bh,Th,Ch,Eh,kh,Sh,Ph,Ah,Ih,Fh,Oh,zh,Dh,Lh,Yh,Zh,nf,sf,af,of,lf,uf],Xt=function(){function o(w,M){return Xt=w.exports,Xt=function(){var S=Xt,ne={};for(let[He,st]of Object.entries(S))ne[He]=typeof st=="function"?(...At)=>{lc.push(He);try{return st(...At)}finally{Sn||(lc.pop(),ps&&Xs===1&&lc.length===0&&(Xs=0,yi+=1,oc(vf),typeof Fibers<"u"&&Fibers.tc()))}}:st;return ne}(),Xt=function(){var S=Xt,ne=st=>At=>st(At)>>>0,He=st=>()=>st()>>>0;return(S=Object.assign({},S)).Ca=ne(S.Ca),S.fb=He(S.fb),S.hb=ne(S.hb),S.emscripten_main_runtime_thread_id=He(S.emscripten_main_runtime_thread_id),S.sb=ne(S.sb),S.tb=He(S.tb),S}(),mh.push(Xt.ib),cn.unshift(Xt.Ba),Ir=M,sc(),Xt}var h=ph();if(Un++,l.instantiateWasm)try{return l.instantiateWasm(h,o)}catch(w){Ht(`Module.instantiateWasm callback failed with error: ${w}`),m(w)}return Uc||(Uc=l.locateFile?lh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ye):Ye+"ort-wasm-simd-threaded.jsep.wasm":new URL(V("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),V.b).href),function(w,M){var S=Uc;return It||typeof WebAssembly.instantiateStreaming!="function"||lh(S)||uh(S)||typeof fetch!="function"?ch(S,w,M):fetch(S,{credentials:"same-origin"}).then(ne=>WebAssembly.instantiateStreaming(ne,w).then(M,function(He){return Ht(`wasm streaming compile failed: ${He}`),Ht("falling back to ArrayBuffer instantiation"),ch(S,w,M)}))}(h,function(w){o(w.instance,w.module)}).catch(m),{}}(),ff=o=>(ff=Xt.Ca)(o),mf=()=>(mf=Xt.Da)();l._OrtInit=(o,h)=>(l._OrtInit=Xt.Ea)(o,h),l._OrtGetLastError=(o,h)=>(l._OrtGetLastError=Xt.Fa)(o,h),l._OrtCreateSessionOptions=(o,h,w,M,S,ne,He,st,At,Rt)=>(l._OrtCreateSessionOptions=Xt.Ga)(o,h,w,M,S,ne,He,st,At,Rt),l._OrtAppendExecutionProvider=(o,h)=>(l._OrtAppendExecutionProvider=Xt.Ha)(o,h),l._OrtAddFreeDimensionOverride=(o,h,w)=>(l._OrtAddFreeDimensionOverride=Xt.Ia)(o,h,w),l._OrtAddSessionConfigEntry=(o,h,w)=>(l._OrtAddSessionConfigEntry=Xt.Ja)(o,h,w),l._OrtReleaseSessionOptions=o=>(l._OrtReleaseSessionOptions=Xt.Ka)(o),l._OrtCreateSession=(o,h,w)=>(l._OrtCreateSession=Xt.La)(o,h,w),l._OrtReleaseSession=o=>(l._OrtReleaseSession=Xt.Ma)(o),l._OrtGetInputOutputCount=(o,h,w)=>(l._OrtGetInputOutputCount=Xt.Na)(o,h,w),l._OrtGetInputName=(o,h)=>(l._OrtGetInputName=Xt.Oa)(o,h),l._OrtGetOutputName=(o,h)=>(l._OrtGetOutputName=Xt.Pa)(o,h),l._OrtFree=o=>(l._OrtFree=Xt.Qa)(o),l._OrtCreateTensor=(o,h,w,M,S,ne)=>(l._OrtCreateTensor=Xt.Ra)(o,h,w,M,S,ne),l._OrtGetTensorData=(o,h,w,M,S)=>(l._OrtGetTensorData=Xt.Sa)(o,h,w,M,S),l._OrtReleaseTensor=o=>(l._OrtReleaseTensor=Xt.Ta)(o),l._OrtCreateRunOptions=(o,h,w,M)=>(l._OrtCreateRunOptions=Xt.Ua)(o,h,w,M),l._OrtAddRunConfigEntry=(o,h,w)=>(l._OrtAddRunConfigEntry=Xt.Va)(o,h,w),l._OrtReleaseRunOptions=o=>(l._OrtReleaseRunOptions=Xt.Wa)(o),l._OrtCreateBinding=o=>(l._OrtCreateBinding=Xt.Xa)(o),l._OrtBindInput=(o,h,w)=>(l._OrtBindInput=Xt.Ya)(o,h,w),l._OrtBindOutput=(o,h,w,M)=>(l._OrtBindOutput=Xt.Za)(o,h,w,M),l._OrtClearBoundOutputs=o=>(l._OrtClearBoundOutputs=Xt._a)(o),l._OrtReleaseBinding=o=>(l._OrtReleaseBinding=Xt.$a)(o),l._OrtRunWithBinding=(o,h,w,M,S)=>(l._OrtRunWithBinding=Xt.ab)(o,h,w,M,S),l._OrtRun=(o,h,w,M,S,ne,He,st)=>(l._OrtRun=Xt.bb)(o,h,w,M,S,ne,He,st),l._OrtEndProfiling=o=>(l._OrtEndProfiling=Xt.cb)(o),l._JsepOutput=(o,h,w)=>(l._JsepOutput=Xt.db)(o,h,w),l._JsepGetNodeName=o=>(l._JsepGetNodeName=Xt.eb)(o);var hc,io=()=>(io=Xt.fb)(),hs=l._free=o=>(hs=l._free=Xt.gb)(o),fc=l._malloc=o=>(fc=l._malloc=Xt.hb)(o),lp=(o,h,w,M,S,ne)=>(lp=Xt.kb)(o,h,w,M,S,ne),_f=()=>(_f=Xt.lb)(),gf=(o,h,w,M,S)=>(gf=Xt.mb)(o,h,w,M,S),up=o=>(up=Xt.nb)(o),mc=o=>(mc=Xt.ob)(o),wf=()=>(wf=Xt.pb)(),yf=(o,h)=>(yf=Xt.qb)(o,h),_c=o=>(_c=Xt.rb)(o),dp=o=>(dp=Xt.sb)(o),cp=()=>(cp=Xt.tb)(),bf=l.dynCall_ii=(o,h)=>(bf=l.dynCall_ii=Xt.vb)(o,h),Mf=o=>(Mf=Xt.wb)(o),vf=()=>(vf=Xt.xb)(),xf=o=>(xf=Xt.yb)(o),Tf=()=>(Tf=Xt.zb)();function Cf(){0cp(),l.stackRestore=o=>_c(o),l.stackAlloc=o=>dp(o),l.UTF8ToString=yn,l.stringToUTF8=no,l.lengthBytesUTF8=Xc,Gs=function o(){hc||Cf(),hc||(Gs=o)},Cf(),T}),Ie=ge,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&ge()}),Ne,tt,wt,mt,Ct,ft,Lt,jt,Ft=L(()=>{var e,t;dr(),Ne=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),tt=typeof location>"u"?void 0:location.origin,wt=(r,n)=>{try{let i=n??Ne;return(i?new URL(r,i):new URL(r)).origin===tt}catch{return!1}},mt=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Ct=(bn(),B(Cr)).default,ft=async()=>{if(!Ne)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(wt(Ne))return[void 0,Ct()];let r=await mt(Ne);return[r,Ct(r)]},Lt=(Se(),B(at)).default,jt=async(r,n,i)=>[void 0,Lt]}),Fe,Oe,ct,Ut,sr,br,Nr,mr,kr=L(()=>{Ft(),Oe=!1,ct=!1,Ut=!1,sr=()=>{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}},br=()=>{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}},Nr=async e=>{if(Oe)return Promise.resolve();if(ct)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ut)throw new Error("previous call to 'initializeWebAssembly()' failed.");ct=!0;let t=e.initTimeout,r=e.numThreads;if(!br())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=sr();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 i=e.wasmPaths,a=typeof i=="string"?i:void 0,s=i==null?void 0:i.mjs,u=(s==null?void 0:s.href)??s,d=i==null?void 0:i.wasm,c=(d==null?void 0:d.href)??d,g=e.wasmBinary,[m,l]=await jt(u,a,r>1),T=!1,x=[];if(t>0&&x.push(new Promise(C=>{setTimeout(()=>{T=!0,C()},t)})),x.push(new Promise((C,z)=>{let U={numThreads:r};g?U.wasmBinary=g:(c||a)&&(U.locateFile=(A,ee)=>c??(a??ee)+A),l(U).then(A=>{ct=!1,Oe=!0,Fe=A,C(),m&&URL.revokeObjectURL(m)},A=>{ct=!1,Ut=!0,z(A)})})),await Promise.race(x),T)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},mr=()=>{if(Oe&&Fe)return Fe;throw new Error("WebAssembly is not initialized yet.")}}),gr,$n,Ur,fs=L(()=>{kr(),gr=(e,t)=>{let r=mr(),n=r.lengthBytesUTF8(e)+1,i=r._malloc(n);return r.stringToUTF8(e,i,n),t.push(i),i},$n=(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(([i,a])=>{let s=t?t+i:i;if(typeof a=="object")$n(a,s+".",r,n);else if(typeof a=="string"||typeof a=="number")n(s,a.toString());else if(typeof a=="boolean")n(s,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Ur=e=>{let t=mr(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let i=t.HEAP32[n/4],a=t.HEAPU32[n/4+1],s=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${s}`)}finally{t.stackRestore(r)}}}),$s,qn=L(()=>{kr(),fs(),$s=e=>{let t=mr(),r=0,n=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.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)i.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&&(i.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=gr(e.tag,n)),r=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),r===0&&Ur("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&$n(e.extra,"",new WeakSet,(s,u)=>{let d=gr(s,n),c=gr(u,n);t._OrtAddRunConfigEntry(r,d,c)!==0&&Ur(`Can't set a run config entry: ${s} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(s=>t._free(s)),a}}}),Es,ks,Ss,Ps,As,ns=L(()=>{kr(),fs(),Es=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}`)}},ks=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ss=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)},Ps=(e,t,r)=>{for(let n of t){let i=typeof n=="string"?n:n.name;switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let s=n==null?void 0:n.deviceType;if(s){let u=gr("deviceType",r),d=gr(s,r);mr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Ur(`Can't set a session config entry: 'deviceType' - ${s}.`)}}break;case"webgpu":if(i="JS",typeof n!="string"){let s=n;if(s!=null&&s.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let u=gr("preferredLayout",r),d=gr(s.preferredLayout,r);mr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Ur(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=gr(i,r);mr()._OrtAppendExecutionProvider(e,a)!==0&&Ur(`Can't append execution provider: ${i}.`)}},As=e=>{let t=mr(),r=0,n=[],i=e||{};Ss(i);try{let a=Es(i.graphOptimizationLevel??"all"),s=ks(i.executionMode??"sequential"),u=typeof i.logId=="string"?gr(i.logId,n):0,d=i.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let g=typeof i.optimizedModelFilePath=="string"?gr(i.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,s,!!i.enableProfiling,0,u,d,c,g),r===0&&Ur("Can't create session options."),i.executionProviders&&Ps(r,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let m=gr("enableGraphCapture",n),l=gr(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,m,l)!==0&&Ur(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[m,l]of Object.entries(i.freeDimensionOverrides)){if(typeof m!="string")throw new Error(`free dimension override name must be a string: ${m}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let T=gr(m,n);t._OrtAddFreeDimensionOverride(r,T,l)!==0&&Ur(`Can't set a free dimension override: ${m} - ${l}.`)}return i.extra!==void 0&&$n(i.extra,"",new WeakSet,(m,l)=>{let T=gr(m,n),x=gr(l,n);t._OrtAddSessionConfigEntry(r,T,x)!==0&&Ur(`Can't set a session config entry: ${m} - ${l}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(s=>t._free(s)),a}}}),Hn,An,Rn,ms,Ln,_s,gs,ws,Yt=L(()=>{Hn=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}`)}},An=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}`)}},Rn=(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((i,a)=>i*a,1);return r>0?Math.ceil(n*r):void 0},ms=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}`)}},Ln=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}`)}},_s=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",gs=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool",ws=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),ss,Is=L(()=>{dr(),ss=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 i=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 s=0;for(;;){let{done:u,value:d}=await i.read();if(u)break;let c=d.byteLength;new Uint8Array(a,s,c).set(d),s+=c}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Fs,ys,Os,zs,is,Ds,ae,_=L(()=>{Yt(),Fs=["V","I","W","E","F"],ys=(e,t)=>{console.log(`[${Fs[e]},${new Date().toISOString()}]${t}`)},is=(e,t)=>{Os=e,zs=t},Ds=(e,t)=>{let r=Ln(e),n=Ln(Os);r>=n&&ys(r,typeof t=="function"?t():t)},ae=(...e)=>{zs&&Ds(...e)}}),I,Q=L(()=>{Yt(),I=(e,t)=>new(ms(t))(e)}),oe=L(()=>{}),_e,Ge,gt,$t,Tt,Ot,er,Sr,ur,Wr=L(()=>{_(),oe(),_e=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]]),Ge=[],gt=e=>Math.ceil(e/16)*16,$t=e=>{for(let t=0;tTt++,er=async(e,t,r,n)=>{let i=gt(r),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=e.getCommandEncoder();e.endComputePass(),s.copyBufferToBuffer(t,0,a,0,i),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()}},Sr=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of _e)Ge.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let r=t.buffer,n=t.byteOffset,i=t.byteLength,a=gt(i),s=this.storageCache.get(e);if(!s)throw new Error("gpu data for uploading does not exist");if(s.originalSize!==i)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${i}`);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,i)),u.unmap();let c=this.backend.getCommandEncoder();this.backend.endComputePass(),c.copyBufferToBuffer(u,0,s.gpuData.buffer,0,a),ae("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 i=gt(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,i)}registerExternalBuffer(e,t,r){let n;if(r){if(n=r[0],e===r[1])return ae("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else n=Ot();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),ae("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),ae("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=$t(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let u=(i?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 s={id:Ot(),type:0,buffer:n};return this.storageCache.set(s.id,{gpuData:s,originalSize:e}),ae("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${s.id}`),s}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){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return ae("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 er(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=_e.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(ae("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ur=(...e)=>new Sr(...e)}),en,or,Pr=L(()=>{en=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}},or=e=>new en(e)}),_n,Mn,$e,tn,ln,In,Nn,Kt=L(()=>{_n=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Mn=class{static calcShape(e,t,r=!1){let n=e.length,i=t.length;if(n===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),s=new Array(a);if(r){if(n<2||i<2)return;let u=_n.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(u===void 0)return;[s[a-2],s[a-1]]=u}for(let u=r?3:1;u<=a;u++){let d=n-u<0?1:e[n-u],c=i-u<0?1:t[i-u];if(d!==c&&d>1&&c>1)return;let g=Math.max(d,c);if(d&&c)s[a-u]=Math.max(d,c);else{if(g>1)return;s[a-u]=0}}return s}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let i=1;i<=r;i++)if(e[r-i]!==1&&e[r-i]!==t[n-i])return!1;return!0}},$e=class gc{static size(t){return gc.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let i=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){i[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");i[a]=1,r/=t[a],a--}for(a--;a>=0;a--)i[a]=t[a];return i}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 gc.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 gc.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let i=1;for(let a=r;a=0;--i)n[i]=n[i+1]*t[i+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((i,a)=>i+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,i)=>n===r[i])}},tn=class bd{static adjustPoolAttributes(t,r,n,i,a,s){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]||s[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,i,a,s,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(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{Yt(),Kt(),pn=64,Xr=(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}`)}},fr=(e,t=1)=>{let r=Xr(e,t);return typeof r=="string"?r:r[0]},Fr=(e,t=1)=>{let r=Xr(e,t);return typeof r=="string"?r:r[1]},Et=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:$e.computeStrides(r)})}),t},_r=e=>e%4===0?4:e%2===0?2:1,as=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Kn=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,jn=(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,Wt=(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,Ys=(e,t,r,n,i)=>{let a=typeof r=="number",s=a?r:r.length,u=[...new Array(s).keys()],d=s<2?"u32":s<=4?`vec${s}`:`array`,c=Xr(t,i),g=typeof c=="string"?c:c[1],m=typeof c=="string"?c:c[0],l={indices:d,value:g,storage:m,tensor:t},T=qe=>typeof qe=="string"?qe:`${qe}u`,x={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},C=a?"uniforms.":"",z=`${C}${e}_shape`,U=`${C}${e}_strides`,A="";for(let qe=0;qe ${l.indices} { var indices: ${l.indices}; var current = offset; ${A} return indices; }`,te=qe=>(x.offsetToIndices=!0,s<2?qe:`o2i_${e}(${qe})`),ie=[];if(s>=2)for(let qe=s-1;qe>=0;qe--)ie.push(`${Wt(U,qe,s)} * (indices[${qe}])`);let ke=s<2?"":` fn i2o_${e}(indices: ${l.indices}) -> u32 { return ${ie.join("+")}; }`,Pe=qe=>(x.indicesToOffset=!0,s<2?qe:`i2o_${e}(${qe})`),Ye=(...qe)=>s===0?"0u":`${l.indices}(${qe.map(T).join(",")})`,It=(qe,vt)=>s<2?`${qe}`:`${Wt(qe,vt,s)}`,Bt=(qe,vt,rr)=>s<2?`${qe}=${rr};`:`${Wt(qe,vt,s)}=${rr};`,ar={},nr=(qe,vt)=>{x.broadcastedIndicesToOffset=!0;let rr=`${vt.name}broadcastedIndicesTo${e}Offset`;if(rr in ar)return`${rr}(${qe})`;let Br=[];for(let sn=s-1;sn>=0;sn--){let an=vt.indicesGet("outputIndices",sn+vt.rank-s);Br.push(`${It(U,sn)} * (${an} % ${It(z,sn)})`)}return ar[rr]=`fn ${rr}(outputIndices: ${vt.type.indices}) -> u32 { return ${Br.length>0?Br.join("+"):"0u"}; }`,`${rr}(${qe})`},Ht=(qe,vt)=>(()=>{if(l.storage===l.value)return`${e}[${qe}]=${vt};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${qe}]=vec2(u32(${vt}), select(0u, 0xFFFFFFFFu, ${vt} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${qe}]=vec2(u32(${vt}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${qe}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${vt}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Er=qe=>(()=>{if(l.storage===l.value)return`${e}[${qe}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${qe}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${qe}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${qe}] & 0xFFu), bool(${e}[${qe}] & 0xFF00u), bool(${e}[${qe}] & 0xFF0000u), bool(${e}[${qe}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),jr=s<2?"":` fn get_${e}ByIndices(indices: ${l.indices}) -> ${g} { return ${Er(`i2o_${e}(indices)`)}; }`,hr=s<2?"":(()=>{let qe=u.map(rr=>`d${rr}: u32`).join(", "),vt=u.map(rr=>`d${rr}`).join(", ");return` fn get_${e}(${qe}) -> ${g} { return get_${e}ByIndices(${Ye(vt)}); }`})(),Ir=(...qe)=>{if(qe.length!==s)throw new Error(`indices length must be ${s}`);let vt=qe.map(T).join(",");return s===0?Er("0u"):s===1?Er(vt[0]):(x.get=!0,x.getByIndices=!0,x.indicesToOffset=!0,`get_${e}(${vt})`)},Gt=qe=>s<2?Er(qe):(x.getByIndices=!0,x.indicesToOffset=!0,`get_${e}ByIndices(${qe})`),Qt=s<2?"":` fn set_${e}ByIndices(indices: ${l.indices}, value: ${g}) { ${Ht(`i2o_${e}(indices)`,"value")} }`,xr=s<2?"":(()=>{let qe=u.map(rr=>`d${rr}: u32`).join(", "),vt=u.map(rr=>`d${rr}`).join(", ");return` fn set_${e}(${qe}, value: ${g}) { set_${e}ByIndices(${Ye(vt)}, value); }`})();return{impl:()=>{let qe=[],vt=!1;return x.offsetToIndices&&(qe.push(ee),vt=!0),x.indicesToOffset&&(qe.push(ke),vt=!0),x.broadcastedIndicesToOffset&&(Object.values(ar).forEach(rr=>qe.push(rr)),vt=!0),x.set&&(qe.push(xr),vt=!0),x.setByIndices&&(qe.push(Qt),vt=!0),x.get&&(qe.push(hr),vt=!0),x.getByIndices&&(qe.push(jr),vt=!0),!a&&vt&&qe.unshift(`const ${z} = ${l.indices}(${r.join(",")});`,`const ${U} = ${l.indices}(${$e.computeStrides(r).join(",")});`),qe.join(` `)},type:l,offsetToIndices:te,indicesToOffset:Pe,broadcastedIndicesToOffset:nr,indices:Ye,indicesGet:It,indicesSet:Bt,set:(...qe)=>{if(qe.length!==s+1)throw new Error(`indices length must be ${s}`);let vt=qe[s];if(typeof vt!="string")throw new Error("value must be string");let rr=qe.slice(0,s).map(T).join(",");return s===0?Ht("0u",vt):s===1?Ht(rr[0],vt):(x.set=!0,x.setByIndices=!0,x.indicesToOffset=!0,`set_${e}(${rr}, ${vt})`)},setByOffset:Ht,setByIndices:(qe,vt)=>s<2?Ht(qe,vt):(x.setByIndices=!0,x.indicesToOffset=!0,`set_${e}ByIndices(${qe}, ${vt});`),get:Ir,getByOffset:Er,getByIndices:Gt,usage:n,name:e,strides:U,shape:z,rank:s}},Qe=(e,t,r,n=1)=>Ys(e,t,r,"input",n),qt=(e,t,r,n=1)=>Ys(e,t,r,"output",n),xi=(e,t,r,n=1)=>Ys(e,t,r,"internal",n),Ti=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=pn){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 i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,s=i?`let global_idx = global_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) fn main(${a}) { ${s} `}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 i=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${i}`)}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])}},oo=(e,t)=>new Ti(e,t),bs=(e,t)=>{let r=e.length,n=[];for(let i=0;i1&&s===1&&n.unshift(a)}return n}}),lo,Ci,os,uo,Md,xn,vd,co,Vn=L(()=>{Yt(),Kt(),Pr(),pr(),lo=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Ci=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,os=(e,t)=>$e.sortBasedOnPerm(e,Ci(e.length,t)),uo=(e,t,r,n)=>{let i=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`;for(let a=0;a{let r=[],n=[];for(let i=0;i{let r=e.dataType,n=e.dims.length,i=Ci(n,t),a=os(e.dims,i),{newShape:s,newPerm:u}=Md(e.dims,i),d=$e.areEqual(u,[2,3,1]),c=$e.areEqual(u,[3,1,2]),g=s.length===2&&u[0]>u[1]||d||c,m=g?s:e.dims,l=a;g&&(m=d?[s[0],s[1]*s[2]]:c?[s[0]*s[1],s[2]]:s,l=[m[1],m[0]]);let T=Qe("a",r,m.length),x=qt("output",r,l.length),C=16,z;return g?z=U=>` ${U.registerUniform("output_size","u32").declareVariables(T,x)} var tile : array, ${C}>; ${U.mainStart([C,C,1])} let stride = (uniforms.output_shape[1] - 1) / ${C} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${C}u + local_id.x; let input_row = workgroup_id_x * ${C}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${T.getByIndices(`${T.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${C}u + local_id.x; let output_row = workgroup_id_y * ${C}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${x.setByIndices(`${x.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`:z=U=>` ${U.registerUniform("output_size","u32").declareVariables(T,x)} ${uo(i,n,T,x)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${x.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${x.setByOffset("global_idx",T.getByIndices("aIndices"))} }`,{name:g?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let U=$e.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:g?{x:Math.ceil(l[1]/C),y:Math.ceil(l[0]/C)}:{x:Math.ceil(U/64)},programUniforms:[{type:12,data:U},...Et(m,l)]}},getShaderSource:z}},vd=(e,t)=>{lo(e.inputs),e.compute(xn(e.inputs[0],t.perm))},co=e=>or({perm:e.perm})}),po,ho,fo,mo,_o,$i,go,wo,Ei,yo,Fn,ki,bo,Mo,Si,vo,xo,Pi,To,Co,Ai,xd=L(()=>{Yt(),Kt(),pr(),ji(),Vn(),po={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"},ho={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"},fo={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},mo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},_o=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,i]},go=(e,t)=>{let r=e.length+t.length,n=[],i=0;for(let a=0;a{for(let r=0;r{let r=[];if(!wo(e,t)){for(let n=0;nr.push(n))}return r},yo=(e,t,r,n,i,a,s)=>{let u=r[0].dims,d=$e.size(a),c=$e.size(s),g=Qe("_A",r[0].dataType,u),m=qt("output",i,a),l=32,T=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:x=>` ${x.registerUniform("reduceSize","u32").declareVariables(g,m)} ${T} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${x.mainStart(l)} let outputIndex = global_idx / ${l}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${fo[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${l}) { let candidate = f32(${g.getByOffset("offset + k")}); bestValue = ${po[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 = ${ho[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${m.setByOffset("outputIndex",`${n==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${mo[n]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:d},programUniforms:[{type:12,data:c}]})}},Fn=(e,t,r,n)=>{let i=e.inputs.length===1?r:Fi(e.inputs,r),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((T,x)=>x));let s=$e.normalizeAxes(a,e.inputs[0].dims.length),u=s,d=e.inputs[0],c=Ei(u,e.inputs[0].dims.length);c.length>0&&(d=e.compute(xn(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],u=_o(u.length,d.dims.length));let[g,m]=$i(d.dims,u),l=g;i.keepDims&&(l=go(g,s)),e.compute(yo(t,{hint:i.cacheKey,inputDependencies:["type"]},[d],n,e.inputs[0].dataType,l,m),{inputs:[d]})},ki=(e,t)=>{Fn(e,"ReduceMeanShared",t,"mean")},bo=(e,t)=>{Fn(e,"ReduceL1Shared",t,"l1")},Mo=(e,t)=>{Fn(e,"ReduceL2Shared",t,"l2")},Si=(e,t)=>{Fn(e,"ReduceLogSumExpShared",t,"logSumExp")},vo=(e,t)=>{Fn(e,"ReduceMaxShared",t,"max")},xo=(e,t)=>{Fn(e,"ReduceMinShared",t,"min")},Pi=(e,t)=>{Fn(e,"ReduceProdShared",t,"prod")},To=(e,t)=>{Fn(e,"ReduceSumShared",t,"sum")},Co=(e,t)=>{Fn(e,"ReduceSumSquareShared",t,"sumSquare")},Ai=(e,t)=>{Fn(e,"ReduceLogSumShared",t,"logSum")}}),On,Ii,Zs,Fi,En,$o,Eo,Oi,ko,So,zi,Po,Ao,Di,Io,zn,Li,Fo,Oo,Bi,zo,Do,Ri,Lo,Bo,Ni,ji=L(()=>{Yt(),Kt(),Pr(),pr(),xd(),On=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.")},Ii=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Zs=(e,t,r,n,i,a,s=!1,u=!1)=>{let d=[],c=r[0].dims,g=c.length,m=$e.normalizeAxes(i,g),l=!u&&m.length===0;c.forEach((C,z)=>{l||m.indexOf(z)>=0?s&&d.push(1):d.push(C)});let T=d.length,x=$e.size(d);return{name:e,shaderCache:t,getShaderSource:C=>{let z=[],U=Qe("_A",r[0].dataType,g),A=qt("output",a,T),ee=n(U,A,m),te=ee[2];for(let ie=0,ke=0;ie=0?(s&&ke++,te=`for(var j${ie}: u32 = 0; j${ie} < ${c[ie]}; j${ie}++) { ${ee[2].includes("last_index")?`let last_index = j${ie};`:""} ${U.indicesSet("input_indices",ie,`j${ie}`)} ${te} }`):(z.push(`${U.indicesSet("input_indices",ie,A.indicesGet("output_indices",ke))};`),ke++);return` ${C.registerUniform("output_size","u32").declareVariables(U,A)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${U.type.indices}; let output_indices = ${A.offsetToIndices("global_idx")}; ${z.join(` `)} ${ee[0]} // init ops for reduce max/min ${ee[1]} ${te} ${ee[3]} ${ee.length===4?A.setByOffset("global_idx","value"):ee.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:d,dataType:a}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:[{type:12,data:x},...Et(c,d)]})}},Fi=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),or({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},En=(e,t,r,n)=>{let i=e.inputs,a=i.length===1?r:Fi(i,r);e.compute(Zs(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?Ii:n,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},$o=(e,t)=>{On(e.inputs),En(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Eo=(e,t)=>{On(e.inputs),En(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Oi=(e,t)=>{On(e.inputs),En(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);"])},ko=(e,t)=>{On(e.inputs),En(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},So=(e,t)=>{On(e.inputs),En(e,"ReduceMax",t,(r,n,i)=>{let a=[];for(let s=0;s=0||i.length===0)&&a.push(r.indicesSet("input_indices",s,0));return[`${a.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},zi=(e,t)=>{On(e.inputs),En(e,"ReduceMean",t,(r,n,i)=>{let a=1;for(let s=0;s=0||i.length===0)&&(a*=e.inputs[0].dims[s]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Po=(e,t)=>{On(e.inputs),En(e,"ReduceMin",t,(r,n,i)=>{let a=[];for(let s=0;s=0||i.length===0)&&a.push(`input_indices[${s}] = 0;`);return[`${a.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},Ao=(e,t)=>{On(e.inputs),En(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Di=(e,t)=>{On(e.inputs),En(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Io=(e,t)=>{On(e.inputs),En(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;`,""])},zn=(e,t,r)=>{if(t.length===0)return r;let n=1,i=1;for(let a=0;a1024},Li=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zi(e,t):ki(e,t)},Fo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Eo(e,t):bo(e,t)},Oo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Oi(e,t):Mo(e,t)},Bi=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ko(e,t):Si(e,t)},zo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?So(e,t):vo(e,t)},Do=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Po(e,t):xo(e,t)},Ri=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ao(e,t):Pi(e,t)},Lo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Di(e,t):To(e,t)},Bo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Io(e,t):Co(e,t)},Ni=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$o(e,t):Ai(e,t)}}),Vi,Ui,Ro,Wi,No=L(()=>{Yt(),Pr(),ji(),Vi=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.")},Ui=(e,t)=>{Vi(e.inputs);let r=(n,i,a)=>{let s=[];for(let u=0;u=0||a.length===0)&&s.push(`input_indices[${u}] = 0;`);return[`${s.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); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Zs("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Ro=(e,t)=>{Vi(e.inputs);let r=(n,i,a)=>{let s=[];for(let u=0;u=0||a.length===0)&&s.push(`input_indices[${u}] = 0;`);return[`${s.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); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Zs("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Wi=e=>or(e)}),jo,Js,Gi,Vo,Uo,Ms,Wo,Go,ei=L(()=>{Yt(),Kt(),oe(),pr(),jo=(e,t)=>{let r=e[0],n=e[1],i=e[2],a=e[3],s=e[4],u=e[5];if(s&&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],c=r.dims[1],g=r.dims[2];if(i.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]!==g)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let m=i.dims[0]/3,l=m,T=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ee of t.qkvHiddenSizes)if(ee%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");m=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],T=t.qkvHiddenSizes[2]}let x=c;if(m!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==m+l+T)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let C=0;if(s){if(l!==T)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(s.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(s.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(C=s.dims[3])}let z=x+C,U=-1,A=0;if(a)throw new Error("Mask not supported");if(s)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]!==c||u.dims[3]!==z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:c,pastSequenceLength:C,kvSequenceLength:x,totalSequenceLength:z,maxSequenceLength:U,inputHiddenSize:g,hiddenSize:m,vHiddenSize:T,headSize:Math.floor(m/t.numHeads),vHeadSize:Math.floor(T/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:A,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Js=(e,t,r)=>t&&e?` let total_sequence_length_input = u32(${t.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; var past_sequence_length: u32 = 0; if (is_first_prompt == false) { past_sequence_length = total_sequence_length - sequence_length; } `:` ${r?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; `,Gi=(e,t,r,n,i,a,s,u)=>{let d=_r(s?1:a),c=64,g=a/d;g{let A=qt("x",e.dataType,e.dims,d),ee=[A],te=s?Qe("seq_lens",s.dataType,s.dims):void 0;te&&ee.push(te);let ie=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;ie&&ee.push(ie);let ke=Fr(e.dataType),Pe=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${U.registerUniforms(Pe).declareVariables(...ee)} ${U.mainStart([c,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; ${Js(te,ie,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${s?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; var thread_max_vector = ${x}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${x}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(d){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: ${d}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${c}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${x}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${x}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(d){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: ${d}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${c}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${A.type.value}(${ke}(1.0) / ${ke}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${x}(x[offset + i]); x[offset + i] = ${A.type.value}(exp(f32input - max_value) / sum); } } ${s?` for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${A.type.value}(${ke}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${T};${d}`,inputDependencies:C},getShaderSource:z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/c),y:i,z:t*r},programUniforms:l})}},Vo=(e,t,r,n,i,a,s,u,d)=>{let c=s+a.kvSequenceLength,g=[a.batchSize,a.numHeads,a.sequenceLength,c],m=e>1&&n,l=a.kvNumHeads?a.kvNumHeads:a.numHeads,T=m?[a.batchSize,l,c,a.headSize]:void 0,x=a.nReps?a.nReps:1,C=a.scale===0?1/Math.sqrt(a.headSize):a.scale,z=_r(a.headSize),U=a.headSize/z,A=12,ee={x:Math.ceil(c/A),y:Math.ceil(a.sequenceLength/A),z:a.batchSize*a.numHeads},te=[{type:12,data:a.sequenceLength},{type:12,data:U},{type:12,data:c},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:C},{type:12,data:s},{type:12,data:a.kvSequenceLength},{type:12,data:x}],ie=m&&n&&$e.size(n.dims)>0,ke=["type","type"];ie&&ke.push("type"),i&&ke.push("type"),u&&ke.push("type"),d&&ke.push("type");let Pe=[{dims:g,dataType:t.dataType,gpuDataType:0}];m&&Pe.push({dims:T,dataType:t.dataType,gpuDataType:0});let Ye=It=>{let Bt=Qe("q",t.dataType,t.dims,z),ar=Qe("key",r.dataType,r.dims,z),nr=[Bt,ar];if(ie){let Qt=Qe("past_key",n.dataType,n.dims,z);nr.push(Qt)}i&&nr.push(Qe("attention_bias",i.dataType,i.dims));let Ht=u?Qe("seq_lens",u.dataType,u.dims):void 0;Ht&&nr.push(Ht);let Er=d?Qe("total_sequence_length_input",d.dataType,d.dims):void 0;Er&&nr.push(Er);let jr=qt("output",t.dataType,g),hr=[jr];m&&hr.push(qt("present_key",t.dataType,T,z));let Ir=Fr(1,z),Gt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${A}u; var tileQ: array<${Bt.type.storage}, ${A*A}>; var tileK: array<${Bt.type.storage}, ${A*A}>; ${It.registerUniforms(Gt).declareVariables(...nr,...hr)} ${It.mainStart([A,A,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${x===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${x===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; ${Js(Ht,Er,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${ie&&m?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${m?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} var value = ${Ir}(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; ${ie&&m?` if (n + local_id.y < past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; }`:` if (n + local_id.y < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; }`} ${m?`if (n + local_id.y < present_sequence_length) { present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${Ir}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { let headOffset = workgroup_id.z * uniforms.M * uniforms.N; let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(z){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${z}`)}})()}; output[outputIdx] = ${jr.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${z};${i!==void 0};${n!==void 0};${e}`,inputDependencies:ke},getRunData:()=>({outputs:Pe,dispatchGroup:ee,programUniforms:te}),getShaderSource:Ye}},Uo=(e,t,r,n,i,a,s=void 0,u=void 0)=>{let d=a+i.kvSequenceLength,c=i.nReps?i.nReps:1,g=i.vHiddenSize*c,m=e>1&&n,l=i.kvNumHeads?i.kvNumHeads:i.numHeads,T=m?[i.batchSize,l,d,i.headSize]:void 0,x=[i.batchSize,i.sequenceLength,g],C=12,z={x:Math.ceil(i.vHeadSize/C),y:Math.ceil(i.sequenceLength/C),z:i.batchSize*i.numHeads},U=[{type:12,data:i.sequenceLength},{type:12,data:d},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:g},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:c}],A=m&&n&&$e.size(n.dims)>0,ee=["type","type"];A&&ee.push("type"),s&&ee.push("type"),u&&ee.push("type");let te=[{dims:x,dataType:t.dataType,gpuDataType:0}];m&&te.push({dims:T,dataType:t.dataType,gpuDataType:0});let ie=ke=>{let Pe=Qe("probs",t.dataType,t.dims),Ye=Qe("v",r.dataType,r.dims),It=[Pe,Ye];A&&It.push(Qe("past_value",n.dataType,n.dims));let Bt=s?Qe("seq_lens",s.dataType,s.dims):void 0;s&&It.push(Bt);let ar=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&It.push(ar);let nr=[qt("output",t.dataType,x)];m&&nr.push(qt("present_value",t.dataType,T));let Ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${C}u; var tileQ: array<${Pe.type.value}, ${C*C}>; var tileV: array<${Pe.type.value}, ${C*C}>; ${ke.registerUniforms(Ht).declareVariables(...It,...nr)} ${ke.mainStart([C,C,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; ${Js(Bt,ar,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${A&&m?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${m?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} var value = ${Pe.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; ${A&&m?` if (w + local_id.y < past_sequence_length) { tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; } `:` if (w + local_id.y < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; }`} ${m?` if (w + local_id.y < present_sequence_length) { present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + headIdx * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:ee},getRunData:()=>({outputs:te,dispatchGroup:z,programUniforms:U}),getShaderSource:ie}},Ms=(e,t,r,n,i,a,s,u,d,c,g=void 0,m=void 0)=>{let l=Math.min(e.outputCount,1+(s?1:0)+(u?1:0)),T=l>1?c.pastSequenceLength:0,x=T+c.kvSequenceLength,C=d&&$e.size(d.dims)>0?d:void 0,z=[t,r];l>1&&s&&$e.size(s.dims)>0&&z.push(s),C&&z.push(C),g&&z.push(g),m&&z.push(m);let U=e.compute(Vo(l,t,r,s,C,c,T,g,m),{inputs:z,outputs:l>1?[-1,1]:[-1]})[0];e.compute(Gi(U,c.batchSize,c.numHeads,T,c.sequenceLength,x,g,m),{inputs:g&&m?[U,g,m]:[U],outputs:[]});let A=[U,n];l>1&&u&&$e.size(u.dims)>0&&A.push(u),g&&A.push(g),m&&A.push(m),e.compute(Uo(l,U,n,u,c,T,g,m),{inputs:A,outputs:l>1?[0,2]:[0]})},Wo=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,s=12,u={x:Math.ceil(t.headSize/s),y:Math.ceil(t.sequenceLength/s),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:n},{type:12,data:i},{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}],g=m=>{let l=qt("output_q",d[0].dataType,r),T=qt("output_k",d[0].dataType,r),x=qt("output_v",d[0].dataType,r),C=Qe("input",d[0].dataType,d[0].dims),z=Qe("weight",d[1].dataType,d[1].dims),U=Qe("bias",d[2].dataType,d[2].dims),A=C.type.storage,ee=[{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 = ${s}u; var tileInput: array<${A}, ${s*s}>; var tileWeightQ: array<${A}, ${s*s}>; var tileWeightK: array<${A}, ${s*s}>; var tileWeightV: array<${A}, ${s*s}>; ${m.registerUniforms(ee).declareVariables(C,z,U,l,T,x)} ${m.mainStart([s,s,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 = ${A}(0); var valueK = ${A}(0); var valueV = ${A}(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:c}),getShaderSource:g},{inputs:d,outputs:[-1,-1,-1]})},Go=(e,t)=>{let r=jo(e.inputs,t),[n,i,a]=Wo(e,r);return Ms(e,n,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}}),qo,Ho,qi,Ko,Td=L(()=>{Pt(),Yt(),Kt(),Pr(),pr(),qo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,i,a)=>{let s=i.length;if(s!==n.length)throw new Error(`${a}: num dimensions != ${s}`);i.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")},Ho=(e,t)=>{let{epsilon:r,spatial:n,format:i}=t,a=e[0].dims,s=n?_r(a[a.length-1]):1,u=i==="NHWC"&&a.length>1?s:1,d=$e.size(a)/s,c=n,g=c?a.length:a,m=Qe("x",e[0].dataType,e[0].dims,s),l=Qe("scale",e[1].dataType,e[1].dims,u),T=Qe("bias",e[2].dataType,e[2].dims,u),x=Qe("inputMean",e[3].dataType,e[3].dims,u),C=Qe("inputVar",e[4].dataType,e[4].dims,u),z=qt("y",e[0].dataType,g,s),U=()=>{let ee="";if(n)ee=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${s}`:"outputIndices[1]"};`;else if(i==="NCHW")ee=` ${z.indicesSet("outputIndices","0","0")} let cOffset = ${z.indicesToOffset("outputIndices")};`;else{ee=`var cIndices = ${l.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let te=1;te` const epsilon = ${r}; ${ee.registerUniform("outputSize","u32").declareVariables(m,l,T,x,C,z)} ${ee.mainStart()} ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${z.offsetToIndices(`global_idx * ${s}`)}; ${U()} let scale = ${l.getByOffset("cOffset")}; let bias = ${T.getByOffset("cOffset")}; let inputMean = ${x.getByOffset("cOffset")}; let inputVar = ${C.getByOffset("cOffset")}; let x = ${m.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${z.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${s}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:A,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c?[{type:12,data:d},...Et(a)]:[{type:12,data:d}]})}},qi=e=>or(e),Ko=(e,t)=>{let{inputs:r,outputCount:n}=e,i=qi({...t,outputCount:n});if(E.webgpu.validateInputContent&&qo(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ho(r,i))}}),Hi,Xo,Qo,Cd=L(()=>{Kt(),pr(),Hi=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")},Xo=e=>{let t=e[0].dims,r=e[0].dims[2],n=$e.size(t)/4,i=e[0].dataType,a=Qe("input",i,t,4),s=Qe("bias",i,[r],4),u=Qe("residual",i,t,4),d=qt("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:c=>` const channels = ${r}u / 4; ${c.declareVariables(a,s,u,d)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${a.getByOffset("global_idx")} + ${s.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; ${d.setByOffset("global_idx","value")} }`}},Qo=e=>{Hi(e.inputs),e.compute(Xo(e.inputs))}}),Yo,Mr,Zo,Jo,el,tl,Ki,rl,nl,sl,il,Xi,al,ol,Qi,ll,Ls,Yi,ti,ul,Zi,dl,cl,Ji,pl,hl,ri,fl,ml,ea,ta,_l,ra,gl,wl,na,sa,ia,aa,yl,oa,bl,Ml,la,vl,ua=L(()=>{Yt(),Kt(),Pr(),pr(),Yo=(e,t,r,n,i,a,s)=>{let u=Math.ceil(t/4),d="";typeof i=="string"?d=`${i}(a)`:d=i("a");let c=Qe("inputData",r,[u],4),g=qt("outputData",n,[u],4),m=[{name:"vec_size",type:"u32"}];return s&&m.push(...s),` ${e.registerUniforms(m).declareVariables(c,g)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${c.getByOffset("global_idx")}; ${g.setByOffset("global_idx",d)} }`},Mr=(e,t,r,n,i,a=e.dataType,s,u)=>{let d=[{type:12,data:Math.ceil($e.size(e.dims)/4)}];return s&&d.push(...s),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:c=>Yo(c,$e.size(e.dims),e.dataType,a,r,n,u),getRunData:c=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil($e.size(c[0].dims)/64/4)},programUniforms:d})}},Zo=e=>{e.compute(Mr(e.inputs[0],"Abs","abs"))},Jo=e=>{e.compute(Mr(e.inputs[0],"Acos","acos"))},el=e=>{e.compute(Mr(e.inputs[0],"Acosh","acosh"))},tl=e=>{e.compute(Mr(e.inputs[0],"Asin","asin"))},Ki=e=>{e.compute(Mr(e.inputs[0],"Asinh","asinh"))},rl=e=>{e.compute(Mr(e.inputs[0],"Atan","atan"))},nl=e=>{e.compute(Mr(e.inputs[0],"Atanh","atanh"))},sl=e=>or(e),il=(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(Mr(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Xi=e=>{let t,r,n=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return or({min:t,max:r})},al=(e,t)=>{let r=t||Xi(e.inputs),n=Fr(e.inputs[0].dataType);e.compute(Mr(e.inputs[0],"Clip",i=>`clamp(${i}, 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]})},ol=e=>{e.compute(Mr(e.inputs[0],"Ceil","ceil"))},Qi=e=>{e.compute(Mr(e.inputs[0],"Cos","cos"))},ll=e=>{e.compute(Mr(e.inputs[0],"Cosh","cosh"))},Ls=e=>or(e),Yi=(e,t)=>{let r=Fr(e.inputs[0].dataType);e.compute(Mr(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))},ti=(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)); }`,ul=e=>{let t=Fr(e.inputs[0].dataType);e.compute(Mr(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,ti(t)))},Zi=e=>{e.compute(Mr(e.inputs[0],"Exp","exp"))},dl=e=>{e.compute(Mr(e.inputs[0],"Floor","floor"))},cl=e=>{let t=Fr(e.inputs[0].dataType);e.compute(Mr(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,ti(t)))},Ji=(e,t)=>{let r=Fr(e.inputs[0].dataType);e.compute(Mr(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},pl=e=>{e.compute(Mr(e.inputs[0],"Not",t=>`!${t}`))},hl=e=>{e.compute(Mr(e.inputs[0],"Neg",t=>`-${t}`))},ri=e=>{e.compute(Mr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},fl=e=>{let t=Fr(e.inputs[0].dataType);e.compute(Mr(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},ml=e=>{e.compute(Mr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ea=e=>or(e),ta=(e,t)=>{let r=Fr(e.inputs[0].dataType);e.compute(Mr(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))},_l=e=>{e.compute(Mr(e.inputs[0],"Sin","sin"))},ra=e=>{e.compute(Mr(e.inputs[0],"Sinh","sinh"))},gl=e=>{e.compute(Mr(e.inputs[0],"Sqrt","sqrt"))},wl=e=>{e.compute(Mr(e.inputs[0],"Tan","tan"))},na=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,sa=e=>{e.compute(Mr(e.inputs[0],"Tanh",na))},ia=(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 ${na("v")}; } `,aa=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,yl=e=>{let t=Fr(e.inputs[0].dataType);e.compute(Mr(e.inputs[0],"FastGelu",aa,ia(t),void 0,e.inputs[0].dataType))},oa=(e,t)=>{let r=Fr(e.inputs[0].dataType);return e.compute(Mr(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},bl=e=>{e.compute(Mr(e.inputs[0],"Log","log"))},Ml=(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; } `,la=e=>`quick_gelu_impl(${e})`,vl=(e,t)=>{let r=Fr(e.inputs[0].dataType);e.compute(Mr(e.inputs[0],"QuickGelu",la,Ml(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),da,xl,Tl,Cl=L(()=>{Kt(),pr(),ua(),da=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")},xl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Qe("input",e[0].dataType,e[0].dims,4),n=Qe("bias",e[0].dataType,[e[0].dims[2]],4),i=qt("output",e[0].dataType,t,4),a=$e.size(t)/4,s=fr(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,i)} ${ti(s)} ${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); ${i.setByOffset("global_idx","valueLeft * geluRight")} }`}},Tl=e=>{da(e.inputs),e.compute(xl(e.inputs))}}),$l,El,kn,kl,Sl,ca,Pl,Al,Il,Fl,ni,Ol,zl,$d=L(()=>{Yt(),Kt(),pr(),$l=(e,t,r,n,i,a,s,u,d,c,g,m)=>{let l,T;typeof u=="string"?l=T=(A,ee)=>`${u}((${A}),(${ee}))`:typeof u=="function"?l=T=u:(l=u.scalar,T=u.vector);let x=qt("outputData",g,n.length,4),C=Qe("aData",d,t.length,4),z=Qe("bData",c,r.length,4),U;if(i)if(a){let A=$e.size(t)===1,ee=$e.size(r)===1,te=t.length>0&&t[t.length-1]%4===0,ie=r.length>0&&r[r.length-1]%4===0;A||ee?U=x.setByOffset("global_idx",T(A?`${C.type.value}(${C.getByOffset("0")}.x)`:C.getByOffset("global_idx"),ee?`${z.type.value}(${z.getByOffset("0")}.x)`:z.getByOffset("global_idx"))):U=` let outputIndices = ${x.offsetToIndices("global_idx * 4u")}; let offsetA = ${C.broadcastedIndicesToOffset("outputIndices",x)}; let offsetB = ${z.broadcastedIndicesToOffset("outputIndices",x)}; ${x.setByOffset("global_idx",T(s||te?C.getByOffset("offsetA / 4u"):`${C.type.value}(${C.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||ie?z.getByOffset("offsetB / 4u"):`${z.type.value}(${z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else U=x.setByOffset("global_idx",T(C.getByOffset("global_idx"),z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let A=(ee,te,ie="")=>{let ke=`aData[indexA${te}][componentA${te}]`,Pe=`bData[indexB${te}][componentB${te}]`;return` let outputIndices${te} = ${x.offsetToIndices(`global_idx * 4u + ${te}u`)}; let offsetA${te} = ${C.broadcastedIndicesToOffset(`outputIndices${te}`,x)}; let offsetB${te} = ${z.broadcastedIndicesToOffset(`outputIndices${te}`,x)}; let indexA${te} = offsetA${te} / 4u; let indexB${te} = offsetB${te} / 4u; let componentA${te} = offsetA${te} % 4u; let componentB${te} = offsetB${te} % 4u; ${ee}[${te}] = ${ie}(${l(ke,Pe)}); `};g===9?U=` var data = vec4(0); ${A("data",0,"u32")} ${A("data",1,"u32")} ${A("data",2,"u32")} ${A("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:U=` ${A("outputData[global_idx]",0)} ${A("outputData[global_idx]",1)} ${A("outputData[global_idx]",2)} ${A("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(C,z,x)} ${m??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${U} }`},El=(e,t,r,n,i,a,s=r.dataType)=>{let u=!$e.areEqual(r.dims,n.dims),d=r.dims,c=$e.size(r.dims),g=!1,m=!1,l=[u];if(u){let T=Mn.calcShape(r.dims,n.dims,!1);if(!T)throw new Error("Can't perform binary op on the given tensors");d=T,c=$e.size(d);let x=$e.size(r.dims)===1,C=$e.size(n.dims)===1,z=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,U=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;l.push(x),l.push(C),l.push(z),l.push(U);let A=1;for(let ee=1;eeT.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:T=>$l(T,r.dims,n.dims,d,g,u,m,i,r.dataType,n.dataType,s,a),getRunData:()=>({outputs:[{dims:d,dataType:s}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil($e.size(d)/4)},...Et(r.dims,n.dims,d)]})}},kn=(e,t,r,n,i,a)=>{e.compute(El(t,i??"",e.inputs[0],e.inputs[1],r,n,a))},kl=e=>{kn(e,"Add",(t,r)=>`${t}+${r}`)},Sl=e=>{kn(e,"Div",(t,r)=>`${t}/${r}`)},ca=e=>{kn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Pl=e=>{kn(e,"Mul",(t,r)=>`${t}*${r}`)},Al=e=>{let t=Qe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;kn(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)); } `)},Il=e=>{kn(e,"Sub",(t,r)=>`${t}-${r}`)},Fl=e=>{kn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},ni=e=>{kn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Ol=e=>{kn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},zl=e=>{kn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),Dl,Ll,pa,Bl,Rl,ha,Ed=L(()=>{Yt(),Kt(),Pr(),pr(),Dl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],i=n.dataType,a=n.dims.length;e.forEach((s,u)=>{if(u!==r){if(s.dataType!==i)throw new Error("input tensors should be one type");if(s.dims.length!==a)throw new Error("input tensors should have the same shape");s.dims.forEach((d,c)=>{if(c!==t&&d!==n.dims[c])throw new Error("non concat dimensions must match")})}})},Ll=(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; }`,pa=(e,t)=>{let r=e.length,n=[];for(let i=0;i{let i=$e.size(r),a=new Array(e.length),s=new Array(e.length),u=0,d=[],c=[],g=[{type:12,data:i}];for(let C=0;C`uniforms.sizeInConcatAxis${C}`).join(","),x=C=>` ${(()=>{C.registerUniform("outputSize","u32");for(let z=0;z(${T}); ${l} -= sizeInConcatAxis[inputIndex - 1u]; } ${pa(s,m)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:g}),getShaderSource:x}},Rl=(e,t)=>{let r=e.inputs,n=r[0].dims,i=$e.normalizeAxis(t.axis,n.length);Dl(r,i);let a=n.slice();a[i]=r.reduce((u,d)=>u+(d.dims.length>i?d.dims[i]:0),0);let s=r.filter(u=>$e.size(u.dims)>0);e.compute(Bl(s,i,a,r[0].dataType),{inputs:s})},ha=e=>or({axis:e.axis})}),Xn,Qn,Yn,si,Zn=L(()=>{Yt(),Kt(),Xn=(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}`)}},Qn=(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})},Yn=(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"})},si=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)||[In,Nn];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}}}),hn,ii,ai=L(()=>{hn=(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.`)}},ii=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),fa,ma=L(()=>{fa=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)); } `}),Nl,jl,Bs,_a,Vl,oi,Ul,ga,li=L(()=>{Yt(),Kt(),pr(),Zn(),ai(),Nl=(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":""}); `,jl=(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];"} }`,Bs=(e,t,r="f32",n,i=!1,a=32,s=!1,u=32)=>{let d=t[1]*e[1],c=t[0]*e[0],g=i?d:a,m=i?a:d,l=g/t[0],T=a/t[1];if(!((i&&l===4&&e[1]===4||!i&&(l===3||l===4))&&g%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${l} must be 3 or 4. tileAWidth ${g} 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, ${g/l}>, ${m}>; var mm_Bsub: array, ${c/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 = ${s?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${d}; let num_tiles = ${s?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${s?`i32(globalId.z) * ${u}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${T}; 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; ${Nl(i,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${T}; 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];"} ${jl(i,l)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},_a=(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":""}); `,Vl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",oi=(e,t,r="f32",n,i=!1,a=32,s=!1,u=32,d=!1)=>{let c=e[1]*t[1],g=e[0]*t[0],m=i?c:a,l=i?a:c;if(!(l%t[1]===0&&m%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let T=l/t[1],x=m/t[0],C=a/t[1],z=d?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${c}; let globalColStart = i32(workgroupId.x) * ${g}; // 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 < ${m}; inputCol = inputCol + ${t[0]}) { ${_a(i,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${g}; 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 = ${i?`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) * ${c}; let tileRowA = i32(localId.y) * ${T}; let tileColA = i32(localId.x) * ${x}; let tileRowB = i32(localId.y) * ${C}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${T}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${x}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${_a(i,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${C}; 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) { ${Vl(i)} 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 = ${s?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${s?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${s?`i32(globalId.z) * ${u}`:"0"}; var acc : array, rowPerThread>; ${z} } `},Ul=(e,t,r,n,i,a=!1)=>{let[s,u,d]=i,[c,g,m,l]=n,T=bs(s,d),x=bs(u,d),C=fr(n[0].type.tensor),z=()=>{let A=g.rank,ee=c.rank,te=`var aIndices: ${g.type.indices};`;for(let ie=A-2-1,ke=ee-1;ie>=0;ie--,ke--)te+=` aIndices[${ie}] = ${ee>1?`batchIndices[${ke}]`:"batchIndices"};`;return T.forEach(ie=>{te+=` aIndices[${ie}] = 0;`}),te+=` aIndices[${A-2}] = u32(row); aIndices[${A-1}] = u32(colIn);`,te},U=()=>{let A=m.rank,ee=c.rank,te=`var bIndices: ${m.type.indices};`;for(let ie=A-2-1,ke=ee-1;ie>=0;ie--,ke--)te+=` bIndices[${ie}] = ${ee>1?`batchIndices[${ke}]`:"batchIndices"};`;return x.forEach(ie=>{te+=` bIndices[${ie}] = 0;`}),te+=` bIndices[${A-2}] = u32(row); bIndices[${A-1}] = u32(colIn);`,te};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${c.type.indices}) -> ${hn(e,C)} { var value = ${hn(e,C)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${z()} value = ${g.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${c.type.indices}) -> ${hn(e,C)} { var value = ${hn(e,C)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${U()} value = ${m.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${hn(e,C)}) { 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]":`${hn(e,C)}(bias[row])`};`:""} ${r} ${l.setByIndices("vec3(coords)","value")} } } `},ga=(e,t,r,n,i=!1,a)=>{let s=e[0].dims,u=e[1].dims,d=s.slice(0,-2),c=u.slice(0,-2),g=n?n.slice(0,-2):r.slice(0,-2),m=$e.size(g),l=s[s.length-2],T=s[s.length-1],x=u[u.length-1],C=T%4===0&&x%4===0,z=l<=8?[4,1,1]:[4,4,1],U=[8,8,1],A=[Math.ceil(x/U[0]/z[0]),Math.ceil(l/U[1]/z[1]),Math.ceil(m/U[2]/z[2])],ee=C?4:1,te=[...d,l,T/ee],ie=te.length,ke=[...c,T,x/ee],Pe=ke.length,Ye=[m,l,x/ee],It=[{type:6,data:l},{type:6,data:x},{type:6,data:T}];Qn(t,It),It.push(...Et(g,te,ke));let Bt=["rank","rank"],ar=e.length>2;ar&&(It.push(...Et(e[2].dims)),Bt.push("rank")),It.push(...Et(Ye));let nr=Ht=>{let Er=g.length,jr=xi("batchDims",e[0].dataType,Er,1),hr=fr(e[0].dataType),Ir=Qe("a",e[0].dataType,ie,ee),Gt=Qe("b",e[1].dataType,Pe,ee),Qt=qt("result",e[0].dataType,Ye.length,ee),xr=[Ir,Gt];if(ar){let sn=i?ee:1;xr.push(Qe("bias",e[2].dataType,e[2].dims.length,sn))}let qe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Yn(t,qe);let vt=fr(Qt.type.tensor),rr=Xn(t,Qt.type.value,vt),Br=Ul(ee,ar,rr,[jr,Ir,Gt,Qt],[d,c,g],i);return` ${Ht.registerUniforms(qe).registerInternalVariables(jr).declareVariables(...xr,Qt)} ${Br} ${C?Bs(z,U,hr,jr):oi(z,U,hr,jr)} `};return{name:"MatMul",shaderCache:{hint:`${z};${t.activation};${C};${i}`,inputDependencies:Bt},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:It}),getShaderSource:nr}}}),wa,Wl,kd=L(()=>{Yt(),_(),pr(),Zn(),ai(),ma(),li(),wa=(e,t,r,n,i=!1,a,s=4,u=4,d=4,c="f32")=>{let g=It=>{switch(It){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${It} is not supported.`)}},m=It=>{switch(It){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 ${It} is not supported.`)}},l=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,T=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,x=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",C=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",z=e?"row":"col",U=e?"col":"row",A=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${z} / outWidth; let outCol = ${z} % outWidth; let WRow = ${U} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${U} / 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 = ${U} % inChannels; var resData = ${hn(s,c)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${x} && xCol >= 0 && xCol < ${C}) { ${l} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${g(s)} } return resData;`,ee=e?t&&n?` let col = colIn * ${s}; ${A}`:` let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${A} } return ${hn(s,c)}(0.0);`:n&&r?` let col = colIn * ${s}; ${A}`:` let col = colIn * ${s}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${A} } return ${hn(s,c)}(0.0);`,te=`${m(u)}`,ie=hn(d,c),ke=hn(e?s:u,c),Pe=hn(e?u:s,c),Ye=Xn(a,ie,c);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${ke} { ${e?ee:te} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Pe} { ${e?te:ee} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${ie}) { 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])"}; ${T} ${ii(i)} ${Ye} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Wl=(e,t,r,n,i,a,s,u,d)=>{let c=t.format==="NHWC",g=c?e[0].dims[3]:e[0].dims[1],m=r[0],l=c?r[2]:r[3],T=c?r[1]:r[2],x=c?r[3]:r[1],C=c&&(g%4===0||g%3===0)&&x%4===0,z=c?x:l*T,U=c?l*T:x,A=[8,8,1],ee=n<=8?[4,1,1]:[4,4,1],te=[Math.ceil(z/A[0]/ee[0]),Math.ceil(U/A[1]/ee[1]),Math.ceil(m/A[2]/ee[2])];ae("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${te}`);let ie=C?c&&g%4!==0?3:4:1,ke=A[1]*ee[1],Pe=A[0]*ee[0],Ye=Math.max(A[0]*ie,A[1]),It=n%ke===0,Bt=i%Pe===0,ar=a%Ye===0,nr=C?[ie,4,4]:[1,1,1],Ht=[{type:6,data:n},{type:6,data:i},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Qn(t,Ht),Ht.push(...Et(e[0].dims,e[1].dims));let Er=["rank","rank"];s&&(Ht.push(...Et(e[2].dims)),Er.push("rank")),Ht.push(...Et(r));let jr=hr=>{let Ir=[{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}];Yn(t,Ir);let Gt=C?4:1,Qt=fr(e[0].dataType),xr=` fn setOutputAtIndex(flatIndex : i32, value : ${C?`vec4<${Qt}>`:Qt}) { result[flatIndex] = ${C?`vec4<${Qt}>`:Qt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${C?`vec4<${Qt}>`:Qt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${C?"/ 4":""}, value); }`,qe=Qe("x",e[0].dataType,e[0].dims.length,ie===3?1:ie),vt=Qe("w",e[1].dataType,e[1].dims.length,Gt),rr=[qe,vt],Br=qt("result",e[0].dataType,r.length,Gt);if(s){let sn=Qe("bias",e[2].dataType,e[2].dims.length,Gt);rr.push(sn),xr+=` fn getBiasByOutputCoords(coords : vec4) -> ${C?`vec4<${Qt}>`:Qt} { return bias[coords.${c?"w":"y"}${C?"/ 4":""}]; }`}return` ${fa("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 }; ${hr.registerUniforms(Ir).declareVariables(...rr,Br)} ${xr} ${wa(c,It,Bt,ar,s,t,nr[0],nr[1],nr[2],Qt)} ${C?Bs(ee,A,Qt,void 0,!c,Ye):oi(ee,A,Qt,void 0,!c,Ye,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${ie};${C};${It};${Bt};${ar};${ke};${Pe};${Ye}`,inputDependencies:Er},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:te[0],y:te[1],z:te[2]},programUniforms:Ht}),getShaderSource:jr}}}),ya,ba,Rs,Jn,Ma,Gl,ql,Hl,Kl=L(()=>{Yt(),_(),Kt(),pr(),Zn(),ai(),ya=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Rs=(e,t)=>t<=1?e:e+(e-1)*(t-1),Jn=(e,t,r,n=1)=>{let i=Rs(t,n);return Math.floor((e[0]*(r-1)-r+i)/2)},Ma=(e,t,r,n,i)=>{i==null&&(i=Jn(e,t[0],n[0]));let a=[0,0,0,r];for(let s=0;s<3;s++)e[s]+2*i>=t[s]&&(a[s]=Math.trunc((e[s]-t[s]+2*i)/n[s]+1));return a},Gl=(e,t,r,n,i,a,s,u,d,c)=>{let g,m,l,T;if(e==="VALID"&&(e=0),typeof e=="number"){g={top:e,bottom:e,left:e,right:e,front:e,back:e};let x=Ma([t,r,n,1],[u,d,c],1,[i,a,s],e);m=x[0],l=x[1],T=x[2]}else if(Array.isArray(e)){if(!e.every((C,z,U)=>C===U[0]))throw Error(`Unsupported padding parameter: ${e}`);g={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let x=Ma([t,r,n,1],[u,d,c],1,[i,a,s],e[0]);m=x[0],l=x[1],T=x[2]}else if(e==="SAME_UPPER"){m=Math.ceil(t/i),l=Math.ceil(r/a),T=Math.ceil(n/s);let x=(m-1)*i+u-t,C=(l-1)*a+d-r,z=(T-1)*s+c-n,U=Math.floor(x/2),A=x-U,ee=Math.floor(C/2),te=C-ee,ie=Math.floor(z/2),ke=z-ie;g={top:ee,bottom:te,left:ie,right:ke,front:U,back:A}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:g,outDepth:m,outHeight:l,outWidth:T}},ql=(e,t,r,n,i,a=!1,s="channelsLast")=>{let u,d,c,g,m;if(s==="channelsLast")[u,d,c,g,m]=e;else if(s==="channelsFirst")[u,m,d,c,g]=e;else throw new Error(`Unknown dataFormat ${s}`);let[l,,T,x,C]=t,[z,U,A]=ba(r),[ee,te,ie]=ba(n),ke=Rs(T,ee),Pe=Rs(x,te),Ye=Rs(C,ie),{padInfo:It,outDepth:Bt,outHeight:ar,outWidth:nr}=Gl(i,d,c,g,z,U,A,ke,Pe,Ye),Ht=a?l*m:l,Er=[0,0,0,0,0];return s==="channelsFirst"?Er=[u,Ht,Bt,ar,nr]:s==="channelsLast"&&(Er=[u,Bt,ar,nr,Ht]),{batchSize:u,dataFormat:s,inDepth:d,inHeight:c,inWidth:g,inChannels:m,outDepth:Bt,outHeight:ar,outWidth:nr,outChannels:Ht,padInfo:It,strideDepth:z,strideHeight:U,strideWidth:A,filterDepth:T,filterHeight:x,filterWidth:C,effectiveFilterDepth:ke,effectiveFilterHeight:Pe,effectiveFilterWidth:Ye,dilationDepth:ee,dilationHeight:te,dilationWidth:ie,inShape:e,outShape:Er,filterShape:t}},Hl=(e,t,r,n,i,a)=>{let s=a==="channelsLast";s?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],d={x:r.map((z,U)=>U)},c=[Math.ceil(ya(d.x.map(z=>r[z]))/u[0]),1,1];ae("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let g=1,m=$e.size(r),l=[{type:12,data:m},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];Qn(t,l),l.push(...Et(e[0].dims,e[1].dims));let T=["rank","rank"],x=e.length===3;x&&(l.push(...Et(e[2].dims)),T.push("rank")),l.push(...Et(r));let C=z=>{let U=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Yn(t,U);let A=1,ee=fr(e[0].dataType),te=Qe("x",e[0].dataType,e[0].dims.length,g),ie=Qe("W",e[1].dataType,e[1].dims.length,A),ke=[te,ie],Pe=qt("result",e[0].dataType,r.length,A),Ye="";if(x){let ar=Qe("bias",e[2].dataType,e[2].dims.length,A);ke.push(ar),Ye+=` fn getBiasByOutputCoords(coords : array) -> ${ee} { return bias[${s?Wt("coords",4,5):Wt("coords",1,5)}]; }`}let It=hn(g,ee),Bt=Xn(t,It,ee);return` ${Ye} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${te.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${ie.getByIndices("aIndices")}; } ${z.registerUniforms(U).declareVariables(...ke,Pe)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Pe.offsetToIndices("global_idx")}; let batch = ${Wt("coords",0,te.rank)}; let d2 = ${s?Wt("coords",te.rank-1,te.rank):Wt("coords",1,te.rank)}; let xFRCCorner = vec3(${s?Wt("coords",1,te.rank):Wt("coords",2,te.rank)}, ${s?Wt("coords",2,te.rank):Wt("coords",3,te.rank)}, ${s?Wt("coords",3,te.rank):Wt("coords",4,te.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${s?Wt("uniforms.x_shape",1,te.rank):Wt("uniforms.x_shape",2,te.rank)}; let xShapeZ = ${s?Wt("uniforms.x_shape",2,te.rank):Wt("uniforms.x_shape",3,te.rank)}; let xShapeW = ${s?Wt("uniforms.x_shape",3,te.rank):Wt("uniforms.x_shape",4,te.rank)}; let xShapeU = ${s?Wt("uniforms.x_shape",4,te.rank):Wt("uniforms.x_shape",1,te.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) { ${s?`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) { ${s?`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) { ${s?`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) { ${s?`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); } } } } ${x?"value = value + getBiasByOutputCoords(coords)":""}; ${Bt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${s};${g};${x}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:l}),getShaderSource:C}}}),Xl,Ql,Sd=L(()=>{Yt(),Kt(),pr(),Zn(),Xl=(e,t,r,n)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",s=e[0].dims,u=e[1].dims,d=t.format==="NHWC",c=d?r[3]:r[1],g=c/t.group,m=d&&g>=4?_r(c):1,l=$e.size(r)/m,T=[{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:g}];Qn(t,T),T.push(...Et(s,[u[0],u[1],u[2],u[3]/m]));let x=i?["rank","rank","rank"]:["rank","rank"];T.push(...Et([r[0],r[1],r[2],r[3]/m]));let C=z=>{let U=qt("output",e[0].dataType,r.length,m),A=fr(U.type.tensor),ee=Xn(t,U.type.value,A),te=Qe("x",e[0].dataType,s.length),ie=Qe("w",e[1].dataType,u.length,m),ke=[te,ie];i&&ke.push(Qe("b",e[2].dataType,e[2].dims,m));let Pe=[{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"}];Yn(t,Pe);let Ye=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 = ${te.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${ie.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 = ${te.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${ie.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${z.registerUniforms(Pe).declareVariables(...ke,U)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${U.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 * ${m} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; var value: ${U.type.value} = ${U.type.value}(0); ${Ye} ${a} ${ee} ${U.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${m}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:T}),getShaderSource:C}},Ql=(e,t,r,n)=>{let i=e.length>2,a=_r(r[3]),s=_r(r[2]),u=$e.size(r)/a/s,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],g=[r[0],r[1],r[2],r[3]/a],m=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Qn(t,m),m.push(...Et(d,c,g));let l=(s-1)*t.strides[1]+c[1],T=x=>{let C=qt("output",e[0].dataType,g.length,a),z=fr(C.type.tensor),U=Xn(t,C.type.value,z),A=Qe("x",e[0].dataType,d.length,a),ee=Qe("w",e[1].dataType,c.length,a),te=[A,ee];i&&te.push(Qe("b",e[2].dataType,e[2].dims,a));let ie=i?"value += b[output_channel];":"",ke=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Yn(t,ke),` ${x.registerUniforms(ke).declareVariables(...te,C)} ${x.mainStart()} ${x.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] / ${s}u; let col = (index1 % width1) * ${s}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<${A.type.value}, ${l}>; var values: array<${C.type.value}, ${s}>; 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 < ${c[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] = ${A.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${A.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { let w_val = ${ee.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${s}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${s}u; i++) { var value = values[i]; ${ie} ${U} ${C.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${s};${l};${c[0]};${c[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:m}),getShaderSource:T}}}),va,ui,Yl,Zl=L(()=>{Yt(),Kt(),li(),pr(),Zn(),va=(e,t,r,n,i=!1,a)=>{let s=e[0].dims,u=e[1].dims,d=s[s.length-2],c=u[u.length-1],g=s[s.length-1],m=_r(c),l=_r(g),T=_r(d),x=$e.size(r)/m/T,C=e.length>2,z=n?n.slice(0,-2):r.slice(0,-2),U=[$e.size(z),d,c],A=[{type:12,data:x},{type:12,data:d},{type:12,data:c},{type:12,data:g}];Qn(t,A),A.push(...Et(z,s,u)),C&&A.push(...Et(e[2].dims)),A.push(...Et(U));let ee=te=>{let ie=xi("batch_dims",e[0].dataType,z.length),ke=Qe("a",e[0].dataType,s.length,l),Pe=Qe("b",e[1].dataType,u.length,m),Ye=qt("output",e[0].dataType,U.length,m),It=fr(Ye.type.tensor),Bt=Xn(t,Ye.type.value,It),ar=[ke,Pe],nr="";if(C){let xr=i?m:1;ar.push(Qe("bias",e[2].dataType,e[2].dims.length,xr)),nr=`${i?`value += bias[col / ${xr}];`:`value += ${Ye.type.value}(bias[row + i]);`}`}let Ht=s.slice(0,-2),Er=u.slice(0,-2),jr=bs(Ht,z),hr=bs(Er,z),Ir=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Yn(t,Ir);let Gt=(xr,qe)=>{let vt=xr.rank,rr=xr.name;if(vt===2)return`var ${rr}_indices = ${xr.type.indices}(0u, 0u);`;let Br=ie.rank,sn=`var ${rr}_indices: ${xr.type.indices};`;for(let an=vt-2-1,Ws=Br-1;an>=0;an--,Ws--)sn+=` ${rr}_indices[${an}] = ${Br>1?`batch_indices[${Ws}]`:"batch_indices"};`;return qe.forEach(an=>{sn+=` ${rr}_indices[${an}] = 0;`}),sn+=`${rr}_indices[${vt-2}] = 0u; ${rr}_indices[${vt-1}] = 0u;`,sn},Qt=()=>{let xr=`var a_data: ${ke.type.value};`;for(let qe=0;qe; for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { ${Qt()} } for (var i = 0u; i < ${T}u; i++) { var value = values[i]; ${nr} ${Bt} let cur_indices = ${Ye.type.indices}(batch, row + i, col); let offset = ${Ye.indicesToOffset("cur_indices")}; ${Ye.setByOffset(`offset / ${m}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${l};${T};${i}`,inputDependencies:C?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:A}),getShaderSource:ee}},ui=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.")},Yl=e=>{ui(e.inputs);let t=Mn.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(va(e.inputs,{activation:""},t)):e.compute(ga(e.inputs,{activation:""},t))}}),Jl,ls,eu,di,xa,Ta,ci,tu,Ca,Pd=L(()=>{Kt(),kd(),Kl(),li(),Sd(),Zn(),Zl(),Vn(),Jl=(e,t,r,n,i,a)=>{let s=e[0],u=e.slice(a?1:2,a?3:4),d=u.length,c=t[0],g=t.slice(2).map((l,T)=>l+(l-1)*(r[T]-1)),m=u.map((l,T)=>l+n[T]+n[T+d]).map((l,T)=>Math.floor((l-g[T]+i[T])/i[T]));return m.splice(0,0,s),m.splice(a?3:1,0,c),m},ls=[2,3,1,0],eu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let 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 i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},di=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=si(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,a=e.group,s=e.kernel_shape,u=e.pads,d=e.strides,c=e.w_is_const();return{autoPad:n,format:r,dilations:i,group:a,kernelShape:s,pads:u,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},Ta=(e,t,r,n)=>{let i=r.format==="NHWC",a=Jl(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,i);if(r.group!==1){let ke=[t[0]];if(i){let Pe=e.kernelCustomData.wT??e.compute(xn(t[1],ls),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Pe),ke.push(Pe)}else ke.push(t[1]);t.length===3&&ke.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(Ql(ke,r,a,n),{inputs:ke}):e.compute(Xl(ke,r,a,n),{inputs:ke});return}let s=t.length===3,u=t[0].dims[i?1:2],d=t[0].dims[i?2:3],c=t[0].dims[i?3:1],g=t[1].dims[2],m=t[1].dims[3],l=a[i?1:2],T=a[i?2:3],x=a[i?3:1],C=i&&g===u&&m===d&&r.pads[0]===0&&r.pads[1]===0;if(C||g===1&&m===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 ke=a[0],Pe,Ye,It,Bt=[];if(i){let Ht=e.kernelCustomData.wT??e.compute(xn(t[1],ls),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ht),C){let Er=u*d*c;Pe=t[0].reshape([1,ke,Er]),Ye=Ht.reshape([1,Er,x]),It=[1,ke,x]}else Pe=t[0].reshape([ke,u*d,c]),Ye=Ht.reshape([1,c,x]),It=[ke,l*T,x];Bt.push(Pe),Bt.push(Ye)}else Pe=t[0].reshape([ke,c,u*d]),Ye=t[1].reshape([1,x,c]),It=[ke,x,l*T],Bt.push(Ye),Bt.push(Pe);s&&Bt.push(t[2]);let ar=It[2],nr=Bt[0].dims[Bt[0].dims.length-1];ar<8&&nr<8?e.compute(va(Bt,r,a,It,i,n),{inputs:Bt}):e.compute(ga(Bt,r,a,It,i,n),{inputs:Bt});return}let z=!0,U=e.kernelCustomData.wT??e.compute(xn(t[1],ls),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=U);let A=[t[0],U];s&&A.push(t[2]);let ee=i?l*T:x,te=i?x:l*T,ie=g*m*c;e.compute(Wl(A,r,a,ee,te,ie,s,z,n),{inputs:A})},ci=(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 i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),s=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=di({...t,pads:i,strides:a,dilations:s,kernelShape:u},n);Ta(e,n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},tu=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",i=di(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,s=ql(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(Hl(t,i,s.outShape,[s.filterDepth,s.filterHeight,s.filterWidth],[s.padInfo.front,s.padInfo.top,s.padInfo.left],n))},Ca=(e,t)=>{if(eu(e.inputs,t),e.inputs[0].dims.length===3)ci(e,t);else if(e.inputs[0].dims.length===5)tu(e,e.inputs,t);else{let r=di(t,e.inputs);Ta(e,e.inputs,r)}}}),Ad,ru,Id=L(()=>{Yt(),_(),pr(),Zn(),ai(),ma(),li(),Ad=(e,t=!1,r,n,i=4)=>{let a=z=>{switch(z){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 ${z} is not supported.`)}},s=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])",c=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",g=e?"row":"col",m=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 = ${g} / outWidth; let outCol = ${g} % outWidth; let WRow = ${m} / (uniforms.filter_dims[1] * inChannels); let WCol = ${m} / 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(${c}) || fract(xC) > 0.0) { return ${n}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${m} % inChannels; ${s} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,T=e?` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${l} } return ${n}(0.0);`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${l} } return ${n}(0.0);`,x=` let col = colIn * ${i}; 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(i)} } return ${n}(0.0); `,C=Xn(r,n);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?T:x} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?x:T} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { let col = colIn * ${i}; 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} ${ii(t)} ${C} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value; } }`},ru=(e,t,r,n,i,a,s,u)=>{let d=t.format==="NHWC",c=d?e[0].dims[3]:e[0].dims[1],g=r[0],m=d?r[2]:r[3],l=d?r[1]:r[2],T=d?r[3]:r[1],x=d&&c%4===0&&c%3&&T%4===0,C=d?T:m*l,z=d?m*l:T,U=[8,8,1],A=n<=8?[4,1,1]:[4,4,1],ee=[Math.ceil(C/U[0]/A[0]),Math.ceil(z/U[1]/A[1]),Math.ceil(g/U[2]/A[2])];ae("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ee}`);let te=x?4:1,ie=Math.max(U[0]*te,U[1]),ke=x?4:1,Pe=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],Ye=[Pe[0]+(t.dilations[0]<=1?0:(Pe[0]-1)*(t.dilations[0]-1)),Pe[1]+(t.dilations[1]<=1?0:(Pe[1]-1)*(t.dilations[1]-1))],It=[Ye[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),Ye[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Bt=[{type:6,data:n},{type:6,data:i},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Pe},{type:6,data:It}];Qn(t,Bt),Bt.push(...Et(e[0].dims,e[1].dims));let ar=["rank","rank"];s&&(Bt.push(...Et(e[2].dims)),ar.push("rank")),Bt.push(...Et(r));let nr=Ht=>{let Er=Qe("x",e[0].dataType,e[0].dims.length,ke),jr=Qe("w",e[1].dataType,e[1].dims.length,1),hr=qt("result",e[0].dataType,r.length,ke),Ir=[Er,jr],Gt="";if(s){let qe=Qe("bias",e[2].dataType,e[2].dims.length,ke);Ir.push(qe),Gt+=` fn getBiasByOutputCoords(coords : vec4) -> ${qe.type.value} { return bias[coords.${d?"w":"y"}${x?"/ 4":""}]; }`}let Qt=[{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:Pe.length},{name:"pads",type:"i32",length:It.length}];Yn(t,Qt);let xr=fr(e[0].dataType,1);if(xr!=="f16"&&xr!=="f32")throw new Error(`elemType ${xr} is not supported.`);return` ${fa("uniforms.result_strides")} ${Ht.registerUniforms(Qt).declareVariables(...Ir,hr)}; ${Gt} ${Ad(d,s,t,Er.type.value,te)} ${x?Bs(A,U,xr,void 0,!d,ie):oi(A,U,xr,void 0,!d,ie,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${A};${U};${x}`,inputDependencies:ar},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ee[0],y:ee[1],z:ee[2]},programUniforms:Bt}),getShaderSource:nr}}}),nu,us,Fd=L(()=>{Yt(),_(),Kt(),pr(),nu=(e,t,r,n,i,a=!1,s,u,d=!1)=>{let c=d?1:2,g=d?2:3,m=d?3:1,l=a?2:1,T=` fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${s}>`:s}) { result[flatIndex] = ${a?`vec4<${s}>`:s}(value); }`;n&&(T+=` fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${s}>`:s} { return bias[coords.${d?"w":"y"}${a?"/ 4":""}]; }`);let x=a?4:1,C=Qe("W",t[1].dataType,t[1].dims.length,x),z=Qe("Dy",t[0].dataType,t[0].dims.length,x),U=[z,C];n&&U.push(Qe("bias",t[2].dataType,[r[m]].length,x));let A=qt("result",t[0].dataType,r.length,x),ee=`{ let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${i?"global_id.y":"workgroup_id.y"} * ${l}; let d1: u32 = ${i?"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<${s}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${s}(dyCorner.x) + ${s}(wR)) / ${s}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${s}(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 = (${s}(dyCorner.y) + ${s}(wC)) / ${s}(uniforms.strides.y); let dyC2 = (${s}(dyCorner.y) + 1.0 + ${s}(wC)) / ${s}(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 >= ${s}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${s}(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 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${z.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${z.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${m}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${z.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${s}>(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 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${z.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${s}>(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<${s}>(0.0)`}; ${A.set("batch","r","c + i","d1","value")}; } }`,te=` let outputIndices = ${A.offsetToIndices("global_idx")}; let batch = ${A.indicesGet("outputIndices",0)}; let d1 = ${A.indicesGet("outputIndices",m)}; let r = ${A.indicesGet("outputIndices",c)}; let c = ${A.indicesGet("outputIndices",g)}; 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 = ${s}(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 = (${s}(dyRCorner) + ${s}(wR)) / ${s}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[${c}]) || 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 = (${s}(dyCCorner) + ${s}(wC)) / ${s}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[${g}]) || 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?z.get("batch","idyR","idyC","inputChannel"):z.get("batch","inputChannel","idyR","idyC")}; let wValue = ${C.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${n?"bias[d1]":`${s}(0.0)`}; ${A.setByOffset("global_idx","value")}; `;return` ${e.registerUniforms(u).declareVariables(...U,A)} ${T} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${a?ee:te}}`},us=(e,t,r)=>{let n=e.length>2,i=t.outputShape,a=$e.size(i),s=[Math.ceil(a/64),1,1];ae("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let u=t.format==="NHWC",d=["rank","rank"],c=[t.strides[0],t.strides[1]],g=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],m=[t.dilations[0],t.dilations[1]],l=[g[0]+(t.dilations[0]<=1?0:(t.kernelShape[u?1:2]-1)*(t.dilations[0]-1)),g[1]+(t.dilations[1]<=1?0:(t.kernelShape[u?2:3]-1)*(t.dilations[1]-1))],T=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],x=!1,C=t.group,z=e[1].dims,U=z[0]/C,A=z[1],ee=[{type:12,data:a},{type:12,data:c},{type:12,data:g},{type:12,data:m},{type:12,data:l},{type:6,data:T},{type:12,data:U},{type:12,data:A},...Et(e[0].dims,e[1].dims)];n&&(ee.push(...Et(e[2].dims)),d.push("rank")),ee.push(...Et(i));let te=s[1]===1&&s[2]===1,ie=ke=>{let Pe=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:c.length},{name:"filter_dims",type:"u32",length:g.length},{name:"dilations",type:"u32",length:g.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:T.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ye=fr(e[0].dataType);return`${nu(ke,e,i,n,te,x,Ye,Pe,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:r?r(i):i,dataType:e[0].dataType}],programUniforms:ee}),getShaderSource:ie}}}),su,iu,au,$a,pi,Od,ou,lu,uu,du,zd=L(()=>{Id(),Fd(),Zn(),Vn(),su=(e,t,r,n,i,a)=>(e-1)*t+r+(n-1)*i+1-a,iu=(e,t,r,n,i)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[i]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[i]=a)},au=(e,t,r,n,i,a,s,u,d,c)=>{let g=e.length-2,m=c.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((m,l)=>m*l,1)===0){r.length=0;for(let m=2;mm+l,0)===0){let m=t[0].dims.length-2;d=new Array(m).fill(1)}let c=e.strides.slice();if(c.reduce((m,l)=>m+l,0)===0){let m=t[0].dims.length-2;c=new Array(m).fill(1)}au(u,r,d,e.autoPad,e.group,i,c,n,s,a);let g=Object.assign({},e);return Object.assign(g,{kernelShape:r,pads:i,outputPadding:s,outputShape:a,dilations:d,strides:c}),g},pi=e=>{let t=si(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,a=e.group,s=e.kernelShape,u=e.pads,d=e.strides,c=e.wIsConst(),g=e.outputPadding,m=e.outputShape;return{autoPad:n,format:r,dilations:i,group:a,kernelShape:s,outputPadding:g,outputShape:m,pads:u,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},Od=(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 i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((s,u)=>s+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((s,u)=>s+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((s,u)=>s+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((s,u)=>s+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")},ou=[2,3,1,0],lu=(e,t,r)=>{let n=$a(r,t),i=r.format==="NHWC",a=n.outputShape,s=a[i?3:1],u=t[0].dims[i?3:1];if(n.group!==1||s===1&&u===1){e.compute(us(t,n));return}let d=a[i?1:2],c=a[i?2:3],g=t[1].dims[2],m=t[1].dims[3],l=i?d*c:s,T=i?s:d*c,x=g*m*u,C=!0,z=e.kernelCustomData.wT??e.compute(xn(t[1],ou),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=z);let U=[t[0],z],A=t.length===3;A&&(!i&&t[2].dims.length===1?U.push(t[2].reshape([t[2].dims[0],1,1])):U.push(t[2])),e.compute(ru(U,n,a,l,T,x,A,C),{inputs:U})},uu=(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 i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let s=t.strides;(s.length===0||s[0]===0)&&(s=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],s=[1].concat(s),a=[1].concat(a),i=[1].concat(i);let d=$a({...t,pads:u,strides:s,dilations:a,kernelShape:i},n);e.compute(us(n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]]))},du=(e,t)=>{Od(e.inputs,t),e.inputs[0].dims.length===3?uu(e,t):lu(e,e.inputs,t)}}),Ea,cu,pu,hu=L(()=>{Yt(),Kt(),Pr(),pr(),Ea=(e,t,r,n)=>{let i=$e.size(t),a=t.length,s=Qe("input",e,a),u=qt("output",e,a),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),c=$e.normalizeAxis(d,a),g=m=>{let l=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,T=Wt("uniforms.input_shape","uniforms.axis",a),x=n.reverse?l+(n.exclusive?" + 1":""):"0",C=n.reverse?T:l+(n.exclusive?"":" + 1");return` ${m.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,u)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${u.offsetToIndices("global_idx")}; var sum = ${u.type.value}(0); let first : i32 = ${x}; let last : i32 = ${C}; for (var i : i32 = first; i < last; i++) { ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${s.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(i/64)},programUniforms:[{type:12,data:i},{type:12,data:c},...Et(t,t)]}),getShaderSource:g}},cu=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(Ea(n,r,i,t),{inputs:[0]})},pu=e=>{let t=e.exclusive===1,r=e.reverse===1;return or({exclusive:t,reverse:r})}}),fu,mu,ka,_u,gu,Sa=L(()=>{Yt(),Kt(),Pr(),pr(),fu=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.")},mu=(e,t,r,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let a=0;a{let r,n,i,a,s,u,d=t.format==="NHWC",c=t.blocksize,g=t.mode==="DCR";d?([r,n,i,a]=e.dims,s=g?[r,n,i,c,c,a/c**2]:[r,n,i,a/c**2,c,c],u=g?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],s=g?[r,c,c,a/c**2,n,i]:[r,a/c**2,c,c,n,i],u=g?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let m=e.reshape(s),l=m.dims.length,T=e.dataType,x=Qe("a",T,l),C=qt("output",T,l),z=U=>` ${U.registerUniform("output_size","u32").declareVariables(x,C)} ${mu(u,l,x,C)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${C.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${C.setByOffset("global_idx",x.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:U=>{let A=d?[r,n*c,i*c,a/c**2]:[r,a/c**2,n*c,i*c],ee=$e.size(A),te=m.dims,ie=$e.sortBasedOnPerm(te,u);return{outputs:[{dims:A,dataType:U[0].dataType}],dispatchGroup:{x:Math.ceil(ee/64)},programUniforms:[{type:12,data:ee},...Et(te,ie)]}},getShaderSource:z}},_u=(e,t)=>{fu(e.inputs),e.compute(ka(e.inputs[0],t))},gu=e=>or({blocksize:e.blocksize,mode:e.mode,format:e.format})}),hi,Ns,Pa,wu,Aa,fi,Dd,Ia,yu,Fa,bu,Ld=L(()=>{Yt(),Kt(),Pr(),pr(),hi="[a-zA-Z]|\\.\\.\\.",Ns="("+hi+")+",Pa="^"+Ns+"$",wu="("+Ns+",)*"+Ns,Aa="^"+wu+"$",fi=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)}},Dd=class{constructor(e,t){var i;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(Aa)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,s)=>{let u=e[s].dims.slice();if(!a.match(RegExp(Pa)))throw new Error("Invalid LHS term");let d=this.processTerm(a,!0,u,s);this.lhs.push(d)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,s])=>s.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Ns)))throw new Error("Invalid RHS");(i=n.match(RegExp(hi,"g")))==null||i.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let s=this.symbolToInfo.get(a);if(s===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(s.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 i=r.length,a=!1,s=[],u=0;if(!e.match(RegExp(Pa))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(hi,"g")),c=new fi(n);return d==null||d.forEach((g,m)=>{if(g==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let l=i-d.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(s=r.slice(u,u+l),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=s;else throw new Error("Ellipsis must be specified in the LHS");for(let T=0;Te+"_max",yu=(e,t,r,n)=>{let i=e.map(c=>c.length).map((c,g)=>Qe(`input${g}`,t,c)),a=$e.size(n),s=qt("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(c=>!r.rhs.symbolToIndices.has(c)),d=c=>{let g=[],m="var prod = 1.0;",l="var sum = 0.0;",T="sum += prod;",x=[],C=[],z=[],U=[],A=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((te,ie)=>{var ke;if(r.rhs.symbolToIndices.has(ie)){let Pe=(ke=r.rhs.symbolToIndices.get(ie))==null?void 0:ke[0];Pe!==void 0&&r.lhs.forEach((Ye,It)=>{if(te.inputIndices.includes(It)){let Bt=Ye.symbolToIndices.get(ie);if(Bt===void 0)throw new Error("Invalid symbol error");Bt.forEach(ar=>{g.push(`${i[It].indicesSet(`input${It}Indices`,ar,s.indicesGet("outputIndices",Pe))}`)})}})}else r.lhs.forEach((Pe,Ye)=>{if(te.inputIndices.includes(Ye)){let It=Pe.symbolToIndices.get(ie);if(It===void 0)throw new Error("Invalid symbol error");It.forEach(Bt=>{x.push(`${i[Ye].indicesSet(`input${Ye}Indices`,Bt,`${ie}`)}`)}),U.push(`prod *= ${i[Ye].getByIndices(`input${Ye}Indices`)};`)}}),C.push(`for(var ${ie}: u32 = 0; ${ie} < uniforms.${Ia(ie)}; ${ie}++) {`),z.push("}")});let ee=A?[...g,`let sum = ${i.map((te,ie)=>te.getByIndices(`input${ie}Indices`)).join(" * ")};`]:[...g,l,...C,...x,m,...U,T,...z];return` ${c.registerUniforms(u.map(te=>({name:`${Ia(te)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,s)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${s.offsetToIndices("global_idx")}; ${i.map((te,ie)=>`var input${ie}Indices: ${i[ie].type.indices};`).join(` `)} ${ee.join(` `)}; ${s.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=u.filter(m=>r.symbolToInfo.has(m)).map(m=>{var l;return{type:12,data:((l=r.symbolToInfo.get(m))==null?void 0:l.dimValue)||0}});c.push({type:12,data:a});let g=e.map((m,l)=>[...Et(m)]).reduce((m,l)=>m.concat(l),c);return g.push(...Et(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:g}},getShaderSource:d}},Fa=(e,t)=>{let r=new Dd(e.inputs,t.equation),n=r.outputDims,i=e.inputs.map((a,s)=>a.dims);e.compute(yu(i,e.inputs[0].dataType,r,n))},bu=e=>{let t=e.equation.replace(/\s+/g,"");return or({equation:t})}}),Oa,za,Mu,Da,Bd,bc=L(()=>{Yt(),Kt(),pr(),Oa=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 i=0;ie.length>t.length?za(e,t):za(t,e),Da=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Mu(t,r),i=e[0].dataType,a=i===9?4:1,s=Math.ceil($e.size(n)/a),u=c=>{let g=Qe("input",i,t.length,a),m=qt("output",i,n.length,a),l;if(i===9){let T=(x,C,z="")=>` let outputIndices${C} = ${m.offsetToIndices(`outputOffset + ${C}u`)}; let offset${C} = ${g.broadcastedIndicesToOffset(`outputIndices${C}`,m)}; let index${C} = offset${C} / 4u; let component${C} = offset${C} % 4u; ${x}[${C}] = ${z}(${g.getByOffset(`index${C}`)}[component${C}]); `;l=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${T("data",0,"u32")} ${T("data",1,"u32")} ${T("data",2,"u32")} ${T("data",3,"u32")} ${m.setByOffset("global_idx","data")} }`}else l=` let outputIndices = ${m.offsetToIndices("global_idx")}; let inputOffset = ${g.broadcastedIndicesToOffset("outputIndices",m)}; ${m.setByOffset("global_idx",g.getByOffset("inputOffset"))} }`;return` ${c.registerUniform("vec_size","u32").declareVariables(g,m)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${l}`},d=[{type:12,data:s},...Et(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(s/64)},programUniforms:d})}},Bd=e=>{Oa(e.inputs),e.compute(Da(e.inputs),{inputs:[0]})}}),La,Ba,Rd=L(()=>{Yt(),Kt(),pr(),ua(),La=e=>{let t=e[0].dataType,r=$e.size(e[0].dims),n=$e.size(e[1].dims),i=n%4===0,a=s=>{let u=Qe("x",t,[1],4),d=Qe("bias",t,[1],4),c=qt("y",t,[1],4),g=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],m=T=>` let bias${T}_offset: u32 = (global_idx * 4 + ${T}) % uniforms.bias_size; let bias${T} = ${d.getByOffset(`bias${T}_offset / 4`)}[bias${T}_offset % 4];`,l=i?` let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${m(0)}${m(1)}${m(2)}${m(3)} let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${s.registerUniforms(g).declareVariables(u,d,c)} ${ia(Fr(t))} ${s.mainStart(pn)} ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${u.getByOffset("global_idx")}; ${l} let x_in = x + bias; ${c.setByOffset("global_idx",aa("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:s=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/pn/4)}})}},Ba=e=>{e.inputs.length<2||$e.size(e.inputs[1].dims)===0?yl(e):e.compute(La(e.inputs))}}),vu,Ra,xu,Tu,Cu=L(()=>{Yt(),Kt(),Pr(),pr(),vu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ra=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,a=$e.normalizeAxis(t.axis,i),s=r.slice(0);s.splice(a,1,...n);let u=r[a],d=e[0].dataType===9?4:1,c=Math.ceil($e.size(s)/d),g=[{type:12,data:c},{type:6,data:u},{type:12,data:a},...Et(e[0].dims,e[1].dims,s)],m=l=>{let T=Qe("data",e[0].dataType,e[0].dims.length,d),x=Qe("inputIndices",e[1].dataType,e[1].dims.length),C=qt("output",e[0].dataType,s.length,d),z=A=>{let ee=n.length,te=`var indicesIndices${A} = ${x.type.indices}(0);`;for(let ie=0;ie1?`indicesIndices${A}[${ie}]`:`indicesIndices${A}`} = ${s.length>1?`outputIndices${A}[uniforms.axis + ${ie}]`:`outputIndices${A}`};`;te+=` var idx${A} = ${x.getByIndices(`indicesIndices${A}`)}; if (idx${A} < 0) { idx${A} = idx${A} + uniforms.axisDimLimit; } var dataIndices${A} : ${T.type.indices}; `;for(let ie=0,ke=0;ie1?`dataIndices${A}[${ie}]`:`dataIndices${A}`} = u32(idx${A});`,ke+=ee):(te+=`${i>1?`dataIndices${A}[${ie}]`:`dataIndices${A}`} = ${s.length>1?`outputIndices${A}[${ke}]`:`outputIndices${A}`};`,ke++);return te},U;if(e[0].dataType===9){let A=(ee,te,ie="")=>` let outputIndices${te} = ${C.offsetToIndices(`outputOffset + ${te}u`)}; ${z(te)}; let offset${te} = ${T.indicesToOffset(`dataIndices${te}`)}; let index${te} = offset${te} / 4u; let component${te} = offset${te} % 4u; ${ee}[${te}] = ${ie}(${T.getByOffset(`index${te}`)}[component${te}]); `;U=` let outputOffset = global_idx * ${d}; var value = vec4(0); ${A("value",0,"u32")} ${A("value",1,"u32")} ${A("value",2,"u32")} ${A("value",3,"u32")} ${C.setByOffset("global_idx","value")} `}else U=` let outputIndices = ${C.offsetToIndices("global_idx")}; ${z("")}; let value = ${T.getByIndices("dataIndices")}; ${C.setByOffset("global_idx","value")}; `;return` ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(T,x,C)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${U} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:m}},xu=e=>or({axis:e.axis}),Tu=(e,t)=>{let r=e.inputs;vu(r),e.compute(Ra(e.inputs,t))}}),$u,Eu,Na,ku,Nd=L(()=>{Yt(),Kt(),Pr(),pr(),$u=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=$e.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,i=e[0],a=e[2],s=e.length===4?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.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(s){if(s.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(s.dims.length!==a.dims.length||!s.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.")}},Eu=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,a=$e.normalizeAxis(t.gatherAxis,i),s=$e.normalizeAxis(t.quantizeAxis,i),u=r.slice(0);u.splice(a,1,...n);let d=$e.size(u),c=e[2].dataType,g=e[0].dataType===22,m=[{type:12,data:d},{type:12,data:s},{type:12,data:a},{type:12,data:t.blockSize},...Et(...e.map((T,x)=>T.dims),u)],l=T=>{let x=Qe("data",e[0].dataType,e[0].dims.length),C=Qe("inputIndices",e[1].dataType,e[1].dims.length),z=Qe("scales",e[2].dataType,e[2].dims.length),U=e.length>3?Qe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,A=qt("output",c,u.length),ee=[x,C,z];U&&ee.push(U);let te=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${T.registerUniforms(te).declareVariables(...ee,A)} ${T.mainStart()} let output_indices = ${A.offsetToIndices("global_idx")}; var indices_indices = ${C.type.indices}(0); ${n.length>1?` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${A.indicesGet("output_indices","uniforms.gather_axis + i")}; ${C.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${A.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${x.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${A.indicesGet("output_indices","i")}; ${x.indicesSet("data_indices","i","index")}; } var index_from_indices = ${C.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${r[a]}; } ${x.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { let index = ${A.indicesGet("output_indices",`i + ${n.length} - 1`)}; ${x.indicesSet("data_indices","i","index")}; } let data_offset = ${x.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${x.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${z.getByIndices("scale_indices")}; ${U?` let zero_point_indices = scale_indices; let zero_point_offset = ${U.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${U.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${Fr(c)}(quantized_data - zero_point) * scale; ${A.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((T,x)=>x!==1).map(T=>T.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(T,x)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:c}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m}),getShaderSource:l}},Na=(e,t)=>{let r=e.inputs;$u(r,t),e.compute(Eu(e.inputs,t))},ku=e=>or({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Su,Pu,Or,jd,Mc=L(()=>{Yt(),Kt(),Pr(),pr(),Su=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.`)},Pu=(e,t)=>{let r=e[0].dims,n=e[0].dataType,i=r.length,a=e[1].dims,s=e[1].dataType,u=$e.normalizeAxis(t.axis,i),d=r[u],c=a.slice(0),g=$e.size(c),m=Qe("input",n,i),l=Qe("indicesInput",s,a.length),T=qt("output",n,c.length),x=[{type:12,data:g},{type:6,data:d},{type:12,data:u}];return x.push(...Et(r,a,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:x}),getShaderSource:C=>` ${C.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,l,T)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${T.offsetToIndices("global_idx")}; var idx = ${l.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${m.type.indices}(outputIndices); ${m.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${m.getByIndices("inputIndices")}; ${T.setByOffset("global_idx","value")}; }`}},Or=e=>or({axis:e.axis}),jd=(e,t)=>{let r=e.inputs;Su(r),e.compute(Pu(e.inputs,t))}}),Vd,ja,Au,Iu,Ud=L(()=>{Yt(),Kt(),pr(),Vd=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")},ja=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[i,a,s]=ln.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[i,a];if(!u)throw new Error("Can't use gemm on the given tensors");let d=$e.size(u),c=[{type:12,data:d},{type:12,data:i},{type:12,data:a},{type:12,data:s},{type:1,data:t.alpha},{type:1,data:t.beta}],g=["type","type"];e.length===3&&(c.push(...Et(e[2].dims)),g.push("rank")),c.push(...Et(u));let m=l=>{let T="";t.transA&&t.transB?T="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?T="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?T="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(T="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let x=t.alpha===1?"":"value *= uniforms.alpha;",C=Qe("a",e[0].dataType,e[0].dims),z=Qe("b",e[1].dataType,e[1].dims),U=C.type.value,A=null,ee=[C,z];e.length===3&&(A=Qe("c",e[2].dataType,e[2].dims.length),ee.push(A));let te=qt("output",e[0].dataType,u.length);ee.push(te);let ie=[{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(ie).declareVariables(...ee)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${U}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${T} } ${x} ${A!=null?`let cOffset = ${A.broadcastedIndicesToOffset("vec2(m, n)",te)}; value += ${U}(uniforms.beta) * ${A.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:m}},Au=e=>{let t=e.transA,r=e.transB,n=e.alpha,i=e.beta;return{transA:t,transB:r,alpha:n,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Iu=(e,t)=>{Vd(e.inputs),e.compute(ja(e.inputs,t))}}),gn,Va,Ua,Wa,Fu,vs,Wd,Gd=L(()=>{Yt(),Kt(),Pr(),oe(),ei(),pr(),Vn(),gn=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Va=(e,t)=>{let r=e[0],n=gn(e,1),i=gn(e,2),a=gn(e,3),s=gn(e,4),u=gn(e,5),d=gn(e,6),c=gn(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 g=r.dims[0],m=r.dims[1],l=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],T=m,x=0,C=0,z=Math.floor(l/t.numHeads);if(d&&c&&$e.size(d.dims)&&$e.size(c.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==g||d.dims[1]!==t.numHeads||d.dims[3]!==z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==g||c.dims[1]!==t.numHeads||c.dims[3]!==z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');x=d.dims[2],C=d.dims[2]}else if(d&&$e.size(d.dims)||c&&$e.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let U;if(n&&$e.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');U=2,T=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');U=5,T=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');U=0,T=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');U=3}if(a&&$e.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let A=x+T,ee=0;if(s&&$e.size(s.dims)>0){ee=8;let Pe=s.dims;throw Pe.length===1?Pe[0]===g?ee=1:Pe[0]===3*g+2&&(ee=3):Pe.length===2&&Pe[0]===g&&Pe[1]===A&&(ee=5),ee===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let te=!1,ie=l;if(i&&$e.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(T!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ie=i.dims[2]}else{if(T!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');ie=i.dims[1]*i.dims[3],te=!0}}let ke=!1;if(s&&$e.size(s.dims)>0)throw new Error("Key padding mask is not supported");if(u&&$e.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]!==g||u.dims[1]!==t.numHeads||u.dims[2]!==m||u.dims[3]!==A)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:g,sequenceLength:m,pastSequenceLength:x,kvSequenceLength:T,totalSequenceLength:A,maxSequenceLength:C,inputHiddenSize:0,hiddenSize:l,vHiddenSize:ie,headSize:z,vHeadSize:Math.floor(ie/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ee,scale:t.scale,broadcastResPosBias:ke,passPastInKv:te,qkvFormat:U}},Ua=e=>or({...e}),Wa=or({perm:[0,2,1,3]}),Fu=(e,t,r,n,i,a,s)=>{let u=[n,i,a],d=$e.size(u),c=[{type:12,data:d},{type:12,data:s},{type:12,data:a}],g=m=>{let l=qt("qkv_with_bias",t.dataType,u),T=Qe("qkv",t.dataType,u),x=Qe("bias",r.dataType,u),C=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${m.registerUniforms(C).declareVariables(T,x,l)} ${m.mainStart()} ${m.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:c}),getShaderSource:g},{inputs:[t,r],outputs:[-1]})[0]},vs=(e,t,r,n,i,a,s,u)=>{let d=a;if(s&&$e.size(s.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Fu(e,a,s,t,n,r*i,u),d=d.reshape([t,n,r,i]),r===1||n===1?d:e.compute(xn(d,Wa.perm),{inputs:[d],outputs:[-1]})[0]}else return a.dims.length===3&&(d=a.reshape([t,n,r,i])),r===1||n===1?d:e.compute(xn(d,Wa.perm),{inputs:[d],outputs:[-1]})[0]},Wd=(e,t)=>{let r=Va(e.inputs,t),n=e.inputs[0],i=gn(e.inputs,1),a=gn(e.inputs,2),s=gn(e.inputs,3),u=gn(e.inputs,4),d=gn(e.inputs,5),c=gn(e.inputs,6),g=gn(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let m=i&&a&&i.dims.length===4&&a.dims.length===4,l=vs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,s,0);if(m)return Ms(e,l,i,a,u,void 0,c,g,d,r);if(!i||!a)throw new Error("key and value must be provided");let T=vs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,s,r.hiddenSize),x=vs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,s,2*r.hiddenSize);Ms(e,l,T,x,u,void 0,c,g,d,r)}}),Ou,zu,Du,Lu,Ga,Bu,Ru,Nu=L(()=>{Yt(),Kt(),Pr(),pr(),Ou=e=>{if(!e||e.length<1)throw new Error("too few inputs")},zu=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),n=r.length),or({numOutputs:n,axis:t.axis,splitSizes:r})},Du=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Wt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Lu=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=$e.size(r),i=e[0].dataType,a=$e.normalizeAxis(t.axis,r.length),s=new Array(t.numOutputs),u=Qe("input",i,r.length),d=new Array(t.numOutputs),c=[],g=[],m=0,l=[{type:12,data:n}];for(let x=0;x` ${x.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...s)} ${Du(d.length)} ${Lu(s)} ${x.mainStart()} ${x.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 -= ${Wt("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:T,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:l})}},Bu=(e,t)=>{Ou(e.inputs);let r=e.inputs.length===1?t:zu(e.inputs,t);e.compute(Ga(e.inputs,r),{inputs:[0]})},Ru=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 or({axis:t,numOutputs:n,splitSizes:r})}}),ju,Vu,qa,Uu,qd=L(()=>{Pr(),ei(),Gd(),Nu(),Vn(),ju=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=e[0],n=e[1],i=e[2],a=e[3],s=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,d=r.dims[0],c=r.dims[1],g=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],m=c,l=0,T=!n||n.dims.length===0,x=Math.floor(T?g/(t.numHeads+2*t.kvNumHeads):g/t.numHeads);T&&(g=x*t.numHeads);let C=a&&a.dims.length!==0,z=s&&s.dims.length!==0;if(C&&a.dims.length===4&&a.dims[0]===d&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===x)throw new Error("BSNH pastKey/pastValue is not supported");if(C&&z){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(s.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=a.dims[2]}else if(C||z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let U=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');m=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');m=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==x)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');m=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');U=3}let A=0,ee=!1,te=t.kvNumHeads?x*t.kvNumHeads:g;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(m!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');te=i.dims[2]}else{if(m!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');te=i.dims[1]*i.dims[3],ee=!0}}let ie=e.length>4?e[5]:void 0;if(ie&&ie.dims.length!==1&&ie.dims[0]!==d)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:d,sequenceLength:c,pastSequenceLength:l,kvSequenceLength:m,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:g,vHiddenSize:te,headSize:x,vHeadSize:Math.floor(te/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:A,scale:t.scale,broadcastResPosBias:!1,passPastInKv:ee,qkvFormat:U}},Vu=or({perm:[0,2,1,3]}),qa=(e,t,r)=>{let n=t,i=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,i,r.headSize]),n=e.compute(xn(n,Vu.perm),{inputs:[n],outputs:[-1]})[0]),n},Uu=(e,t)=>{var z;let r=ju(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((z=e.inputs[1])==null?void 0:z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,s=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,g=r.kvNumHeads?r.kvNumHeads:r.numHeads,m=or({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,g*r.headSize,g*r.headSize]}),[l,T,x]=!i&&!a?e.compute(Ga([n],m),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,a],C=vs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,l,void 0,0);Ms(e,C,qa(e,T,r),qa(e,x,r),void 0,void 0,s,u,void 0,r,d,c)}}),Ha,Wu,Gu,qu,vc=L(()=>{Yt(),Kt(),Vn(),pr(),Ha=(e,t,r,n,i,a,s,u)=>{let d=_r(a),c=d===1?"f32":`vec${d}f`,g=d===1?"vec2f":`mat2x${d}f`,m=i*s,l=[i,s,a/d],T=[i,s,2],x=["rank","type","type"],C=[];C.push(...Et(l,T));let z=U=>{let A=Qe("x",t.dataType,3,d),ee=Qe("scale",r.dataType,r.dims),te=Qe("bias",n.dataType,n.dims),ie=qt("output",1,3,2),ke=[A,ee,te,ie],Pe=64;return` var workgroup_shared : array<${g}, ${Pe}>; const workgroup_size = ${Pe}u; ${U.declareVariables(...ke)} ${U.mainStart(Pe)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${c}(0); var squared_sum = ${c}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${c}(${A.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${g}(sum, squared_sum); workgroupBarrier(); for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { if (local_idx < currSize) { workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; } workgroupBarrier(); } if (local_idx == 0) { let sum_final = ${jn("workgroup_shared[0][0]",d)} / f32(hight * ${d}); let squared_sum_final = ${jn("workgroup_shared[0][1]",d)} / f32(hight * ${d}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:T,dataType:1}],dispatchGroup:{x:m},programUniforms:C}),getShaderSource:z},{inputs:[t,r,n],outputs:[-1]})[0]},Wu=(e,t,r)=>{let n=t[0].dims,i=n,a=2,s=n[0],u=n[1],d=$e.sizeFromDimension(n,a),c=_r(d),g=$e.size(i)/c,m=Ha(e,t[0],t[1],t[2],s,d,u,r.epsilon),l=[s,u,d/c],T=[s,u],x=["type","none"],C=z=>{let U=Qe("x",t[0].dataType,l.length,c),A=Qe("scale_shift",1,T.length,2),ee=qt("output",t[0].dataType,l.length,c),te=[U,A,ee];return` ${z.registerUniform("output_size","u32").declareVariables(...te)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${ee.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${A.getByIndices("vec2(batch, channel)")}; let value = ${U.getByOffset("global_idx")} * ${ee.type.value}(scale_shift.x) + ${ee.type.value}(scale_shift.y); ${ee.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...Et(l,T,l)]}),getShaderSource:C},{inputs:[t[0],m]})},Gu=(e,t,r)=>{let n=t[0].dims,i=n,a=n[0],s=n[n.length-1],u=$e.sizeFromDimension(n,1)/s,d=_r(s),c=$e.size(i)/d,g=[{type:12,data:u},{type:12,data:Math.floor(s/d)}],m=["type","type"],l=[0,n.length-1];for(let z=0;z{let U=fr(t[0].dataType),A=d===1?"vec2f":`mat${d}x2f`,ee=ke=>{let Pe=ke===0?"x":"y",Ye=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${U}(${Ye}(scale.${Pe}))`;case 2:return`vec2<${U}>(${Ye}(scale[0].${Pe}, scale[1].${Pe}))`;case 4:return`vec4<${U}>(${Ye}(scale[0].${Pe}, scale[1].${Pe}, scale[2].${Pe}, scale[3].${Pe}))`;default:throw new Error(`Not supported compoents ${d}`)}},te=Qe("input",t[0].dataType,t[0].dims,d),ie=qt("output",t[0].dataType,i,d);return` @group(0) @binding(0) var input : array<${te.type.storage}>; @group(0) @binding(1) var scale_input : array<${A}>; @group(0) @binding(2) var output : array<${ie.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${z.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${ee(0)}, ${ee(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:C},{inputs:[t[0],x]})},qu=(e,t)=>{t.format==="NHWC"?Gu(e,e.inputs,t):Wu(e,e.inputs,t)}}),Ka,Hu,Ku,Hd=L(()=>{Yt(),Kt(),pr(),Ka=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Hu=(e,t,r)=>{let n=t.simplified,i=e[0].dims,a=e[1],s=!n&&e[2],u=i,d=$e.normalizeAxis(t.axis,i.length),c=$e.sizeToDimension(i,d),g=$e.sizeFromDimension(i,d),m=$e.size(a.dims),l=s?$e.size(s.dims):0;if(m!==g||s&&l!==g)throw new Error(`Size of X.shape()[axis:] == ${g}. Size of scale and bias (if provided) must match this. Got scale size of ${m} and bias size of ${l}`);let T=[];for(let ie=0;ie1,A=r>2,ee=ie=>{let ke=fr(e[0].dataType),Pe=[Qe("x",e[0].dataType,e[0].dims,x),Qe("scale",a.dataType,a.dims,x)];s&&Pe.push(Qe("bias",s.dataType,s.dims,x)),Pe.push(qt("output",e[0].dataType,u,x)),U&&Pe.push(qt("mean_data_output",1,T)),A&&Pe.push(qt("inv_std_output",1,T));let Ye=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${ie.registerUniforms(Ye).declareVariables(...Pe)} ${ie.mainStart()} ${ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${as("f32",x)}; var mean_square_vector = ${as("f32",x)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Kn(ke,x,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${jn("mean_vector",x)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${jn("mean_square_vector",x)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Kn(ke,x,"x[j + offset]")}; let f32scale = ${Kn(ke,x,"scale[j]")}; output[j + offset] = ${Pe[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${s?`+ ${Kn(ke,x,"bias[j]")}`:""} ); } ${U?"mean_data_output[global_idx] = mean":""}; ${A?"inv_std_output[global_idx] = inv_std_dev":""}; }`},te=[{dims:u,dataType:e[0].dataType}];return U&&te.push({dims:T,dataType:1}),A&&te.push({dims:T,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${x};${r};${n}`,inputDependencies:C},getRunData:()=>({outputs:te,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:z}),getShaderSource:ee}},Ku=(e,t)=>{Ka(e.inputs),e.compute(Hu(e.inputs,t,e.outputCount))}}),Xu,Qu,Yu,Zu,Ju,Kd=L(()=>{Yt(),Kt(),Pr(),pr(),Xu=(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 i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,s=e[1];if(!$e.areEqual(s.dims,[t.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if($e.size(u)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,c=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if($e.size(d)!==c)throw new Error("zeroPoints input size error.")}},Qu=(e,t)=>{let r=e[0].dims,n=r.length,i=r[n-2],a=t.k,s=t.n,u=r.slice(0,n-2),d=$e.size(u),c=e[1].dims[2]/4,g=e[0].dataType,m=_r(t.k),l=_r(c),T=_r(s),x=u.concat([i,s]),C=i>1&&s/T%2===0?2:1,z=$e.size(x)/T/C,U=64,A=[],ee=[d,i,a/m],te=$e.convertShape(e[1].dims).slice();te.splice(-1,1,c/l),A.push(...Et(ee)),A.push(...Et(te)),A.push(...Et(e[2].dims)),e.length===4&&A.push(...Et($e.convertShape(e[3].dims)));let ie=[d,i,s/T];A.push(...Et(ie));let ke=Pe=>{let Ye=ee.length,It=Qe("a",e[0].dataType,Ye,m),Bt=Qe("b",12,te.length,l),ar=Qe("scales",e[2].dataType,e[2].dims.length),nr=[It,Bt,ar],Ht=e.length===4?Qe("zero_points",12,e[3].dims.length):void 0;Ht&&nr.push(Ht);let Er=ie.length,jr=qt("output",e[0].dataType,Er,T),hr=fr(e[0].dataType),Ir=(()=>{switch(m){case 1:return`array<${hr}, 8>`;case 2:return`mat4x2<${hr}>`;case 4:return`mat2x4<${hr}>`;default:throw new Error(`${m}-component is not supported.`)}})(),Gt=()=>{let qe=` // reuse a data var input_offset = ${It.indicesToOffset(`${It.type.indices}(batch, row, word_offset)`)}; var a_data: ${Ir}; for (var j: u32 = 0; j < ${8/m}; j++) { a_data[j] = ${It.getByOffset("input_offset")}; input_offset++; } `;for(let vt=0;vt> 4) & b_mask); b_quantized_values = ${Ir}(${Array.from({length:4},(rr,Br)=>`${hr}(b_value_lower[${Br}]), ${hr}(b_value_upper[${Br}])`).join(", ")}); b_dequantized_values = ${m===1?`${Ir}(${Array.from({length:8},(rr,Br)=>`(b_quantized_values[${Br}] - ${Ht?`zero_point${vt}`:"zero_point"}) * scale${vt}`).join(", ")});`:`(b_quantized_values - ${Ir}(${Array(8).fill(`${Ht?`zero_point${vt}`:"zero_point"}`).join(",")})) * scale${vt};`}; workgroup_shared[local_id.x * ${C} + ${Math.floor(vt/T)}]${T>1?`[${vt%T}]`:""} += ${Array.from({length:8/m},(rr,Br)=>`${m===1?`a_data[${Br}] * b_dequantized_values[${Br}]`:`dot(a_data[${Br}], b_dequantized_values[${Br}])`}`).join(" + ")}; `;return qe},Qt=()=>{let qe=` var col_index = col * ${T}; ${Ht?` 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 = ${hr}(8);`} `;for(let vt=0;vt> 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 = ${Ht.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${vt} = ${hr}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return qe},xr=()=>{let qe=`col_index = col * ${T};`;for(let vt=0;vt; var b_value_upper: vec4; var b_quantized_values: ${Ir}; var b_dequantized_values: ${Ir};`,qe};return` var workgroup_shared: array<${jr.type.value}, ${C*U}>; ${Pe.declareVariables(...nr,jr)} ${Pe.mainStart([U,1,1])} let output_indices = ${jr.offsetToIndices(`(global_idx / ${U}) * ${C}`)}; 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 += ${U}) { //process one block var word_offset: u32 = block * ${t.blockSize/m}; ${Qt()} for (var word: u32 = 0; word < ${c}; word += ${l}) { ${xr()} for (var i: u32 = 0; i < ${l}; i++) { ${Gt()} word_offset += ${8/m}; } } } workgroupBarrier(); if (local_id.x < ${C}) { var output_value: ${jr.type.value} = ${jr.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${U}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${C}; } ${jr.setByIndices(`${jr.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${m};${l};${T};${C};${U}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:x,dataType:g}],dispatchGroup:{x:z},programUniforms:A}),getShaderSource:ke}},Yu=(e,t)=>{let r=e[0].dims,n=r.length,i=r[n-2],a=t.k,s=t.n,u=r.slice(0,n-2),d=$e.size(u),c=e[1].dims[2]/4,g=e[0].dataType,m=_r(t.k),l=_r(c),T=u.concat([i,s]),x=128,C=s%8===0?8:s%4===0?4:1,z=x/C,U=z*l*8,A=U/m,ee=U/t.blockSize,te=$e.size(T)/C,ie=[],ke=[d,i,a/m],Pe=$e.convertShape(e[1].dims).slice();Pe.splice(-1,1,c/l),ie.push(...Et(ke)),ie.push(...Et(Pe)),ie.push(...Et(e[2].dims)),e.length===4&&ie.push(...Et($e.convertShape(e[3].dims)));let Ye=[d,i,s];ie.push(...Et(Ye));let It=Bt=>{let ar=ke.length,nr=Qe("a",e[0].dataType,ar,m),Ht=Qe("b",12,Pe.length,l),Er=Qe("scales",e[2].dataType,e[2].dims.length),jr=[nr,Ht,Er],hr=e.length===4?Qe("zero_points",12,e[3].dims.length):void 0;hr&&jr.push(hr);let Ir=Ye.length,Gt=qt("output",e[0].dataType,Ir),Qt=fr(e[0].dataType),xr=()=>{switch(m){case 1:return` let a_data0 = vec4<${Qt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Qt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${Qt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Qt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${m}-component is not supported.`)}};return` var sub_a: array<${nr.type.value}, ${A}>; var inter_results: array, ${C}>; ${Bt.declareVariables(...jr,Gt)} ${Bt.mainStart([z,C,1])} let output_indices = ${Gt.offsetToIndices(`workgroup_index * ${C}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let n_blocks_per_col = uniforms.b_shape[1]; let num_tiles = (n_blocks_per_col - 1) / ${ee} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${A}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${A}; a_offset += ${x}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${nr.getByIndices(`${nr.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${nr.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${ee} + local_id.x; ${hr?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${hr.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Qt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Qt}(8);`} let scale = ${Er.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${Ht.getByIndices(`${Ht.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/m}; for (var i: u32 = 0; i < ${l}; i++) { ${xr()} let b_value = ${l===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${Qt}>(${Array.from({length:4},(qe,vt)=>`${Qt}(b_value_lower[${vt}]), ${Qt}(b_value_upper[${vt}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Qt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(qe,vt)=>`${`dot(a_data${vt}, b_dequantized_values[${vt}])`}`).join(" + ")}; word_offset += ${8/m}; } workgroupBarrier(); } if (local_idx < ${C}) { var output_value: ${Gt.type.value} = ${Gt.type.value}(0); for (var b = 0u; b < ${z}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${Gt.setByIndices(`${Gt.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${m};${l};${z};${C}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:T,dataType:g}],dispatchGroup:{x:te},programUniforms:ie}),getShaderSource:It}},Zu=(e,t)=>{Xu(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Yu(e.inputs,t)):e.compute(Qu(e.inputs,t))},Ju=e=>or(e)}),ed,td,rd,nd,sd,id,ad,od,ld,Xd=L(()=>{Yt(),Kt(),pr(),ed=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].")}},td=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Wt("uniforms.pads",i,r)}; if (k < 0) { break; } if (k >= i32(${Wt("uniforms.x_shape",i,t)})) { break; } offset += k * i32(${Wt("uniforms.x_strides",i,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]; } `},rd=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Wt("uniforms.pads",i,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Wt("uniforms.x_shape",i,t)}) - 1); k = k % _2n_1; if(k >= i32(${Wt("uniforms.x_shape",i,t)})) { k = _2n_1 - k; } } offset += k * i32(${Wt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},nd=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Wt("uniforms.pads",i,r)}; if (k < 0) { k = 0; } if (k >= i32(${Wt("uniforms.x_shape",i,t)})) { k = i32(${Wt("uniforms.x_shape",i,t)}) - 1; } offset += k * i32(${Wt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},sd=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Wt("uniforms.pads",i,r)}; if (k < 0) { k += i32(${Wt("uniforms.x_shape",i,t)}]); } if (k >= i32(${Wt("uniforms.x_shape",i,t)})) { k -= i32(${Wt("uniforms.x_shape",i,t)}); } offset += k * i32(${Wt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},id=(e,t,r)=>{switch(r.mode){case 0:return td(e,t,r.pads.length);case 1:return rd(e,t,r.pads.length);case 2:return nd(e,t,r.pads.length);case 3:return sd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},ad=(e,t)=>{let r=$e.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=$e.size(r),a=[{type:12,data:i},{type:6,data:t.pads}],s=e.length>=3&&e[2].data;t.mode===0&&a.push({type:s?e[2].dataType:1,data:t.value}),a.push(...Et(e[0].dims,r));let u=["rank"],d=c=>{let g=qt("output",e[0].dataType,r.length),m=Qe("x",e[0].dataType,n.length),l=m.type.value,T=id(g,n.length,t),x=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&x.push({name:"constant_value",type:s?l:"f32"}),` ${c.registerUniforms(x).declareVariables(m,g)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${g.offsetToIndices("global_idx")}; var value = ${l}(0); ${T} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${s}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($e.size(r)/64)},programUniforms:a}),getShaderSource:d}},od=(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,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;da[Number(d)]=Number(u));let s=[];return a.forEach(u=>s.push(u)),{mode:t.mode,value:n,pads:s}}else return t},ld=(e,t)=>{ed(e.inputs);let r=od(e.inputs,t);e.compute(ad(e.inputs,r),{inputs:[0]})}}),js,Xa,Qa,Ya,Za,ud,dd,Ja,cd,cr,pd,nn,un,fn,es,Qd,hd,fd,f,b=L(()=>{Pt(),Yt(),Kt(),pr(),js=e=>{if(E.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Xa=(e,t,r)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),u=t.strides.slice(),d=a?t.dilations.slice():[],c=t.pads.slice();tn.adjustPoolAttributes(r,i,s,u,d,c);let g=tn.computePoolOutputShape(r,i,u,d,s,c,t.autoPad),m=Object.assign({},t);a?Object.assign(m,{kernelShape:s,strides:u,pads:c,dilations:d,cacheKey:t.cacheKey}):Object.assign(m,{kernelShape:s,strides:u,pads:c,cacheKey:t.cacheKey});let l=g.slice();return l.push(l.splice(1,1)[0]),[m,n?l:g]},Qa=(e,t)=>{let r=t.format==="NHWC",n=$e.size(e),i=$e.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:i}],s=[{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],c=t.pads[t.pads.length/2-1],g=t.pads[t.pads.length-1],m=!!(c+g);a.push({type:12,data:u},{type:12,data:d},{type:12,data:c},{type:12,data:g}),s.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 T=t.kernelShape[t.kernelShape.length-2],x=t.strides[t.strides.length-2],C=t.pads[t.pads.length/2-2],z=t.pads[t.pads.length-2];l=!!(C+z),a.push({type:12,data:T},{type:12,data:x},{type:12,data:C},{type:12,data:z}),s.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,s,!0,m,l]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=$e.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),s.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((c,g)=>c+g);return[a,s,!!d,!1,!1]}},Ya=(e,t,r,n,i,a,s,u,d,c,g,m)=>{let l=i.format==="NHWC",T=t.type.value,x=qt("output",t.type.tensor,n);if(i.kernelShape.length<=2){let C="",z="",U="",A=r-(l?2:1);if(g?C=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${A}] = indices[${A}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${A}] < 0 || xIndices[${A}] >= uniforms.x_shape[${A}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:C=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${A}] = indices[${A}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`,i.kernelShape.length===2){let ee=r-(l?3:2);m?z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ee}] = indices[${ee}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${ee}] < 0 || xIndices[${ee}] >= uniforms.x_shape[${ee}]) { pad += i32(uniforms.kw); continue; } `:z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ee}] = indices[${ee}] * uniforms.sh - uniforms.phStart + j; `,U=` } `}return` ${e.registerUniforms(d).declareVariables(t,x)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${x.offsetToIndices("global_idx")}; var xIndices = ${x.offsetToIndices("global_idx")}; var value = ${T}(${u}); var pad = 0; ${z} ${C} ${U} ${s} output[global_idx] = value; }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let C=i.kernelShape.length,z=i.pads.length,U="";return c?U=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:U=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} `,` ${e.registerUniforms(d).declareVariables(t,x)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${x.offsetToIndices("global_idx")}; var xIndices = ${x.offsetToIndices("global_idx")}; var offsets: array; var value = ${T}(${u}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${C-1}u; j++) { offsets[j] = offset / ${Wt("uniforms.kernelStrides","j",C)}; offset -= offsets[j] * ${Wt("uniforms.kernelStrides","j",C)}; } offsets[${C-1}] = offset; isPad = false; for (var j = ${r-C}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${Wt("uniforms.strides",`j - ${r-C}u`,C)} + offsets[j - ${r-C}u] - ${Wt("uniforms.pads","j - 2u",z)}; ${U} } ${s} output[global_idx] = value; }`}},Za=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,ud=e=>`${Za(e)};${e.countIncludePad}`,dd=e=>`${Za(e)};${e.storageOrder};${e.dilations}`,Ja=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}),cd=(e,t,r,n)=>{let[i,a]=Xa(t,n,r),s=Qe("x",t.dataType,t.dims.length),u=s.type.value,d="value += x_val;",c="";i.countIncludePad?c+=`value /= ${u}(uniforms.kernelSize);`:c+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[g,m,l,T,x]=Qa(a,i);g.push(...Et(t.dims,a));let C=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${l};${T};${x}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil($e.size(a)/64)},programUniforms:g}),getShaderSource:z=>Ya(z,s,t.dims.length,a.length,i,d,c,0,m,l,T,x)}},cr=e=>{let t=e.count_include_pad!==0,r=Ja(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:ud(n)}},pd=(e,t)=>{js(e.inputs),e.compute(cd("AveragePool",e.inputs[0],!1,t))},nn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},un=e=>{let t=e.format;return{format:t,...nn,cacheKey:t}},fn=(e,t)=>{js(e.inputs),e.compute(cd("GlobalAveragePool",e.inputs[0],!0,t))},es=(e,t,r,n)=>{let[i,a]=Xa(t,n,r),s=` value = max(x_val, value); `,u="",d=Qe("x",t.dataType,t.dims.length),c=["rank"],[g,m,l,T,x]=Qa(a,i);return g.push(...Et(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${l};${T};${x}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil($e.size(a)/64)},programUniforms:g}),getShaderSource:C=>Ya(C,d,t.dims.length,a.length,i,s,u,t.dataType===10?-65504:-1e5,m,l,T,x)}},Qd=(e,t)=>{js(e.inputs),e.compute(es("MaxPool",e.inputs[0],!1,t))},hd=e=>{let t=e.storage_order,r=e.dilations,n=Ja(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 i={storageOrder:t,dilations:r,...n,cacheKey:""};return{...i,cacheKey:dd(i)}},fd=e=>{let t=e.format;return{format:t,...nn,cacheKey:t}},f=(e,t)=>{js(e.inputs),e.compute(es("GlobalMaxPool",e.inputs[0],!0,t))}}),R,Me,Ue,Le,pt=L(()=>{Yt(),Kt(),Pr(),pr(),R=(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((i,a)=>a===t.axis||i===e[0].dims[a]).reduce((i,a)=>i&&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)].")}},Me=(e,t)=>{let r=$e.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,a=e[0].dims,s=e[1].dataType,u=$e.size(a),d=n===3||n===2,c=d?[Math.ceil($e.size(e[0].dims)/4)]:e[0].dims,g=e[1].dims,m=e.length>2?e[2]:void 0,l=m?d?[Math.ceil($e.size(m.dims)/4)]:m.dims:void 0,T=g.length===0||g.length===1&&g[0]===1,x=T===!1&&g.length===1,C=_r(u),z=T&&(!d||C===4),U=z?C:1,A=z&&!d?C:1,ee=Qe("input",d?12:n,c.length,A),te=Qe("scale",s,g.length),ie=m?Qe("zero_point",d?12:n,l.length):void 0,ke=qt("output",s,a.length,U),Pe=[ee,te];ie&&Pe.push(ie);let Ye=[c,g];m&&Ye.push(l);let It=[{type:12,data:u/U},{type:12,data:r},{type:12,data:t.blockSize},...Et(...Ye,a)],Bt=ar=>{let nr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${ar.registerUniforms(nr).declareVariables(...Pe,ke)} ${ar.mainStart()} ${ar.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${ke.offsetToIndices("global_idx")}; // Set input x ${d?` let input = ${ee.getByOffset("global_idx / 4")}; let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${U===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ee.getByOffset("global_idx")};`}; // Set scale input ${T?`let scale_value= ${te.getByOffset("0")}`:x?` let scale_index = ${ke.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${te.getByOffset("scale_index")};`:` var scale_indices: ${te.type.indices} = output_indices; let index = ${te.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${te.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${te.getByIndices("scale_indices")};`}; // Set zero-point input ${ie?T?d?` let zero_point_input = ${ie.getByOffset("0")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${ie.getByOffset("0")}`:x?d?` let zero_point_index = ${ke.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${ie.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${ke.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${ie.getByOffset("zero_point_index")};`:d?` let zero_point_offset = ${te.indicesToOffset("scale_indices")}; let zero_point_input = ${ie.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${ie.getByIndices("scale_indices")};`:`let zero_point_value = ${d?i?"i32":"u32":ee.type.value}(0);`}; // Compute and write output ${ke.setByOffset("global_idx",`${ke.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:ie?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Bt,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(u/U/64),y:1,z:1},programUniforms:It})}},Ue=(e,t)=>{R(e.inputs,t),e.compute(Me(e.inputs,t))},Le=e=>or({axis:e.axis,blockSize:e.blockSize})}),kt,Vt,tr,zr=L(()=>{Pt(),Yt(),pr(),kt=(e,t,r)=>{let n=e===t,i=et&&r>0;if(n||i||a)throw new Error("Range these inputs' contents are invalid.")},Vt=(e,t,r,n)=>{let i=Math.abs(Math.ceil((t-e)/r)),a=[i],s=i,u=[{type:12,data:s},{type:n,data:e},{type:n,data:r},...Et(a)],d=c=>{let g=qt("output",n,a.length),m=g.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:m},{name:"delta",type:m}];return` ${c.registerUniforms(l).declareVariables(g)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${m}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},tr=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]),E.webgpu.validateInputContent&&kt(t,r,n),e.compute(Vt(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),Dr,wr,ir,Ar,$r,yr,Lr,Tn,dn,Gr,Qr,Kr,wn,ts,mi,eo,xc,Bn,xs,Tc=L(()=>{Yt(),Kt(),Pr(),pr(),Dr=(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")}},wr=(e,t,r)=>{t.every(i=>i>=0&&i{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((i,a)=>n[i]=e[a]),n},ir=(e,t,r,n,i,a)=>{let[s,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(s>0&&e.length>s&&e[s].dims.length>0)e[s].getFloat32Array().forEach(g=>a.push(g));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach(g=>n.push(g)),n.length!==0&&n.length!==c&&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");Dr(n,t),t.axes.length>0&&wr(n,t.axes,c).forEach((g,m)=>n[m]=g)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(g=>i.push(Number(g))),i.length!==0&&i.length!==c&&r>=18&&i.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.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 i<"u"&&n.length>0&&i.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Ar=(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`)}})()+"}",$r=(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`)}})()+"}",yr=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),i=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,s)=>{n[a]=i[s],n[s+r]=i[t.length+s]}),n):i},Lr=(e,t,r,n)=>{let i=[];if(r.length>0)if(n.length>0){if(e.forEach(a=>i.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,s)=>i[a]=r[s])}else r.forEach(a=>i.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((a,s)=>Math.round(a*t[s]))}return i},Tn=(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 i=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.axes.forEach(a=>i[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),i.forEach((a,s)=>i[s]=Math.round(a*t[s]))),i},dn=(e,t,r,n,i)=>` 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 = ${Wt("uniforms.scales","i",n)}; var roi_low = ${Wt("uniforms.roi","i",i)}; var roi_hi = ${Wt("uniforms.roi",`i + ${t.length}`,i)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Wt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Wt("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; }`,Gr=(e,t,r,n,i,a,s)=>` 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 = ${Wt("uniforms.scales","i",i)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Wt("uniforms.roi","i",a)}; var roi_hi = ${Wt("uniforms.roi",`i + ${r.length}`,a)}; var input_shape_i = ${Wt("uniforms.input_shape","i",r.length)}; var output_shape_i = ${Wt("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${s} || (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; }`,Qr=(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 >= ${Wt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,Kr=(e,t,r,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",wn=(e,t,r,n,i)=>{let[a,s,u,d]=r.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",s,`max(0, min(row, ${r[s]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; ${Kr(e,d,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${c} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${c} = originalIndices[${s}]; var col:${c} = originalIndices[${u}]; ${n?`if (row < 0 || row > (${r[s]} - 1) || col < 0 || col > (${r[u]} - 1)) { return ${i}; }`:""}; row = max(0, min(row, ${r[s]} - 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: ${c} = getInputValue(batch, channel, row1, col1); var x12: ${c} = getInputValue(batch, channel, row1, col2); var x21: ${c} = getInputValue(batch, channel, row2, col1); var x22: ${c} = getInputValue(batch, channel, row2, col2); var dx1: ${c} = abs(row - ${c}(row1)); var dx2: ${c} = abs(${c}(row2) - row); var dy1: ${c} = abs(col - ${c}(col1)); var dy2: ${c} = abs(${c}(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); }`},ts=(e,t,r,n,i,a,s,u,d,c)=>{let g=r.length===2,[m,l]=g?[0,1]:[2,3],T=e.type.value,x=C=>{let z=C===m?"row":"col";return` fn ${z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${T} { var output_index = ${t.indicesGet("output_indices",C)}; var originalIdx: ${T} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[C]}, ${n[C]}, ${r[C]}, ${a[C]}, ${a[C]} + ${r.length}); var fractOriginalIdx: ${T} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${u} && (originalIdx < 0 || originalIdx > (${r[C]} - 1))) { return ${d}; } var data: array<${T}, 4> = array<${T}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${z}: ${T} = originalIdx + ${T}(i); if (${z} < 0 || ${z} >= ${r[C]}) { ${c?`coefs[i + 1] = 0.0; continue;`:u?`return ${d};`:`${z} = max(0, min(${z}, ${r[C]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",C,`u32(${z})`)}; data[i + 1] = ${C===m?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${x(m)}; ${x(l)}; fn getCubicInterpolationCoefs(s: ${T}) -> array<${T}, 4> { var absS = abs(s); var coeffs: array<${T}, 4> = array<${T}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${T} = 1.0 - absS; var twoMinusAbsS: ${T} = 2.0 - absS; var onePlusAbsS: ${T} = 1.0 + absS; coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s}; coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1; coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s}; return coeffs; } fn cubicInterpolation1D(x: array<${T}, 4>, coefs: array<${T}, 4>) -> ${T} { var coefsSum: ${T} = 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}) -> ${T} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},mi=(e,t,r,n,i)=>{let[a,s,u,d,c]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],g=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${g} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",s,`max(0, min(depth, ${r[s]} - 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))`)}; ${Kr(e,c,a,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${g} = originalIndices[${s}]; var height:${g} = originalIndices[${u}]; var width:${g} = originalIndices[${d}]; ${n?`if (depth < 0 || depth > (${r[s]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { return ${i}; }`:""}; depth = max(0, min(depth, ${r[s]} - 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[${c}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${g} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${g} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${g} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${g} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${g} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${g} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${g} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${g} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${g} = abs(depth - ${g}(depth1)); var dx2: ${g} = abs(${g}(depth2) - depth); var dy1: ${g} = abs(height - ${g}(height1)); var dy2: ${g} = abs(${g}(height2) - height); var dz1: ${g} = abs(width - ${g}(width1)); var dz2: ${g} = abs(${g}(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); }`},eo=(e,t,r,n,i,a)=>{let s=e.dims,u=yr(a,t.axes,s.length),d=Lr(s,n,i,t.axes),c=n.slice();n.length===0&&(c=s.map((A,ee)=>A===0?1:d[ee]/A),t.keepAspectRatioPolicy!=="stretch"&&(d=Tn(s,c,t)));let g=qt("output",e.dataType,d.length),m=Qe("input",e.dataType,s.length),l=$e.size(d),T=s.length===d.length&&s.every((A,ee)=>A===d[ee]),x=t.coordinateTransformMode==="tf_crop_and_resize",C=t.extrapolationValue,z=m.type.value,U=A=>` ${T?"":` ${Ar(t.coordinateTransformMode,z)}; ${(()=>{switch(t.mode){case"nearest":return` ${Qr(m,s)}; ${$r(t.nearestMode,r,z)}; ${Gr(m,g,s,d,c.length,u.length,x)}; `;case"linear":return` ${dn(g,s,d,c.length,u.length)}; ${(()=>{if(s.length===2||s.length===4)return`${wn(m,g,s,x,C)}`;if(s.length===3||s.length===5)return`${mi(m,g,s,x,C)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(s.length===2||s.length===4)return`${ts(m,g,s,d,c,u,t.cubicCoeffA,x,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")}})()}; `} ${A.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",u.length).declareVariables(m,g)} ${A.mainStart()} ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${T?"output[global_idx] = input[global_idx];":` let output_indices = ${g.offsetToIndices("global_idx")}; var input_indices: ${m.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${m.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${s.length===2||s.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}|${c.length>0?c:""}|${i.length>0?i:""}|${u.length>0?u:""}|${T}|${s}`,inputDependencies:["rank"]},getShaderSource:U,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:c},{type:1,data:u},...Et(s,d)]})}},xc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Bn=(e,t)=>{let r=[],n=[],i=[],a=xc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");ir(e.inputs,t,a,r,n,i),e.compute(eo(e.inputs[0],t,a,r,n,i),{inputs:[0]})},xs=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,s=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return or({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:a,extrapolationValue:s,keepAspectRatioPolicy:u,mode:d,nearestMode:c})}}),Yd,Zd,md,Ff=L(()=>{Yt(),Kt(),Pr(),pr(),Yd=(e,t)=>{let[r,n,i,a]=e,{numHeads:s,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(!$e.areEqual(n.dims,[])&&!$e.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!$e.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&s===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],c=r.dims[r.dims.length-2],g=i.dims[0],m=$e.sizeFromDimension(r.dims,1)/c,l=u===0?i.dims[1]*2:m/s;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(c!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(l/2!==i.dims[1]&&u/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(c>g)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Zd=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:i,scale:a}=t,s=e[0].dims[0],u=$e.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],c=u/d,g=e[2].dims[1],m=i===0?g*2:c/n,l=new Array(s,d,c/m,m-g),T=$e.computeStrides(l),x=[{type:1,data:a},{type:12,data:l},{type:12,data:T},...e[0].dims.length===3?new Array({type:12,data:[u,c,m,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,m,d*m,1]}):[],...Et(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],C=z=>{let U=Qe("input",e[0].dataType,e[0].dims.length),A=Qe("position_ids",e[1].dataType,e[1].dims.length),ee=Qe("cos_cache",e[2].dataType,e[2].dims.length),te=Qe("sin_cache",e[3].dataType,e[3].dims.length),ie=qt("output",e[0].dataType,e[0].dims.length);return z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:T.length},{name:"input_output_strides",type:"u32",length:T.length}]),` ${z.declareVariables(U,A,ee,te,ie)} ${z.mainStart(pn)} let half_rotary_emb_dim = uniforms.${ee.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${z.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${A.broadcastedIndicesToOffset("bsnh.xy",qt("",A.type.tensor,2))}; let position_id = u32(${A.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 = ${U.getByOffset("i")} * ${ee.get("position_id","bsnh[3]")} - ${U.getByOffset("j")} * ${te.get("position_id","bsnh[3]")}; ${ie.setByOffset("i","re")} let im = ${U.getByOffset("i")} * ${te.get("position_id","bsnh[3]")} + ${U.getByOffset("j")} * ${ee.get("position_id","bsnh[3]")}; ${ie.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${ie.setByOffset("k",U.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:or({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:C,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($e.size(l)/pn)},programUniforms:x})}},md=(e,t)=>{Yd(e.inputs,t),e.compute(Zd(e.inputs,t))}}),hp,fp,mp,Of=L(()=>{Yt(),Kt(),pr(),hp=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 i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==i)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]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let s=e[3];if(s.dims.length!==1)throw new Error("Beta must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let s=e[4];if(s.dims.length!==1)throw new Error("Bias must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},fp=(e,t,r,n)=>{let i=t.simplified,a=e[0].dims,s=$e.size(a),u=a,d=s,c=a.slice(-1)[0],g=n?a.slice(0,-1).concat(1):[],m=!i&&e.length>3,l=e.length>4,T=n&&r>1,x=n&&r>2,C=r>3,z=64,U=_r(c),A=[{type:12,data:d},{type:12,data:U},{type:12,data:c},{type:1,data:t.epsilon}],ee=ie=>{let ke=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Pe=[Qe("x",e[0].dataType,e[0].dims,U),Qe("skip",e[1].dataType,e[1].dims,U),Qe("gamma",e[2].dataType,e[2].dims,U)];m&&Pe.push(Qe("beta",e[3].dataType,e[3].dims,U)),l&&Pe.push(Qe("bias",e[4].dataType,e[4].dims,U)),Pe.push(qt("output",e[0].dataType,u,U)),T&&Pe.push(qt("mean_output",1,g)),x&&Pe.push(qt("inv_std_output",1,g)),C&&Pe.push(qt("input_skip_bias_sum",e[0].dataType,u,U));let Ye=fr(e[0].dataType),It=fr(1,U);return` ${ie.registerUniforms(ke).declareVariables(...Pe)} var sum_shared : array<${It}, ${z}>; var sum_squared_shared : array<${It}, ${z}>; ${ie.mainStart([z,1,1])} let ix = local_id.x; let iy = global_id.x / ${z}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${z}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${z-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${l?"bias[offset1d + i]":Ye+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${C?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Kn(Ye,U,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${z}; for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { reduce_size = curr_size + (reduce_size & 1); if (ix < curr_size) { sum_shared[ix] += sum_shared[ix + reduce_size]; sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; } workgroupBarrier(); } let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; let mean = ${jn("sum",U)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${jn("square_sum",U)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); ${T?"mean_output[global_idx] = mean;":""} ${x?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${i?"":`- ${Ye}(mean)`}) * ${Ye}(inv_std_dev) * gamma[offset1d + i] ${m?"+ beta[offset1d + i]":""}; } }`},te=[{dims:u,dataType:e[0].dataType}];return r>1&&te.push({dims:g,dataType:1}),r>2&&te.push({dims:g,dataType:1}),r>3&&te.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${U};${T};${x};${C}`,inputDependencies:e.map((ie,ke)=>"type")},getShaderSource:ee,getRunData:()=>({outputs:te,dispatchGroup:{x:Math.ceil(d/c)},programUniforms:A})}},mp=(e,t)=>{hp(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(fp(e.inputs,t,e.outputCount,!1),{outputs:r})}}),_p,_d,gp,Cc,wp,yp,bp,Mp,zf=L(()=>{Yt(),Kt(),Pr(),pr(),_p=(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`)})},_d=(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},gp=(e,t)=>{if(e.length>1){let r=_d(e,1),n=_d(e,2),i=_d(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),or({starts:r,ends:n,axes:i})}else return t},Cc=(e,t,r,n,i)=>{let a=e;return e<0&&(a+=r[n[t]]),i[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},wp=(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 = ${Wt("uniforms.input_shape","i",r.length)}; let steps_i = ${Wt("uniforms.steps","i",r.length)}; let signs_i = ${Wt("uniforms.signs","i",r.length)}; let starts_i = ${Wt("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; }`,yp=(e,t)=>{let r=e[0].dims,n=$e.size(r),i=t.axes.length>0?$e.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=_d(e,4);a.forEach(U=>U!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let s=t.starts.map((U,A)=>Cc(U,A,r,i,a)),u=t.ends.map((U,A)=>Cc(U,A,r,i,a));if(i.length!==s.length||i.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let U=0;UMath.sign(U));a.forEach((U,A,ee)=>{if(U<0){let te=(u[A]-s[A])/U,ie=s[A],ke=ie+te*a[A];s[A]=ke,u[A]=ie,ee[A]=-U}});let c=r.slice(0);i.forEach((U,A)=>{c[U]=Math.ceil((u[U]-s[U])/a[U])});let g={dims:c,dataType:e[0].dataType},m=qt("output",e[0].dataType,c.length),l=Qe("input",e[0].dataType,e[0].dims.length),T=$e.size(c),x=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:a.length}],C=[{type:12,data:T},{type:12,data:s},{type:6,data:d},{type:12,data:a},...Et(e[0].dims,c)],z=U=>` ${U.registerUniforms(x).declareVariables(l,m)} ${wp(l,m,r)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${m.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${m.setByOffset("global_idx",l.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${s.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:z,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:C})}},bp=(e,t)=>{_p(e.inputs,t);let r=gp(e.inputs,t);e.compute(yp(e.inputs,r),{inputs:[0]})},Mp=e=>{let t=e.starts,r=e.ends,n=e.axes;return or({starts:t,ends:r,axes:n})}}),vp,xp,Tp,Cp,Df=L(()=>{Yt(),Kt(),Pr(),Vn(),pr(),vp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},xp=(e,t)=>{let r=e.inputs[0],n=r.dims,i=$e.size(n),a=64,s=n.length,u=$e.normalizeAxis(t.axis,s),d=uYe),g[u]=s-1,g[s-1]=u,c=e.compute(xn(r,g),{inputs:[r],outputs:[-1]})[0]):c=r;let m=c.dims,l=m[s-1],T=i/l,x=_r(l),C=l/x,z=(Pe,Ye)=>Ye===4?`max(max(${Pe}.x, ${Pe}.y), max(${Pe}.z, ${Pe}.w))`:Ye===2?`max(${Pe}.x, ${Pe}.y)`:Ye===3?`max(max(${Pe}.x, ${Pe}.y), ${Pe}.z)`:Pe,U=Qe("x",c.dataType,c.dims,x),A=qt("result",c.dataType,c.dims,x),ee=U.type.value,te=fr(c.dataType)==="f32"?`var threadMax = ${ee}(-3.402823e+38f);`:`var threadMax = ${ee}(-65504.0h);`,ie=Pe=>` var rowMaxShared : ${ee}; var rowSumShared : ${ee}; var threadShared : array<${ee}, ${a}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${ee} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${ee}) { let index = row * row_stride + col; result[index] = value; } ${Pe.registerUniform("packedCols","i32").declareVariables(U,A)} ${Pe.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${a}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${te} 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 = ${ee}(${z("threadShared[0]",x)}); } workgroupBarrier(); // find the rows sum var threadSum = ${ee}(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 = ${ee}(${jn("threadShared[0]",x)}); } 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); } }`,ke=e.compute({name:"Softmax",shaderCache:{hint:`${x}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:c.dataType}],dispatchGroup:{x:T},programUniforms:[{type:6,data:C}]}),getShaderSource:ie},{inputs:[c],outputs:[d?-1:0]})[0];d&&e.compute(xn(ke,g),{inputs:[ke]})},Tp=(e,t)=>{vp(e.inputs),xp(e,t)},Cp=e=>or({axis:e.axis})}),$c,$p,Ep,kp,Sp,Lf=L(()=>{Yt(),Kt(),pr(),$c=e=>Array.from(e.getBigInt64Array(),Number),$p=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($c(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")},Ep=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??$c(e[1]),i=Ep(r,n),a=$e.size(i),s=e[0].dataType,u=Qe("input",s,r.length),d=qt("output",s,i.length),c=g=>` const inputShape = ${u.indices(...r)}; ${g.registerUniform("output_size","u32").declareVariables(u,d)} ${g.mainStart()} ${g.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:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...Et(e[0].dims,i)]}),getShaderSource:c}},Sp=e=>{$p(e.inputs),e.compute(kp(e.inputs),{inputs:[0]})}}),Pp,Ap,Ip,Bf=L(()=>{Yt(),Kt(),pr(),Pp=(e,t,r,n,i)=>{let a=qt("output_data",i,r.length,4),s=Qe("a_data",t[1].dataType,t[1].dims.length,4),u=Qe("b_data",t[2].dataType,t[2].dims.length,4),d=Qe("c_data",t[0].dataType,t[0].dims.length,4),c,g=(m,l,T)=>`select(${l}, ${m}, ${T})`;if(!n)c=a.setByOffset("global_idx",g(s.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let m=(l,T,x="")=>{let C=`a_data[index_a${T}][component_a${T}]`,z=`b_data[index_b${T}][component_b${T}]`,U=`bool(c_data[index_c${T}] & (0xffu << (component_c${T} * 8)))`;return` let output_indices${T} = ${a.offsetToIndices(`global_idx * 4u + ${T}u`)}; let offset_a${T} = ${s.broadcastedIndicesToOffset(`output_indices${T}`,a)}; let offset_b${T} = ${u.broadcastedIndicesToOffset(`output_indices${T}`,a)}; let offset_c${T} = ${d.broadcastedIndicesToOffset(`output_indices${T}`,a)}; let index_a${T} = offset_a${T} / 4u; let index_b${T} = offset_b${T} / 4u; let index_c${T} = offset_c${T} / 4u; let component_a${T} = offset_a${T} % 4u; let component_b${T} = offset_b${T} % 4u; let component_c${T} = offset_c${T} % 4u; ${l}[${T}] = ${x}(${g(C,z,U)}); `};i===9?c=` var data = vec4(0); ${m("data",0,"u32")} ${m("data",1,"u32")} ${m("data",2,"u32")} ${m("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` ${m("output_data[global_idx]",0)} ${m("output_data[global_idx]",1)} ${m("output_data[global_idx]",2)} ${m("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(d,s,u,a)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${c} }`},Ap=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,i=e[1].dataType,a=!($e.areEqual(t,r)&&$e.areEqual(r,n)),s=t,u=$e.size(t);if(a){let c=Mn.calcShape(Mn.calcShape(t,r,!1),n,!1);if(!c)throw new Error("Can't perform where op on the given tensors");s=c,u=$e.size(s)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Pp(c,e,s,a,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...Et(n,t,r,s)]})}},Ip=e=>{e.compute(Ap(e.inputs))}}),Fp,Rf=L(()=>{No(),ei(),Td(),Cd(),Cl(),$d(),Ed(),Pd(),zd(),hu(),Sa(),Ld(),bc(),Rd(),Cu(),Nd(),Mc(),Ud(),qd(),vc(),Hd(),Zl(),Kd(),Gd(),Xd(),b(),pt(),zr(),ji(),Tc(),Ff(),Of(),zf(),Df(),Nu(),Lf(),Vn(),ua(),Bf(),Fp=new Map([["Abs",[Zo]],["Acos",[Jo]],["Acosh",[el]],["Add",[kl]],["ArgMax",[Ro,Wi]],["ArgMin",[Ui,Wi]],["Asin",[tl]],["Asinh",[Ki]],["Atan",[rl]],["Atanh",[nl]],["Attention",[Go]],["AveragePool",[pd,cr]],["BatchNormalization",[Ko]],["BiasAdd",[Qo]],["BiasSplitGelu",[Tl]],["Cast",[il,sl]],["Ceil",[ol]],["Clip",[al]],["Concat",[Rl,ha]],["Conv",[Ca,xa]],["ConvTranspose",[du,pi]],["Cos",[Qi]],["Cosh",[ll]],["CumSum",[cu,pu]],["DepthToSpace",[_u,gu]],["DequantizeLinear",[Ue,Le]],["Div",[Sl]],["Einsum",[Fa,bu]],["Elu",[Yi,Ls]],["Equal",[ca]],["Erf",[ul]],["Exp",[Zi]],["Expand",[Bd]],["FastGelu",[Ba]],["Floor",[dl]],["FusedConv",[Ca,xa]],["Gather",[Tu,xu]],["GatherElements",[jd,Or]],["GatherBlockQuantized",[Na,ku]],["Gelu",[cl]],["Gemm",[Iu,Au]],["GlobalAveragePool",[fn,un]],["GlobalMaxPool",[f,fd]],["Greater",[Fl]],["GreaterOrEqual",[Ol]],["GroupQueryAttention",[Uu]],["HardSigmoid",[ta,ea]],["InstanceNormalization",[qu]],["LayerNormalization",[Ku]],["LeakyRelu",[Ji,Ls]],["Less",[ni]],["LessOrEqual",[zl]],["Log",[bl]],["MatMul",[Yl]],["MatMulNBits",[Zu,Ju]],["MaxPool",[Qd,hd]],["Mul",[Pl]],["MultiHeadAttention",[Wd,Ua]],["Neg",[hl]],["Not",[pl]],["Pad",[ld]],["Pow",[Al]],["QuickGelu",[vl,Ls]],["Range",[tr]],["Reciprocal",[ri]],["ReduceMin",[Do]],["ReduceMean",[Li]],["ReduceMax",[zo]],["ReduceSum",[Lo]],["ReduceProd",[Ri]],["ReduceL1",[Fo]],["ReduceL2",[Oo]],["ReduceLogSum",[Ni]],["ReduceLogSumExp",[Bi]],["ReduceSumSquare",[Bo]],["Relu",[fl]],["Resize",[Bn,xs]],["RotaryEmbedding",[md]],["Sigmoid",[ml]],["Sin",[_l]],["Sinh",[ra]],["Slice",[bp,Mp]],["SkipLayerNormalization",[mp]],["Split",[Bu,Ru]],["Sqrt",[gl]],["Softmax",[Tp,Cp]],["Sub",[Il]],["Tan",[wl]],["Tanh",[sa]],["ThresholdedRelu",[oa,Ls]],["Tile",[Sp]],["Transpose",[vd,co]],["Where",[Ip]]])}),Op,Nf=L(()=>{Pt(),_(),pr(),Op=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,i){je(e.programInfo.name);let a=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let c of t)u.push({binding:u.length,resource:{buffer:c.buffer}});for(let c of r)u.push({binding:u.length,resource:{buffer:c.buffer}});i&&u.push({binding:u.length,resource:i});let d=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:d,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}s.setPipeline(e.computePipeline),s.setBindGroup(0,d),s.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(),Ve(e.programInfo.name)}dispose(){}build(e,t){je(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let i=oo(t,this.backend.device.limits),a=e.getShaderSource(i),s=`${n.join(` `)} ${i.additionalImplementations} ${a}`,u=r.createShaderModule({code:s,label:e.name});ae("verbose",()=>`[WebGPU] ${e.name} shader code: ${s}`);let d=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Ve(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:i.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,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&r<=i&&n<=i)return[t,r,n];let a=t*r*n,s=Math.ceil(Math.sqrt(a));if(s>i){if(s=Math.ceil(Math.cbrt(a)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}else return[s,s,1]}}}),zp,Dp,Lp,Bp,jf=L(()=>{Pt(),Yt(),_(),Q(),Wr(),Rf(),Nf(),zp=(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 i,a;let n=e.name;return(i=e.shaderCache)!=null&&i.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${zp(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Lp=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Bp=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 Lp(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ur(this),this.programManager=new Op(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,is(e.logLevel,!!e.debug),this.device.onuncapturederror=i=>{i.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${i.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;je(),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 i=0;i"u"&&(this.queryTimeBase=T);let C=Number(T-this.queryTimeBase),z=Number(x-this.queryTimeBase);if(!Number.isSafeInteger(C)||!Number.isSafeInteger(z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map(U=>({dims:U.dims,dataType:An(U.dataType)})),outputsMetadata:l.map(U=>({dims:U.dims,dataType:An(U.dataType)})),kernelId:s,kernelType:d,kernelName:c,programName:g,startTime:C,endTime:z});else{let U="";m.forEach((ee,te)=>{U+=`input[${te}]: [${ee.dims}] | ${An(ee.dataType)}, `});let A="";l.forEach((ee,te)=>{A+=`output[${te}]: [${ee.dims}] | ${An(ee.dataType)}, `}),console.log(`[profiling] kernel "${s}|${d}|${c}|${g}" ${U}${A}execution time: ${z-C} ns`)}Ke("GPU",`${g}::${T}::${x}`)}e.unmap(),this.pendingQueries.delete(e)}),Ve()}run(e,t,r,n,i,a){je(e.name);let s=[];for(let A=0;Aee):r;if(g.length!==u.length)throw new Error(`Output size ${g.length} must be equal to ${u.length}.`);let m=[],l=[];for(let A=0;A=a)throw new Error(`Invalid output index: ${g[A]}`);if(g[A]===-3)continue;let ee=g[A]===-1,te=g[A]===-2,ie=ee||te?i(u[A].dataType,u[A].dims):n(g[A],u[A].dataType,u[A].dims);if(m.push(ie),ie.data===0)continue;let ke=this.gpuDataManager.get(ie.data);if(!ke)throw new Error(`no GPU data for output: ${ie.data}`);if(ee&&this.temporaryData.push(ke),te){let Pe=this.kernelPersistentData.get(this.currentKernelId);Pe||(Pe=[],this.kernelPersistentData.set(this.currentKernelId,Pe)),Pe.push(ke)}l.push(ke)}if(s.length!==t.length||l.length!==m.length){if(l.length===0)return Ve(e.name),m;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let T;if(c){let A=0,ee=[];c.forEach(Pe=>{let Ye=typeof Pe.data=="number"?[Pe.data]:Pe.data;if(Ye.length===0)return;let It=Pe.type===10?2:4,Bt,ar;Pe.type===10?(ar=Ye.length>4?16:Ye.length>2?8:Ye.length*It,Bt=Ye.length>4?16:It*Ye.length):(ar=Ye.length<=2?Ye.length*It:16,Bt=16),A=Math.ceil(A/ar)*ar,ee.push(A);let nr=Pe.type===10?8:4;A+=Ye.length>4?Math.ceil(Ye.length/nr)*Bt:Ye.length*It});let te=16;A=Math.ceil(A/te)*te;let ie=new ArrayBuffer(A);c.forEach((Pe,Ye)=>{let It=ee[Ye],Bt=typeof Pe.data=="number"?[Pe.data]:Pe.data;if(Pe.type===6)new Int32Array(ie,It,Bt.length).set(Bt);else if(Pe.type===12)new Uint32Array(ie,It,Bt.length).set(Bt);else if(Pe.type===10)new Uint16Array(ie,It,Bt.length).set(Bt);else if(Pe.type===1)new Float32Array(ie,It,Bt.length).set(Bt);else throw new Error(`Unsupported uniform type: ${An(Pe.type)}`)});let ke=this.gpuDataManager.create(A,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(ke.buffer,0,ie,0,A),this.gpuDataManager.release(ke.id),T={offset:0,size:A,buffer:ke.buffer}}let x=this.programManager.normalizeDispatchGroupSize(d),C=x[1]===1&&x[2]===1,z=Dp(e,t,C),U=this.programManager.getArtifact(z);if(U||(U=this.programManager.build(e,x),this.programManager.setArtifact(z,U),ae("info",()=>`[artifact] key: ${z}, programName: ${e.name}`)),c&&U.uniformVariablesInfo){if(c.length!==U.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${U.uniformVariablesInfo.length}, got ${c.length} in program "${U.programInfo.name}".`);for(let A=0;A`[ProgramManager] run "${e.name}" (key=${z}) with ${x[0]}x${x[1]}x${x[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let A={kernelId:this.currentKernelId,programName:U.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push(A),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(A)}return this.programManager.run(U,s,l,x,T),Ve(e.name),m}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 i=Fp.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[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 i=n.kernelType,a=n.kernelName,s=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),ae("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),s(t,u[1]),0}catch(c){return r.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${c}`)),1}finally{d&&r.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${a}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),s=this.gpuDataManager.registerExternalBuffer(r,n,a);return i.set(t,[s,r]),s}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let n=await er(this,e,t);return I(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(){ae("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(){ae("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ae("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Rp,Ec,kc,Sc,Np,jp,Vf=L(()=>{_(),Rp=1,Ec=()=>Rp++,kc=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}destroy(){ae("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.every((r,n)=>r===t[n])}},Sc=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&this.tensorManager.releaseTensor(this.tensorWrapper)}async ensureTensor(e,t,r){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;r&&(this.activeUpload=new Uint8Array(await this.wrapper.read())),this.tensorManager.releaseTensor(this.wrapper)}let n=MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,!0,!0),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper){this.wrapper.write(e);return}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Np=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Ec();return this.tensorTrackersById.set(e,new Sc(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n){ae("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${n}}`);let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(t,r,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){ae("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,n){let i=Ec(),a=new kc({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(i,new Sc(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,r,n,i){let a=this.backend.currentSessionId;for(let[d,c]of this.freeTensors.entries())if(c.sameTypeAndShape(e,t)){let g=this.freeTensors.splice(d,1)[0];return g.sessionId=a,g}let s=this.backend.currentContext;ae("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let u=await s.createTensor({dataType:e,shape:t,dimensions:t,usage:r,writable:n,readable:i});return new kc({sessionId:a,context:s,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},jp=(...e)=>new Np(...e)}),Pc,Vp,Uf=L(()=>{Yt(),kr(),Q(),Vf(),_(),Pc=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Vp=class{constructor(e){this.tensorManager=jp(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,is(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);r.delete(e),r.size===0&&this.sessionIdsByMLContext.delete(t)}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ae("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n){let i=Pc.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,r,n)}uploadTensor(e,t){if(!mr().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ae("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return I(r,t)}}registerMLTensor(e,t,r){let n=Pc.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,n,r);return ae("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${r}} -> {tensorId: ${i}}`),i}registerMLConstant(e,t,r,n,i,a){if(!a)throw new Error("External mounted files are not available.");let s=e;e.startsWith("./")&&(s=e.substring(2));let u=a.get(s);if(!u)throw new Error(`File with name ${s} not found in preloaded files.`);if(t+r>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let d=u.slice(t,t+r).buffer,c;switch(i.dataType){case"float32":c=new Float32Array(d);break;case"float16":c=new Uint16Array(d);break;case"int32":c=new Int32Array(d);break;case"uint32":c=new Uint32Array(d);break;case"int64":c=new BigInt64Array(d);break;case"uint64":c=new BigUint64Array(d);break;case"int8":c=new Int8Array(d);break;case"uint8":c=new Uint8Array(d);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return ae("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),n.constant(i,c)}flush(){}}}),Up={};P(Up,{init:()=>Gp});var Jd,Wp,Gp,Wf=L(()=>{Yt(),jf(),_(),Kt(),Uf(),Jd=class Sf{constructor(t,r,n,i){this.module=t,this.dataType=r,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=$e.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=$e.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=$e.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=$e.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if($e.size(t)!==$e.size(this.dims))throw new Error("Invalid new shape");return new Sf(this.module,this.dataType,this.data,t)}},Wp=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,i=r>>>2;this.opKernelContext=n[i++];let a=n[i++];this.outputCount=n[i++],this.customDataOffset=n[i++],this.customDataSize=n[i++];let s=[];for(let u=0;utypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(u,d,c)=>new Jd(this.module,d,this.output(u,c),c),a=(u,d)=>{let c=Rn(u,d);if(!c)throw new Error(`Unsupported data type: ${u}`);let g=c>0?this.backend.gpuDataManager.create(c).id:0;return new Jd(this.module,u,g,d)};return this.backend.run(e,r,n,i,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),i=n>>2;this.module.HEAPU32[i++]=t.length;for(let a=0;a{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Bp;await a.initialize(r,n),i("webgpu",[a,s=>a.alloc(s),s=>a.free(s),(s,u,d,c=!1)=>{if(c)ae("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${u}, size=${d}`),a.memcpy(s,u);else{ae("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${u}, size=${d}`);let g=t.HEAPU8.subarray(s>>>0,(s>>>0)+d);a.upload(u,g)}},async(s,u,d)=>{ae("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${s}, dataOffset=${u}, size=${d}`),await a.download(s,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+d))},(s,u,d)=>a.createKernel(s,u,d,t.UTF8ToString(t._JsepGetNodeName(u))),s=>a.releaseKernel(s),(s,u,d,c)=>{ae("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${s}, contextDataOffset=${u}`);let g=new Wp(t,a,u);return a.computeKernel(s,g,c)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new Vp(r);i("webnn",[a,()=>a.reserveTensorId(),s=>a.releaseTensorId(s),async(s,u,d,c)=>a.ensureTensor(s,u,d,c),(s,u)=>{a.uploadTensor(s,u)},async(s,u)=>a.downloadTensor(s,u)])}}}),qp,Ac,Ic,Vs,Hp,ec,Fc,Oc,zc,Dc,Lc,Bc,Kp=L(()=>{qn(),ns(),Yt(),kr(),fs(),Is(),qp=(e,t)=>{mr()._OrtInit(e,t)!==0&&Ur("Can't initialize onnxruntime.")},Ac=async e=>{qp(e.wasm.numThreads,Ln(e.logLevel))},Ic=async(e,t)=>{{let r=(Wf(),B(Up)).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 i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);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:i,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,Hp=e=>{let t=mr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Ur("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},ec=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]},Fc=async(e,t)=>{var m,l,T;let r,n,i=mr();Array.isArray(e)?[r,n]=e:e.buffer===i.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=ec(e);let a=0,s=0,u=0,d=[],c=[],g=[];try{if([s,d]=As(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let ie=[];for(let ke of t.externalData){let Pe=typeof ke=="string"?ke:ke.path;ie.push(ss(typeof ke=="string"?ke:ke.data).then(Ye=>{i.mountExternalData(Pe,Ye)}))}await Promise.all(ie)}for(let ie of(t==null?void 0:t.executionProviders)??[])if((typeof ie=="string"?ie:ie.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,i.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof ie!="string"){let ke=ie,Pe=ke==null?void 0:ke.context,Ye=ke==null?void 0:ke.gpuDevice,It=ke==null?void 0:ke.deviceType,Bt=ke==null?void 0:ke.powerPreference;Pe?i.currentContext=Pe:Ye?i.currentContext=await navigator.ml.createContext(Ye):i.currentContext=await navigator.ml.createContext({deviceType:It,powerPreference:Bt})}else i.currentContext=await navigator.ml.createContext();break}a=await i._OrtCreateSession(r,n,s),a===0&&Ur("Can't create a session."),(m=i.jsepOnCreateSession)==null||m.call(i),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[x,C]=Hp(a),z=!!(t!=null&&t.enableGraphCapture),U=[],A=[],ee=[];for(let ie=0;ieie==="gpu-buffer"||ie==="ml-tensor")&&(u=i._OrtCreateBinding(a),u===0&&Ur("Can't create IO binding."),te={handle:u,outputPreferredLocations:ee,outputPreferredLocationsEncoded:ee.map(ie=>ws(ie))}),Vs.set(a,[a,c,g,te,z,!1]),[a,U,A]}catch(x){throw c.forEach(C=>i._OrtFree(C)),g.forEach(C=>i._OrtFree(C)),u!==0&&i._OrtReleaseBinding(u),a!==0&&i._OrtReleaseSession(a),x}finally{i._free(r),s!==0&&i._OrtReleaseSessionOptions(s),d.forEach(x=>i._free(x)),(T=i.unmountExternalData)==null||T.call(i)}},Oc=e=>{var d;let t=mr(),r=Vs.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,a,s,u]=r;s&&(u&&t._OrtClearBoundOutputs(s.handle),t._OrtReleaseBinding(s.handle)),(d=t.jsepOnReleaseSession)==null||d.call(t,e),i.forEach(c=>t._OrtFree(c)),a.forEach(c=>t._OrtFree(c)),t._OrtReleaseSession(n),Vs.delete(e)},zc=(e,t,r,n,i,a=!1)=>{if(!e){t.push(0);return}let s=mr(),u=e[0],d=e[1],c=e[3],g,m;if(u==="string"&&(c==="gpu-buffer"||c==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&c!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(c==="gpu-buffer"){let x=e[2].gpuBuffer;m=Rn(Hn(u),d);let C=s.jsepRegisterBuffer;if(!C)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=C(n,i,x,m)}else if(c==="ml-tensor"){let x=e[2].mlTensor;m=Rn(Hn(u),d);let C=s.jsepRegisterMLTensor;if(!C)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=C(x,Hn(u),d)}else{let x=e[2];if(Array.isArray(x)){m=4*x.length,g=s._malloc(m),r.push(g);let C=g/4;for(let z=0;zs.HEAP32[x++]=z);let C=s._OrtCreateTensor(Hn(u),g,m,T,d.length,ws(c));C===0&&Ur(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(C)}finally{s.stackRestore(l)}},Dc=async(e,t,r,n,i,a)=>{var Bt,ar;let s=mr(),u=Vs.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=u[0],c=u[1],g=u[2],m=u[3],l=u[4],T=u[5],x=t.length,C=n.length,z=0,U=[],A=[],ee=[],te=[],ie=s.stackSave(),ke=s.stackAlloc(x*4),Pe=s.stackAlloc(x*4),Ye=s.stackAlloc(C*4),It=s.stackAlloc(C*4);try{(Bt=s.jsepOnRunStart)==null||Bt.call(s,d),[z,U]=$s(a);for(let Gt=0;Gtcn*vn,1);rr=An(an);let wi=m==null?void 0:m.outputPreferredLocations[n[Gt]];if(rr==="string"){if(wi==="gpu-buffer"||wi==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let cn=[],vn=Br/4;for(let Un=0;Un0){let cn=s.jsepGetBuffer;if(!cn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let vn=cn(Br),Un=Rn(an,mn);if(Un===void 0||!_s(rr))throw new Error(`Unsupported data type: ${rr}`);vt=!0,Ir.push([rr,Sn,{gpuBuffer:vn,download:s.jsepCreateDownloader(vn,Un,rr),dispose:()=>{s._OrtReleaseTensor(Qt)}},"gpu-buffer"])}else if(wi==="ml-tensor"&&mn>0){let cn=s.jsepEnsureTensor;if(!cn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Rn(an,mn)===void 0||!gs(rr))throw new Error(`Unsupported data type: ${rr}`);let vn=await cn(Br,an,Sn,!1);vt=!0,Ir.push([rr,Sn,{mlTensor:vn,download:s.jsepCreateMLTensorDownloader(Br,rr),dispose:()=>{s.jsepReleaseTensorId(Br),s._OrtReleaseTensor(Qt)}},"ml-tensor"])}else{let cn=ms(rr),vn=new cn(mn);new Uint8Array(vn.buffer,vn.byteOffset,vn.byteLength).set(s.HEAPU8.subarray(Br,Br+vn.byteLength)),Ir.push([rr,Sn,vn,"cpu"])}}finally{s.stackRestore(xr),rr==="string"&&Br&&s._free(Br),vt||s._OrtReleaseTensor(Qt)}}return m&&!l&&(s._OrtClearBoundOutputs(m.handle),Vs.set(e,[d,c,g,m,l,!1])),Ir}finally{s.stackRestore(ie),A.forEach(nr=>s._OrtReleaseTensor(nr)),ee.forEach(nr=>s._OrtReleaseTensor(nr)),te.forEach(nr=>s._free(nr)),z!==0&&s._OrtReleaseRunOptions(z),U.forEach(nr=>s._free(nr))}},Lc=e=>{let t=mr(),r=Vs.get(e);if(!r)throw new Error("invalid session id");let n=r[0],i=t._OrtEndProfiling(n);i===0&&Ur("Can't get an profile file name."),t._OrtFree(i)},Bc=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,to,gd,wd,tc,Rc,rc,_i,gi,Xp,Qp,Yp,Zp,Jp,eh,th,rh,nh=L(()=>{Pt(),Kp(),kr(),Ft(),Us=()=>!!E.wasm.proxy&&typeof document<"u",to=!1,gd=!1,wd=!1,rc=new Map,_i=(e,t)=>{let r=rc.get(e);r?r.push(t):rc.set(e,[t])},gi=()=>{if(to||!gd||wd||!Dn)throw new Error("worker not ready")},Xp=e=>{switch(e.data.type){case"init-wasm":to=!1,e.data.err?(wd=!0,Rc[1](e.data.err)):(gd=!0,Rc[0]()),tc&&(URL.revokeObjectURL(tc),tc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=rc.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Qp=async()=>{if(!gd){if(to)throw new Error("multiple calls to 'initWasm()' detected.");if(wd)throw new Error("previous call to 'initWasm()' failed.");if(to=!0,Us())return new Promise((e,t)=>{Dn==null||Dn.terminate(),ft().then(([r,n])=>{try{Dn=n,Dn.onerror=a=>t(a),Dn.onmessage=Xp,Rc=[e,t];let i={type:"init-wasm",in:E};Dn.postMessage(i),tc=r}catch(i){t(i)}},t)});try{await Nr(E.wasm),await Ac(E),gd=!0}catch(e){throw wd=!0,e}finally{to=!1}}},Yp=async e=>{if(Us())return gi(),new Promise((t,r)=>{_i("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:E}};Dn.postMessage(n)});await Ic(E,e)},Zp=async e=>Us()?(gi(),new Promise((t,r)=>{_i("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Dn.postMessage(n,[e.buffer])})):ec(e),Jp=async(e,t)=>{if(Us()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return gi(),new Promise((r,n)=>{_i("create",[r,n]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Dn.postMessage(i,a)})}else return Fc(e,t)},eh=async e=>{if(Us())return gi(),new Promise((t,r)=>{_i("release",[t,r]);let n={type:"release",in:e};Dn.postMessage(n)});Oc(e)},th=async(e,t,r,n,i,a)=>{if(Us()){if(r.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return gi(),new Promise((s,u)=>{_i("run",[s,u]);let d=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:a}};Dn.postMessage(c,Bc(d))})}else return Dc(e,t,r,n,i,a)},rh=async e=>{if(Us())return gi(),new Promise((t,r)=>{_i("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Dn.postMessage(n)});Lc(e)}}),Nc,sh,ih,Gf=L(()=>{Pt(),nh(),Yt(),dr(),Is(),Nc=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},sh=e=>{switch(e[3]){case"cpu":return new Z(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!_s(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:i}=e[2];return Z.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!gs(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:i}=e[2];return Z.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},ih=class{async fetchModelAndCopyToWasmMemory(e){return Zp(await ss(e))}async loadModel(e,t){je();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await Jp(r,t),Ve()}async dispose(){return eh(this.sessionId)}async run(e,t,r){je();let n=[],i=[];Object.entries(e).forEach(m=>{let l=m[0],T=m[1],x=this.inputNames.indexOf(l);if(x===-1)throw new Error(`invalid input '${l}'`);n.push(T),i.push(x)});let a=[],s=[];Object.entries(t).forEach(m=>{let l=m[0],T=m[1],x=this.outputNames.indexOf(l);if(x===-1)throw new Error(`invalid output '${l}'`);a.push(T),s.push(x)});let u=n.map((m,l)=>Nc(m,()=>`input "${this.inputNames[i[l]]}"`)),d=a.map((m,l)=>m?Nc(m,()=>`output "${this.outputNames[s[l]]}"`):null),c=await th(this.sessionId,i,u,s,d,r),g={};for(let m=0;mVc,initializeFlags:()=>jc,wasmBackend:()=>oh});var jc,Vc,oh,qf=L(()=>{Pt(),nh(),Gf(),Ft(),jc=()=>{if((typeof E.wasm.initTimeout!="number"||E.wasm.initTimeout<0)&&(E.wasm.initTimeout=0),E.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof E.wasm.proxy!="boolean"&&(E.wasm.proxy=!1),typeof E.wasm.trace!="boolean"&&(E.wasm.trace=!1),typeof E.wasm.numThreads!="number"||!Number.isInteger(E.wasm.numThreads)||E.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)E.wasm.numThreads=1;else{let e=typeof navigator>"u"?Te("node:os").cpus().length:navigator.hardwareConcurrency;E.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Vc=class{async init(e){jc(),await Qp(),await Yp(e)}async createInferenceSessionHandler(e,t){let r=new ih;return await r.loadModel(e,t),Promise.resolve(r)}},oh=new Vc});Pt(),Pt(),Pt();var Hf="1.21.0-dev.20241024-d9ca84ef96",Kf=zt;{let e=(qf(),B(ah)).wasmBackend;fe("webgpu",e,5),fe("webnn",e,5),fe("cpu",e,10),fe("wasm",e,10)}Object.defineProperty(E.versions,"web",{value:Hf,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":(Dt,Ee,V)=>{var F;V.r(Ee),V.d(Ee,{Tensor:()=>Te.Tensor,createInferenceSession:()=>O,deviceToExecutionProviders:()=>fe,isONNXProxy:()=>X,isONNXTensor:()=>J});var ce=V("./src/env.js"),we=V("?2ce3"),ye=V("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Te=V("./node_modules/onnxruntime-common/dist/esm/index.js");const L=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"}}),P=[];let D,B;const q=Symbol.for("onnxruntime");if(q in globalThis)B=globalThis[q];else if(ce.apis.IS_NODE_ENV){switch(B=we??(F||(F=V.t(we,2))),process.platform){case"win32":P.push("dml");break;case"linux":process.arch==="x64"&&P.push("cuda");break}P.push("cpu"),D=["cpu"]}else B=ye,ce.apis.IS_WEBNN_AVAILABLE&&P.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ce.apis.IS_WEBGPU_AVAILABLE&&P.push("webgpu"),P.push("wasm"),D=["wasm"];const re=B.InferenceSession;function fe(K=null){if(!K)return D;switch(K){case"auto":return P;case"gpu":return P.filter(j=>["webgpu","cuda","dml","webnn-gpu"].includes(j))}if(P.includes(K))return[L[K]??K];throw new Error(`Unsupported device: "${K}". Should be one of: ${P.join(", ")}.`)}let le=null;async function O(K,j,k){le&&await le;const N=re.create(K,j);le??(le=N);const E=await N;return E.config=k,E}function J(K){return K instanceof B.Tensor}const pe=B==null?void 0:B.env;pe!=null&&pe.wasm&&(pe.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${ce.env.version}/dist/`,pe.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(pe.wasm.numThreads=1)),pe!=null&&pe.webgpu&&(pe.webgpu.powerPreference="high-performance");function X(){var K;return(K=pe==null?void 0:pe.wasm)==null?void 0:K.proxy}ce.env.backends.onnx=pe},"./src/configs.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{AutoConfig:()=>P,PretrainedConfig:()=>L,getKeyValueShapes:()=>Te});var F=V("./src/utils/core.js"),ce=V("./src/utils/hub.js");async function we(D,B){return await(0,ce.getModelJSON)(D,"config.json",!0,B)}function ye(D){const B={};let q={};switch(D.model_type){case"llava":case"paligemma":case"florence2":q=ye(D.text_config);break;case"moondream1":q=ye(D.phi_config);break;case"musicgen":q=ye(D.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":B.num_heads="n_head",B.num_layers="n_layer",B.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":B.num_heads="num_attention_heads",B.num_layers="num_hidden_layers",B.hidden_size="hidden_size";break;case"llama":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":B.num_heads="num_key_value_heads",B.num_layers="num_hidden_layers",B.hidden_size="hidden_size",B.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":B.num_heads="num_key_value_heads",B.num_layers="num_hidden_layers",B.dim_kv="head_dim";break;case"openelm":B.num_heads="num_kv_heads",B.num_layers="num_transformer_layers",B.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":B.num_heads="num_heads",B.num_layers="num_layers",B.hidden_size="hidden_size";break;case"bloom":B.num_heads="n_head",B.num_layers="n_layer",B.hidden_size="hidden_size";break;case"mpt":B.num_heads="n_heads",B.num_layers="n_layers",B.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":B.num_decoder_layers="num_decoder_layers",B.num_decoder_heads="num_heads",B.decoder_dim_kv="d_kv",B.num_encoder_layers="num_layers",B.num_encoder_heads="num_heads",B.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":B.num_decoder_layers="decoder_layers",B.num_decoder_heads="decoder_attention_heads",B.decoder_hidden_size="d_model",B.num_encoder_layers="encoder_layers",B.num_encoder_heads="encoder_attention_heads",B.encoder_hidden_size="d_model";break;case"speecht5":B.num_decoder_layers="decoder_layers",B.num_decoder_heads="decoder_attention_heads",B.decoder_hidden_size="hidden_size",B.num_encoder_layers="encoder_layers",B.num_encoder_heads="encoder_attention_heads",B.encoder_hidden_size="hidden_size";break;case"trocr":B.num_encoder_layers=B.num_decoder_layers="decoder_layers",B.num_encoder_heads=B.num_decoder_heads="decoder_attention_heads",B.encoder_hidden_size=B.decoder_hidden_size="d_model";break;case"musicgen_decoder":B.num_encoder_layers=B.num_decoder_layers="num_hidden_layers",B.num_encoder_heads=B.num_decoder_heads="num_attention_heads",B.encoder_hidden_size=B.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const fe=ye(D.decoder),le="num_decoder_layers"in fe,O=(0,F.pick)(D,["model_type","is_encoder_decoder"]);return le?(O.num_decoder_layers=fe.num_decoder_layers,O.num_decoder_heads=fe.num_decoder_heads,O.decoder_hidden_size=fe.decoder_hidden_size,O.num_encoder_layers=fe.num_encoder_layers,O.num_encoder_heads=fe.num_encoder_heads,O.encoder_hidden_size=fe.encoder_hidden_size):(O.num_layers=fe.num_layers,O.num_heads=fe.num_heads,O.hidden_size=fe.hidden_size),O}const re={...q,...(0,F.pick)(D,["model_type","multi_query","is_encoder_decoder"])};for(const fe in B)re[fe]=D[B[fe]];return re}function Te(D,{prefix:B="past_key_values"}={}){const q={},re=D.normalized_config,fe=1;if(re.is_encoder_decoder&&"num_encoder_heads"in re&&"num_decoder_heads"in re){const le=re.encoder_dim_kv??re.encoder_hidden_size/re.num_encoder_heads,O=re.decoder_dim_kv??re.decoder_hidden_size/re.num_decoder_heads,J=[fe,re.num_encoder_heads,0,le],pe=[fe,re.num_decoder_heads,0,O];for(let X=0;X{var E;V.r(Ee),V.d(Ee,{apis:()=>O,env:()=>k});var F=V("?569f"),ce=V("?3f59"),we=V("?154a");const ye="3.0.1",Te=typeof self<"u",L=Te&&self.constructor.name==="DedicatedWorkerGlobalScope",P=Te&&"caches"in self,D=typeof navigator<"u"&&"gpu"in navigator,B=typeof navigator<"u"&&"ml"in navigator,q=typeof process<"u",re=q&&((E=process==null?void 0:process.release)==null?void 0:E.name)==="node",fe=!N(F),le=!N(ce),O=Object.freeze({IS_BROWSER_ENV:Te,IS_WEBWORKER_ENV:L,IS_WEB_CACHE_AVAILABLE:P,IS_WEBGPU_AVAILABLE:D,IS_WEBNN_AVAILABLE:B,IS_PROCESS_AVAILABLE:q,IS_NODE_ENV:re,IS_FS_AVAILABLE:fe,IS_PATH_AVAILABLE:le}),J=fe&&le,pe=J?ce.dirname(ce.dirname(we.fileURLToPath(self.location.href))):"./",X=J?ce.join(pe,"/.cache/"):null,K="/models/",j=J?ce.join(pe,K):K,k={version:ye,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Te,localModelPath:j,useFS:fe,useBrowserCache:P,useFSCache:fe,cacheDir:X,useCustomCache:!1,customCache:null};function N(ue){return Object.keys(ue).length===0}},"./src/generation/configuration_utils.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{GenerationConfig:()=>ce});var F=V("./src/utils/core.js");class ce{constructor(ye){ve(this,"max_length",20);ve(this,"max_new_tokens",null);ve(this,"min_length",0);ve(this,"min_new_tokens",null);ve(this,"early_stopping",!1);ve(this,"max_time",null);ve(this,"do_sample",!1);ve(this,"num_beams",1);ve(this,"num_beam_groups",1);ve(this,"penalty_alpha",null);ve(this,"use_cache",!0);ve(this,"temperature",1);ve(this,"top_k",50);ve(this,"top_p",1);ve(this,"typical_p",1);ve(this,"epsilon_cutoff",0);ve(this,"eta_cutoff",0);ve(this,"diversity_penalty",0);ve(this,"repetition_penalty",1);ve(this,"encoder_repetition_penalty",1);ve(this,"length_penalty",1);ve(this,"no_repeat_ngram_size",0);ve(this,"bad_words_ids",null);ve(this,"force_words_ids",null);ve(this,"renormalize_logits",!1);ve(this,"constraints",null);ve(this,"forced_bos_token_id",null);ve(this,"forced_eos_token_id",null);ve(this,"remove_invalid_values",!1);ve(this,"exponential_decay_length_penalty",null);ve(this,"suppress_tokens",null);ve(this,"begin_suppress_tokens",null);ve(this,"forced_decoder_ids",null);ve(this,"guidance_scale",null);ve(this,"num_return_sequences",1);ve(this,"output_attentions",!1);ve(this,"output_hidden_states",!1);ve(this,"output_scores",!1);ve(this,"return_dict_in_generate",!1);ve(this,"pad_token_id",null);ve(this,"bos_token_id",null);ve(this,"eos_token_id",null);ve(this,"encoder_no_repeat_ngram_size",0);ve(this,"decoder_start_token_id",null);ve(this,"generation_kwargs",{});Object.assign(this,(0,F.pick)(ye,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{ClassifierFreeGuidanceLogitsProcessor:()=>J,ForcedBOSTokenLogitsProcessor:()=>L,ForcedEOSTokenLogitsProcessor:()=>P,LogitsProcessor:()=>we,LogitsProcessorList:()=>Te,LogitsWarper:()=>ye,MinLengthLogitsProcessor:()=>fe,MinNewTokensLengthLogitsProcessor:()=>le,NoBadWordsLogitsProcessor:()=>O,NoRepeatNGramLogitsProcessor:()=>q,RepetitionPenaltyLogitsProcessor:()=>re,SuppressTokensAtBeginLogitsProcessor:()=>D,TemperatureLogitsWarper:()=>pe,TopKLogitsWarper:()=>K,TopPLogitsWarper:()=>X,WhisperTimeStampLogitsProcessor:()=>B});var F=V("./src/utils/generic.js");V("./src/utils/tensor.js");var ce=V("./src/utils/maths.js");class we extends F.Callable{_call(k,N){throw Error("`_call` should be implemented in a subclass")}}class ye extends F.Callable{_call(k,N){throw Error("`_call` should be implemented in a subclass")}}class Te extends F.Callable{constructor(){super(),this.processors=[]}push(k){this.processors.push(k)}extend(k){this.processors.push(...k)}_call(k,N){let E=N;for(const ue of this.processors)E=ue(k,E);return E}[Symbol.iterator](){return this.processors.values()}}class L extends we{constructor(k){super(),this.bos_token_id=k}_call(k,N){for(let E=0;E=1&&be[be.length-1]>=this.timestamp_begin,De=be.length<2||be[be.length-2]>=this.timestamp_begin;if(Ce&&(De?ue.subarray(this.timestamp_begin).fill(-1/0):ue.subarray(0,this.eos_token_id).fill(-1/0)),k[E].length===this.begin_index&&this.max_initial_timestamp_index!==null){const lt=this.timestamp_begin+this.max_initial_timestamp_index;ue.subarray(lt+1).fill(-1/0)}const ze=(0,ce.log_softmax)(ue),it=Math.log(ze.subarray(this.timestamp_begin).map(Math.exp).reduce((lt,me)=>lt+me)),rt=(0,ce.max)(ze.subarray(0,this.timestamp_begin))[0];it>rt&&ue.subarray(0,this.timestamp_begin).fill(-1/0)}return N}}class q extends we{constructor(k){super(),this.no_repeat_ngram_size=k}getNgrams(k){const N=k.length,E=[];for(let be=0;be1 to use the classifier free guidance processor, got guidance scale ${k}.`);this.guidance_scale=k}_call(k,N){if(N.dims[0]!==2*k.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 ${N.dims[0]} for the logits and ${k.length} for the input ids.`);const E=k.length,ue=N.slice([0,E],null),be=N.slice([E,N.dims[0]],null);for(let Ce=0;Ce1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${k}`);if(!Number.isInteger(E)||E<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${E}`);this.top_p=k,this.filter_value=N,this.min_tokens_to_keep=E}}class K extends ye{constructor(k,{filter_value:N=-1/0,min_tokens_to_keep:E=1}={}){if(super(),!Number.isInteger(k)||k<0)throw new Error(`\`top_k\` must be a positive integer, but is ${k}`);this.top_k=Math.max(k,E),this.filter_value=N}}},"./src/generation/logits_sampler.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{LogitsSampler:()=>ye});var F=V("./src/utils/generic.js"),ce=V("./src/utils/tensor.js"),we=V("./src/utils/maths.js");V("./src/generation/configuration_utils.js");class ye extends F.Callable{constructor(B){super(),this.generation_config=B}async _call(B){return this.sample(B)}async sample(B){throw Error("sample should be implemented in subclasses.")}getLogits(B,q){let re=B.dims.at(-1),fe=B.data;if(q===-1)fe=fe.slice(-re);else{let le=q*re;fe=fe.slice(le,le+re)}return fe}randomSelect(B){let q=0;for(let fe=0;fe1)return new P(B);if(B.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${B.num_return_sequences}.`);return new Te(B)}}class Te extends ye{async sample(B){const q=(0,we.max)(B.data)[1];return[[BigInt(q),0]]}}class L extends ye{async sample(B){let q=B.dims.at(-1);this.generation_config.top_k>0&&(q=Math.min(this.generation_config.top_k,q));const[re,fe]=await(0,ce.topk)(B,q),le=(0,we.softmax)(re.data);return Array.from({length:this.generation_config.num_beams},()=>{const O=this.randomSelect(le);return[fe.data[O],Math.log(le[O])]})}}class P extends ye{async sample(B){let q=B.dims.at(-1);this.generation_config.top_k>0&&(q=Math.min(this.generation_config.top_k,q));const[re,fe]=await(0,ce.topk)(B,q),le=(0,we.softmax)(re.data);return Array.from({length:this.generation_config.num_beams},(O,J)=>[fe.data[J],Math.log(le[J])])}}},"./src/generation/stopping_criteria.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{EosTokenCriteria:()=>Te,InterruptableStoppingCriteria:()=>L,MaxLengthCriteria:()=>ye,StoppingCriteria:()=>ce,StoppingCriteriaList:()=>we});var F=V("./src/utils/generic.js");class ce extends F.Callable{_call(D,B){throw Error("StoppingCriteria needs to be subclassed")}}class we extends F.Callable{constructor(){super(),this.criteria=[]}push(D){this.criteria.push(D)}extend(D){D instanceof we?D=D.criteria:D instanceof ce&&(D=[D]),this.criteria.push(...D)}_call(D,B){const q=new Array(D.length).fill(!1);for(const re of this.criteria){const fe=re(D,B);for(let le=0;leB.length>=this.max_length)}}class Te extends ce{constructor(D){super(),Array.isArray(D)||(D=[D]),this.eos_token_id=D}_call(D,B){return D.map(q=>{const re=q.at(-1);return this.eos_token_id.some(fe=>re==fe)})}}class L extends ce{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(D,B){return new Array(D.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{BaseStreamer:()=>ye,TextStreamer:()=>L,WhisperTextStreamer:()=>P});var F=V("./src/utils/core.js"),ce=V("./src/tokenizers.js"),we=V("./src/env.js");class ye{put(B){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Te=we.apis.IS_PROCESS_AVAILABLE?D=>process.stdout.write(D):D=>console.log(D);class L extends ye{constructor(B,{skip_prompt:q=!1,callback_function:re=null,token_callback_function:fe=null,decode_kwargs:le={},...O}={}){super(),this.tokenizer=B,this.skip_prompt=q,this.callback_function=re??Te,this.token_callback_function=fe,this.decode_kwargs={...le,...O},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(B){var le;if(B.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 q=B[0];(le=this.token_callback_function)==null||le.call(this,q),this.token_cache=(0,F.mergeArrays)(this.token_cache,q);const re=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let fe;re.endsWith(` `)?(fe=re.slice(this.print_len),this.token_cache=[],this.print_len=0):re.length>0&&(0,ce.is_chinese_char)(re.charCodeAt(re.length-1))?(fe=re.slice(this.print_len),this.print_len+=fe.length):(fe=re.slice(this.print_len,re.lastIndexOf(" ")+1),this.print_len+=fe.length),this.on_finalized_text(fe,!1)}end(){let B;this.token_cache.length>0?(B=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):B="",this.next_tokens_are_prompt=!0,this.on_finalized_text(B,!0)}on_finalized_text(B,q){var re,fe;B.length>0&&((re=this.callback_function)==null||re.call(this,B)),q&&this.callback_function===Te&&we.apis.IS_PROCESS_AVAILABLE&&((fe=this.callback_function)==null||fe.call(this,` `))}}class P extends L{constructor(B,{skip_prompt:q=!1,callback_function:re=null,token_callback_function:fe=null,on_chunk_start:le=null,on_chunk_end:O=null,on_finalize:J=null,time_precision:pe=.02,skip_special_tokens:X=!0,decode_kwargs:K={}}={}){super(B,{skip_prompt:q,callback_function:re,token_callback_function:fe,decode_kwargs:{skip_special_tokens:X,...K}}),this.timestamp_begin=B.timestamp_begin,this.on_chunk_start=le,this.on_chunk_end=O,this.on_finalize=J,this.time_precision=pe,this.waiting_for_timestamp=!1}put(B){var re,fe;if(B.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const q=B[0];if(q.length===1){const le=Number(q[0])-this.timestamp_begin;if(le>=0){const O=le*this.time_precision;this.waiting_for_timestamp?(re=this.on_chunk_end)==null||re.call(this,O):(fe=this.on_chunk_start)==null||fe.call(this,O),this.waiting_for_timestamp=!this.waiting_for_timestamp,B=[[]]}}return super.put(B)}end(){var B;super.end(),(B=this.on_finalize)==null||B.call(this)}}},"./src/models.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{ASTForAudioClassification:()=>Ys,ASTModel:()=>Wt,ASTPreTrainedModel:()=>jn,AlbertForMaskedLM:()=>Yt,AlbertForQuestionAnswering:()=>ws,AlbertForSequenceClassification:()=>gs,AlbertModel:()=>_s,AlbertPreTrainedModel:()=>Ln,AutoModel:()=>Ka,AutoModelForAudioClassification:()=>Xd,AutoModelForAudioFrameClassification:()=>Xa,AutoModelForCTC:()=>ld,AutoModelForCausalLM:()=>Zu,AutoModelForDepthEstimation:()=>ud,AutoModelForDocumentQuestionAnswering:()=>Qa,AutoModelForImageClassification:()=>td,AutoModelForImageFeatureExtraction:()=>Ja,AutoModelForImageMatting:()=>Ya,AutoModelForImageSegmentation:()=>rd,AutoModelForImageToImage:()=>Za,AutoModelForMaskGeneration:()=>od,AutoModelForMaskedLM:()=>Ju,AutoModelForNormalEstimation:()=>dd,AutoModelForObjectDetection:()=>id,AutoModelForQuestionAnswering:()=>Kd,AutoModelForSemanticSegmentation:()=>nd,AutoModelForSeq2SeqLM:()=>Hd,AutoModelForSequenceClassification:()=>Hu,AutoModelForSpeechSeq2Seq:()=>Xu,AutoModelForTextToSpectrogram:()=>Qu,AutoModelForTextToWaveform:()=>Yu,AutoModelForTokenClassification:()=>Ku,AutoModelForUniversalSegmentation:()=>sd,AutoModelForVision2Seq:()=>ed,AutoModelForXVector:()=>js,AutoModelForZeroShotObjectDetection:()=>ad,BartForConditionalGeneration:()=>Q,BartForSequenceClassification:()=>oe,BartModel:()=>I,BartPretrainedModel:()=>_,BaseModelOutput:()=>dt,BeitForImageClassification:()=>hl,BeitModel:()=>pl,BeitPreTrainedModel:()=>Ji,BertForMaskedLM:()=>Mt,BertForQuestionAnswering:()=>Ae,BertForSequenceClassification:()=>Xe,BertForTokenClassification:()=>Z,BertModel:()=>ht,BertPreTrainedModel:()=>Re,BlenderbotForConditionalGeneration:()=>Sr,BlenderbotModel:()=>er,BlenderbotPreTrainedModel:()=>Ot,BlenderbotSmallForConditionalGeneration:()=>en,BlenderbotSmallModel:()=>Wr,BlenderbotSmallPreTrainedModel:()=>ur,BloomForCausalLM:()=>Uo,BloomModel:()=>Vo,BloomPreTrainedModel:()=>Gi,CLIPModel:()=>uo,CLIPPreTrainedModel:()=>os,CLIPSegForImageSegmentation:()=>wo,CLIPSegModel:()=>go,CLIPSegPreTrainedModel:()=>$i,CLIPTextModel:()=>Md,CLIPTextModelWithProjection:()=>xn,CLIPVisionModel:()=>vd,CLIPVisionModelWithProjection:()=>co,CamembertForMaskedLM:()=>Yr,CamembertForQuestionAnswering:()=>bn,CamembertForSequenceClassification:()=>Rr,CamembertForTokenClassification:()=>Jr,CamembertModel:()=>Cr,CamembertPreTrainedModel:()=>dr,CausalLMOutput:()=>es,CausalLMOutputWithPast:()=>Qd,ChineseCLIPModel:()=>_o,ChineseCLIPPreTrainedModel:()=>mo,ClapAudioModelWithProjection:()=>Pa,ClapModel:()=>hi,ClapPreTrainedModel:()=>Sa,ClapTextModelWithProjection:()=>Ns,CodeGenForCausalLM:()=>Eo,CodeGenModel:()=>$o,CodeGenPreTrainedModel:()=>En,CohereForCausalLM:()=>zn,CohereModel:()=>Io,CoherePreTrainedModel:()=>Di,ConvBertForMaskedLM:()=>$,ConvBertForQuestionAnswering:()=>nt,ConvBertForSequenceClassification:()=>Y,ConvBertForTokenClassification:()=>he,ConvBertModel:()=>H,ConvBertPreTrainedModel:()=>v,ConvNextForImageClassification:()=>hn,ConvNextModel:()=>Zn,ConvNextPreTrainedModel:()=>si,ConvNextV2ForImageClassification:()=>fa,ConvNextV2Model:()=>ai,ConvNextV2PreTrainedModel:()=>ii,DPTForDepthEstimation:()=>Al,DPTModel:()=>Pl,DPTPreTrainedModel:()=>ca,DebertaForMaskedLM:()=>ge,DebertaForQuestionAnswering:()=>Ne,DebertaForSequenceClassification:()=>Ie,DebertaForTokenClassification:()=>Se,DebertaModel:()=>G,DebertaPreTrainedModel:()=>at,DebertaV2ForMaskedLM:()=>mt,DebertaV2ForQuestionAnswering:()=>Lt,DebertaV2ForSequenceClassification:()=>Ct,DebertaV2ForTokenClassification:()=>ft,DebertaV2Model:()=>wt,DebertaV2PreTrainedModel:()=>tt,DecisionTransformerModel:()=>Pu,DecisionTransformerPreTrainedModel:()=>Su,DeiTForImageClassification:()=>Ml,DeiTModel:()=>bl,DeiTPreTrainedModel:()=>oa,DepthAnythingForDepthEstimation:()=>Fl,DepthAnythingPreTrainedModel:()=>Il,DepthProForDepthEstimation:()=>Ll,DepthProPreTrainedModel:()=>Dl,DetrForObjectDetection:()=>ml,DetrForSegmentation:()=>ea,DetrModel:()=>fl,DetrObjectDetectionOutput:()=>ta,DetrPreTrainedModel:()=>ri,DetrSegmentationOutput:()=>_l,Dinov2ForImageClassification:()=>jl,Dinov2Model:()=>Nl,Dinov2PreTrainedModel:()=>ma,DistilBertForMaskedLM:()=>Ut,DistilBertForQuestionAnswering:()=>ct,DistilBertForSequenceClassification:()=>Fe,DistilBertForTokenClassification:()=>Oe,DistilBertModel:()=>Ft,DistilBertPreTrainedModel:()=>jt,DonutSwinModel:()=>Yn,DonutSwinPreTrainedModel:()=>Qn,EfficientNetForImageClassification:()=>Mu,EfficientNetModel:()=>za,EfficientNetPreTrainedModel:()=>Oa,ElectraForMaskedLM:()=>yt,ElectraForQuestionAnswering:()=>Pt,ElectraForSequenceClassification:()=>bt,ElectraForTokenClassification:()=>zt,ElectraModel:()=>Nt,ElectraPreTrainedModel:()=>Je,EsmForMaskedLM:()=>Nr,EsmForSequenceClassification:()=>mr,EsmForTokenClassification:()=>kr,EsmModel:()=>br,EsmPreTrainedModel:()=>sr,FalconForCausalLM:()=>gu,FalconModel:()=>_u,FalconPreTrainedModel:()=>ka,FastViTForImageClassification:()=>nl,FastViTModel:()=>rl,FastViTPreTrainedModel:()=>Ki,Florence2ForConditionalGeneration:()=>Ci,Florence2PreTrainedModel:()=>lo,GLPNForDepthEstimation:()=>Xn,GLPNModel:()=>Ed,GLPNPreTrainedModel:()=>ha,GPT2LMHeadModel:()=>Fn,GPT2Model:()=>yo,GPT2PreTrainedModel:()=>Ei,GPTBigCodeForCausalLM:()=>Fi,GPTBigCodeModel:()=>Zs,GPTBigCodePreTrainedModel:()=>Ii,GPTJForCausalLM:()=>On,GPTJModel:()=>xd,GPTJPreTrainedModel:()=>Ai,GPTNeoForCausalLM:()=>xo,GPTNeoModel:()=>vo,GPTNeoPreTrainedModel:()=>Si,GPTNeoXForCausalLM:()=>Co,GPTNeoXModel:()=>To,GPTNeoXPreTrainedModel:()=>Pi,Gemma2ForCausalLM:()=>Do,Gemma2Model:()=>zo,Gemma2PreTrainedModel:()=>Bi,GemmaForCausalLM:()=>Oo,GemmaModel:()=>Fo,GemmaPreTrainedModel:()=>Li,GraniteForCausalLM:()=>Ao,GraniteModel:()=>Po,GranitePreTrainedModel:()=>zi,GroupViTModel:()=>tl,GroupViTPreTrainedModel:()=>el,HieraForImageClassification:()=>ua,HieraModel:()=>vl,HieraPreTrainedModel:()=>la,HubertForCTC:()=>Id,HubertForSequenceClassification:()=>nu,HubertModel:()=>ru,HubertPreTrainedModel:()=>Ad,ImageMattingOutput:()=>hd,JAISLMHeadModel:()=>Mo,JAISModel:()=>bo,JAISPreTrainedModel:()=>ki,LlamaForCausalLM:()=>So,LlamaModel:()=>ko,LlamaPreTrainedModel:()=>Oi,LlavaForConditionalGeneration:()=>bs,LlavaPreTrainedModel:()=>oo,LongT5ForConditionalGeneration:()=>zs,LongT5Model:()=>Os,LongT5PreTrainedModel:()=>ys,M2M100ForConditionalGeneration:()=>Rs,M2M100Model:()=>ba,M2M100PreTrainedModel:()=>ya,MBartForCausalLM:()=>Tt,MBartForConditionalGeneration:()=>gt,MBartForSequenceClassification:()=>$t,MBartModel:()=>Ge,MBartPreTrainedModel:()=>_e,MPNetForMaskedLM:()=>ks,MPNetForQuestionAnswering:()=>As,MPNetForSequenceClassification:()=>Ss,MPNetForTokenClassification:()=>Ps,MPNetModel:()=>Es,MPNetPreTrainedModel:()=>qn,MT5ForConditionalGeneration:()=>ae,MT5Model:()=>Ds,MT5PreTrainedModel:()=>is,MarianMTModel:()=>kd,MarianModel:()=>Wl,MarianPreTrainedModel:()=>wa,MaskFormerForInstanceSegmentation:()=>Rl,MaskFormerModel:()=>Bl,MaskFormerPreTrainedModel:()=>pa,MaskedLMOutput:()=>un,MistralForCausalLM:()=>pu,MistralModel:()=>cu,MistralPreTrainedModel:()=>Ea,MobileBertForMaskedLM:()=>Ur,MobileBertForQuestionAnswering:()=>$s,MobileBertForSequenceClassification:()=>fs,MobileBertModel:()=>$n,MobileBertPreTrainedModel:()=>gr,MobileNetV1ForImageClassification:()=>vu,MobileNetV1Model:()=>Rd,MobileNetV1PreTrainedModel:()=>Ba,MobileNetV2ForImageClassification:()=>Tu,MobileNetV2Model:()=>xu,MobileNetV2PreTrainedModel:()=>Ra,MobileNetV3ForImageClassification:()=>Eu,MobileNetV3Model:()=>$u,MobileNetV3PreTrainedModel:()=>Cu,MobileNetV4ForImageClassification:()=>Nd,MobileNetV4Model:()=>ku,MobileNetV4PreTrainedModel:()=>Na,MobileViTForImageClassification:()=>ol,MobileViTModel:()=>al,MobileViTPreTrainedModel:()=>Xi,MobileViTV2ForImageClassification:()=>Ls,MobileViTV2Model:()=>ll,MobileViTV2PreTrainedModel:()=>Qi,ModelOutput:()=>Ze,Moondream1ForConditionalGeneration:()=>pr,MptForCausalLM:()=>Go,MptModel:()=>Wo,MptPreTrainedModel:()=>Ms,MusicgenForCausalLM:()=>bc,MusicgenForConditionalGeneration:()=>La,MusicgenModel:()=>Bd,MusicgenPreTrainedModel:()=>Da,NomicBertModel:()=>et,NomicBertPreTrainedModel:()=>Ke,OPTForCausalLM:()=>Ho,OPTModel:()=>qo,OPTPreTrainedModel:()=>ei,OpenELMForCausalLM:()=>Bo,OpenELMModel:()=>Lo,OpenELMPreTrainedModel:()=>Ri,OwlViTForObjectDetection:()=>ul,OwlViTModel:()=>ti,OwlViTPreTrainedModel:()=>Yi,Owlv2ForObjectDetection:()=>cl,Owlv2Model:()=>dl,Owlv2PreTrainedModel:()=>Zi,Phi3ForCausalLM:()=>Js,Phi3Model:()=>jo,Phi3PreTrainedModel:()=>No,PhiForCausalLM:()=>Wi,PhiModel:()=>Ro,PhiPreTrainedModel:()=>Ui,PreTrainedModel:()=>se,PretrainedMixin:()=>Or,PvtForImageClassification:()=>Qo,PvtModel:()=>Xo,PvtPreTrainedModel:()=>Hi,PyAnnoteForAudioFrameClassification:()=>Ql,PyAnnoteModel:()=>Xl,PyAnnotePreTrainedModel:()=>Kl,QuestionAnsweringModelOutput:()=>fn,Qwen2ForCausalLM:()=>Vi,Qwen2Model:()=>ji,Qwen2PreTrainedModel:()=>Ni,RTDetrForObjectDetection:()=>wl,RTDetrModel:()=>gl,RTDetrObjectDetectionOutput:()=>na,RTDetrPreTrainedModel:()=>ra,ResNetForImageClassification:()=>Tl,ResNetModel:()=>xl,ResNetPreTrainedModel:()=>da,RoFormerForMaskedLM:()=>ut,RoFormerForQuestionAnswering:()=>xt,RoFormerForSequenceClassification:()=>_t,RoFormerForTokenClassification:()=>St,RoFormerModel:()=>Ve,RoFormerPreTrainedModel:()=>je,RobertaForMaskedLM:()=>_n,RobertaForQuestionAnswering:()=>tn,RobertaForSequenceClassification:()=>Mn,RobertaForTokenClassification:()=>$e,RobertaModel:()=>Pr,RobertaPreTrainedModel:()=>or,SamImageSegmentationOutput:()=>li,SamModel:()=>ga,SamPreTrainedModel:()=>Ul,SapiensForDepthEstimation:()=>zl,SapiensForNormalEstimation:()=>$d,SapiensForSemanticSegmentation:()=>Ol,SapiensPreTrainedModel:()=>ni,SegformerForImageClassification:()=>Ia,SegformerForSemanticSegmentation:()=>yu,SegformerModel:()=>Dd,SegformerPreTrainedModel:()=>fi,Seq2SeqLMOutput:()=>cd,SequenceClassifierOutput:()=>cr,SiglipModel:()=>po,SiglipPreTrainedModel:()=>Vn,SiglipTextModel:()=>ho,SiglipVisionModel:()=>fo,SpeechT5ForSpeechToText:()=>ou,SpeechT5ForTextToSpeech:()=>lu,SpeechT5HifiGan:()=>uu,SpeechT5Model:()=>Od,SpeechT5PreTrainedModel:()=>pi,SqueezeBertForMaskedLM:()=>An,SqueezeBertForQuestionAnswering:()=>ms,SqueezeBertForSequenceClassification:()=>Rn,SqueezeBertModel:()=>Hn,SqueezeBertPreTrainedModel:()=>ns,StableLmForCausalLM:()=>Ld,StableLmModel:()=>bu,StableLmPreTrainedModel:()=>Fa,Starcoder2ForCausalLM:()=>mu,Starcoder2Model:()=>fu,Starcoder2PreTrainedModel:()=>hu,Swin2SRForImageSuperResolution:()=>Sl,Swin2SRModel:()=>kl,Swin2SRPreTrainedModel:()=>kn,SwinForImageClassification:()=>El,SwinModel:()=>$l,SwinPreTrainedModel:()=>Cl,T5ForConditionalGeneration:()=>Fs,T5Model:()=>Is,T5PreTrainedModel:()=>ss,TableTransformerForObjectDetection:()=>aa,TableTransformerModel:()=>ia,TableTransformerObjectDetectionOutput:()=>yl,TableTransformerPreTrainedModel:()=>sa,TokenClassifierOutput:()=>nn,TrOCRForCausalLM:()=>zd,TrOCRPreTrainedModel:()=>du,UniSpeechForCTC:()=>Zl,UniSpeechForSequenceClassification:()=>Jl,UniSpeechModel:()=>Yl,UniSpeechPreTrainedModel:()=>ui,UniSpeechSatForAudioFrameClassification:()=>Ta,UniSpeechSatForCTC:()=>di,UniSpeechSatForSequenceClassification:()=>xa,UniSpeechSatModel:()=>eu,UniSpeechSatPreTrainedModel:()=>ls,ViTForImageClassification:()=>Td,ViTMAEModel:()=>Yo,ViTMAEPreTrainedModel:()=>Cd,ViTMSNForImageClassification:()=>Jo,ViTMSNModel:()=>Zo,ViTMSNPreTrainedModel:()=>Mr,ViTModel:()=>Ko,ViTPreTrainedModel:()=>qi,VisionEncoderDecoderModel:()=>Ti,VitMatteForImageMatting:()=>il,VitMattePreTrainedModel:()=>sl,VitsModel:()=>Aa,VitsModelOutput:()=>fd,VitsPreTrainedModel:()=>wu,Wav2Vec2BertForCTC:()=>Ca,Wav2Vec2BertForSequenceClassification:()=>Pd,Wav2Vec2BertModel:()=>tu,Wav2Vec2BertPreTrainedModel:()=>ci,Wav2Vec2ForAudioFrameClassification:()=>Hl,Wav2Vec2ForCTC:()=>Gl,Wav2Vec2ForSequenceClassification:()=>ql,Wav2Vec2Model:()=>Ma,Wav2Vec2PreTrainedModel:()=>Jn,WavLMForAudioFrameClassification:()=>$a,WavLMForCTC:()=>su,WavLMForSequenceClassification:()=>iu,WavLMForXVector:()=>au,WavLMModel:()=>Fd,WavLMPreTrainedModel:()=>us,WeSpeakerResNetModel:()=>va,WeSpeakerResNetPreTrainedModel:()=>Sd,WhisperForConditionalGeneration:()=>xi,WhisperModel:()=>qt,WhisperPreTrainedModel:()=>Qe,XLMForQuestionAnswering:()=>Xr,XLMForSequenceClassification:()=>Kt,XLMForTokenClassification:()=>pn,XLMModel:()=>In,XLMPreTrainedModel:()=>ln,XLMRobertaForMaskedLM:()=>Et,XLMRobertaForQuestionAnswering:()=>Kn,XLMRobertaForSequenceClassification:()=>_r,XLMRobertaForTokenClassification:()=>as,XLMRobertaModel:()=>Fr,XLMRobertaPreTrainedModel:()=>fr,XLMWithLMHeadModel:()=>Nn,XVectorOutput:()=>pd,YolosForObjectDetection:()=>Vl,YolosModel:()=>_a,YolosObjectDetectionOutput:()=>oi,YolosPreTrainedModel:()=>Bs});var F=V("./src/configs.js"),ce=V("./src/backends/onnx.js"),we=V("./src/utils/dtypes.js"),ye=V("./src/utils/generic.js"),Te=V("./src/utils/core.js"),L=V("./src/utils/hub.js"),P=V("./src/utils/constants.js"),D=V("./src/generation/logits_process.js"),B=V("./src/generation/configuration_utils.js"),q=V("./src/utils/tensor.js"),re=V("./src/utils/maths.js"),fe=V("./src/generation/stopping_criteria.js"),le=V("./src/generation/logits_sampler.js"),O=V("./src/env.js"),J=V("./src/models/whisper/generation_whisper.js"),pe=V("./src/models/whisper/common_whisper.js");const X={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},K=new Map,j=new Map,k=new Map;async function N(f,b,R){var dn;const Me=((dn=R.config)==null?void 0:dn["transformers.js_config"])??{};let Ue=R.device??Me.device;Ue&&typeof Ue!="string"&&(Ue.hasOwnProperty(b)?Ue=Ue[b]:(console.warn(`device not specified for "${b}". Using the default device.`),Ue=null));const Le=Ue??(O.apis.IS_NODE_ENV?"cpu":"wasm"),pt=(0,ce.deviceToExecutionProviders)(Le);let kt=R.dtype??Me.dtype;typeof kt!="string"&&(kt&&kt.hasOwnProperty(b)?kt=kt[b]:(kt=we.DEFAULT_DEVICE_DTYPE_MAPPING[Le]??we.DATA_TYPES.fp32,console.warn(`dtype not specified for "${b}". Using the default dtype (${kt}) for this device (${Le}).`)));const Vt=kt;if(we.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Vt)){if(Vt===we.DATA_TYPES.fp16&&Le==="webgpu"&&!await(0,we.isWebGpuFp16Supported)())throw new Error(`The device (${Le}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Vt}. Should be one of: ${Object.keys(we.DATA_TYPES).join(", ")}`);const tr=Me.kv_cache_dtype?typeof Me.kv_cache_dtype=="string"?Me.kv_cache_dtype:Me.kv_cache_dtype[Vt]??"float32":void 0;if(tr&&!["float32","float16"].includes(tr))throw new Error(`Invalid kv_cache_dtype: ${tr}. Should be one of: float32, float16`);const zr={dtype:Vt,kv_cache_dtype:tr},Dr=we.DEFAULT_DTYPE_SUFFIX_MAPPING[Vt],wr=`${R.subfolder??""}/${b}${Dr}.onnx`,ir={...R.session_options};ir.executionProviders??(ir.executionProviders=pt);const Ar=Me.free_dimension_overrides;Ar?ir.freeDimensionOverrides??(ir.freeDimensionOverrides=Ar):Le.startsWith("webnn")&&!ir.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 $r=(0,L.getModelFile)(f,wr,!0,R),yr=R.use_external_data_format??Me.use_external_data_format;let Lr=[];if(yr&&(yr===!0||typeof yr=="object"&&yr.hasOwnProperty(b)&&yr[b]===!0)){if(O.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const Gr=`${b}${Dr}.onnx_data`,Qr=`${R.subfolder??""}/${Gr}`;Lr.push(new Promise(async(Kr,wn)=>{const ts=await(0,L.getModelFile)(f,Qr,!0,R);Kr({path:Gr,data:ts})}))}else ir.externalData!==void 0&&(Lr=ir.externalData.map(async Gr=>{if(typeof Gr.data=="string"){const Qr=await(0,L.getModelFile)(f,Gr.data,!0,R);return{...Gr,data:Qr}}return Gr}));if(Lr.length>0&&(ir.externalData=await Promise.all(Lr)),Le==="webgpu"){const Gr=(0,F.getKeyValueShapes)(R.config,{prefix:"present"});if(Object.keys(Gr).length>0&&!(0,ce.isONNXProxy)()){const Qr={};for(const Kr in Gr)Qr[Kr]="gpu-buffer";ir.preferredOutputLocation=Qr}}return{buffer:await $r,session_options:ir,session_config:zr}}async function E(f,b,R){return Object.fromEntries(await Promise.all(Object.keys(b).map(async Me=>{const{buffer:Ue,session_options:Le,session_config:pt}=await N(f,b[Me],R),kt=await(0,ce.createInferenceSession)(Ue,Le,pt);return[Me,kt]})))}async function ue(f,b,R){return Object.fromEntries(await Promise.all(Object.keys(b).map(async Me=>{const Ue=await(0,L.getModelJSON)(f,b[Me],!1,R);return[Me,Ue]})))}function be(f,b){const R=Object.create(null),Me=[];for(const pt of f.inputNames){const kt=b[pt];if(!(kt instanceof q.Tensor)){Me.push(pt);continue}R[pt]=(0,ce.isONNXProxy)()?kt.clone():kt}if(Me.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Me.join(", ")}.`);const Ue=Object.keys(b).length,Le=f.inputNames.length;if(Ue>Le){let pt=Object.keys(b).filter(kt=>!f.inputNames.includes(kt));console.warn(`WARNING: Too many inputs were provided (${Ue} > ${Le}). The following inputs will be ignored: "${pt.join(", ")}".`)}return R}async function Ce(f,b){const R=be(f,b);try{const Me=Object.fromEntries(Object.entries(R).map(([Le,pt])=>[Le,pt.ort_tensor]));let Ue=await f.run(Me);return Ue=De(Ue),Ue}catch(Me){throw console.error(`An error occurred during model execution: "${Me}".`),console.error("Inputs given to model:",R),Me}}function De(f){for(let b in f)(0,ce.isONNXTensor)(f[b])?f[b]=new q.Tensor(f[b]):typeof f[b]=="object"&&De(f[b]);return f}function ze(f){if(f instanceof q.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(b=>b.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 q.Tensor("int64",BigInt64Array.from(f.flat().map(b=>BigInt(b))),[f.length,f[0].length])}else return new q.Tensor("int64",BigInt64Array.from(f.map(b=>BigInt(b))),[1,f.length])}function it(f){return new q.Tensor("bool",[f],[1])}async function rt(f,b){let{encoder_outputs:R,input_ids:Me,decoder_input_ids:Ue,...Le}=b;if(!R){const kt=(0,Te.pick)(b,f.sessions.model.inputNames);R=(await lt(f,kt)).last_hidden_state}return Le.input_ids=Ue,Le.encoder_hidden_states=R,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Le.encoder_attention_mask=b.attention_mask),await me(f,Le,!0)}async function lt(f,b){const R=f.sessions.model,Me=(0,Te.pick)(b,R.inputNames);if(R.inputNames.includes("inputs_embeds")&&!Me.inputs_embeds){if(!b.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Me.inputs_embeds=await f.encode_text({input_ids:b.input_ids})}return R.inputNames.includes("token_type_ids")&&!Me.token_type_ids&&(Me.token_type_ids=new q.Tensor("int64",new BigInt64Array(Me.input_ids.data.length),Me.input_ids.dims)),await Ce(R,Me)}async function me(f,b,R=!1){const Me=f.sessions[R?"decoder_model_merged":"model"],{past_key_values:Ue,...Le}=b;Me.inputNames.includes("use_cache_branch")&&(Le.use_cache_branch=it(!!Ue)),Me.inputNames.includes("position_ids")&&Le.attention_mask&&!Le.position_ids&&(Le.position_ids=de(Le,Ue)),f.addPastKeyValues(Le,Ue);const pt=(0,Te.pick)(Le,Me.inputNames);return await Ce(Me,pt)}async function W(f,{input_ids:b=null,attention_mask:R=null,pixel_values:Me=null,position_ids:Ue=null,inputs_embeds:Le=null,past_key_values:pt=null,generation_config:kt=null,logits_processor:Vt=null,...tr}){if(!Le){if(Le=await f.encode_text({input_ids:b}),Me&&b.dims[1]!==1){const Dr=await f.encode_image({pixel_values:Me});({inputs_embeds:Le,attention_mask:R}=f._merge_input_ids_with_image_features({image_features:Dr,inputs_embeds:Le,input_ids:b,attention_mask:R}))}else if(pt&&Me&&b.dims[1]===1){const Dr=b.dims[1],wr=Object.values(pt)[0].dims.at(-2);R=(0,q.cat)([(0,q.ones)([b.dims[0],wr]),R.slice(null,[R.dims[1]-Dr,R.dims[1]])],1)}}return await me(f,{inputs_embeds:Le,past_key_values:pt,attention_mask:R,position_ids:Ue,generation_config:kt,logits_processor:Vt},!0)}function de(f,b=null){const{input_ids:R,inputs_embeds:Me,attention_mask:Ue}=f,[Le,pt]=Ue.dims,kt=new BigInt64Array(Ue.data.length);for(let tr=0;trLe.dims[1])){if(Uekt==f.config.image_token_index)){const kt=f.config.num_image_tokens;if(!kt)throw new Error("`num_image_tokens` is missing in the model configuration.");const Vt=Le.dims[1]-(Ue-kt);R.input_ids=Le.slice(null,[-Vt,null]),R.attention_mask=(0,q.ones)([1,Ue+Vt])}}}return R}function We(f,b,R,Me){return R.past_key_values&&(b=b.map(Ue=>[Ue.at(-1)])),{...R,decoder_input_ids:ze(b)}}function ot(f,...b){return f.config.is_encoder_decoder?We(f,...b):xe(f,...b)}class se extends ye.Callable{constructor(R,Me,Ue){super();ve(this,"main_input_name","input_ids");ve(this,"forward_params",["input_ids","attention_mask"]);this.config=R,this.sessions=Me,this.configs=Ue;const Le=k.get(this.constructor),pt=K.get(Le);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,pt){case X.DecoderOnly:this.can_generate=!0,this._forward=me,this._prepare_inputs_for_generation=xe;break;case X.Seq2Seq:case X.Vision2Seq:case X.Musicgen:this.can_generate=!0,this._forward=rt,this._prepare_inputs_for_generation=We;break;case X.EncoderDecoder:this._forward=rt;break;case X.ImageTextToText:this.can_generate=!0,this._forward=W,this._prepare_inputs_for_generation=ot;break;default:this._forward=lt;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var Me;const R=[];for(const Ue of Object.values(this.sessions))(Me=Ue==null?void 0:Ue.handler)!=null&&Me.dispose&&R.push(Ue.handler.dispose());return await Promise.all(R)}static async from_pretrained(R,{progress_callback:Me=null,config:Ue=null,cache_dir:Le=null,local_files_only:pt=!1,revision:kt="main",model_file_name:Vt=null,subfolder:tr="onnx",device:zr=null,dtype:Dr=null,use_external_data_format:wr=null,session_options:ir={}}={}){let Ar={progress_callback:Me,config:Ue,cache_dir:Le,local_files_only:pt,revision:kt,model_file_name:Vt,subfolder:tr,device:zr,dtype:Dr,use_external_data_format:wr,session_options:ir};const $r=k.get(this),yr=K.get($r);Ue=Ar.config=await F.AutoConfig.from_pretrained(R,Ar);let Lr;if(yr===X.DecoderOnly)Lr=await Promise.all([E(R,{model:Ar.model_file_name??"model"},Ar),ue(R,{generation_config:"generation_config.json"},Ar)]);else if(yr===X.Seq2Seq||yr===X.Vision2Seq)Lr=await Promise.all([E(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Ar),ue(R,{generation_config:"generation_config.json"},Ar)]);else if(yr===X.MaskGeneration)Lr=await Promise.all([E(R,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Ar)]);else if(yr===X.EncoderDecoder)Lr=await Promise.all([E(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Ar)]);else if(yr===X.ImageTextToText){const Tn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ue.is_encoder_decoder&&(Tn.model="encoder_model"),Lr=await Promise.all([E(R,Tn,Ar),ue(R,{generation_config:"generation_config.json"},Ar)])}else yr===X.Musicgen?Lr=await Promise.all([E(R,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Ar),ue(R,{generation_config:"generation_config.json"},Ar)]):(yr!==X.EncoderOnly&&console.warn(`Model type for '${$r??(Ue==null?void 0:Ue.model_type)}' not found, assuming encoder-only architecture. Please report this at ${P.GITHUB_ISSUE_URL}.`),Lr=await Promise.all([E(R,{model:Ar.model_file_name??"model"},Ar)]));return new this(Ue,...Lr)}async _call(R){return await this.forward(R)}async forward(R){return await this._forward(this,R)}get generation_config(){var R;return((R=this.configs)==null?void 0:R.generation_config)??null}_get_logits_warper(R){const Me=new D.LogitsProcessorList;return R.temperature!==null&&R.temperature!==1&&Me.push(new D.TemperatureLogitsWarper(R.temperature)),R.top_k!==null&&R.top_k!==0&&Me.push(new D.TopKLogitsWarper(R.top_k)),R.top_p!==null&&R.top_p<1&&Me.push(new D.TopPLogitsWarper(R.top_p)),Me}_get_logits_processor(R,Me,Ue=null){const Le=new D.LogitsProcessorList;if(R.repetition_penalty!==null&&R.repetition_penalty!==1&&Le.push(new D.RepetitionPenaltyLogitsProcessor(R.repetition_penalty)),R.no_repeat_ngram_size!==null&&R.no_repeat_ngram_size>0&&Le.push(new D.NoRepeatNGramLogitsProcessor(R.no_repeat_ngram_size)),R.bad_words_ids!==null&&Le.push(new D.NoBadWordsLogitsProcessor(R.bad_words_ids,R.eos_token_id)),R.min_length!==null&&R.eos_token_id!==null&&R.min_length>0&&Le.push(new D.MinLengthLogitsProcessor(R.min_length,R.eos_token_id)),R.min_new_tokens!==null&&R.eos_token_id!==null&&R.min_new_tokens>0&&Le.push(new D.MinNewTokensLengthLogitsProcessor(Me,R.min_new_tokens,R.eos_token_id)),R.forced_bos_token_id!==null&&Le.push(new D.ForcedBOSTokenLogitsProcessor(R.forced_bos_token_id)),R.forced_eos_token_id!==null&&Le.push(new D.ForcedEOSTokenLogitsProcessor(R.max_length,R.forced_eos_token_id)),R.begin_suppress_tokens!==null){const pt=Me>1||R.forced_bos_token_id===null?Me:Me+1;Le.push(new D.SuppressTokensAtBeginLogitsProcessor(R.begin_suppress_tokens,pt))}return R.guidance_scale!==null&&R.guidance_scale>1&&Le.push(new D.ClassifierFreeGuidanceLogitsProcessor(R.guidance_scale)),Ue!==null&&Le.extend(Ue),Le}_prepare_generation_config(R,Me,Ue=B.GenerationConfig){const Le={...this.config};for(const kt of["decoder","generator","text_config"])kt in Le&&Object.assign(Le,Le[kt]);const pt=new Ue(Le);return Object.assign(pt,this.generation_config??{}),R&&Object.assign(pt,R),Me&&Object.assign(pt,(0,Te.pick)(Me,Object.getOwnPropertyNames(pt))),pt}_get_stopping_criteria(R,Me=null){const Ue=new fe.StoppingCriteriaList;return R.max_length!==null&&Ue.push(new fe.MaxLengthCriteria(R.max_length,this.config.max_position_embeddings??null)),R.eos_token_id!==null&&Ue.push(new fe.EosTokenCriteria(R.eos_token_id)),Me&&Ue.extend(Me),Ue}_validate_model_class(){if(!this.can_generate){const R=[Ua,vs,Va,ja],Me=k.get(this.constructor),Ue=new Set,Le=this.config.model_type;for(const kt of R){const Vt=kt.get(Le);Vt&&Ue.add(Vt[0])}let pt=`The current model class (${Me}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ue.size>0&&(pt+=` Please use the following class instead: ${[...Ue].join(", ")}`),Error(pt)}}prepare_inputs_for_generation(...R){return this._prepare_inputs_for_generation(this,...R)}_update_model_kwargs_for_generation({generated_input_ids:R,outputs:Me,model_inputs:Ue,is_encoder_decoder:Le}){return Ue.past_key_values=this.getPastKeyValues(Me,Ue.past_key_values),Ue.input_ids=new q.Tensor("int64",R.flat(),[R.length,1]),Le||(Ue.attention_mask=(0,q.cat)([Ue.attention_mask,(0,q.ones)([Ue.attention_mask.dims[0],1])],1)),Ue.position_ids=null,Ue}_prepare_model_inputs({inputs:R,bos_token_id:Me,model_kwargs:Ue}){const Le=(0,Te.pick)(Ue,this.forward_params),pt=this.main_input_name;if(pt in Le){if(R)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Le[pt]=R;return{inputs_tensor:Le[pt],model_inputs:Le,model_input_name:pt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:R,model_inputs:Me,model_input_name:Ue,generation_config:Le}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Me.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:kt,pixel_values:Vt,attention_mask:tr,...zr}=Me,Dr=await this._prepare_inputs_embeds(Me);Me={...zr,...(0,Te.pick)(Dr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:pt}=await lt(this,Me);if(Le.guidance_scale!==null&&Le.guidance_scale>1)pt=(0,q.cat)([pt,(0,q.full_like)(pt,0)],0),"attention_mask"in Me&&(Me.attention_mask=(0,q.cat)([Me.attention_mask,(0,q.zeros_like)(Me.attention_mask)],0));else if(Me.decoder_input_ids){const kt=ze(Me.decoder_input_ids).dims[0];if(kt!==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 (${kt}).`);pt=(0,q.cat)(Array.from({length:kt},()=>pt),0)}}return Me.encoder_outputs=pt,Me}_prepare_decoder_input_ids_for_generation({batch_size:R,model_input_name:Me,model_kwargs:Ue,decoder_start_token_id:Le,bos_token_id:pt,generation_config:kt}){let{decoder_input_ids:Vt,...tr}=Ue;if(!(Vt instanceof q.Tensor)){if(Vt)Array.isArray(Vt[0])||(Vt=Array.from({length:R},()=>Vt));else if(Le??(Le=pt),this.config.model_type==="musicgen")Vt=Array.from({length:R*this.config.decoder.num_codebooks},()=>[Le]);else if(Array.isArray(Le)){if(Le.length!==R)throw new Error(`\`decoder_start_token_id\` expcted to have length ${R} but got ${Le.length}`);Vt=Le}else Vt=Array.from({length:R},()=>[Le]);Vt=ze(Vt)}return Ue.decoder_attention_mask=(0,q.ones_like)(Vt),{input_ids:Vt,model_inputs:tr}}async generate({inputs:R=null,generation_config:Me=null,logits_processor:Ue=null,stopping_criteria:Le=null,streamer:pt=null,...kt}){this._validate_model_class(),Me=this._prepare_generation_config(Me,kt);let{inputs_tensor:Vt,model_inputs:tr,model_input_name:zr}=this._prepare_model_inputs({inputs:R,model_kwargs:kt});const Dr=this.config.is_encoder_decoder;Dr&&("encoder_outputs"in tr||(tr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Vt,model_inputs:tr,model_input_name:zr,generation_config:Me})));let wr;Dr?{input_ids:wr,model_inputs:tr}=this._prepare_decoder_input_ids_for_generation({batch_size:tr[zr].dims.at(0),model_input_name:zr,model_kwargs:tr,decoder_start_token_id:Me.decoder_start_token_id,bos_token_id:Me.bos_token_id,generation_config:Me}):wr=tr[zr];let ir=wr.dims.at(-1);Me.max_new_tokens!==null&&(Me.max_length=ir+Me.max_new_tokens);const Ar=this._get_logits_processor(Me,ir,Ue),$r=this._get_stopping_criteria(Me,Le),yr=tr[zr].dims.at(0),Lr=le.LogitsSampler.getSampler(Me),Tn=new Array(yr).fill(0),dn=wr.tolist();pt&&pt.put(dn);let Gr,Qr={};for(;;){if(tr=this.prepare_inputs_for_generation(dn,tr,Me),Gr=await this.forward(tr),Me.output_attentions&&Me.return_dict_in_generate){const Bn=this.getAttentions(Gr);for(const xs in Bn)xs in Qr||(Qr[xs]=[]),Qr[xs].push(Bn[xs])}const ts=Gr.logits.slice(null,-1,null),mi=Ar(dn,ts),eo=[];for(let Bn=0;BnBn))break;tr=this._update_model_kwargs_for_generation({generated_input_ids:eo,outputs:Gr,model_inputs:tr,is_encoder_decoder:Dr})}pt&&pt.end();const Kr=this.getPastKeyValues(Gr,tr.past_key_values,!0),wn=new q.Tensor("int64",dn.flat(),[dn.length,dn[0].length]);if(Me.return_dict_in_generate)return{sequences:wn,past_key_values:Kr,...Qr};for(const ts of Object.values(Gr))ts.location==="gpu-buffer"&&ts.dispose();return wn}getPastKeyValues(R,Me,Ue=!1){const Le=Object.create(null);for(const pt in R)if(pt.startsWith("present")){const kt=pt.replace("present","past_key_values"),Vt=pt.includes("encoder");if(Vt&&Me?Le[kt]=Me[kt]:Le[kt]=R[pt],Me&&(!Vt||Ue)){const tr=Me[kt];tr.location==="gpu-buffer"&&tr.dispose()}}return Le}getAttentions(R){const Me={};for(const Ue of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Le in R)Le.startsWith(Ue)&&(Ue in Me||(Me[Ue]=[]),Me[Ue].push(R[Le]));return Me}addPastKeyValues(R,Me){var Ue;if(Me)Object.assign(R,Me);else{const Le=this.sessions.decoder_model_merged??this.sessions.model,pt=((Ue=Le==null?void 0:Le.config)==null?void 0:Ue.kv_cache_dtype)??"float32",kt=pt==="float16"?new Uint16Array:[],Vt=(0,F.getKeyValueShapes)(this.config);for(const tr in Vt)R[tr]=new q.Tensor(pt,kt,Vt[tr])}}async encode_image({pixel_values:R}){const Me=(await Ce(this.sessions.vision_encoder,{pixel_values:R})).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 (${Me.dims[1]}).`),this.config.num_image_tokens=Me.dims[1]),Me}async encode_text({input_ids:R}){return(await Ce(this.sessions.embed_tokens,{input_ids:R})).inputs_embeds}}class Ze{}class dt extends Ze{constructor({last_hidden_state:b,hidden_states:R=null,attentions:Me=null}){super(),this.last_hidden_state=b,this.hidden_states=R,this.attentions=Me}}class Re extends se{}class ht extends Re{}class Mt extends Re{async _call(b){return new un(await super._call(b))}}class Xe extends Re{async _call(b){return new cr(await super._call(b))}}class Z extends Re{async _call(b){return new nn(await super._call(b))}}class Ae extends Re{async _call(b){return new fn(await super._call(b))}}class Ke extends se{}class et extends Ke{}class je extends se{}class Ve extends je{}class ut extends je{async _call(b){return new un(await super._call(b))}}class _t extends je{async _call(b){return new cr(await super._call(b))}}class St extends je{async _call(b){return new nn(await super._call(b))}}class xt extends je{async _call(b){return new fn(await super._call(b))}}class v extends se{}class H extends v{}class $ extends v{async _call(b){return new un(await super._call(b))}}class Y extends v{async _call(b){return new cr(await super._call(b))}}class he extends v{async _call(b){return new nn(await super._call(b))}}class nt extends v{async _call(b){return new fn(await super._call(b))}}class Je extends se{}class Nt extends Je{}class yt extends Je{async _call(b){return new un(await super._call(b))}}class bt extends Je{async _call(b){return new cr(await super._call(b))}}class zt extends Je{async _call(b){return new nn(await super._call(b))}}class Pt extends Je{async _call(b){return new fn(await super._call(b))}}class dr extends se{}class Cr extends dr{}class Yr extends dr{async _call(b){return new un(await super._call(b))}}class Rr extends dr{async _call(b){return new cr(await super._call(b))}}class Jr extends dr{async _call(b){return new nn(await super._call(b))}}class bn extends dr{async _call(b){return new fn(await super._call(b))}}class at extends se{}class G extends at{}class ge extends at{async _call(b){return new un(await super._call(b))}}class Ie extends at{async _call(b){return new cr(await super._call(b))}}class Se extends at{async _call(b){return new nn(await super._call(b))}}class Ne extends at{async _call(b){return new fn(await super._call(b))}}class tt extends se{}class wt extends tt{}class mt extends tt{async _call(b){return new un(await super._call(b))}}class Ct extends tt{async _call(b){return new cr(await super._call(b))}}class ft extends tt{async _call(b){return new nn(await super._call(b))}}class Lt extends tt{async _call(b){return new fn(await super._call(b))}}class jt extends se{}class Ft extends jt{}class Fe extends jt{async _call(b){return new cr(await super._call(b))}}class Oe extends jt{async _call(b){return new nn(await super._call(b))}}class ct extends jt{async _call(b){return new fn(await super._call(b))}}class Ut extends jt{async _call(b){return new un(await super._call(b))}}class sr extends se{}class br extends sr{}class Nr extends sr{async _call(b){return new un(await super._call(b))}}class mr extends sr{async _call(b){return new cr(await super._call(b))}}class kr extends sr{async _call(b){return new nn(await super._call(b))}}class gr extends se{}class $n extends gr{}class Ur extends gr{async _call(b){return new un(await super._call(b))}}class fs extends gr{async _call(b){return new cr(await super._call(b))}}class $s extends gr{async _call(b){return new fn(await super._call(b))}}class qn extends se{}class Es extends qn{}class ks extends qn{async _call(b){return new un(await super._call(b))}}class Ss extends qn{async _call(b){return new cr(await super._call(b))}}class Ps extends qn{async _call(b){return new nn(await super._call(b))}}class As extends qn{async _call(b){return new fn(await super._call(b))}}class ns extends se{}class Hn extends ns{}class An extends ns{async _call(b){return new un(await super._call(b))}}class Rn extends ns{async _call(b){return new cr(await super._call(b))}}class ms extends ns{async _call(b){return new fn(await super._call(b))}}class Ln extends se{}class _s extends Ln{}class gs extends Ln{async _call(b){return new cr(await super._call(b))}}class ws extends Ln{async _call(b){return new fn(await super._call(b))}}class Yt extends Ln{async _call(b){return new un(await super._call(b))}}class ss extends se{constructor(){super(...arguments);ve(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Is extends ss{}class Fs extends ss{}class ys extends se{}class Os extends ys{}class zs extends ys{}class is extends se{}class Ds extends is{}class ae extends is{}class _ extends se{}class I extends _{}class Q extends _{}class oe extends _{async _call(b){return new cr(await super._call(b))}}class _e extends se{}class Ge extends _e{}class gt extends _e{}class $t extends _e{async _call(b){return new cr(await super._call(b))}}class Tt extends _e{}class Ot extends se{}class er extends Ot{}class Sr extends Ot{}class ur extends se{}class Wr extends ur{}class en extends ur{}class or extends se{}class Pr extends or{}class _n extends or{async _call(b){return new un(await super._call(b))}}class Mn extends or{async _call(b){return new cr(await super._call(b))}}class $e extends or{async _call(b){return new nn(await super._call(b))}}class tn extends or{async _call(b){return new fn(await super._call(b))}}class ln extends se{}class In extends ln{}class Nn extends ln{async _call(b){return new un(await super._call(b))}}class Kt extends ln{async _call(b){return new cr(await super._call(b))}}class pn extends ln{async _call(b){return new nn(await super._call(b))}}class Xr extends ln{async _call(b){return new fn(await super._call(b))}}class fr extends se{}class Fr extends fr{}class Et extends fr{async _call(b){return new un(await super._call(b))}}class _r extends fr{async _call(b){return new cr(await super._call(b))}}class as extends fr{async _call(b){return new nn(await super._call(b))}}class Kn extends fr{async _call(b){return new fn(await super._call(b))}}class jn extends se{}class Wt extends jn{}class Ys extends jn{}class Qe extends se{constructor(){super(...arguments);ve(this,"requires_attention_mask",!1);ve(this,"main_input_name","input_features");ve(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class qt extends Qe{}class xi extends Qe{_prepare_generation_config(b,R){return super._prepare_generation_config(b,R,J.WhisperGenerationConfig)}_retrieve_init_tokens(b){const R=[b.decoder_start_token_id];let Me=b.language;const Ue=b.task;if(b.is_multilingual){Me||(console.warn("No language specified - defaulting to English (en)."),Me="en");const pt=`<|${(0,pe.whisper_language_to_code)(Me)}|>`;R.push(b.lang_to_id[pt]),R.push(b.task_to_id[Ue??"transcribe"])}else if(Me||Ue)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!b.return_timestamps&&b.no_timestamps_token_id&&R.at(-1)!==b.no_timestamps_token_id?R.push(b.no_timestamps_token_id):b.return_timestamps&&R.at(-1)===b.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),R.pop()),R.filter(Le=>Le!=null)}async generate({inputs:b=null,generation_config:R=null,logits_processor:Me=null,stopping_criteria:Ue=null,...Le}){R=this._prepare_generation_config(R,Le);const pt=Le.decoder_input_ids??this._retrieve_init_tokens(R);if(R.return_timestamps&&(Me??(Me=new D.LogitsProcessorList),Me.push(new D.WhisperTimeStampLogitsProcessor(R,pt))),R.begin_suppress_tokens&&(Me??(Me=new D.LogitsProcessorList),Me.push(new D.SuppressTokensAtBeginLogitsProcessor(R.begin_suppress_tokens,pt.length))),R.return_token_timestamps){if(!R.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.");R.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),R.output_attentions=!0,R.return_dict_in_generate=!0}const kt=await super.generate({inputs:b,generation_config:R,logits_processor:Me,decoder_input_ids:pt,...Le});return R.return_token_timestamps&&(kt.token_timestamps=this._extract_token_timestamps(kt,R.alignment_heads,R.num_frames)),kt}_extract_token_timestamps(b,R,Me=null,Ue=.02){if(!b.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`.");Me==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 Le=this.config.median_filter_width;Le===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Le=7);const pt=b.cross_attentions,kt=Array.from({length:this.config.decoder_layers},($r,yr)=>(0,q.cat)(pt.map(Lr=>Lr[yr]),2)),Vt=(0,q.stack)(R.map(([$r,yr])=>{if($r>=kt.length)throw new Error(`Layer index ${$r} is out of bounds for cross attentions (length ${kt.length}).`);return Me?kt[$r].slice(null,yr,null,[0,Me]):kt[$r].slice(null,yr)})).transpose(1,0,2,3),[tr,zr]=(0,q.std_mean)(Vt,-2,0,!0),Dr=Vt.clone();for(let $r=0;$rLr[wn+1]-Lr[wn]),Gr=(0,Te.mergeArrays)([1],dn).map(Kr=>!!Kr),Qr=[];for(let Kr=0;Krwr.findIndex(ir=>ir==Le)),Vt=kt.every(wr=>wr===-1),tr=kt.every(wr=>wr!==-1);if(!Vt&&!tr)throw new Error("Every input should contain either 0 or 1 image token.");if(Vt)return{inputs_embeds:b,attention_mask:Ue};const zr=[],Dr=[];for(let wr=0;wrLe*pt,1);b.input_labels=new q.Tensor("int64",new BigInt64Array(Ue).fill(1n),Me)}const R={image_embeddings:b.image_embeddings,image_positional_embeddings:b.image_positional_embeddings};return b.input_points&&(R.input_points=b.input_points),b.input_labels&&(R.input_labels=b.input_labels),b.input_boxes&&(R.input_boxes=b.input_boxes),await Ce(this.sessions.prompt_encoder_mask_decoder,R)}async _call(b){return new li(await super._call(b))}}class li extends Ze{constructor({iou_scores:b,pred_masks:R}){super(),this.iou_scores=b,this.pred_masks=R}}class wa extends se{}class Wl extends wa{}class kd extends wa{}class ya extends se{}class ba extends ya{}class Rs extends ya{}class Jn extends se{}class Ma extends Jn{}class Gl extends Jn{async _call(b){return new es(await super._call(b))}}class ql extends Jn{async _call(b){return new cr(await super._call(b))}}class Hl extends Jn{async _call(b){return new nn(await super._call(b))}}class Kl extends se{}class Xl extends Kl{}class Ql extends Kl{async _call(b){return new nn(await super._call(b))}}class Sd extends se{}class va extends Sd{}class ui extends se{}class Yl extends ui{}class Zl extends ui{async _call(b){return new es(await super._call(b))}}class Jl extends ui{async _call(b){return new cr(await super._call(b))}}class ls extends se{}class eu extends ls{}class di extends ls{async _call(b){return new es(await super._call(b))}}class xa extends ls{async _call(b){return new cr(await super._call(b))}}class Ta extends ls{async _call(b){return new nn(await super._call(b))}}class ci extends se{}class tu extends ci{}class Ca extends ci{async _call(b){return new es(await super._call(b))}}class Pd extends ci{async _call(b){return new cr(await super._call(b))}}class Ad extends se{}class ru extends Jn{}class Id extends Jn{async _call(b){return new es(await super._call(b))}}class nu extends Jn{async _call(b){return new cr(await super._call(b))}}class us extends se{}class Fd extends us{}class su extends us{async _call(b){return new es(await super._call(b))}}class iu extends us{async _call(b){return new cr(await super._call(b))}}class au extends us{async _call(b){return new pd(await super._call(b))}}class $a extends us{async _call(b){return new nn(await super._call(b))}}class pi extends se{}class Od extends pi{}class ou extends pi{}class lu extends pi{async generate_speech(b,R,{threshold:Me=.5,minlenratio:Ue=0,maxlenratio:Le=20,vocoder:pt=null}={}){const kt={input_ids:b},{encoder_outputs:Vt,encoder_attention_mask:tr}=await lt(this,kt),zr=Vt.dims[1]/this.config.reduction_factor,Dr=Math.floor(zr*Le),wr=Math.floor(zr*Ue),ir=this.config.num_mel_bins;let Ar=[],$r=null,yr=null,Lr=0;for(;;){++Lr;const Gr=it(!!yr);let Qr;yr?Qr=yr.output_sequence_out:Qr=new q.Tensor("float32",new Float32Array(ir),[1,1,ir]);let Kr={use_cache_branch:Gr,output_sequence:Qr,encoder_attention_mask:tr,speaker_embeddings:R,encoder_hidden_states:Vt};this.addPastKeyValues(Kr,$r),yr=await Ce(this.sessions.decoder_model_merged,Kr),$r=this.getPastKeyValues(yr,$r);const{prob:wn,spectrum:ts}=yr;if(Ar.push(ts),Lr>=wr&&(Array.from(wn.data).filter(mi=>mi>=Me).length>0||Lr>=Dr))break}const Tn=(0,q.cat)(Ar),{waveform:dn}=await Ce(pt.sessions.model,{spectrogram:Tn});return{spectrogram:Tn,waveform:dn}}}class uu extends se{constructor(){super(...arguments);ve(this,"main_input_name","spectrogram")}}class du extends se{}class zd extends du{}class Ea extends se{}class cu extends Ea{}class pu extends Ea{}class hu extends se{}class fu extends hu{}class mu extends hu{}class ka extends se{}class _u extends ka{}class gu extends ka{}class Sa extends se{}class hi extends Sa{}class Ns extends Sa{static async from_pretrained(b,R={}){return R.model_file_name??(R.model_file_name="text_model"),super.from_pretrained(b,R)}}class Pa extends Sa{static async from_pretrained(b,R={}){return R.model_file_name??(R.model_file_name="audio_model"),super.from_pretrained(b,R)}}class wu extends se{}class Aa extends wu{async _call(b){return new fd(await super._call(b))}}class fi extends se{}class Dd extends fi{}class Ia extends fi{}class yu extends fi{}class Fa extends se{}class bu extends Fa{}class Ld extends Fa{}class Oa extends se{}class za extends Oa{}class Mu extends Oa{async _call(b){return new cr(await super._call(b))}}class Da extends se{}class Bd extends Da{}class bc extends Da{}class La extends se{constructor(){super(...arguments);ve(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(R){const[Me,Ue]=R.dims,Le=this.config.decoder.num_codebooks,pt=Ue-Le;let kt=0;for(let zr=0;zr0&&ir<=pt&&(R.data[kt++]=R.data[zr])}const Vt=Math.floor(Me/Le),tr=kt/(Vt*Le);return new q.Tensor(R.type,R.data.slice(0,kt),[Vt,Le,tr])}prepare_inputs_for_generation(R,Me,Ue){let Le=structuredClone(R);for(let kt=0;kt=Vt&&(Le[kt][Vt]=BigInt(this.config.decoder.pad_token_id));return Ue.guidance_scale!==null&&Ue.guidance_scale>1&&(Le=Le.concat(Le)),super.prepare_inputs_for_generation(Le,Me,Ue)}async generate(R){const Me=await super.generate(R),Ue=this._apply_and_filter_by_delay_pattern_mask(Me).unsqueeze_(0),{audio_values:Le}=await Ce(this.sessions.encodec_decode,{audio_codes:Ue});return Le}}class Ba extends se{}class Rd extends Ba{}class vu extends Ba{async _call(b){return new cr(await super._call(b))}}class Ra extends se{}class xu extends Ra{}class Tu extends Ra{async _call(b){return new cr(await super._call(b))}}class Cu extends se{}class $u extends Cu{}class Eu extends Cu{async _call(b){return new cr(await super._call(b))}}class Na extends se{}class ku extends Na{}class Nd extends Na{async _call(b){return new cr(await super._call(b))}}class Su extends se{}class Pu extends Su{}class Or{static async from_pretrained(b,{progress_callback:R=null,config:Me=null,cache_dir:Ue=null,local_files_only:Le=!1,revision:pt="main",model_file_name:kt=null,subfolder:Vt="onnx",device:tr=null,dtype:zr=null,use_external_data_format:Dr=null,session_options:wr={}}={}){const ir={progress_callback:R,config:Me,cache_dir:Ue,local_files_only:Le,revision:pt,model_file_name:kt,subfolder:Vt,device:tr,dtype:zr,use_external_data_format:Dr,session_options:wr};if(ir.config=await F.AutoConfig.from_pretrained(b,ir),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const Ar of this.MODEL_CLASS_MAPPINGS){const $r=Ar.get(ir.config.model_type);if($r)return await $r[1].from_pretrained(b,ir)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${ir.config.model_type}", attempting to construct from base class.`),await se.from_pretrained(b,ir);throw Error(`Unsupported model type: ${ir.config.model_type}`)}}ve(Or,"MODEL_CLASS_MAPPINGS",null),ve(Or,"BASE_IF_FAIL",!1);const jd=new Map([["bert",["BertModel",ht]],["nomic_bert",["NomicBertModel",et]],["roformer",["RoFormerModel",Ve]],["electra",["ElectraModel",Nt]],["esm",["EsmModel",br]],["convbert",["ConvBertModel",H]],["camembert",["CamembertModel",Cr]],["deberta",["DebertaModel",G]],["deberta-v2",["DebertaV2Model",wt]],["mpnet",["MPNetModel",Es]],["albert",["AlbertModel",_s]],["distilbert",["DistilBertModel",Ft]],["roberta",["RobertaModel",Pr]],["xlm",["XLMModel",In]],["xlm-roberta",["XLMRobertaModel",Fr]],["clap",["ClapModel",hi]],["clip",["CLIPModel",uo]],["clipseg",["CLIPSegModel",go]],["chinese_clip",["ChineseCLIPModel",_o]],["siglip",["SiglipModel",po]],["mobilebert",["MobileBertModel",$n]],["squeezebert",["SqueezeBertModel",Hn]],["wav2vec2",["Wav2Vec2Model",Ma]],["wav2vec2-bert",["Wav2Vec2BertModel",tu]],["unispeech",["UniSpeechModel",Yl]],["unispeech-sat",["UniSpeechSatModel",eu]],["hubert",["HubertModel",ru]],["wavlm",["WavLMModel",Fd]],["audio-spectrogram-transformer",["ASTModel",Wt]],["vits",["VitsModel",Aa]],["pyannote",["PyAnnoteModel",Xl]],["wespeaker-resnet",["WeSpeakerResNetModel",va]],["detr",["DetrModel",fl]],["rt_detr",["RTDetrModel",gl]],["table-transformer",["TableTransformerModel",ia]],["vit",["ViTModel",Ko]],["pvt",["PvtModel",Xo]],["vit_msn",["ViTMSNModel",Zo]],["vit_mae",["ViTMAEModel",Yo]],["groupvit",["GroupViTModel",tl]],["fastvit",["FastViTModel",rl]],["mobilevit",["MobileViTModel",al]],["mobilevitv2",["MobileViTV2Model",ll]],["owlvit",["OwlViTModel",ti]],["owlv2",["Owlv2Model",dl]],["beit",["BeitModel",pl]],["deit",["DeiTModel",bl]],["hiera",["HieraModel",vl]],["convnext",["ConvNextModel",Zn]],["convnextv2",["ConvNextV2Model",ai]],["dinov2",["Dinov2Model",Nl]],["resnet",["ResNetModel",xl]],["swin",["SwinModel",$l]],["swin2sr",["Swin2SRModel",kl]],["donut-swin",["DonutSwinModel",Yn]],["yolos",["YolosModel",_a]],["dpt",["DPTModel",Pl]],["glpn",["GLPNModel",Ed]],["hifigan",["SpeechT5HifiGan",uu]],["efficientnet",["EfficientNetModel",za]],["decision_transformer",["DecisionTransformerModel",Pu]],["mobilenet_v1",["MobileNetV1Model",Rd]],["mobilenet_v2",["MobileNetV2Model",xu]],["mobilenet_v3",["MobileNetV3Model",$u]],["mobilenet_v4",["MobileNetV4Model",ku]],["maskformer",["MaskFormerModel",Bl]]]),Mc=new Map([["t5",["T5Model",Is]],["longt5",["LongT5Model",Os]],["mt5",["MT5Model",Ds]],["bart",["BartModel",I]],["mbart",["MBartModel",Ge]],["marian",["MarianModel",Wl]],["whisper",["WhisperModel",qt]],["m2m_100",["M2M100Model",ba]],["blenderbot",["BlenderbotModel",er]],["blenderbot-small",["BlenderbotSmallModel",Wr]]]),Vd=new Map([["bloom",["BloomModel",Vo]],["jais",["JAISModel",bo]],["gpt2",["GPT2Model",yo]],["gptj",["GPTJModel",xd]],["gpt_bigcode",["GPTBigCodeModel",Zs]],["gpt_neo",["GPTNeoModel",vo]],["gpt_neox",["GPTNeoXModel",To]],["codegen",["CodeGenModel",$o]],["llama",["LlamaModel",ko]],["granite",["GraniteModel",Po]],["cohere",["CohereModel",Io]],["gemma",["GemmaModel",Fo]],["gemma2",["Gemma2Model",zo]],["openelm",["OpenELMModel",Lo]],["qwen2",["Qwen2Model",ji]],["phi",["PhiModel",Ro]],["phi3",["Phi3Model",jo]],["mpt",["MptModel",Wo]],["opt",["OPTModel",qo]],["mistral",["MistralModel",cu]],["starcoder2",["Starcoder2Model",fu]],["falcon",["FalconModel",_u]],["stablelm",["StableLmModel",bu]]]),ja=new Map([["speecht5",["SpeechT5ForSpeechToText",ou]],["whisper",["WhisperForConditionalGeneration",xi]]]),Au=new Map([["speecht5",["SpeechT5ForTextToSpeech",lu]]]),Iu=new Map([["vits",["VitsModel",Aa]],["musicgen",["MusicgenForConditionalGeneration",La]]]),Ud=new Map([["bert",["BertForSequenceClassification",Xe]],["roformer",["RoFormerForSequenceClassification",_t]],["electra",["ElectraForSequenceClassification",bt]],["esm",["EsmForSequenceClassification",mr]],["convbert",["ConvBertForSequenceClassification",Y]],["camembert",["CamembertForSequenceClassification",Rr]],["deberta",["DebertaForSequenceClassification",Ie]],["deberta-v2",["DebertaV2ForSequenceClassification",Ct]],["mpnet",["MPNetForSequenceClassification",Ss]],["albert",["AlbertForSequenceClassification",gs]],["distilbert",["DistilBertForSequenceClassification",Fe]],["roberta",["RobertaForSequenceClassification",Mn]],["xlm",["XLMForSequenceClassification",Kt]],["xlm-roberta",["XLMRobertaForSequenceClassification",_r]],["bart",["BartForSequenceClassification",oe]],["mbart",["MBartForSequenceClassification",$t]],["mobilebert",["MobileBertForSequenceClassification",fs]],["squeezebert",["SqueezeBertForSequenceClassification",Rn]]]),gn=new Map([["bert",["BertForTokenClassification",Z]],["roformer",["RoFormerForTokenClassification",St]],["electra",["ElectraForTokenClassification",zt]],["esm",["EsmForTokenClassification",kr]],["convbert",["ConvBertForTokenClassification",he]],["camembert",["CamembertForTokenClassification",Jr]],["deberta",["DebertaForTokenClassification",Se]],["deberta-v2",["DebertaV2ForTokenClassification",ft]],["mpnet",["MPNetForTokenClassification",Ps]],["distilbert",["DistilBertForTokenClassification",Oe]],["roberta",["RobertaForTokenClassification",$e]],["xlm",["XLMForTokenClassification",pn]],["xlm-roberta",["XLMRobertaForTokenClassification",as]]]),Va=new Map([["t5",["T5ForConditionalGeneration",Fs]],["longt5",["LongT5ForConditionalGeneration",zs]],["mt5",["MT5ForConditionalGeneration",ae]],["bart",["BartForConditionalGeneration",Q]],["mbart",["MBartForConditionalGeneration",gt]],["marian",["MarianMTModel",kd]],["m2m_100",["M2M100ForConditionalGeneration",Rs]],["blenderbot",["BlenderbotForConditionalGeneration",Sr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",en]]]),Ua=new Map([["bloom",["BloomForCausalLM",Uo]],["gpt2",["GPT2LMHeadModel",Fn]],["jais",["JAISLMHeadModel",Mo]],["gptj",["GPTJForCausalLM",On]],["gpt_bigcode",["GPTBigCodeForCausalLM",Fi]],["gpt_neo",["GPTNeoForCausalLM",xo]],["gpt_neox",["GPTNeoXForCausalLM",Co]],["codegen",["CodeGenForCausalLM",Eo]],["llama",["LlamaForCausalLM",So]],["granite",["GraniteForCausalLM",Ao]],["cohere",["CohereForCausalLM",zn]],["gemma",["GemmaForCausalLM",Oo]],["gemma2",["Gemma2ForCausalLM",Do]],["openelm",["OpenELMForCausalLM",Bo]],["qwen2",["Qwen2ForCausalLM",Vi]],["phi",["PhiForCausalLM",Wi]],["phi3",["Phi3ForCausalLM",Js]],["mpt",["MptForCausalLM",Go]],["opt",["OPTForCausalLM",Ho]],["mbart",["MBartForCausalLM",Tt]],["mistral",["MistralForCausalLM",pu]],["starcoder2",["Starcoder2ForCausalLM",mu]],["falcon",["FalconForCausalLM",gu]],["trocr",["TrOCRForCausalLM",zd]],["stablelm",["StableLmForCausalLM",Ld]]]),Wa=new Map([["bert",["BertForMaskedLM",Mt]],["roformer",["RoFormerForMaskedLM",ut]],["electra",["ElectraForMaskedLM",yt]],["esm",["EsmForMaskedLM",Nr]],["convbert",["ConvBertForMaskedLM",$]],["camembert",["CamembertForMaskedLM",Yr]],["deberta",["DebertaForMaskedLM",ge]],["deberta-v2",["DebertaV2ForMaskedLM",mt]],["mpnet",["MPNetForMaskedLM",ks]],["albert",["AlbertForMaskedLM",Yt]],["distilbert",["DistilBertForMaskedLM",Ut]],["roberta",["RobertaForMaskedLM",_n]],["xlm",["XLMWithLMHeadModel",Nn]],["xlm-roberta",["XLMRobertaForMaskedLM",Et]],["mobilebert",["MobileBertForMaskedLM",Ur]],["squeezebert",["SqueezeBertForMaskedLM",An]]]),Fu=new Map([["bert",["BertForQuestionAnswering",Ae]],["roformer",["RoFormerForQuestionAnswering",xt]],["electra",["ElectraForQuestionAnswering",Pt]],["convbert",["ConvBertForQuestionAnswering",nt]],["camembert",["CamembertForQuestionAnswering",bn]],["deberta",["DebertaForQuestionAnswering",Ne]],["deberta-v2",["DebertaV2ForQuestionAnswering",Lt]],["mpnet",["MPNetForQuestionAnswering",As]],["albert",["AlbertForQuestionAnswering",ws]],["distilbert",["DistilBertForQuestionAnswering",ct]],["roberta",["RobertaForQuestionAnswering",tn]],["xlm",["XLMForQuestionAnswering",Xr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Kn]],["mobilebert",["MobileBertForQuestionAnswering",$s]],["squeezebert",["SqueezeBertForQuestionAnswering",ms]]]),vs=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ti]]]),Wd=new Map([["llava",["LlavaForConditionalGeneration",bs]],["moondream1",["Moondream1ForConditionalGeneration",pr]],["florence2",["Florence2ForConditionalGeneration",Ci]]]),Gd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ti]]]),Ou=new Map([["vit",["ViTForImageClassification",Td]],["pvt",["PvtForImageClassification",Qo]],["vit_msn",["ViTMSNForImageClassification",Jo]],["fastvit",["FastViTForImageClassification",nl]],["mobilevit",["MobileViTForImageClassification",ol]],["mobilevitv2",["MobileViTV2ForImageClassification",Ls]],["beit",["BeitForImageClassification",hl]],["deit",["DeiTForImageClassification",Ml]],["hiera",["HieraForImageClassification",ua]],["convnext",["ConvNextForImageClassification",hn]],["convnextv2",["ConvNextV2ForImageClassification",fa]],["dinov2",["Dinov2ForImageClassification",jl]],["resnet",["ResNetForImageClassification",Tl]],["swin",["SwinForImageClassification",El]],["segformer",["SegformerForImageClassification",Ia]],["efficientnet",["EfficientNetForImageClassification",Mu]],["mobilenet_v1",["MobileNetV1ForImageClassification",vu]],["mobilenet_v2",["MobileNetV2ForImageClassification",Tu]],["mobilenet_v3",["MobileNetV3ForImageClassification",Eu]],["mobilenet_v4",["MobileNetV4ForImageClassification",Nd]]]),zu=new Map([["detr",["DetrForObjectDetection",ml]],["rt_detr",["RTDetrForObjectDetection",wl]],["table-transformer",["TableTransformerForObjectDetection",aa]],["yolos",["YolosForObjectDetection",Vl]]]),Du=new Map([["owlvit",["OwlViTForObjectDetection",ul]],["owlv2",["Owlv2ForObjectDetection",cl]]]),Lu=new Map([["detr",["DetrForSegmentation",ea]],["clipseg",["CLIPSegForImageSegmentation",wo]]]),Ga=new Map([["segformer",["SegformerForSemanticSegmentation",yu]],["sapiens",["SapiensForSemanticSegmentation",Ol]]]),Bu=new Map([["detr",["DetrForSegmentation",ea]],["maskformer",["MaskFormerForInstanceSegmentation",Rl]]]),Ru=new Map([["sam",["SamModel",ga]]]),Nu=new Map([["wav2vec2",["Wav2Vec2ForCTC",Gl]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ca]],["unispeech",["UniSpeechForCTC",Zl]],["unispeech-sat",["UniSpeechSatForCTC",di]],["wavlm",["WavLMForCTC",su]],["hubert",["HubertForCTC",Id]]]),ju=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",ql]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Pd]],["unispeech",["UniSpeechForSequenceClassification",Jl]],["unispeech-sat",["UniSpeechSatForSequenceClassification",xa]],["wavlm",["WavLMForSequenceClassification",iu]],["hubert",["HubertForSequenceClassification",nu]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ys]]]),Vu=new Map([["wavlm",["WavLMForXVector",au]]]),qa=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Ta]],["wavlm",["WavLMForAudioFrameClassification",$a]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Hl]],["pyannote",["PyAnnoteForAudioFrameClassification",Ql]]]),Uu=new Map([["vitmatte",["VitMatteForImageMatting",il]]]),qd=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Sl]]]),Ha=new Map([["dpt",["DPTForDepthEstimation",Al]],["depth_anything",["DepthAnythingForDepthEstimation",Fl]],["glpn",["GLPNForDepthEstimation",Xn]],["sapiens",["SapiensForDepthEstimation",zl]],["depth_pro",["DepthProForDepthEstimation",Ll]]]),Wu=new Map([["sapiens",["SapiensForNormalEstimation",$d]]]),Gu=new Map([["clip",["CLIPVisionModelWithProjection",co]],["siglip",["SiglipVisionModel",fo]]]),qu=[[jd,X.EncoderOnly],[Mc,X.EncoderDecoder],[Vd,X.DecoderOnly],[Ud,X.EncoderOnly],[gn,X.EncoderOnly],[Va,X.Seq2Seq],[ja,X.Seq2Seq],[Ua,X.DecoderOnly],[Wa,X.EncoderOnly],[Fu,X.EncoderOnly],[vs,X.Vision2Seq],[Wd,X.ImageTextToText],[Ou,X.EncoderOnly],[Lu,X.EncoderOnly],[Bu,X.EncoderOnly],[Ga,X.EncoderOnly],[Uu,X.EncoderOnly],[qd,X.EncoderOnly],[Ha,X.EncoderOnly],[Wu,X.EncoderOnly],[zu,X.EncoderOnly],[Du,X.EncoderOnly],[Ru,X.MaskGeneration],[Nu,X.EncoderOnly],[ju,X.EncoderOnly],[Au,X.Seq2Seq],[Iu,X.EncoderOnly],[Vu,X.EncoderOnly],[qa,X.EncoderOnly],[Gu,X.EncoderOnly]];for(const[f,b]of qu)for(const[R,Me]of f.values())K.set(R,b),k.set(Me,R),j.set(R,Me);const vc=[["MusicgenForConditionalGeneration",La,X.Musicgen],["CLIPTextModelWithProjection",xn,X.EncoderOnly],["SiglipTextModel",ho,X.EncoderOnly],["ClapTextModelWithProjection",Ns,X.EncoderOnly],["ClapAudioModelWithProjection",Pa,X.EncoderOnly]];for(const[f,b,R]of vc)K.set(f,R),k.set(b,f),j.set(f,b);class Ka extends Or{}ve(Ka,"MODEL_CLASS_MAPPINGS",qu.map(b=>b[0])),ve(Ka,"BASE_IF_FAIL",!0);class Hu extends Or{}ve(Hu,"MODEL_CLASS_MAPPINGS",[Ud]);class Ku extends Or{}ve(Ku,"MODEL_CLASS_MAPPINGS",[gn]);class Hd extends Or{}ve(Hd,"MODEL_CLASS_MAPPINGS",[Va]);class Xu extends Or{}ve(Xu,"MODEL_CLASS_MAPPINGS",[ja]);class Qu extends Or{}ve(Qu,"MODEL_CLASS_MAPPINGS",[Au]);class Yu extends Or{}ve(Yu,"MODEL_CLASS_MAPPINGS",[Iu]);class Zu extends Or{}ve(Zu,"MODEL_CLASS_MAPPINGS",[Ua]);class Ju extends Or{}ve(Ju,"MODEL_CLASS_MAPPINGS",[Wa]);class Kd extends Or{}ve(Kd,"MODEL_CLASS_MAPPINGS",[Fu]);class ed extends Or{}ve(ed,"MODEL_CLASS_MAPPINGS",[vs]);class td extends Or{}ve(td,"MODEL_CLASS_MAPPINGS",[Ou]);class rd extends Or{}ve(rd,"MODEL_CLASS_MAPPINGS",[Lu]);class nd extends Or{}ve(nd,"MODEL_CLASS_MAPPINGS",[Ga]);class sd extends Or{}ve(sd,"MODEL_CLASS_MAPPINGS",[Bu]);class id extends Or{}ve(id,"MODEL_CLASS_MAPPINGS",[zu]);class ad extends Or{}ve(ad,"MODEL_CLASS_MAPPINGS",[Du]);class od extends Or{}ve(od,"MODEL_CLASS_MAPPINGS",[Ru]);class ld extends Or{}ve(ld,"MODEL_CLASS_MAPPINGS",[Nu]);class Xd extends Or{}ve(Xd,"MODEL_CLASS_MAPPINGS",[ju]);class js extends Or{}ve(js,"MODEL_CLASS_MAPPINGS",[Vu]);class Xa extends Or{}ve(Xa,"MODEL_CLASS_MAPPINGS",[qa]);class Qa extends Or{}ve(Qa,"MODEL_CLASS_MAPPINGS",[Gd]);class Ya extends Or{}ve(Ya,"MODEL_CLASS_MAPPINGS",[Uu]);class Za extends Or{}ve(Za,"MODEL_CLASS_MAPPINGS",[qd]);class ud extends Or{}ve(ud,"MODEL_CLASS_MAPPINGS",[Ha]);class dd extends Or{}ve(dd,"MODEL_CLASS_MAPPINGS",[Wu]);class Ja extends Or{}ve(Ja,"MODEL_CLASS_MAPPINGS",[Gu]);class cd extends Ze{constructor({logits:b,past_key_values:R,encoder_outputs:Me,decoder_attentions:Ue=null,cross_attentions:Le=null}){super(),this.logits=b,this.past_key_values=R,this.encoder_outputs=Me,this.decoder_attentions=Ue,this.cross_attentions=Le}}class cr extends Ze{constructor({logits:b}){super(),this.logits=b}}class pd extends Ze{constructor({logits:b,embeddings:R}){super(),this.logits=b,this.embeddings=R}}class nn extends Ze{constructor({logits:b}){super(),this.logits=b}}class un extends Ze{constructor({logits:b}){super(),this.logits=b}}class fn extends Ze{constructor({start_logits:b,end_logits:R}){super(),this.start_logits=b,this.end_logits=R}}class es extends Ze{constructor({logits:b}){super(),this.logits=b}}class Qd extends Ze{constructor({logits:b,past_key_values:R}){super(),this.logits=b,this.past_key_values=R}}class hd extends Ze{constructor({alphas:b}){super(),this.alphas=b}}class fd extends Ze{constructor({waveform:b,spectrogram:R}){super(),this.waveform=b,this.spectrogram=R}}},"./src/models/whisper/common_whisper.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{WHISPER_LANGUAGE_MAPPING:()=>ce,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>we,whisper_language_to_code:()=>ye});const F=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],ce=new Map(F),we=new Map([...F.map(([Te,L])=>[L,Te]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function ye(Te){Te=Te.toLowerCase();let L=we.get(Te);if(L===void 0)if(ce.has(Te))L=Te;else{const D=Te.length===2?ce.keys():ce.values();throw new Error(`Language "${Te}" is not supported. Must be one of: ${JSON.stringify(D)}`)}return L}},"./src/models/whisper/generation_whisper.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{WhisperGenerationConfig:()=>ce});var F=V("./src/generation/configuration_utils.js");class ce extends F.GenerationConfig{constructor(){super(...arguments);ve(this,"return_timestamps",null);ve(this,"return_token_timestamps",null);ve(this,"num_frames",null);ve(this,"alignment_heads",null);ve(this,"task",null);ve(this,"language",null);ve(this,"no_timestamps_token_id",null);ve(this,"prompt_ids",null);ve(this,"is_multilingual",null);ve(this,"lang_to_id",null);ve(this,"task_to_id",null);ve(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{TensorOpRegistry:()=>ye});var F=V("./src/backends/onnx.js"),ce=V("./src/utils/tensor.js");const we=async(Te,L,P)=>{const D=await(0,F.createInferenceSession)(new Uint8Array(Te),L);return async B=>{const q=Object.fromEntries(Object.entries(B).map(([fe,le])=>[fe,le.ort_tensor])),re=await D.run(q);return Array.isArray(P)?P.map(fe=>new ce.Tensor(re[fe])):new ce.Tensor(re[P])}};class ye{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=we([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=we([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=we([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=we([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=we([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=we([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}ve(ye,"session_options",{})},"./src/pipelines.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{AudioClassificationPipeline:()=>De,AutomaticSpeechRecognitionPipeline:()=>it,DepthEstimationPipeline:()=>Ze,DocumentQuestionAnsweringPipeline:()=>We,FeatureExtractionPipeline:()=>be,FillMaskPipeline:()=>X,ImageClassificationPipeline:()=>lt,ImageFeatureExtractionPipeline:()=>Ce,ImageSegmentationPipeline:()=>me,ImageToImagePipeline:()=>se,ImageToTextPipeline:()=>rt,ObjectDetectionPipeline:()=>de,Pipeline:()=>le,QuestionAnsweringPipeline:()=>pe,SummarizationPipeline:()=>j,Text2TextGenerationPipeline:()=>K,TextClassificationPipeline:()=>O,TextGenerationPipeline:()=>E,TextToAudioPipeline:()=>ot,TokenClassificationPipeline:()=>J,TranslationPipeline:()=>k,ZeroShotAudioClassificationPipeline:()=>ze,ZeroShotClassificationPipeline:()=>ue,ZeroShotImageClassificationPipeline:()=>W,ZeroShotObjectDetectionPipeline:()=>xe,pipeline:()=>ht});var F=V("./src/tokenizers.js"),ce=V("./src/models.js"),we=V("./src/processors.js"),ye=V("./src/utils/generic.js"),Te=V("./src/utils/core.js"),L=V("./src/utils/maths.js"),P=V("./src/utils/audio.js"),D=V("./src/utils/tensor.js"),B=V("./src/utils/image.js");async function q(Xe){return Array.isArray(Xe)||(Xe=[Xe]),await Promise.all(Xe.map(Z=>B.RawImage.read(Z)))}async function re(Xe,Z){return Array.isArray(Xe)||(Xe=[Xe]),await Promise.all(Xe.map(Ae=>typeof Ae=="string"||Ae instanceof URL?(0,P.read_audio)(Ae,Z):Ae instanceof Float64Array?new Float32Array(Ae):Ae))}function fe(Xe,Z){Z&&(Xe=Xe.map(Ve=>Ve|0));const[Ae,Ke,et,je]=Xe;return{xmin:Ae,ymin:Ke,xmax:et,ymax:je}}class le extends ye.Callable{constructor({task:Z,model:Ae,tokenizer:Ke=null,processor:et=null}){super(),this.task=Z,this.model=Ae,this.tokenizer=Ke,this.processor=et}async dispose(){await this.model.dispose()}}class O extends le{constructor(Z){super(Z)}async _call(Z,{top_k:Ae=1}={}){const Ke=this.tokenizer(Z,{padding:!0,truncation:!0}),et=await this.model(Ke),je=this.model.config.problem_type==="multi_label_classification"?_t=>_t.sigmoid():_t=>new D.Tensor("float32",(0,L.softmax)(_t.data),_t.dims),Ve=this.model.config.id2label,ut=[];for(const _t of et.logits){const St=je(_t),xt=await(0,D.topk)(St,Ae),v=xt[0].tolist(),$=xt[1].tolist().map((Y,he)=>({label:Ve?Ve[Y]:`LABEL_${Y}`,score:v[he]}));Ae===1?ut.push(...$):ut.push($)}return Array.isArray(Z)||Ae===1?ut:ut[0]}}class J extends le{constructor(Z){super(Z)}async _call(Z,{ignore_labels:Ae=["O"]}={}){const Ke=Array.isArray(Z),et=this.tokenizer(Ke?Z:[Z],{padding:!0,truncation:!0}),Ve=(await this.model(et)).logits,ut=this.model.config.id2label,_t=[];for(let St=0;Styt==this.tokenizer.sep_token_id);_t[v].map((yt,bt)=>yt==1&&(bt===0||bt>$&&St.findIndex(zt=>zt==H[bt])===-1));const Y=je[v].tolist(),he=Ve[v].tolist();for(let yt=1;ytbt==H[yt])!==-1)&&(Y[yt]=-1/0,he[yt]=-1/0);const nt=(0,L.softmax)(Y).map((yt,bt)=>[yt,bt]),Je=(0,L.softmax)(he).map((yt,bt)=>[yt,bt]);nt[0][0]=0,Je[0][0]=0;const Nt=(0,Te.product)(nt,Je).filter(yt=>yt[0][1]<=yt[1][1]).map(yt=>[yt[0][1],yt[1][1],yt[0][0]*yt[1][0]]).sort((yt,bt)=>bt[2]-yt[2]);for(let yt=0;ytY==this.tokenizer.mask_token_id);if(St===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const xt=et[ut][St],v=await(0,D.topk)(new D.Tensor("float32",(0,L.softmax)(xt.data),xt.dims),Ae),H=v[0].tolist(),$=v[1].tolist();je.push($.map((Y,he)=>{const nt=_t.slice();return nt[St]=Y,{score:H[he],token:Number(Y),token_str:this.tokenizer.model.vocab[Y],sequence:this.tokenizer.decode(nt,{skip_special_tokens:!0})}}))}return Array.isArray(Z)?je:je[0]}}class K extends le{constructor(Ae){super(Ae);ve(this,"_key","generated_text")}async _call(Ae,Ke={}){Array.isArray(Ae)||(Ae=[Ae]),this.model.config.prefix&&(Ae=Ae.map(St=>this.model.config.prefix+St));const et=this.model.config.task_specific_params;et&&et[this.task]&&et[this.task].prefix&&(Ae=Ae.map(St=>et[this.task].prefix+St));const je=this.tokenizer,Ve={padding:!0,truncation:!0};let ut;this instanceof k&&"_build_translation_inputs"in je?ut=je._build_translation_inputs(Ae,Ve,Ke):ut=je(Ae,Ve);const _t=await this.model.generate({...ut,...Ke});return je.batch_decode(_t,{skip_special_tokens:!0}).map(St=>({[this._key]:St}))}}class j extends K{constructor(Ae){super(Ae);ve(this,"_key","summary_text")}}class k extends K{constructor(Ae){super(Ae);ve(this,"_key","translation_text")}}function N(Xe){return Array.isArray(Xe)&&Xe.every(Z=>"role"in Z&&"content"in Z)}class E extends le{constructor(Z){super(Z)}async _call(Z,Ae={}){let Ke=!1,et=!1,je;if(typeof Z=="string")je=Z=[Z];else if(Array.isArray(Z)&&Z.every($=>typeof $=="string"))Ke=!0,je=Z;else{if(N(Z))Z=[Z];else if(Array.isArray(Z)&&Z.every(N))Ke=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");et=!0,je=Z.map($=>this.tokenizer.apply_chat_template($,{tokenize:!1,add_generation_prompt:!0}))}const Ve=Ae.add_special_tokens??!1,ut=et?!1:Ae.return_full_text??!0;this.tokenizer.padding_side="left";const _t=this.tokenizer(je,{add_special_tokens:Ve,padding:!0,truncation:!0}),St=await this.model.generate({..._t,...Ae}),xt=this.tokenizer.batch_decode(St,{skip_special_tokens:!0});let v;!ut&&_t.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(_t.input_ids,{skip_special_tokens:!0}).map($=>$.length));const H=Array.from({length:Z.length},$=>[]);for(let $=0;$[Ae.toLowerCase(),Ke])),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(Z,Ae,{hypothesis_template:Ke="This example is {}.",multi_label:et=!1}={}){const je=Array.isArray(Z);je||(Z=[Z]),Array.isArray(Ae)||(Ae=[Ae]);const Ve=Ae.map(St=>Ke.replace("{}",St)),ut=et||Ae.length===1,_t=[];for(const St of Z){const xt=[];for(const $ of Ve){const Y=this.tokenizer(St,{text_pair:$,padding:!0,truncation:!0}),he=await this.model(Y);ut?xt.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):xt.push(he.logits.data[this.entailment_id])}const H=(ut?xt.map($=>(0,L.softmax)($)[1]):(0,L.softmax)(xt)).map(($,Y)=>[$,Y]).sort(($,Y)=>Y[0]-$[0]);_t.push({sequence:St,labels:H.map($=>Ae[$[1]]),scores:H.map($=>$[0])})}return je?_t:_t[0]}}class be extends le{constructor(Z){super(Z)}async _call(Z,{pooling:Ae="none",normalize:Ke=!1,quantize:et=!1,precision:je="binary"}={}){const Ve=this.tokenizer(Z,{padding:!0,truncation:!0}),ut=await this.model(Ve);let _t=ut.last_hidden_state??ut.logits??ut.token_embeddings;if(Ae!=="none")if(Ae==="mean")_t=(0,D.mean_pooling)(_t,Ve.attention_mask);else if(Ae==="cls")_t=_t.slice(null,0);else throw Error(`Pooling method '${Ae}' not supported.`);return Ke&&(_t=_t.normalize(2,-1)),et&&(_t=(0,D.quantize_embeddings)(_t,je)),_t}}class Ce extends le{constructor(Z){super(Z)}async _call(Z,{pool:Ae=null}={}){const Ke=await q(Z),{pixel_values:et}=await this.processor(Ke),je=await this.model({pixel_values:et});let Ve;if(Ae){if(!("pooler_output"in je))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ve=je.pooler_output}else Ve=je.last_hidden_state??je.logits??je.image_embeds;return Ve}}class De extends le{constructor(Z){super(Z)}async _call(Z,{top_k:Ae=5}={}){const Ke=this.processor.feature_extractor.config.sampling_rate,et=await re(Z,Ke),je=this.model.config.id2label,Ve=[];for(const ut of et){const _t=await this.processor(ut),xt=(await this.model(_t)).logits[0],v=await(0,D.topk)(new D.Tensor("float32",(0,L.softmax)(xt.data),xt.dims),Ae),H=v[0].tolist(),Y=v[1].tolist().map((he,nt)=>({label:je?je[he]:`LABEL_${he}`,score:H[nt]}));Ve.push(Y)}return Array.isArray(Z)?Ve:Ve[0]}}class ze extends le{constructor(Z){super(Z)}async _call(Z,Ae,{hypothesis_template:Ke="This is a sound of {}."}={}){const et=!Array.isArray(Z);et&&(Z=[Z]);const je=Ae.map(xt=>Ke.replace("{}",xt)),Ve=this.tokenizer(je,{padding:!0,truncation:!0}),ut=this.processor.feature_extractor.config.sampling_rate,_t=await re(Z,ut),St=[];for(const xt of _t){const v=await this.processor(xt),H=await this.model({...Ve,...v}),$=(0,L.softmax)(H.logits_per_audio.data);St.push([...$].map((Y,he)=>({score:Y,label:Ae[he]})))}return et?St[0]:St}}class it extends le{constructor(Z){super(Z)}async _call(Z,Ae={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(Z,Ae);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(Z,Ae);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Z,Ae){Ae.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Ae.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ke=!Array.isArray(Z);Ke&&(Z=[Z]);const et=this.processor.feature_extractor.config.sampling_rate,je=await re(Z,et),Ve=[];for(const ut of je){const _t=await this.processor(ut),xt=(await this.model(_t)).logits[0],v=[];for(const $ of xt)v.push((0,L.max)($.data)[1]);const H=this.tokenizer.decode(v);Ve.push({text:H})}return Ke?Ve[0]:Ve}async _call_whisper(Z,Ae){const Ke=Ae.return_timestamps??!1,et=Ae.chunk_length_s??0,je=Ae.force_full_sequences??!1;let Ve=Ae.stride_length_s??null;const ut={...Ae};Ke==="word"&&(ut.return_token_timestamps=!0,ut.return_timestamps=!1);const _t=!Array.isArray(Z);_t&&(Z=[Z]);const St=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,xt=this.processor.feature_extractor.config.hop_length,v=this.processor.feature_extractor.config.sampling_rate,H=await re(Z,v),$=[];for(const Y of H){let he=[];if(et>0){if(Ve===null)Ve=et/6;else if(et<=Ve)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Nt=v*et,yt=v*Ve,bt=Nt-2*yt;let zt=0;for(;;){const Pt=zt+Nt,dr=Y.subarray(zt,Pt),Cr=await this.processor(dr),Yr=zt===0,Rr=Pt>=Y.length;if(he.push({stride:[dr.length,Yr?0:yt,Rr?0:yt],input_features:Cr.input_features,is_last:Rr}),Rr)break;zt+=bt}}else he=[{stride:[Y.length,0,0],input_features:(await this.processor(Y)).input_features,is_last:!0}];for(const Nt of he){ut.num_frames=Math.floor(Nt.stride[0]/xt);const yt=await this.model.generate({inputs:Nt.input_features,...ut});Ke==="word"?(Nt.tokens=yt.sequences.tolist()[0],Nt.token_timestamps=yt.token_timestamps.tolist()[0].map(bt=>(0,L.round)(bt,2))):Nt.tokens=yt[0].tolist(),Nt.stride=Nt.stride.map(bt=>bt/v)}const[nt,Je]=this.tokenizer._decode_asr(he,{time_precision:St,return_timestamps:Ke,force_full_sequences:je});$.push({text:nt,...Je})}return _t?$[0]:$}}class rt extends le{constructor(Z){super(Z)}async _call(Z,Ae={}){const Ke=Array.isArray(Z),et=await q(Z),{pixel_values:je}=await this.processor(et),Ve=[];for(const ut of je){ut.dims=[1,...ut.dims];const _t=await this.model.generate({inputs:ut,...Ae}),St=this.tokenizer.batch_decode(_t,{skip_special_tokens:!0}).map(xt=>({generated_text:xt.trim()}));Ve.push(St)}return Ke?Ve:Ve[0]}}class lt extends le{constructor(Z){super(Z)}async _call(Z,{top_k:Ae=5}={}){const Ke=await q(Z),{pixel_values:et}=await this.processor(Ke),je=await this.model({pixel_values:et}),Ve=this.model.config.id2label,ut=[];for(const _t of je.logits){const St=await(0,D.topk)(new D.Tensor("float32",(0,L.softmax)(_t.data),_t.dims),Ae),xt=St[0].tolist(),H=St[1].tolist().map(($,Y)=>({label:Ve?Ve[$]:`LABEL_${$}`,score:xt[Y]}));ut.push(H)}return Array.isArray(Z)?ut:ut[0]}}class me extends le{constructor(Z){super(Z),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Z,{threshold:Ae=.5,mask_threshold:Ke=.5,overlap_mask_area_threshold:et=.8,label_ids_to_fuse:je=null,target_sizes:Ve=null,subtask:ut=null}={}){if(Array.isArray(Z)&&Z.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const St=await q(Z),xt=St.map(Je=>[Je.height,Je.width]),{pixel_values:v,pixel_mask:H}=await this.processor(St),$=await this.model({pixel_values:v,pixel_mask:H});let Y=null;if(ut!==null)Y=this.subtasks_mapping[ut];else for(let[Je,Nt]of Object.entries(this.subtasks_mapping))if(Nt in this.processor.feature_extractor){Y=this.processor.feature_extractor[Nt].bind(this.processor.feature_extractor),ut=Je;break}const he=this.model.config.id2label,nt=[];if(ut==="panoptic"||ut==="instance"){const Je=Y($,Ae,Ke,et,je,Ve??xt)[0],Nt=Je.segmentation;for(const yt of Je.segments_info){const bt=new Uint8ClampedArray(Nt.data.length);for(let Pt=0;PtKe.replace("{}",H)),ut=this.tokenizer(Ve,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:_t}=await this.processor(je),St=await this.model({...ut,pixel_values:_t}),xt=this.model.config.model_type==="siglip"?H=>H.sigmoid().data:H=>(0,L.softmax)(H.data),v=[];for(const H of St.logits_per_image){const Y=[...xt(H)].map((he,nt)=>({score:he,label:Ae[nt]}));Y.sort((he,nt)=>nt.score-he.score),v.push(Y)}return et?v:v[0]}}class de extends le{constructor(Z){super(Z)}async _call(Z,{threshold:Ae=.9,percentage:Ke=!1}={}){const et=Array.isArray(Z);if(et&&Z.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const je=await q(Z),Ve=Ke?null:je.map($=>[$.height,$.width]),{pixel_values:ut,pixel_mask:_t}=await this.processor(je),St=await this.model({pixel_values:ut,pixel_mask:_t}),xt=this.processor.feature_extractor.post_process_object_detection(St,Ae,Ve),v=this.model.config.id2label,H=xt.map($=>$.boxes.map((Y,he)=>({score:$.scores[he],label:v[$.classes[he]],box:fe(Y,!Ke)})));return et?H:H[0]}}class xe extends le{constructor(Z){super(Z)}async _call(Z,Ae,{threshold:Ke=.1,top_k:et=null,percentage:je=!1}={}){const Ve=Array.isArray(Z),ut=await q(Z),_t=this.tokenizer(Ae,{padding:!0,truncation:!0}),St=await this.processor(ut),xt=[];for(let v=0;v({score:nt.scores[yt],label:Ae[nt.classes[yt]],box:fe(Nt,!je)})).sort((Nt,yt)=>yt.score-Nt.score);et!==null&&(Je=Je.slice(0,et)),xt.push(Je)}return Ve?xt:xt[0]}}class We extends le{constructor(Z){super(Z)}async _call(Z,Ae,Ke={}){const et=(await q(Z))[0],{pixel_values:je}=await this.processor(et),Ve=`${Ae}`,ut=this.tokenizer(Ve,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,_t=await this.model.generate({inputs:je,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:ut,...Ke}),xt=this.tokenizer.batch_decode(_t)[0].match(/(.*?)<\/s_answer>/);let v=null;return xt&&xt.length>=2&&(v=xt[1].trim()),[{answer:v}]}}class ot extends le{constructor(Ae){super(Ae);ve(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Ae.vocoder??null}async _call(Ae,{speaker_embeddings:Ke=null}={}){return this.processor?this._call_text_to_spectrogram(Ae,{speaker_embeddings:Ke}):this._call_text_to_waveform(Ae)}async _call_text_to_waveform(Ae){const Ke=this.tokenizer(Ae,{padding:!0,truncation:!0}),{waveform:et}=await this.model(Ke),je=this.model.config.sampling_rate;return{audio:et.data,sampling_rate:je}}async _call_text_to_spectrogram(Ae,{speaker_embeddings:Ke}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await ce.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ke=="string"||Ke instanceof URL)&&(Ke=new Float32Array(await(await fetch(Ke)).arrayBuffer())),Ke instanceof Float32Array)Ke=new D.Tensor("float32",Ke,[1,Ke.length]);else if(!(Ke instanceof D.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:et}=this.tokenizer(Ae,{padding:!0,truncation:!0}),{waveform:je}=await this.model.generate_speech(et,Ke,{vocoder:this.vocoder}),Ve=this.processor.feature_extractor.config.sampling_rate;return{audio:je.data,sampling_rate:Ve}}}class se extends le{constructor(Z){super(Z)}async _call(Z){const Ae=await q(Z),Ke=await this.processor(Ae),et=await this.model(Ke),je=[];for(const Ve of et.reconstruction){const ut=Ve.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");je.push(B.RawImage.fromTensor(ut))}return je.length>1?je:je[0]}}class Ze extends le{constructor(Z){super(Z)}async _call(Z){const Ae=await q(Z),Ke=await this.processor(Ae),{predicted_depth:et}=await this.model(Ke),je=[];for(let Ve=0;Ve1?je:je[0]}}const dt=Object.freeze({"text-classification":{tokenizer:F.AutoTokenizer,pipeline:O,model:ce.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:F.AutoTokenizer,pipeline:J,model:ce.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:F.AutoTokenizer,pipeline:pe,model:ce.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:F.AutoTokenizer,pipeline:X,model:ce.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:F.AutoTokenizer,pipeline:j,model:ce.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:F.AutoTokenizer,pipeline:k,model:ce.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:F.AutoTokenizer,pipeline:K,model:ce.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:F.AutoTokenizer,pipeline:E,model:ce.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:F.AutoTokenizer,pipeline:ue,model:ce.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:De,model:ce.AutoModelForAudioClassification,processor:we.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:F.AutoTokenizer,pipeline:ze,model:ce.AutoModel,processor:we.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:F.AutoTokenizer,pipeline:it,model:[ce.AutoModelForSpeechSeq2Seq,ce.AutoModelForCTC],processor:we.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:F.AutoTokenizer,pipeline:ot,model:[ce.AutoModelForTextToWaveform,ce.AutoModelForTextToSpectrogram],processor:[we.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:F.AutoTokenizer,pipeline:rt,model:ce.AutoModelForVision2Seq,processor:we.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:lt,model:ce.AutoModelForImageClassification,processor:we.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:me,model:[ce.AutoModelForImageSegmentation,ce.AutoModelForSemanticSegmentation,ce.AutoModelForUniversalSegmentation],processor:we.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:F.AutoTokenizer,pipeline:W,model:ce.AutoModel,processor:we.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:de,model:ce.AutoModelForObjectDetection,processor:we.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:F.AutoTokenizer,pipeline:xe,model:ce.AutoModelForZeroShotObjectDetection,processor:we.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:F.AutoTokenizer,pipeline:We,model:ce.AutoModelForDocumentQuestionAnswering,processor:we.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:se,model:ce.AutoModelForImageToImage,processor:we.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ze,model:ce.AutoModelForDepthEstimation,processor:we.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:F.AutoTokenizer,pipeline:be,model:ce.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:we.AutoProcessor,pipeline:Ce,model:[ce.AutoModelForImageFeatureExtraction,ce.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Re=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ht(Xe,Z=null,{progress_callback:Ae=null,config:Ke=null,cache_dir:et=null,local_files_only:je=!1,revision:Ve="main",device:ut=null,dtype:_t=null,model_file_name:St=null,session_options:xt={}}={}){Xe=Re[Xe]??Xe;const v=dt[Xe.split("_",1)[0]];if(!v)throw Error(`Unsupported pipeline: ${Xe}. Must be one of [${Object.keys(dt)}]`);Z||(Z=v.default.model,console.log(`No model specified. Using default model: "${Z}".`));const H={progress_callback:Ae,config:Ke,cache_dir:et,local_files_only:je,revision:Ve,device:ut,dtype:_t,model_file_name:St,session_options:xt},$=new Map([["tokenizer",v.tokenizer],["model",v.model],["processor",v.processor]]),Y=await Mt($,Z,H);Y.task=Xe,(0,Te.dispatchCallback)(Ae,{status:"ready",task:Xe,model:Z});const he=v.pipeline;return new he(Y)}async function Mt(Xe,Z,Ae){const Ke=Object.create(null),et=[];for(const[je,Ve]of Xe.entries()){if(!Ve)continue;let ut;Array.isArray(Ve)?ut=new Promise(async(_t,St)=>{var v,H;let xt;for(const $ of Ve){if($===null){_t(null);return}try{_t(await $.from_pretrained(Z,Ae));return}catch(Y){if((v=Y.message)!=null&&v.includes("Unsupported model type"))xt=Y;else if((H=Y.message)!=null&&H.includes("Could not locate file"))xt=Y;else{St(Y);return}}}St(xt)}):ut=Ve.from_pretrained(Z,Ae),Ke[je]=ut,et.push(ut)}await Promise.all(et);for(const[je,Ve]of Object.entries(Ke))Ke[je]=await Ve;return Ke}},"./src/processors.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{ASTFeatureExtractor:()=>he,AutoProcessor:()=>bn,BeitFeatureExtractor:()=>Ae,BitImageProcessor:()=>be,CLIPFeatureExtractor:()=>De,CLIPImageProcessor:()=>ze,ChineseCLIPFeatureExtractor:()=>it,ClapFeatureExtractor:()=>nt,ConvNextFeatureExtractor:()=>lt,ConvNextImageProcessor:()=>me,DPTFeatureExtractor:()=>E,DPTImageProcessor:()=>ue,DeiTFeatureExtractor:()=>Z,DetrFeatureExtractor:()=>Ve,DonutFeatureExtractor:()=>Ke,DonutImageProcessor:()=>et,EfficientNetImageProcessor:()=>xe,FeatureExtractor:()=>X,Florence2Processor:()=>Jr,GLPNFeatureExtractor:()=>Ce,ImageFeatureExtractor:()=>K,MaskFormerFeatureExtractor:()=>ut,MobileNetV1FeatureExtractor:()=>We,MobileNetV2FeatureExtractor:()=>ot,MobileNetV3FeatureExtractor:()=>se,MobileNetV4FeatureExtractor:()=>Ze,MobileViTFeatureExtractor:()=>dt,MobileViTImageProcessor:()=>Re,NougatImageProcessor:()=>je,OwlViTFeatureExtractor:()=>ht,OwlViTProcessor:()=>Rr,Owlv2ImageProcessor:()=>Mt,Processor:()=>bt,PvtImageProcessor:()=>N,PyAnnoteFeatureExtractor:()=>Je,PyAnnoteProcessor:()=>Cr,RTDetrImageProcessor:()=>Xe,SamImageProcessor:()=>St,SamProcessor:()=>zt,SapiensFeatureExtractor:()=>j,SeamlessM4TFeatureExtractor:()=>Y,SegformerFeatureExtractor:()=>k,SiglipImageProcessor:()=>rt,SpeechT5FeatureExtractor:()=>yt,SpeechT5Processor:()=>Yr,Swin2SRImageProcessor:()=>xt,ViTFeatureExtractor:()=>W,ViTImageProcessor:()=>de,VitMatteImageProcessor:()=>v,Wav2Vec2FeatureExtractor:()=>$,Wav2Vec2ProcessorWithLM:()=>dr,WeSpeakerFeatureExtractor:()=>Nt,WhisperFeatureExtractor:()=>H,WhisperProcessor:()=>Pt,YolosFeatureExtractor:()=>_t});var F=V("./src/utils/generic.js"),ce=V("./src/utils/core.js"),we=V("./src/utils/hub.js"),ye=V("./src/utils/maths.js"),Te=V("./src/utils/tensor.js");V("./src/utils/image.js");var L=V("./src/utils/audio.js");function P([at,G,ge,Ie]){return[at-ge/2,G-Ie/2,at+ge/2,G+Ie/2]}function D(at,G=.5,ge=null,Ie=!1){const Se=at.logits,Ne=at.pred_boxes,[tt,wt,mt]=Se.dims;if(ge!==null&&ge.length!==tt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Ct=[];for(let ft=0;ftG&&Ut.push(br)}else{let br=(0,ye.max)(ct.data)[1];if(br===mt-1||(sr=(0,ye.softmax)(ct.data),sr[br]mr*Lt[(kr+1)%2])),jt.boxes.push(Nr),jt.classes.push(br),jt.scores.push(sr[br])}}Ct.push(jt)}return Ct}function B(at,G=null){const ge=at.logits,Ie=ge.dims[0];if(G!==null&&G.length!==Ie)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Se=[];for(let Ne=0;NeLt[Ut]&&(Lt[Ut]=ct[Ut],jt[Ut]=Oe)}const Ft=new Array(wt.dims[0]);for(let Oe=0;OeOe!==void 0);Se.push({segmentation:ft,labels:Fe})}return Se}function q(at,G,ge,Ie){const Se=[],Ne=[],tt=[];for(let wt=0;wtge&&(Se.push(Ct),Ne.push(jt),tt.push(ft))}return[Se,Ne,tt]}function re(at,G,ge,Ie=.5,Se=.8){const Ne=[];let tt=0,wt=0;const mt=G[ge].data;for(let ft=0;ft=Ie&&++wt;let Ct=tt>0&&wt>0;return Ct&&(Ct=tt/wt>Se),[Ct,Ne]}function fe(at,G,ge,Ie,Se,Ne=null,tt=null){const[wt,mt]=tt??at[0].dims,Ct=new Te.Tensor("int32",new Int32Array(wt*mt),[wt,mt]),ft=[];if(tt!==null)for(let Oe=0;Oejt[sr]&&(Lt[sr]=Oe,jt[sr]=Ut[sr])}let Ft=0;const Fe=Ct.data;for(let Oe=0;OeIe&&(Ne=Math.floor(Se)*G),NeNe?Ct=Math.floor(Ne*mt/Se):Ne>Se&&(mt=Math.floor(Se*Ct/Ne)),await G.resize(Ct,mt,{resample:Ie}))}async crop_margin(G,ge=200){const Ie=G.clone().grayscale(),Se=(0,ye.min)(Ie.data)[0],tt=(0,ye.max)(Ie.data)[0]-Se;if(tt===0)return G;const wt=ge/255;let mt=Ie.width,Ct=Ie.height,ft=0,Lt=0;const jt=Ie.data;for(let Ft=0;Ftthis.preprocess(Ne)));return{pixel_values:(0,Te.stack)(Ie.map(Ne=>Ne.pixel_values),0),original_sizes:Ie.map(Ne=>Ne.original_size),reshaped_input_sizes:Ie.map(Ne=>Ne.reshaped_input_size)}}}class j extends K{post_process_semantic_segmentation(...G){return B(...G)}}class k extends K{post_process_semantic_segmentation(...G){return B(...G)}}class N extends K{}class E extends K{}class ue extends E{}class be extends K{}class Ce extends K{}class De extends K{}class ze extends De{}class it extends K{}class rt extends K{}class lt extends K{constructor(G){super(G),this.crop_pct=this.config.crop_pct??.875}async resize(G){var Ie;const ge=(Ie=this.size)==null?void 0:Ie.shortest_edge;if(ge===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(ge<384){const Se=Math.floor(ge/this.crop_pct),[Ne,tt]=this.get_resize_output_image_size(G,{shortest_edge:Se});G=await G.resize(Ne,tt,{resample:this.resample}),G=await G.center_crop(ge,ge)}else G=await G.resize(ge,ge,{resample:this.resample});return G}}class me extends lt{}class W extends K{}class de extends K{}class xe extends K{constructor(G){super(G),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(ge=>ge*ge))}}class We extends K{}class ot extends K{}class se extends K{}class Ze extends K{}class dt extends K{}class Re extends dt{}class ht extends K{post_process_object_detection(...G){return D(...G)}}class Mt extends ht{}class Xe extends K{post_process_object_detection(...G){return D(...G)}}class Z extends K{}class Ae extends K{}class Ke extends K{pad_image(G,ge,Ie,Se={}){const[Ne,tt,wt]=ge;let mt=this.image_mean;Array.isArray(this.image_mean)||(mt=new Array(wt).fill(mt));let Ct=this.image_std;Array.isArray(Ct)||(Ct=new Array(wt).fill(mt));const ft=mt.map((Lt,jt)=>-Lt/Ct[jt]);return super.pad_image(G,ge,Ie,{center:!0,constant_values:ft,...Se})}}class et extends Ke{}class je extends Ke{}class Ve extends K{async _call(G){const ge=await super._call(G),Ie=[ge.pixel_values.dims[0],64,64],Se=(0,Te.full)(Ie,1n);return{...ge,pixel_mask:Se}}post_process_object_detection(...G){return D(...G)}post_process_panoptic_segmentation(...G){return le(...G)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class ut extends K{post_process_panoptic_segmentation(...G){return le(...G)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class _t extends K{post_process_object_detection(...G){return D(...G)}}class St extends K{reshape_input_points(G,ge,Ie,Se=!1){G=structuredClone(G);let Ne=(0,ce.calculateDimensions)(G);if(Ne.length===3)Se||(Ne=[1,...Ne]),G=[G];else if(Ne.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 tt=0;ttSe!==ge.dims[Ne]))throw Error(`The first ${Ie.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Te.Tensor("int64",G.flat(1/0).map(BigInt),Ie)}async _call(G,{input_points:ge=null,input_labels:Ie=null,input_boxes:Se=null}={}){const Ne=await super._call(G);if(ge&&(Ne.input_points=this.reshape_input_points(ge,Ne.original_sizes,Ne.reshaped_input_sizes)),Ie){if(!Ne.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Ne.input_labels=this.add_input_labels(Ie,Ne.input_points)}return Se&&(Ne.input_boxes=this.reshape_input_points(Se,Ne.original_sizes,Ne.reshaped_input_sizes,!0)),Ne}async post_process_masks(G,ge,Ie,{mask_threshold:Se=0,binarize:Ne=!0,pad_size:tt=null}={}){const wt=[];tt=tt??this.pad_size;const mt=[tt.height,tt.width];for(let Ct=0;CtSe&&(Fe[Oe]=1);jt=new Te.Tensor("bool",Fe,jt.dims)}wt.push(jt)}return wt}generate_crop_boxes(G,ge,{crop_n_layers:Ie=0,overlap_ratio:Se=.3413333333333333,points_per_crop:Ne=32,crop_n_points_downscale_factor:tt=1}={}){}}class xt extends K{pad_image(G,ge,Ie,Se={}){const[Ne,tt,wt]=ge;return super.pad_image(G,ge,{width:tt+(Ie-tt%Ie)%Ie,height:Ne+(Ie-Ne%Ie)%Ie},{mode:"symmetric",center:!1,constant_values:-1,...Se})}}class v extends K{async _call(G,ge){Array.isArray(G)||(G=[G]),Array.isArray(ge)||(ge=[ge]);const Ie=await Promise.all(G.map(tt=>this.preprocess(tt))),Se=await Promise.all(ge.map(tt=>this.preprocess(tt,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,Te.stack)(Ie.map((tt,wt)=>(0,Te.cat)([tt.pixel_values,Se[wt].pixel_values],0)),0),original_sizes:Ie.map(tt=>tt.original_size),reshaped_input_sizes:Ie.map(tt=>tt.reshaped_input_size)}}}class H extends X{constructor(G){var ge;super(G),(ge=this.config).mel_filters??(ge.mel_filters=(0,L.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,L.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(G){const ge=await(0,L.spectrogram)(G,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),Ie=ge.data,Se=(0,ye.max)(Ie)[0];for(let Ne=0;Nethis.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`."),ge=G.slice(0,this.config.n_samples)):(ge=new Float32Array(this.config.n_samples),ge.set(G)),{input_features:(await this._extract_fbank_features(ge)).unsqueeze_(0)}}}class $ extends X{_zero_mean_unit_var_norm(G){const Ie=G.reduce((Ne,tt)=>Ne+tt,0)/G.length,Se=G.reduce((Ne,tt)=>Ne+(tt-Ie)**2,0)/G.length;return G.map(Ne=>(Ne-Ie)/Math.sqrt(Se+1e-7))}async _call(G){O(G,"Wav2Vec2FeatureExtractor"),G instanceof Float64Array&&(G=new Float32Array(G));let ge=G;this.config.do_normalize&&(ge=this._zero_mean_unit_var_norm(ge));const Ie=[1,ge.length];return{input_values:new Te.Tensor("float32",ge,Ie),attention_mask:new Te.Tensor("int64",new BigInt64Array(ge.length).fill(1n),Ie)}}}class Y extends X{constructor(G){super(G);const ge=this.config.sampling_rate,Ie=(0,L.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ge/2),ge,null,"kaldi",!0);for(let Se=0;SeIe*32768),(0,L.spectrogram)(G,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:ge,transpose:!0})}async _call(G,{padding:ge=!0,pad_to_multiple_of:Ie=2,do_normalize_per_mel_bins:Se=!0,return_attention_mask:Ne=!0}={}){O(G,"SeamlessM4TFeatureExtractor");let tt=await this._extract_fbank_features(G,this.config.max_length);if(Se){const[Fe,Oe]=tt.dims,ct=tt.data;for(let Ut=0;Ut0){const sr=new Float32Array(Oe*(Fe+Ut));sr.set(ct),sr.fill(this.config.padding_value,ct.length);const br=Fe+Ut;tt=new Te.Tensor(tt.type,sr,[br,Oe]),Ne&&(wt=new Te.Tensor("int64",new BigInt64Array(br),[1,br]),wt.data.fill(1n,0,Fe))}}const[mt,Ct]=tt.dims,ft=this.config.stride;if(mt%ft!==0)throw new Error(`The number of frames (${mt}) must be a multiple of the stride (${ft}).`);const jt=tt.view(1,Math.floor(mt/ft),Ct*ft),Ft={input_features:jt};if(Ne){const Fe=jt.dims[1],Oe=new BigInt64Array(Fe);if(wt){const ct=wt.data;for(let Ut=1,sr=0;Ut0)if(Ie==="rand_trunc"){const wt=Math.floor(Math.random()*(tt+1));G=G.subarray(wt,wt+ge),Ne=await this._extract_fbank_features(G,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Ie}" not implemented`);else{if(tt<0){let wt=new Float64Array(ge);if(wt.set(G),Se==="repeat")for(let mt=G.length;mt({id:mt,start:Ct*Ie,end:ft*Ie,confidence:Lt/(ft-Ct)})))}return Se}}class Nt extends X{constructor(G){super(G);const ge=this.config.sampling_rate,Ie=(0,L.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ge/2),ge,null,"kaldi",!0);for(let Se=0;Sege*32768),(0,L.spectrogram)(G,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(G){O(G,"WeSpeakerFeatureExtractor");const ge=(await this._extract_fbank_features(G)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Ie=ge.mean(1).data,Se=ge.data,[Ne,tt,wt]=ge.dims;for(let mt=0;mt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(G){typeof G=="string"&&(G=[G]);const ge=[];for(const Ie of G)if(this.task_prompts_without_inputs.has(Ie))ge.push(this.task_prompts_without_inputs.get(Ie));else{for(const[Se,Ne]of this.task_prompts_with_input)if(Ie.includes(Se)){ge.push(Ne.replaceAll("{input}",Ie).replaceAll(Se,""));break}ge.length!==G.length&&ge.push(Ie)}return ge}post_process_generation(G,ge,Ie){const Se=this.tasks_answer_post_processing_type.get(ge)??"pure_text";G=G.replaceAll("","").replaceAll("","");let Ne;switch(Se){case"pure_text":Ne=G;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const tt=Se==="ocr"?"quad_boxes":"bboxes",wt=G.matchAll(this.regexes[tt]),mt=[],Ct=[];for(const[ft,Lt,...jt]of wt)mt.push(Lt?Lt.trim():mt.at(-1)??""),Ct.push(jt.map((Ft,Fe)=>(Number(Ft)+.5)/this.size_per_bin*Ie[Fe%2]));Ne={labels:mt,[tt]:Ct};break;default:throw new Error(`Task "${ge}" (of type "${Se}") not yet implemented.`)}return{[ge]:Ne}}}class bn{static async from_pretrained(G,{progress_callback:ge=null,config:Ie=null,cache_dir:Se=null,local_files_only:Ne=!1,revision:tt="main"}={}){let wt=Ie??await(0,we.getModelJSON)(G,"preprocessor_config.json",!0,{progress_callback:ge,config:Ie,cache_dir:Se,local_files_only:Ne,revision:tt}),mt=wt.feature_extractor_type??wt.image_processor_type,Ct=this.FEATURE_EXTRACTOR_CLASS_MAPPING[mt];if(!Ct)if(wt.size!==void 0)console.warn(`Feature extractor type "${mt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Ct=K;else throw new Error(`Unknown Feature Extractor type: ${mt}`);let ft=this.PROCESSOR_CLASS_MAPPING[wt.processor_class]??bt,Lt=new Ct(wt);return new ft(Lt)}}ve(bn,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:K,WhisperFeatureExtractor:H,ViTFeatureExtractor:W,MobileViTFeatureExtractor:dt,MobileViTImageProcessor:Re,MobileNetV1FeatureExtractor:We,MobileNetV2FeatureExtractor:ot,MobileNetV3FeatureExtractor:se,MobileNetV4FeatureExtractor:Ze,OwlViTFeatureExtractor:ht,Owlv2ImageProcessor:Mt,CLIPFeatureExtractor:De,CLIPImageProcessor:ze,Florence2Processor:Jr,ChineseCLIPFeatureExtractor:it,SiglipImageProcessor:rt,ConvNextFeatureExtractor:lt,ConvNextImageProcessor:me,SegformerFeatureExtractor:k,SapiensFeatureExtractor:j,BitImageProcessor:be,DPTImageProcessor:ue,DPTFeatureExtractor:E,PvtImageProcessor:N,GLPNFeatureExtractor:Ce,BeitFeatureExtractor:Ae,DeiTFeatureExtractor:Z,DetrFeatureExtractor:Ve,RTDetrImageProcessor:Xe,MaskFormerFeatureExtractor:ut,YolosFeatureExtractor:_t,DonutFeatureExtractor:Ke,DonutImageProcessor:et,NougatImageProcessor:je,EfficientNetImageProcessor:xe,ViTImageProcessor:de,VitMatteImageProcessor:v,SamImageProcessor:St,Swin2SRImageProcessor:xt,Wav2Vec2FeatureExtractor:$,SeamlessM4TFeatureExtractor:Y,SpeechT5FeatureExtractor:yt,ASTFeatureExtractor:he,ClapFeatureExtractor:nt,PyAnnoteFeatureExtractor:Je,WeSpeakerFeatureExtractor:Nt}),ve(bn,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:Pt,Wav2Vec2ProcessorWithLM:dr,PyAnnoteProcessor:Cr,SamProcessor:zt,SpeechT5Processor:Yr,OwlViTProcessor:Rr,Florence2Processor:Jr})},"./src/tokenizers.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{AlbertTokenizer:()=>tt,AutoTokenizer:()=>Ds,BartTokenizer:()=>Nr,BertTokenizer:()=>Ne,BlenderbotSmallTokenizer:()=>Fs,BlenderbotTokenizer:()=>Is,BloomTokenizer:()=>$n,CLIPTokenizer:()=>gs,CamembertTokenizer:()=>Oe,CodeGenTokenizer:()=>_s,CodeLlamaTokenizer:()=>$s,CohereTokenizer:()=>is,ConvBertTokenizer:()=>jt,DebertaTokenizer:()=>Ct,DebertaV2Tokenizer:()=>ft,DistilBertTokenizer:()=>Fe,ElectraTokenizer:()=>Ut,EsmTokenizer:()=>Ps,FalconTokenizer:()=>ks,GPT2Tokenizer:()=>br,GPTNeoXTokenizer:()=>Ss,GemmaTokenizer:()=>ns,Grok1Tokenizer:()=>Hn,HerbertTokenizer:()=>Lt,LlamaTokenizer:()=>fs,M2M100Tokenizer:()=>ms,MBart50Tokenizer:()=>kr,MBartTokenizer:()=>mr,MPNetTokenizer:()=>Es,MarianTokenizer:()=>Yt,MobileBertTokenizer:()=>wt,NllbTokenizer:()=>Rn,NougatTokenizer:()=>Os,PreTrainedTokenizer:()=>Se,Qwen2Tokenizer:()=>As,RoFormerTokenizer:()=>Ft,RobertaTokenizer:()=>gr,SiglipTokenizer:()=>ws,SpeechT5Tokenizer:()=>ys,SqueezeBertTokenizer:()=>mt,T5Tokenizer:()=>sr,TokenizerModel:()=>Ce,VitsTokenizer:()=>zs,Wav2Vec2CTCTokenizer:()=>ss,WhisperTokenizer:()=>Ln,XLMRobertaTokenizer:()=>qn,XLMTokenizer:()=>ct,is_chinese_char:()=>X});var F=V("./src/utils/generic.js"),ce=V("./src/utils/core.js"),we=V("./src/utils/hub.js"),ye=V("./src/utils/maths.js"),Te=V("./src/utils/tensor.js"),L=V("./src/utils/data-structures.js"),P=V("./node_modules/@huggingface/jinja/dist/index.js"),D=V("./src/models/whisper/common_whisper.js");V("./src/utils/constants.js");async function B(ae,_){const I=await Promise.all([(0,we.getModelJSON)(ae,"tokenizer.json",!0,_),(0,we.getModelJSON)(ae,"tokenizer_config.json",!0,_)]);return _.legacy!==null&&(I[1].legacy=_.legacy),I}function q(ae,_){const I=[];let Q=0;for(const oe of ae.matchAll(_)){const _e=oe[0];Q0&&I.push(_e),Q=oe.index+_e.length}return Q=19968&&ae<=40959||ae>=13312&&ae<=19903||ae>=131072&&ae<=173791||ae>=173824&&ae<=177983||ae>=177984&&ae<=178207||ae>=178208&&ae<=183983||ae>=63744&&ae<=64255||ae>=194560&&ae<=195103}function K(ae,_,I){const Q=[];let oe=0;for(;oethis.tokens_to_ids.get(I)??this.unk_token_id)}convert_ids_to_tokens(_){return _.map(I=>this.vocab[I]??this.unk_token)}}class De extends Ce{constructor(_){super(_),this.tokens_to_ids=fe(_.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[I,Q]of this.tokens_to_ids)this.vocab[Q]=I}encode(_){const I=[];for(const Q of _){const oe=[...Q];if(oe.length>this.max_input_chars_per_word){I.push(this.unk_token);continue}let _e=!1,Ge=0;const gt=[];for(;Ge0&&(Ot=this.config.continuing_subword_prefix+Ot),this.tokens_to_ids.has(Ot)){Tt=Ot;break}--$t}if(Tt===null){_e=!0;break}gt.push(Tt),Ge=$t}_e?I.push(this.unk_token):I.push(...gt)}return I}}class ze extends Ce{constructor(_,I){super(_);const Q=_.vocab.length;this.vocab=new Array(Q),this.scores=new Array(Q);for(let oe=0;oe[oe,_e])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=I.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,ye.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new L.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(_){const I=_.chars,Q=1;let oe=0;for(;oe{const ae=[...Array.from({length:94},(oe,_e)=>_e+33),...Array.from({length:12},(oe,_e)=>_e+161),...Array.from({length:82},(oe,_e)=>_e+174)],_=ae.slice();let I=0;for(let oe=0;oe<256;++oe)ae.includes(oe)||(ae.push(oe),_.push(256+I),I+=1);const Q=_.map(oe=>String.fromCharCode(oe));return Object.fromEntries(ae.map((oe,_e)=>[oe,Q[_e]]))})(),rt=(0,ce.reverseDictionary)(it);class lt extends Ce{constructor(_){super(_),this.tokens_to_ids=fe(_.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[Q,oe]of this.tokens_to_ids)this.vocab[oe]=Q;const I=Array.isArray(_.merges[0]);this.merges=I?_.merges:_.merges.map(Q=>Q.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Q,oe)=>[JSON.stringify(Q),oe])),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 I=this.cache.get(_);if(I!==void 0)return I;const Q=Array.from(_);this.end_of_word_suffix&&(Q[Q.length-1]+=this.end_of_word_suffix);let oe=[];if(Q.length>1){const _e=new L.PriorityQueue(($t,Tt)=>$t.score`<0x${gt.toString(16).toUpperCase().padStart(2,"0")}>`);Ge.every(gt=>this.tokens_to_ids.has(gt))?I.push(...Ge):I.push(this.unk_token)}else I.push(this.unk_token)}return I}}class me extends Ce{constructor(_,I){super(_),this.tokens_to_ids=fe(I.target_lang?_.vocab[I.target_lang]:_.vocab),this.bos_token=I.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=I.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=I.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=I.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[Q,oe]of this.tokens_to_ids)this.vocab[oe]=Q}encode(_){return _}}class W extends F.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"BertNormalizer":return new Mt(_);case"Precompiled":return new Yr(_);case"Sequence":return new ht(_);case"Replace":return new de(_);case"NFC":return new xe(_);case"NFKC":return new We(_);case"NFKD":return new ot(_);case"Strip":return new se(_);case"StripAccents":return new Ze(_);case"Lowercase":return new dt(_);case"Prepend":return new Re(_);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 I=re(this.config.pattern);return I===null?_:_.replaceAll(I,this.config.content)}}class xe extends W{normalize(_){return _=_.normalize("NFC"),_}}class We extends W{normalize(_){return _=_.normalize("NFKC"),_}}class ot extends W{normalize(_){return _=_.normalize("NFKD"),_}}class se extends W{normalize(_){return this.config.strip_left&&this.config.strip_right?_=_.trim():(this.config.strip_left&&(_=_.trimStart()),this.config.strip_right&&(_=_.trimEnd())),_}}class Ze extends W{normalize(_){return _=J(_),_}}class dt extends W{normalize(_){return _=_.toLowerCase(),_}}class Re extends W{normalize(_){return _=this.config.prepend+_,_}}class ht extends W{constructor(_){super(_),this.normalizers=_.normalizers.map(I=>W.fromConfig(I))}normalize(_){return this.normalizers.reduce((I,Q)=>Q.normalize(I),_)}}class Mt extends W{_tokenize_chinese_chars(_){const I=[];for(let Q=0;Q<_.length;++Q){const oe=_[Q],_e=oe.charCodeAt(0);X(_e)?(I.push(" "),I.push(oe),I.push(" ")):I.push(oe)}return I.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 I=[];for(const Q of _){const oe=Q.charCodeAt(0);oe===0||oe===65533||this._is_control(Q)||(/^\s$/.test(Q)?I.push(" "):I.push(Q))}return I.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 Xe extends F.Callable{static fromConfig(_){if(_===null)return null;switch(_.type){case"BertPreTokenizer":return new Z(_);case"Sequence":return new Rr(_);case"Whitespace":return new Jr(_);case"WhitespaceSplit":return new bn(_);case"Metaspace":return new dr(_);case"ByteLevel":return new Ae(_);case"Split":return new Ke(_);case"Punctuation":return new et(_);case"Digits":return new je(_);case"Replace":return new at(_);default:throw new Error(`Unknown PreTokenizer type: ${_.type}`)}}pre_tokenize_text(_,I){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(_,I){return(Array.isArray(_)?_.map(Q=>this.pre_tokenize_text(Q,I)):this.pre_tokenize_text(_,I)).flat()}_call(_,I){return this.pre_tokenize(_,I)}}class Z extends Xe{constructor(_){super(),this.pattern=new RegExp(`[^\\s${k}]+|[${k}]`,"gu")}pre_tokenize_text(_,I){return _.trim().match(this.pattern)||[]}}class Ae extends Xe{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=it,this.text_encoder=new TextEncoder}pre_tokenize_text(_,I){return this.add_prefix_space&&!_.startsWith(" ")&&(_=" "+_),(this.use_regex?_.match(this.pattern)||[]:[_]).map(oe=>Array.from(this.text_encoder.encode(oe),_e=>this.byte_encoder[_e]).join(""))}}class Ke extends Xe{constructor(_){super(),this.config=_,this.pattern=re(this.config.pattern,this.config.invert)}pre_tokenize_text(_,I){return this.pattern===null?[]:this.config.invert?_.match(this.pattern)||[]:q(_,this.pattern)}}class et extends Xe{constructor(_){super(),this.config=_,this.pattern=new RegExp(`[^${k}]+|[${k}]+`,"gu")}pre_tokenize_text(_,I){return _.match(this.pattern)||[]}}class je extends Xe{constructor(_){super(),this.config=_;const I=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(I,"gu")}pre_tokenize_text(_,I){return _.match(this.pattern)||[]}}class Ve extends F.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"TemplateProcessing":return new St(_);case"ByteLevel":return new xt(_);case"RobertaProcessing":return new _t(_);case"BertProcessing":return new ut(_);case"Sequence":return new v(_);default:throw new Error(`Unknown PostProcessor type: ${_.type}`)}}post_process(_,...I){throw Error("post_process should be implemented in subclass.")}_call(_,...I){return this.post_process(_,...I)}}class ut extends Ve{constructor(_){super(_),this.cls=_.cls[0],this.sep=_.sep[0]}post_process(_,I=null,{add_special_tokens:Q=!0}={}){Q&&(_=(0,ce.mergeArrays)([this.cls],_,[this.sep]));let oe=new Array(_.length).fill(0);if(I!==null){const _e=Q&&this instanceof _t?[this.sep]:[],Ge=Q?[this.sep]:[];_=(0,ce.mergeArrays)(_,_e,I,Ge),oe=(0,ce.mergeArrays)(oe,new Array(I.length+_e.length+Ge.length).fill(1))}return{tokens:_,token_type_ids:oe}}}class _t extends ut{}class St extends Ve{constructor(_){super(_),this.single=_.single,this.pair=_.pair}post_process(_,I=null,{add_special_tokens:Q=!0}={}){const oe=I===null?this.single:this.pair;let _e=[],Ge=[];for(const gt of oe)"SpecialToken"in gt?Q&&(_e.push(gt.SpecialToken.id),Ge.push(gt.SpecialToken.type_id)):"Sequence"in gt&&(gt.Sequence.id==="A"?(_e=(0,ce.mergeArrays)(_e,_),Ge=(0,ce.mergeArrays)(Ge,new Array(_.length).fill(gt.Sequence.type_id))):gt.Sequence.id==="B"&&(_e=(0,ce.mergeArrays)(_e,I),Ge=(0,ce.mergeArrays)(Ge,new Array(I.length).fill(gt.Sequence.type_id))));return{tokens:_e,token_type_ids:Ge}}}class xt extends Ve{post_process(_,I=null){return I&&(_=(0,ce.mergeArrays)(_,I)),{tokens:_}}}class v extends Ve{constructor(_){super(_),this.processors=_.processors.map(I=>Ve.fromConfig(I))}post_process(_,I=null,Q={}){let oe;for(const _e of this.processors)if(_e instanceof xt)_=_e.post_process(_).tokens,I&&(I=_e.post_process(I).tokens);else{const Ge=_e.post_process(_,I,Q);_=Ge.tokens,oe=Ge.token_type_ids}return{tokens:_,token_type_ids:oe}}}class H extends F.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 Je(_);case"Metaspace":return new Cr(_);case"ByteLevel":return new Nt(_);case"Replace":return new $(_);case"ByteFallback":return new Y(_);case"Fuse":return new he(_);case"Strip":return new nt(_);case"Sequence":return new bt(_);case"CTC":return new yt(_);case"BPEDecoder":return new zt(_);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 $ extends H{decode_chain(_){const I=re(this.config.pattern);return I===null?_:_.map(Q=>Q.replaceAll(I,this.config.content))}}class Y extends H{constructor(_){super(_),this.text_decoder=new TextDecoder}decode_chain(_){const I=[];let Q=[];for(const oe of _){let _e=null;if(oe.length===6&&oe.startsWith("<0x")&&oe.endsWith(">")){const Ge=parseInt(oe.slice(3,5),16);isNaN(Ge)||(_e=Ge)}if(_e!==null)Q.push(_e);else{if(Q.length>0){const Ge=this.text_decoder.decode(Uint8Array.from(Q));I.push(Ge),Q=[]}I.push(oe)}}if(Q.length>0){const oe=this.text_decoder.decode(Uint8Array.from(Q));I.push(oe),Q=[]}return I}}class he extends H{decode_chain(_){return[_.join("")]}}class nt extends H{constructor(_){super(_),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(_){return _.map(I=>{let Q=0;for(let _e=0;_e(Q!==0&&(I.startsWith(this.config.prefix)?I=I.replace(this.config.prefix,""):I=" "+I),this.cleanup&&(I=O(I)),I))}}class Nt extends H{constructor(_){super(_),this.byte_decoder=rt,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(_){const I=_.join(""),Q=new Uint8Array([...I].map(_e=>this.byte_decoder[_e]));return this.text_decoder.decode(Q)}decode_chain(_){const I=[];let Q=[];for(const oe of _)this.added_tokens.find(_e=>_e.content===oe)!==void 0?(Q.length>0&&(I.push(this.convert_tokens_to_string(Q)),Q=[]),I.push(oe)):Q.push(oe);return Q.length>0&&I.push(this.convert_tokens_to_string(Q)),I}}class yt extends H{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 I=[_[0]];for(let _e=1;_e<_.length;++_e)_[_e]!==I.at(-1)&&I.push(_[_e]);let oe=I.filter(_e=>_e!==this.pad_token).join("");return this.cleanup&&(oe=O(oe).replaceAll(this.word_delimiter_token," ").trim()),oe}decode_chain(_){return[this.convert_tokens_to_string(_)]}}class bt extends H{constructor(_){super(_),this.decoders=_.decoders.map(I=>H.fromConfig(I))}decode_chain(_){return this.decoders.reduce((I,Q)=>Q.decode_chain(I),_)}}class zt extends H{constructor(_){super(_),this.suffix=this.config.suffix}decode_chain(_){return _.map((I,Q)=>I.replaceAll(this.suffix,Q===_.length-1?"":" "))}}class Pt extends H{decode_chain(_){let I="";for(let Q=1;Q<_.length;Q+=2)I+=_[Q];return[I]}}class dr extends Xe{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:I=void 0}={}){let Q=_.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Q.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&I===0)&&(Q=this.strRep+Q),[Q]}}class Cr extends H{constructor(_){super(_),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement}decode_chain(_){const I=[];for(let Q=0;Q<_.length;++Q){let oe=_[Q].replaceAll(this.replacement," ");this.addPrefixSpace&&Q==0&&oe.startsWith(" ")&&(oe=oe.substring(1)),I.push(oe)}return I}}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(Q=>Q.normalize("NFKC")).join("~"):_=_.normalize("NFKC"),_}}class Rr extends Xe{constructor(_){super(),this.tokenizers=_.pretokenizers.map(I=>Xe.fromConfig(I))}pre_tokenize_text(_,I){return this.tokenizers.reduce((Q,oe)=>oe.pre_tokenize(Q,I),[_])}}class Jr extends Xe{constructor(_){super()}pre_tokenize_text(_,I){return _.match(/\w+|[^\w\s]+/g)||[]}}class bn extends Xe{constructor(_){super()}pre_tokenize_text(_,I){return j(_)}}class at extends Xe{constructor(_){super(),this.config=_,this.pattern=re(this.config.pattern),this.content=this.config.content}pre_tokenize_text(_,I){return this.pattern===null?[_]:[_.replaceAll(this.pattern,this.config.content)]}}const G=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function ge(ae,_,I,Q){for(const oe of Object.keys(ae)){const _e=_-ae[oe].length,Ge=I(oe),gt=new Array(_e).fill(Ge);ae[oe]=Q==="right"?(0,ce.mergeArrays)(ae[oe],gt):(0,ce.mergeArrays)(gt,ae[oe])}}function Ie(ae,_){for(const I of Object.keys(ae))ae[I].length=_}class Se extends F.Callable{constructor(I,Q){super();ve(this,"return_token_type_ids",!1);ve(this,"padding_side","right");this._tokenizer_config=Q,this.normalizer=W.fromConfig(I.normalizer),this.pre_tokenizer=Xe.fromConfig(I.pre_tokenizer),this.model=Ce.fromConfig(I.model,Q),this.post_processor=Ve.fromConfig(I.post_processor),this.decoder=H.fromConfig(I.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const oe of I.added_tokens){const _e=new be(oe);this.added_tokens.push(_e),this.model.tokens_to_ids.set(_e.content,_e.id),this.model.vocab[_e.id]=_e.content,_e.special&&(this.special_tokens.push(_e.content),this.all_special_ids.push(_e.id))}if(this.additional_special_tokens=Q.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((oe,_e)=>_e.content.length-oe.content.length).map(oe=>`${oe.lstrip?"\\s*":""}(${(0,ce.escapeRegExp)(oe.content)})${oe.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=Q.model_max_length,this.remove_space=Q.remove_space,this.clean_up_tokenization_spaces=Q.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Q.do_lowercase_and_remove_accent??!1,Q.padding_side&&(this.padding_side=Q.padding_side),this.legacy=!1,this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){const oe=Object.create(null);for(const{name:_e,template:Ge}of this.chat_template){if(typeof _e!="string"||typeof Ge!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');oe[_e]=Ge}this.chat_template=oe}this._compiled_template_cache=new Map}getToken(...I){for(const Q of I){const oe=this._tokenizer_config[Q];if(oe)if(typeof oe=="object"){if(oe.__type==="AddedToken")return oe.content;throw Error(`Unknown token: ${oe}`)}else return oe}return null}static async from_pretrained(I,{progress_callback:Q=null,config:oe=null,cache_dir:_e=null,local_files_only:Ge=!1,revision:gt="main",legacy:$t=null}={}){const Tt=await B(I,{progress_callback:Q,config:oe,cache_dir:_e,local_files_only:Ge,revision:gt,legacy:$t});return new this(...Tt)}_call(I,{text_pair:Q=null,add_special_tokens:oe=!0,padding:_e=!1,truncation:Ge=null,max_length:gt=null,return_tensor:$t=!0,return_token_type_ids:Tt=null}={}){const Ot=Array.isArray(I);let er;if(Ot){if(I.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(I.length!==Q.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");er=I.map((ur,Wr)=>this._encode_plus(ur,{text_pair:Q[Wr],add_special_tokens:oe,return_token_type_ids:Tt}))}else er=I.map(ur=>this._encode_plus(ur,{add_special_tokens:oe,return_token_type_ids:Tt}))}else{if(I==null)throw Error("text may not be null or undefined");if(Array.isArray(Q))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(I,{text_pair:Q,add_special_tokens:oe,return_token_type_ids:Tt})]}if(gt===null?_e==="max_length"?gt=this.model_max_length:gt=(0,ye.max)(er.map(ur=>ur.input_ids.length))[0]:Ge||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."),gt=Math.min(gt,this.model_max_length??1/0),_e||Ge)for(let ur=0;urgt?Ge&&Ie(er[ur],gt):_e&&ge(er[ur],gt,Wr=>Wr==="input_ids"?this.pad_token_id:0,this.padding_side));const Sr={};if($t){if(!(_e&&Ge)&&er.some(Wr=>{var en;for(const or of Object.keys(Wr))if(Wr[or].length!==((en=er[0][or])==null?void 0:en.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 ur=[er.length,er[0].input_ids.length];for(const Wr of Object.keys(er[0]))Sr[Wr]=new Te.Tensor("int64",BigInt64Array.from(er.flatMap(en=>en[Wr]).map(BigInt)),ur)}else{for(const ur of Object.keys(er[0]))Sr[ur]=er.map(Wr=>Wr[ur]);if(!Ot)for(const ur of Object.keys(Sr))Sr[ur]=Sr[ur][0]}return Sr}_encode_text(I){return I===null?null:(this.added_tokens_regex?I.split(this.added_tokens_regex).filter(_e=>_e):[I]).map((_e,Ge)=>{if(this.added_tokens.find($t=>$t.content===_e)!==void 0)return _e;{if(this.remove_space===!0&&(_e=_e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(_e=pe(_e)),this.normalizer!==null&&(_e=this.normalizer(_e)),_e.length===0)return[];const $t=this.pre_tokenizer!==null?this.pre_tokenizer(_e,{section_index:Ge}):[_e];return this.model($t)}}).flat()}_encode_plus(I,{text_pair:Q=null,add_special_tokens:oe=!0,return_token_type_ids:_e=null}={}){const{tokens:Ge,token_type_ids:gt}=this._tokenize_helper(I,{pair:Q,add_special_tokens:oe}),$t=this.model.convert_tokens_to_ids(Ge),Tt={input_ids:$t,attention_mask:new Array($t.length).fill(1)};return(_e??this.return_token_type_ids)&>&&(Tt.token_type_ids=gt),Tt}_tokenize_helper(I,{pair:Q=null,add_special_tokens:oe=!1}={}){const _e=this._encode_text(I),Ge=this._encode_text(Q);return this.post_processor?this.post_processor(_e,Ge,{add_special_tokens:oe}):{tokens:(0,ce.mergeArrays)(_e??[],Ge??[])}}tokenize(I,{pair:Q=null,add_special_tokens:oe=!1}={}){return this._tokenize_helper(I,{pair:Q,add_special_tokens:oe}).tokens}encode(I,{text_pair:Q=null,add_special_tokens:oe=!0,return_token_type_ids:_e=null}={}){return this._encode_plus(I,{text_pair:Q,add_special_tokens:oe,return_token_type_ids:_e}).input_ids}batch_decode(I,Q={}){return I instanceof Te.Tensor&&(I=I.tolist()),I.map(oe=>this.decode(oe,Q))}decode(I,Q={}){if(I instanceof Te.Tensor&&(I=le(I)),!Array.isArray(I)||I.length===0||!(0,ce.isIntegralNumber)(I[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(I,Q)}decode_single(I,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:oe=null}){let _e=this.model.convert_ids_to_tokens(I);Q&&(_e=_e.filter(gt=>!this.special_tokens.includes(gt)));let Ge=this.decoder?this.decoder(_e):_e.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ge=Ge.replaceAll(this.decoder.end_of_word_suffix," "),Q&&(Ge=Ge.trim())),(oe??this.clean_up_tokenization_spaces)&&(Ge=O(Ge)),Ge}get_chat_template({chat_template:I=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const oe=this.chat_template;if(I!==null&&Object.hasOwn(oe,I))I=oe[I];else if(I===null)if(Q!==null&&"tool_use"in oe)I=oe.tool_use;else if("default"in oe)I=oe.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(oe).sort()}.`)}else if(I===null)if(this.chat_template)I=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 I}apply_chat_template(I,{tools:Q=null,documents:oe=null,chat_template:_e=null,add_generation_prompt:Ge=!1,tokenize:gt=!0,padding:$t=!1,truncation:Tt=!1,max_length:Ot=null,return_tensor:er=!0,return_dict:Sr=!1,tokenizer_kwargs:ur={},...Wr}={}){if(_e=this.get_chat_template({chat_template:_e,tools:Q}),typeof _e!="string")throw Error(`chat_template must be a string, but got ${typeof _e}`);let en=this._compiled_template_cache.get(_e);en===void 0&&(en=new P.Template(_e),this._compiled_template_cache.set(_e,en));const or=Object.create(null);for(const _n of G){const Mn=this.getToken(_n);Mn&&(or[_n]=Mn)}const Pr=en.render({messages:I,add_generation_prompt:Ge,tools:Q,documents:oe,...or,...Wr});if(gt){const _n=this._call(Pr,{add_special_tokens:!1,padding:$t,truncation:Tt,max_length:Ot,return_tensor:er,...ur});return Sr?_n:_n.input_ids}return Pr}}class Ne extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class tt extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class wt extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class mt extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Ct extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class ft extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Lt extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class jt extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Ft extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Fe extends Se{}class Oe extends Se{}class ct extends Se{constructor(I,Q){super(I,Q);ve(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ut extends Se{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class sr extends Se{}class br extends Se{}class Nr extends Se{}class mr extends Se{constructor(_,I){super(_,I),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(_,I,Q){return An(this,_,I,Q)}}class kr extends mr{}class gr extends Se{}class $n extends Se{}const Ur="▁";class fs extends Se{constructor(I,Q){super(I,Q);ve(this,"padding_side","left");this.legacy=Q.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new dr({replacement:Ur,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(I){if(I===null)return null;if(this.legacy||I.length===0)return super._encode_text(I);let Q=super._encode_text(Ur+I.replaceAll(Ur," "));return Q.length>1&&Q[0]===Ur&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class $s extends Se{}class qn extends Se{}class Es extends Se{}class ks extends Se{}class Ss extends Se{}class Ps extends Se{}class As extends Se{}class ns extends Se{}class Hn extends Se{}function An(ae,_,I,Q){if(!("language_codes"in ae)||!Array.isArray(ae.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ae)||!(ae.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ae)||typeof ae.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const oe=Q.src_lang,_e=Q.tgt_lang;if(!ae.language_codes.includes(_e))throw new Error(`Target language code "${_e}" is not valid. Must be one of: {${ae.language_codes.join(", ")}}`);if(oe!==void 0){if(!ae.language_codes.includes(oe))throw new Error(`Source language code "${oe}" is not valid. Must be one of: {${ae.language_codes.join(", ")}}`);for(const Ge of ae.post_processor.config.single)if("SpecialToken"in Ge&&ae.languageRegex.test(Ge.SpecialToken.id)){Ge.SpecialToken.id=ae.lang_to_token(oe);break}}return Q.forced_bos_token_id=ae.model.convert_tokens_to_ids([ae.lang_to_token(_e)])[0],ae._call(_,I)}class Rn extends Se{constructor(_,I){super(_,I),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(_,I,Q){return An(this,_,I,Q)}}class ms extends Se{constructor(_,I){super(_,I),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)).map(Q=>Q.slice(2,-2)),this.lang_to_token=Q=>`__${Q}__`}_build_translation_inputs(_,I,Q){return An(this,_,I,Q)}}class Ln extends Se{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(_,{return_timestamps:I=!1,return_language:Q=!1,time_precision:oe=null,force_full_sequences:_e=!0}={}){if(oe===null)throw Error("Must specify time_precision");let Ge=null;const gt=I==="word";function $t(){return{language:Ge,timestamp:[null,null],text:""}}const Tt=[];let Ot=$t(),er=0;const Sr=this.timestamp_begin;let ur=[],Wr=[],en=!1,or=null;const Pr=new Set(this.all_special_ids);for(const $e of _){const tn=$e.tokens,ln=gt?$e.token_timestamps:null;let In=null,Nn=Sr;if("stride"in $e){const[Xr,fr,Fr]=$e.stride;if(er-=fr,or=Xr-Fr,fr&&(Nn=fr/oe+Sr),Fr)for(let Et=tn.length-1;Et>=0;--Et){const _r=Number(tn[Et]);if(_r>=Sr){if(In!==null&&(_r-Sr)*oe=Sr){const Fr=(fr-Sr)*oe+er,Et=(0,ye.round)(Fr,2);if(In!==null&&fr>=In)en=!0;else if(en||ur.length>0&&fr0?(ur.push(Kt),gt&&Wr.push(pn)):ur.every(Xr=>Xr.length===0)&&(Ot=$t(),ur=[],Kt=[],Wr=[],pn=[])}if(ur.length>0){if(_e&&I)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[$e,tn]=this.findLongestCommonSequence(ur,Wr),ln=this.decode($e);Ot.text=ln,gt&&(Ot.words=this.collateWordTimestamps($e,tn,Ge)),Tt.push(Ot)}let _n=Object.create(null);const Mn=Tt.map($e=>$e.text).join("");if(I||Q){for(let $e=0;$e0;let gt=Ge?[]:null,$t=Ge?I[0]:null;for(let Tt=1;Tt<_.length;++Tt){const Ot=_[Tt];let er=0,Sr=[oe,oe,0,0];const ur=Ot.length;for(let $e=1;$eEt===pn[_r]&&$t[tn+_r]<=I[Tt][Nn+_r]).length:Xr=In.filter((Et,_r)=>Et===pn[_r]).length;const fr=$e/1e4,Fr=Xr/$e+fr;Xr>1&&Fr>er&&(er=Fr,Sr=[tn,ln,Nn,Kt])}const[Wr,en,or,Pr]=Sr,_n=Math.floor((en+Wr)/2),Mn=Math.floor((Pr+or)/2);_e.push(...Q.slice(0,_n)),Q=Ot.slice(Mn),oe=Q.length,Ge&&(gt.push(...$t.slice(0,_n)),$t=I[Tt].slice(Mn))}return _e.push(...Q),Ge?(gt.push(...$t),[_e,gt]):[_e,[]]}collateWordTimestamps(_,I,Q){const[oe,_e,Ge]=this.combineTokensIntoWords(_,Q),gt=[];for(let $t=0;$t=oe){const gt=((Ge-oe)*Q).toFixed(2);_e.push(`<|${gt}|>`),_e.push([])}else _e[_e.length-1].push(Ge);return _e=_e.map(Ge=>typeof Ge=="string"?Ge:super.decode(Ge,I)),_e.join("")}splitTokensOnUnicode(_){const I=this.decode(_,{decode_with_timestamps:!0}),Q="�",oe=[],_e=[],Ge=[];let gt=[],$t=[],Tt=0;for(let Ot=0;Ot<_.length;++Ot){const er=_[Ot];gt.push(er),$t.push(Ot);const Sr=this.decode(gt,{decode_with_timestamps:!0});(!Sr.includes(Q)||I[Tt+Sr.indexOf(Q)]===Q)&&(oe.push(Sr),_e.push(gt),Ge.push($t),gt=[],$t=[],Tt+=Sr.length)}return[oe,_e,Ge]}splitTokensOnSpaces(_){const[I,Q,oe]=this.splitTokensOnUnicode(_),_e=[],Ge=[],gt=[],$t=new RegExp(`^[${k}]$`,"gu");for(let Tt=0;Tt=this.model.tokens_to_ids.get("<|endoftext|>"),Wr=Ot.startsWith(" "),en=Ot.trim(),or=$t.test(en);if(ur||Wr||or||_e.length===0)_e.push(Ot),Ge.push(er),gt.push(Sr);else{const Pr=_e.length-1;_e[Pr]+=Ot,Ge[Pr].push(...er),gt[Pr].push(...Sr)}}return[_e,Ge,gt]}mergePunctuations(_,I,Q,oe,_e){const Ge=structuredClone(_),gt=structuredClone(I),$t=structuredClone(Q);let Tt=Ge.length-2,Ot=Ge.length-1;for(;Tt>=0;)Ge[Tt].startsWith(" ")&&oe.includes(Ge[Tt].trim())?(Ge[Ot]=Ge[Tt]+Ge[Ot],gt[Ot]=(0,ce.mergeArrays)(gt[Tt],gt[Ot]),$t[Ot]=(0,ce.mergeArrays)($t[Tt],$t[Ot]),Ge[Tt]="",gt[Tt]=[],$t[Tt]=[]):Ot=Tt,--Tt;for(Tt=0,Ot=1;Oter),gt.filter(er=>er.length>0),$t.filter(er=>er.length>0)]}}class _s extends Se{}class gs extends Se{}class ws extends Se{}class Yt extends Se{constructor(_,I){super(_,I),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Q=>this.languageRegex.test(Q)),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[I,...Q]=_.trim().split(this.languageRegex);if(Q.length===0)return super._encode_text(I);if(Q.length===2){const[oe,_e]=Q;return this.supported_language_codes.includes(oe)||console.warn(`Unsupported language code "${oe}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,ce.mergeArrays)([oe],super._encode_text(_e))}}}class ss extends Se{}class Is extends Se{}class Fs extends Se{}class ys extends Se{}class Os extends Se{}class zs extends Se{constructor(_,I){super(_,I),this.decoder=new Pt({})}}class is extends Se{}class Ds{static async from_pretrained(_,{progress_callback:I=null,config:Q=null,cache_dir:oe=null,local_files_only:_e=!1,revision:Ge="main",legacy:gt=null}={}){var Sr;const[$t,Tt]=await B(_,{progress_callback:I,config:Q,cache_dir:oe,local_files_only:_e,revision:Ge,legacy:gt}),Ot=((Sr=Tt.tokenizer_class)==null?void 0:Sr.replace(/Fast$/,""))??"PreTrainedTokenizer";let er=this.TOKENIZER_CLASS_MAPPING[Ot];return er||(console.warn(`Unknown tokenizer class "${Ot}", attempting to construct from base class.`),er=Se),new er($t,Tt)}}ve(Ds,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:sr,DistilBertTokenizer:Fe,CamembertTokenizer:Oe,DebertaTokenizer:Ct,DebertaV2Tokenizer:ft,BertTokenizer:Ne,HerbertTokenizer:Lt,ConvBertTokenizer:jt,RoFormerTokenizer:Ft,XLMTokenizer:ct,ElectraTokenizer:Ut,MobileBertTokenizer:wt,SqueezeBertTokenizer:mt,AlbertTokenizer:tt,GPT2Tokenizer:br,BartTokenizer:Nr,MBartTokenizer:mr,MBart50Tokenizer:kr,RobertaTokenizer:gr,WhisperTokenizer:Ln,CodeGenTokenizer:_s,CLIPTokenizer:gs,SiglipTokenizer:ws,MarianTokenizer:Yt,BloomTokenizer:$n,NllbTokenizer:Rn,M2M100Tokenizer:ms,LlamaTokenizer:fs,CodeLlamaTokenizer:$s,XLMRobertaTokenizer:qn,MPNetTokenizer:Es,FalconTokenizer:ks,GPTNeoXTokenizer:Ss,EsmTokenizer:Ps,Wav2Vec2CTCTokenizer:ss,BlenderbotTokenizer:Is,BlenderbotSmallTokenizer:Fs,SpeechT5Tokenizer:ys,NougatTokenizer:Os,VitsTokenizer:zs,Qwen2Tokenizer:As,GemmaTokenizer:ns,Grok1Tokenizer:Hn,CohereTokenizer:is,PreTrainedTokenizer:Se})},"./src/utils/audio.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{hamming:()=>D,hanning:()=>P,mel_filter_bank:()=>J,read_audio:()=>Te,spectrogram:()=>k,window_function:()=>N});var F=V("./src/utils/hub.js"),ce=V("./src/utils/maths.js"),we=V("./src/utils/core.js"),ye=V("./src/utils/tensor.js");async function Te(E,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 be=await(await(0,F.getFile)(E)).arrayBuffer(),Ce=new AudioContext({sampleRate:ue});typeof ue>"u"&&console.warn(`No sampling rate provided, using default of ${Ce.sampleRate}Hz.`);const De=await Ce.decodeAudioData(be);let ze;if(De.numberOfChannels===2){const it=Math.sqrt(2),rt=De.getChannelData(0),lt=De.getChannelData(1);ze=new Float32Array(rt.length);for(let me=0;me2595*Math.log10(1+E/700),kaldi:E=>1127*Math.log(1+E/700),slaney:(E,ue=1e3,be=15,Ce=27/Math.log(6.4))=>E>=ue?be+Math.log(E/ue)*Ce:3*E/200};function q(E,ue="htk"){const be=B[ue];if(!be)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof E=="number"?be(E):E.map(Ce=>be(Ce))}const re={htk:E=>700*(10**(E/2595)-1),kaldi:E=>700*(Math.exp(E/1127)-1),slaney:(E,ue=1e3,be=15,Ce=Math.log(6.4)/27)=>E>=be?ue*Math.exp(Ce*(E-be)):200*E/3};function fe(E,ue="htk"){const be=re[ue];if(!be)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof E=="number"?be(E):E.map(Ce=>be(Ce))}function le(E,ue){const be=Float64Array.from({length:ue.length-1},(it,rt)=>ue[rt+1]-ue[rt]),Ce=Array.from({length:E.length},()=>new Array(ue.length));for(let it=0;itnew Array(E.length));for(let it=0;itE+Ce*ze)}function J(E,ue,be,Ce,De,ze=null,it="htk",rt=!1){if(ze!==null&&ze!=="slaney")throw new Error('norm must be one of null or "slaney"');const lt=q(be,it),me=q(Ce,it),W=O(lt,me,ue+2);let de=fe(W,it),xe;if(rt){const ot=De/(E*2);xe=q(Float64Array.from({length:E},(se,Ze)=>Ze*ot),it),de=W}else xe=O(0,Math.floor(De/2),E);const We=le(xe,de);if(ze!==null&&ze==="slaney")for(let ot=0;otDe)throw Error(`frame_length (${be}) may not be larger than fft_length (${De})`);if(Xe!==be)throw new Error(`Length of the window (${Xe}) must equal frame_length (${be})`);if(Ce<=0)throw new Error("hop_length must be greater than zero");if(ze===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(it){if(rt!=="reflect")throw new Error(`pad_mode="${rt}" not implemented yet.`);const H=Math.floor((De-1)/2)+1;E=pe(E,H,H)}let Z=Math.floor(1+Math.floor((E.length-be)/Ce));dt!==null&&ZZ?ht&&(et=Re):et=Ke=Re);const je=new ce.FFT(De),Ve=new Float64Array(De),ut=new Float64Array(je.outputBufferSize),_t=new Float32Array(Ae*et);for(let H=0;H=1;--he)Ve[he]-=me*Ve[he-1];Ve[0]*=1-me}for(let he=0;heMath.pow(rt,.85));break;default:throw new Error(`Unknown window type ${ue}.`)}if(be&&(it=it.subarray(0,E)),Ce===null)return it;if(E>Ce)throw new Error(`Length of the window (${E}) may not be larger than frame_length (${Ce})`);return it}},"./src/utils/constants.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{GITHUB_ISSUE_URL:()=>F});const F="https://github.com/huggingface/transformers.js/issues/new/choose"},"./src/utils/core.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{calculateDimensions:()=>L,calculateReflectOffset:()=>q,dispatchCallback:()=>F,escapeRegExp:()=>we,isIntegralNumber:()=>Te,isTypedArray:()=>ye,len:()=>fe,mergeArrays:()=>D,pick:()=>re,pop:()=>P,product:()=>B,reverseDictionary:()=>ce});function F(le,O){le&&le(O)}function ce(le){return Object.fromEntries(Object.entries(le).map(([O,J])=>[J,O]))}function we(le){return le.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ye(le){var O,J,pe;return((pe=(J=(O=le==null?void 0:le.prototype)==null?void 0:O.__proto__)==null?void 0:J.constructor)==null?void 0:pe.name)==="TypedArray"}function Te(le){return Number.isInteger(le)||typeof le=="bigint"}function L(le){const O=[];let J=le;for(;Array.isArray(J);)O.push(J.length),J=J[0];return O}function P(le,O,J=void 0){const pe=le[O];if(pe!==void 0)return delete le[O],pe;if(J===void 0)throw Error(`Key ${O} does not exist in object.`);return J}function D(...le){return Array.prototype.concat.apply([],le)}function B(...le){return le.reduce((O,J)=>O.flatMap(pe=>J.map(X=>[pe,X])))}function q(le,O){return Math.abs((le+O)%(2*O)-O)}function re(le,O){return Object.assign({},...O.map(J=>{if(le[J]!==void 0)return{[J]:le[J]}}))}function fe(le){let O=0;for(const J of le)++O;return O}},"./src/utils/data-structures.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{CharTrie:()=>ce,PriorityQueue:()=>F,TokenLattice:()=>ye});class F{constructor(P=(B,q)=>B>q,D=1/0){this._heap=[],this._comparator=P,this._maxSize=D}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...P){return this.extend(P)}extend(P){for(const D of P)if(this.size0&&this._swap(0,D),this._heap.pop(),this._siftDown(),P}replace(P){const D=this.peek();return this._heap[0]=P,this._siftDown(),D}_parent(P){return(P+1>>>1)-1}_left(P){return(P<<1)+1}_right(P){return P+1<<1}_greater(P,D){return this._comparator(this._heap[P],this._heap[D])}_swap(P,D){const B=this._heap[P];this._heap[P]=this._heap[D],this._heap[D]=B}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(P){for(;P>0&&this._greater(P,this._parent(P));)this._swap(P,this._parent(P)),P=this._parent(P)}_siftDown(){let P=0;for(;this._left(P)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const q=new Te(this.bosTokenId,0,0,0,0),re=new Te(this.eosTokenId,1,this.len,0,0);this.nodes.push(q.clone()),this.nodes.push(re.clone()),this.beginNodes[this.len].push(re),this.endNodes[0].push(q)}insert(P,D,B,q){const re=this.nodes.length,fe=new Te(q,re,P,D,B);this.beginNodes[P].push(fe),this.endNodes[P+D].push(fe),this.nodes.push(fe)}viterbi(){const P=this.len;let D=0;for(;D<=P;){if(this.beginNodes[D].length==0)return[];for(let le of this.beginNodes[D]){le.prev=null;let O=0,J=null;for(let pe of this.endNodes[D]){const X=pe.backtraceScore+le.score;(J===null||X>O)&&(J=pe.clone(),O=X)}if(J!==null)le.prev=J,le.backtraceScore=O;else return[]}++D}const B=[],re=this.beginNodes[P][0].prev;if(re===null)return[];let fe=re.clone();for(;fe.prev!==null;)B.push(fe.clone()),fe=fe.clone().prev.clone();return B.reverse(),B}piece(P){return this.chars.slice(P.pos,P.pos+P.length).join("")}tokens(){return this.viterbi().map(D=>this.piece(D))}tokenIds(){return this.viterbi().map(D=>D.tokenId)}}class Te{constructor(P,D,B,q,re){this.tokenId=P,this.nodeId=D,this.pos=B,this.length=q,this.score=re,this.prev=null,this.backtraceScore=0}clone(){const P=new Te(this.tokenId,this.nodeId,this.pos,this.length,this.score);return P.prev=this.prev,P.backtraceScore=this.backtraceScore,P}}},"./src/utils/devices.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{DEVICE_TYPES:()=>F});const F=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{DATA_TYPES:()=>ye,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Te,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>L,isWebGpuFp16Supported:()=>we});var F=V("./src/env.js"),ce=V("./src/utils/devices.js");const we=function(){let P;return async function(){if(P===void 0)if(!F.apis.IS_WEBGPU_AVAILABLE)P=!1;else try{P=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{P=!1}return P}}(),ye=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Te=Object.freeze({[ce.DEVICE_TYPES.wasm]:ye.q8}),L=Object.freeze({[ye.fp32]:"",[ye.fp16]:"_fp16",[ye.int8]:"_int8",[ye.uint8]:"_uint8",[ye.q8]:"_quantized",[ye.q4]:"_q4",[ye.q4f16]:"_q4f16",[ye.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{Callable:()=>F});const F=class{constructor(){let ce=function(...we){return ce._call(...we)};return Object.setPrototypeOf(ce,new.target.prototype)}_call(...ce){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{getFile:()=>D,getModelFile:()=>le,getModelJSON:()=>O});var F=V("?7a2c"),ce=V("?a42a"),we=V("./src/env.js"),ye=V("./src/utils/core.js");const Te={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 L{constructor(K){if(this.filePath=K,this.headers=new Headers,this.exists=F.existsSync(K),this.exists){this.status=200,this.statusText="OK";let j=F.statSync(K);this.headers.set("content-length",j.size.toString()),this.updateContentType();let k=this;this.body=new ReadableStream({start(N){k.arrayBuffer().then(E=>{N.enqueue(new Uint8Array(E)),N.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const K=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Te[K]??"application/octet-stream")}clone(){let K=new L(this.filePath);return K.exists=this.exists,K.status=this.status,K.statusText=this.statusText,K.headers=new Headers(this.headers),K}async arrayBuffer(){return(await F.promises.readFile(this.filePath)).buffer}async blob(){const K=await F.promises.readFile(this.filePath);return new Blob([K],{type:this.headers.get("content-type")})}async text(){return await F.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function P(X,K=null,j=null){let k;try{k=new URL(X)}catch{return!1}return!(K&&!K.includes(k.protocol)||j&&!j.includes(k.hostname))}async function D(X){var K;if(we.env.useFS&&!P(X,["http:","https:","blob:"]))return new L(X);if(typeof process<"u"&&((K=process==null?void 0:process.release)==null?void 0:K.name)==="node"){const j=!!(Cn!=null&&Cn.TESTING_REMOTELY),k=we.env.version,N=new Headers;if(N.set("User-Agent",`transformers.js/${k}; is_ci/${j};`),P(X,["http:","https:"],["huggingface.co","hf.co"])){const ue=(Cn==null?void 0:Cn.HF_TOKEN)??(Cn==null?void 0:Cn.HF_ACCESS_TOKEN);ue&&N.set("Authorization",`Bearer ${ue}`)}return fetch(X,{headers:N})}else return fetch(X)}const B={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 q(X,K,j){if(!j)return null;const k=B[X]??`Error (${X}) occurred while trying to load file`;throw Error(`${k}: "${K}".`)}class re{constructor(K){this.path=K}async match(K){let j=ce.join(this.path,K),k=new L(j);if(k.exists)return k}async put(K,j){const k=Buffer.from(await j.arrayBuffer());let N=ce.join(this.path,K);try{await F.promises.mkdir(ce.dirname(N),{recursive:!0}),await F.promises.writeFile(N,k)}catch(E){console.warn("An error occurred while writing the file to cache:",E)}}}async function fe(X,...K){for(let j of K)try{let k=await X.match(j);if(k)return k}catch{continue}}async function le(X,K,j=!0,k={}){if(!we.env.allowLocalModels){if(k.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(!we.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,ye.dispatchCallback)(k.progress_callback,{status:"initiate",name:X,file:K});let N;if(!N&&we.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{N=await caches.open("transformers-cache")}catch(xe){console.warn("An error occurred while opening the browser cache:",xe)}}if(!N&&we.env.useFSCache&&(N=new re(k.cache_dir??we.env.cacheDir)),!N&&we.env.useCustomCache){if(!we.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!we.env.customCache.match||!we.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");N=we.env.customCache}const E=k.revision??"main";let ue=pe(X,K),be=pe(we.env.localModelPath,ue),Ce=pe(we.env.remoteHost,we.env.remotePathTemplate.replaceAll("{model}",X).replaceAll("{revision}",encodeURIComponent(E)),K),De=E==="main"?ue:pe(X,E,K),ze,it=N instanceof re?De:Ce,rt=!1,lt;N&&(lt=await fe(N,be,it));const me=lt!==void 0;if(lt===void 0){if(we.env.allowLocalModels)if(P(ue,["http:","https:"])){if(k.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ue}.`);if(!we.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ue}.`)}else try{lt=await D(be),ze=be}catch(We){console.warn(`Unable to load from local path "${be}": "${We}"`)}if(lt===void 0||lt.status===404){if(k.local_files_only||!we.env.allowRemoteModels){if(j)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${be}".`);return null}if(lt=await D(Ce),lt.status!==200)return q(lt.status,Ce,j);ze=it}rt=N&&typeof Response<"u"&< instanceof Response&<.status===200}(0,ye.dispatchCallback)(k.progress_callback,{status:"download",name:X,file:K});const W={status:"progress",name:X,file:K};let de;return k.progress_callback?me&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(de=new Uint8Array(await lt.arrayBuffer()),(0,ye.dispatchCallback)(k.progress_callback,{...W,progress:100,loaded:de.length,total:de.length})):de=await J(lt,xe=>{(0,ye.dispatchCallback)(k.progress_callback,{...W,...xe})}):de=new Uint8Array(await lt.arrayBuffer()),rt&&ze&&await N.match(ze)===void 0&&await N.put(ze,new Response(de,{headers:lt.headers})).catch(xe=>{console.warn(`Unable to add response to browser cache: ${xe}.`)}),(0,ye.dispatchCallback)(k.progress_callback,{status:"done",name:X,file:K}),de}async function O(X,K,j=!0,k={}){let N=await le(X,K,j,k);if(N===null)return{};let ue=new TextDecoder("utf-8").decode(N);return JSON.parse(ue)}async function J(X,K){const j=X.headers.get("Content-Length");j===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let k=parseInt(j??"0"),N=new Uint8Array(k),E=0;const ue=X.body.getReader();async function be(){const{done:Ce,value:De}=await ue.read();if(Ce)return;let ze=E+De.length;if(ze>k){k=ze;let rt=new Uint8Array(k);rt.set(N),N=rt}N.set(De,E),E=ze;const it=E/k*100;return K({progress:it,loaded:E,total:k}),be()}return await be(),N}function pe(...X){return X=X.map((K,j)=>(j&&(K=K.replace(new RegExp("^/"),"")),j!==X.length-1&&(K=K.replace(new RegExp("/$"),"")),K)),X.join("/")}},"./src/utils/image.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{RawImage:()=>fe});var F=V("./src/utils/hub.js"),ce=V("./src/env.js"),we=V("./src/utils/tensor.js"),ye=V("?2b25");const Te=typeof self<"u",L=Te&&self.constructor.name==="DedicatedWorkerGlobalScope";let P,D,B;if(Te)P=(le,O)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(le,O)},B=self.createImageBitmap,D=self.ImageData;else if(ye)B=async le=>{const J=(await le.metadata()).channels,{data:pe,info:X}=await le.rotate().raw().toBuffer({resolveWithObject:!0}),K=new fe(new Uint8ClampedArray(pe),X.width,X.height,X.channels);return J!==void 0&&J!==X.channels&&K.convert(J),K};else throw new Error("Unable to load image processing library.");const q={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},re=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class fe{constructor(O,J,pe,X){this.data=O,this.width=J,this.height=pe,this.channels=X}get size(){return[this.width,this.height]}static async read(O){if(O instanceof fe)return O;if(typeof O=="string"||O instanceof URL)return await this.fromURL(O);throw new Error(`Unsupported input type: ${typeof O}`)}static fromCanvas(O){if(!Te)throw new Error("fromCanvas() is only supported in browser environments.");const pe=O.getContext("2d").getImageData(0,0,O.width,O.height).data;return new fe(pe,O.width,O.height,4)}static async fromURL(O){const J=await(0,F.getFile)(O);if(J.status!==200)throw new Error(`Unable to read image from "${O}" (${J.status} ${J.statusText})`);const pe=await J.blob();return this.fromBlob(pe)}static async fromBlob(O){if(Te){const J=await B(O),pe=P(J.width,J.height).getContext("2d");return pe.drawImage(J,0,0),new this(pe.getImageData(0,0,J.width,J.height).data,J.width,J.height,4)}else{const J=ye(await O.arrayBuffer());return await B(J)}}static fromTensor(O,J="CHW"){if(O.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${O.dims.length} dimensions.`);if(J==="CHW")O=O.transpose(1,2,0);else if(J!=="HWC")throw new Error(`Unsupported channel format: ${J}`);if(!(O.data instanceof Uint8ClampedArray||O.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${O.type}`);switch(O.dims[2]){case 1:case 2:case 3:case 4:return new fe(O.data,O.dims[1],O.dims[0],O.dims[2]);default:throw new Error(`Unsupported number of channels: ${O.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const O=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let J=0,pe=0;J=0?N=pe:ue=-pe,X>=0?E=X:be=-X,k.drawImage(j,N,E,O,J,ue,be,O,J),new fe(k.getImageData(0,0,O,J).data,O,J,4).convert(K)}else{let K=this.toSharp();if(pe>=0&&X>=0)K=K.extract({left:Math.floor(pe),top:Math.floor(X),width:O,height:J});else if(pe<=0&&X<=0){const j=Math.floor(-X),k=Math.floor(-pe);K=K.extend({top:j,left:k,right:O-this.width-k,bottom:J-this.height-j})}else{let j=[0,0],k=0;X<0?(j[0]=Math.floor(-X),j[1]=J-this.height-j[0]):k=Math.floor(X);let N=[0,0],E=0;pe<0?(N[0]=Math.floor(-pe),N[1]=O-this.width-N[0]):E=Math.floor(pe),K=K.extend({top:j[0],bottom:j[1],left:N[0],right:N[1]}).extract({left:E,top:k,width:O,height:J})}return await B(K)}}async toBlob(O="image/png",J=1){if(!Te)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:O,quality:J})}toTensor(O="CHW"){let J=new we.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(O!=="HWC")if(O==="CHW")J=J.permute(2,0,1);else throw new Error(`Unsupported channel format: ${O}`);return J}toCanvas(){if(!Te)throw new Error("toCanvas() is only supported in browser environments.");const O=this.clone().rgba(),J=P(O.width,O.height),pe=new D(O.data,O.width,O.height);return J.getContext("2d").putImageData(pe,0,0),J}_update(O,J,pe,X=null){return this.data=O,this.width=J,this.height=pe,X!==null&&(this.channels=X),this}clone(){return new fe(this.data.slice(),this.width,this.height,this.channels)}convert(O){if(this.channels===O)return this;switch(O){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(O){if(Te){if(L)throw new Error("Unable to save an image from a Web Worker.");const J=O.split(".").pop().toLowerCase(),pe=re.get(J)??"image/png",X=await this.toBlob(pe),K=URL.createObjectURL(X),j=document.createElement("a");j.href=K,j.download=O,j.click(),j.remove()}else{if(ce.env.useFS)return await this.toSharp().toFile(O);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Te)throw new Error("toSharp() is only supported in server-side environments.");return ye(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{FFT:()=>le,bankers_round:()=>pe,cos_sim:()=>L,dot:()=>Te,dynamic_time_warping:()=>X,interpolate_data:()=>F,log_softmax:()=>ye,magnitude:()=>P,max:()=>B,medianFilter:()=>O,min:()=>D,permute_data:()=>ce,round:()=>J,softmax:()=>we});function F(K,[j,k,N],[E,ue],be="bilinear",Ce=!1){const De=ue/N,ze=E/k,it=new K.constructor(E*ue*j),rt=k*N,lt=E*ue;for(let me=0;me=0;--Ce)E[Ce]=De,N[Ce]=j[k[Ce]],De*=N[Ce];const ue=k.map((Ce,De)=>E[k.indexOf(De)]),be=new K.constructor(K.length);for(let Ce=0;Ce=0;--ze)De+=it%j[ze]*ue[ze],it=Math.floor(it/j[ze]);be[De]=K[Ce]}return[be,N]}function we(K){const j=B(K)[0],k=K.map(ue=>Math.exp(ue-j)),N=k.reduce((ue,be)=>ue+be,0);return k.map(ue=>ue/N)}function ye(K){const j=B(K)[0];let k=0;for(let ue=0;ueue-j-N)}function Te(K,j){let k=0;for(let N=0;Nj+k*k,0))}function D(K){if(K.length===0)throw Error("Array must not be empty");let j=K[0],k=0;for(let N=1;Nj&&(j=K[N],k=N);return[Number(j),k]}function q(K){return K>0&&(K&K-1)===0}class re{constructor(j){if(this.size=j|0,this.size<=1||!q(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=j<<1,this.table=new Float64Array(this.size*2);for(let N=0;NN;N<<=1)++k;this._width=k%2===0?k-1:k,this._bitrev=new Int32Array(1<>>E&3)<>>1);for(let E=0;E>>1]=j[E];return N}toComplexArray(j,k){const N=k||this.createComplexArray();for(let E=0;E>>1],N[E+1]=0;return N}transform(j,k){if(j===k)throw new Error("Input and output buffers must be different");this._transform4(j,k,1)}realTransform(j,k){if(j===k)throw new Error("Input and output buffers must be different");this._realTransform4(j,k,1)}inverseTransform(j,k){if(j===k)throw new Error("Input and output buffers must be different");this._transform4(j,k,-1);for(let N=0;N>=2;be>=2;be>>=2){Ce=E/be<<1;const lt=Ce>>>2;for(De=0;De>>1,be>>>1)}else for(De=0,ze=0;De>>1,be>>>1,N)}const rt=this.table;for(be>>=2;be>=2;be>>=2){Ce=E/be<<1;const me=Ce>>>1,W=me>>>1,de=W>>>1;for(De=0;De>>1;for(let me=2;me>1;++it){const rt=(it+1-j)**2/2,lt=Math.sqrt(De**2+ze**2)**rt,me=rt*Math.atan2(ze,De),W=2*it;ue[W]=lt*Math.cos(me),ue[W+1]=lt*Math.sin(me),be[W]=ue[W],be[W+1]=-ue[W+1]}this._slicedChirpBuffer=ue.subarray(k,N),this._f=new re(E>>1),this._f.transform(this._chirpBuffer,be)}_transform(j,k,N){const E=this._buffer1,ue=this._buffer2,be=this._outBuffer1,Ce=this._outBuffer2,De=this._chirpBuffer,ze=this._slicedChirpBuffer,it=this._a;if(N)for(let rt=0;rt>1,W=k[me];E[rt]=W*ze[rt],E[lt]=W*ze[lt]}else for(let rt=0;rt=K.length&&(De=2*(K.length-1)-De),N[be++]=K[De]}N.sort(),k[ue]=N[E]}return k}function J(K,j){const k=Math.pow(10,j);return Math.round(K*k)/k}function pe(K){const j=Math.round(K);return Math.abs(K)%1===.5?j%2===0?j:j-1:j}function X(K){const j=K.length,k=K[0].length,N=[j+1,k+1],E=Array.from({length:N[0]},()=>Array(N[1]).fill(1/0));E[0][0]=0;const ue=Array.from({length:N[0]},()=>Array(N[1]).fill(-1));for(let it=1;it0||Ce>0;)switch(De.push(be-1),ze.push(Ce-1),ue[be][Ce]){case 0:--be,--Ce;break;case 1:--be;break;case 2:--Ce;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${be}, ${Ce}]. Please file a bug report.`)}return De.reverse(),ze.reverse(),[De,ze]}},"./src/utils/tensor.js":(Dt,Ee,V)=>{V.r(Ee),V.d(Ee,{Tensor:()=>Te,cat:()=>K,full:()=>be,full_like:()=>Ce,interpolate:()=>D,interpolate_4d:()=>B,layer_norm:()=>O,matmul:()=>q,mean:()=>N,mean_pooling:()=>le,ones:()=>De,ones_like:()=>ze,permute:()=>P,quantize_embeddings:()=>lt,rfft:()=>re,stack:()=>j,std_mean:()=>k,topk:()=>fe,zeros:()=>it,zeros_like:()=>rt});var F=V("./src/utils/maths.js"),ce=V("./src/backends/onnx.js"),we=V("./src/ops/registry.js");const ye=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 Te{constructor(...W){ve(this,"ort_tensor");return(0,ce.isONNXTensor)(W[0])?this.ort_tensor=W[0]:this.ort_tensor=new ce.Tensor(W[0],W[1],W[2]),new Proxy(this,{get:(de,xe)=>{if(typeof xe=="string"){let We=Number(xe);if(Number.isInteger(We))return de._getitem(We)}return de[xe]},set:(de,xe,We)=>de[xe]=We})}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 xe=de.reduce((We,ot)=>We*ot);for(let We=0;We0){const We=xe.reduce((ot,se)=>ot*se);return this._subarray(W,We,xe)}else return new Te(this.type,[this.data[W]],xe)}indexOf(W){const de=this.data;for(let xe=0;xeXe)throw new Error(`Invalid slice: ${ht}`);const Z=[Math.max(Mt,0),Math.min(Xe,this.dims[Re])];xe.push(Z),de.push(Z[1]-Z[0])}else throw new Error(`Invalid slice: ${ht}`)}const We=xe.map(([Re,ht])=>ht-Re),ot=We.reduce((Re,ht)=>Re*ht),se=this.data,Ze=new se.constructor(ot),dt=this.stride();for(let Re=0;Re=0;--Mt){const Z=We[Mt];ht+=(Xe%Z+xe[Mt][0])*dt[Mt],Xe=Math.floor(Xe/Z)}Ze[Re]=se[ht]}return new Te(this.type,Ze,de)}permute(...W){return P(this,W)}transpose(...W){return this.permute(...W)}sum(W=null,de=!1){return this.norm(1,W,de)}norm(W="fro",de=null,xe=!1){if(W==="fro")W=2;else if(typeof W=="string")throw Error(`Unsupported norm: ${W}`);const We=this.data;if(de===null){let Ze=We.reduce((dt,Re)=>dt+Re**W,0)**(1/W);return new Te(this.type,[Ze],[])}de=X(de,this.dims.length);const ot=this.dims.slice();ot[de]=1;const se=new We.constructor(We.length/this.dims[de]);for(let Ze=0;Ze=0;--Re){const Xe=this.dims[Re];if(Re!==de){const Z=ht%Xe;dt+=Z*Mt,Mt*=ot[Re]}ht=Math.floor(ht/Xe)}se[dt]+=We[Ze]**W}if(W!==1)for(let Ze=0;Ze=0;--dt){const Mt=this.dims[dt];if(dt!==de){const Xe=Re%Mt;Ze+=Xe*ht,ht*=this.dims[dt]}Re=Math.floor(Re/Mt)}We[se]/=ot[Ze]}return this}normalize(W=2,de=1){return this.clone().normalize_(W,de)}stride(){return E(this.dims)}squeeze(W=null){return new Te(this.type,this.data,J(this.dims,W))}squeeze_(W=null){return this.dims=J(this.dims,W),this}unsqueeze(W=null){return new Te(this.type,this.data,pe(this.dims,W))}unsqueeze_(W=null){return this.dims=pe(this.dims,W),this}flatten_(W=0,de=-1){de=(de+this.dims.length)%this.dims.length;let xe=this.dims.slice(0,W),We=this.dims.slice(W,de+1),ot=this.dims.slice(de+1);return this.dims=[...xe,We.reduce((se,Ze)=>se*Ze,1),...ot],this}flatten(W=0,de=-1){return this.clone().flatten_(W,de)}view(...W){let de=-1;for(let We=0;WeZe!==de?ot*se:ot,1);W[de]=xe.length/We}return new Te(this.type,xe,W)}neg_(){const W=this.data;for(let de=0;deot*se);if(de!==xe)throw Error(`cannot reshape array of size ${de} into shape (${W})`);let We=me;for(let ot=W.length-1;ot>=0;ot--)We=We.reduce((se,Ze)=>{let dt=se[se.length-1];return dt.lengthde!==1):typeof W=="number"?me[W]===1&&me.splice(W,1):Array.isArray(W)&&(me=me.filter((de,xe)=>de!==1||!W.includes(xe))),me}function pe(me,W){return W=X(W,me.length+1),me=me.slice(),me.splice(W,0,1),me}function X(me,W,de=null,xe=!0){if(xe&&(me<-W||me>=W))throw new Error(`IndexError: index ${me} is out of bounds for dimension${de===null?"":" "+de} with size ${W}`);return me<0&&(me=(me%W+W)%W),me}function K(me,W=0){W=X(W,me[0].dims.length);const de=me[0].dims.slice();de[W]=me.reduce((se,Ze)=>se+Ze.dims[W],0);const xe=de.reduce((se,Ze)=>se*Ze,1),We=new me[0].data.constructor(xe),ot=me[0].type;if(W===0){let se=0;for(const Ze of me){const dt=Ze.data;We.set(dt,se),se+=dt.length}}else{let se=0;for(let Ze=0;Ze=0;--Xe){const Ke=Re[Xe];let et=Z%Ke;Xe===W&&(et+=se),Mt+=et*Ae,Ae*=de[Xe],Z=Math.floor(Z/Ke)}We[Mt]=dt[ht]}se+=Re[W]}}return new Te(ot,We,de)}function j(me,W=0){return K(me.map(de=>de.unsqueeze(W)),W)}function k(me,W=null,de=1,xe=!1){const We=me.data,ot=me.dims;if(W===null){const Xe=We.reduce((et,je)=>et+je,0)/We.length,Z=Math.sqrt(We.reduce((et,je)=>et+(je-Xe)**2,0)/(We.length-de)),Ae=new Te(me.type,[Xe],[]);return[new Te(me.type,[Z],[]),Ae]}W=X(W,ot.length);const se=N(me,W,xe),Ze=se.data,dt=ot.slice();dt[W]=1;const Re=new We.constructor(We.length/ot[W]);for(let Mt=0;Mt=0;--Z){const et=ot[Z];if(Z!==W){const je=Ae%et;Xe+=je*Ke,Ke*=dt[Z]}Ae=Math.floor(Ae/et)}Re[Xe]+=(We[Mt]-Ze[Xe])**2}for(let Mt=0;Mtdt+Re,0);return new Te(me.type,[Ze/xe.length],[])}const We=me.dims;W=X(W,We.length);const ot=We.slice();ot[W]=1;const se=new xe.constructor(xe.length/We[W]);for(let Ze=0;Ze=0;--Re){const Xe=We[Re];if(Re!==W){const Z=ht%Xe;dt+=Z*Mt,Mt*=ot[Re]}ht=Math.floor(ht/Xe)}se[dt]+=xe[Ze]}if(We[W]!==1)for(let Ze=0;Ze=0;--de)W[de]=xe,xe*=me[de];return W}function ue(me,W,de,xe){const We=me.reduce((ot,se)=>ot*se,1);return new Te(de,new xe(We).fill(W),me)}function be(me,W){let de,xe;if(typeof W=="number")de="float32",xe=Float32Array;else if(typeof W=="bigint")de="int64",xe=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof W}`);return ue(me,W,de,xe)}function Ce(me,W){return be(me.dims,W)}function De(me){return ue(me,1n,"int64",BigInt64Array)}function ze(me){return De(me.dims)}function it(me){return ue(me,0n,"int64",BigInt64Array)}function rt(me){return it(me.dims)}function lt(me,W){if(me.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(me.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(W))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=W==="binary",xe=de?"int8":"uint8",We=de?Int8Array:Uint8Array,ot=me.data,se=new We(ot.length/8);for(let Ze=0;Ze0?1:0,Re=Math.floor(Ze/8),ht=Ze%8;se[Re]|=dt<<7-ht,de&&ht===0&&(se[Re]-=128)}return new Te(xe,se,[me.dims[0],me.dims[1]/8])}}},Qs={};function qr(Dt){var Ee=Qs[Dt];if(Ee!==void 0)return Ee.exports;var V=Qs[Dt]={exports:{}};return rs[Dt](V,V.exports,qr),V.exports}qr.m=rs,(()=>{var Dt=Object.getPrototypeOf?V=>Object.getPrototypeOf(V):V=>V.__proto__,Ee;qr.t=function(V,F){if(F&1&&(V=this(V)),F&8||typeof V=="object"&&V&&(F&4&&V.__esModule||F&16&&typeof V.then=="function"))return V;var ce=Object.create(null);qr.r(ce);var we={};Ee=Ee||[null,Dt({}),Dt([]),Dt(Dt)];for(var ye=F&2&&V;typeof ye=="object"&&!~Ee.indexOf(ye);ye=Dt(ye))Object.getOwnPropertyNames(ye).forEach(Te=>we[Te]=()=>V[Te]);return we.default=()=>V,qr.d(ce,we),ce}})(),qr.d=(Dt,Ee)=>{for(var V in Ee)qr.o(Ee,V)&&!qr.o(Dt,V)&&Object.defineProperty(Dt,V,{enumerable:!0,get:Ee[V]})},qr.o=(Dt,Ee)=>Object.prototype.hasOwnProperty.call(Dt,Ee),qr.r=Dt=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Dt,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Dt,"__esModule",{value:!0})},(()=>{var Dt;if(typeof self.location.href=="string"&&(Dt=self.location.href),!Dt)throw new Error("Automatic publicPath is not supported in this browser");Dt=Dt.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),qr.p=Dt})(),qr.b=new URL("./",self.location.href);var p={};/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/qr.r(p),qr.d(p,{ASTFeatureExtractor:()=>Jt.ASTFeatureExtractor,ASTForAudioClassification:()=>y.ASTForAudioClassification,ASTModel:()=>y.ASTModel,ASTPreTrainedModel:()=>y.ASTPreTrainedModel,AlbertForMaskedLM:()=>y.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>y.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>y.AlbertForSequenceClassification,AlbertModel:()=>y.AlbertModel,AlbertPreTrainedModel:()=>y.AlbertPreTrainedModel,AlbertTokenizer:()=>lr.AlbertTokenizer,AudioClassificationPipeline:()=>Hr.AudioClassificationPipeline,AutoConfig:()=>wc.AutoConfig,AutoModel:()=>y.AutoModel,AutoModelForAudioClassification:()=>y.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>y.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>y.AutoModelForCTC,AutoModelForCausalLM:()=>y.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>y.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>y.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>y.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>y.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>y.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>y.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>y.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>y.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>y.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>y.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>y.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>y.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>y.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>y.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>y.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>y.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>y.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>y.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>y.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>y.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>y.AutoModelForVision2Seq,AutoModelForXVector:()=>y.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>y.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Jt.AutoProcessor,AutoTokenizer:()=>lr.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>Hr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>y.BartForConditionalGeneration,BartForSequenceClassification:()=>y.BartForSequenceClassification,BartModel:()=>y.BartModel,BartPretrainedModel:()=>y.BartPretrainedModel,BartTokenizer:()=>lr.BartTokenizer,BaseModelOutput:()=>y.BaseModelOutput,BaseStreamer:()=>yc.BaseStreamer,BeitFeatureExtractor:()=>Jt.BeitFeatureExtractor,BeitForImageClassification:()=>y.BeitForImageClassification,BeitModel:()=>y.BeitModel,BeitPreTrainedModel:()=>y.BeitPreTrainedModel,BertForMaskedLM:()=>y.BertForMaskedLM,BertForQuestionAnswering:()=>y.BertForQuestionAnswering,BertForSequenceClassification:()=>y.BertForSequenceClassification,BertForTokenClassification:()=>y.BertForTokenClassification,BertModel:()=>y.BertModel,BertPreTrainedModel:()=>y.BertPreTrainedModel,BertTokenizer:()=>lr.BertTokenizer,BitImageProcessor:()=>Jt.BitImageProcessor,BlenderbotForConditionalGeneration:()=>y.BlenderbotForConditionalGeneration,BlenderbotModel:()=>y.BlenderbotModel,BlenderbotPreTrainedModel:()=>y.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>y.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>y.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>y.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>lr.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>lr.BlenderbotTokenizer,BloomForCausalLM:()=>y.BloomForCausalLM,BloomModel:()=>y.BloomModel,BloomPreTrainedModel:()=>y.BloomPreTrainedModel,BloomTokenizer:()=>lr.BloomTokenizer,CLIPFeatureExtractor:()=>Jt.CLIPFeatureExtractor,CLIPImageProcessor:()=>Jt.CLIPImageProcessor,CLIPModel:()=>y.CLIPModel,CLIPPreTrainedModel:()=>y.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>y.CLIPSegForImageSegmentation,CLIPSegModel:()=>y.CLIPSegModel,CLIPSegPreTrainedModel:()=>y.CLIPSegPreTrainedModel,CLIPTextModel:()=>y.CLIPTextModel,CLIPTextModelWithProjection:()=>y.CLIPTextModelWithProjection,CLIPTokenizer:()=>lr.CLIPTokenizer,CLIPVisionModel:()=>y.CLIPVisionModel,CLIPVisionModelWithProjection:()=>y.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>y.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>y.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>y.CamembertForSequenceClassification,CamembertForTokenClassification:()=>y.CamembertForTokenClassification,CamembertModel:()=>y.CamembertModel,CamembertPreTrainedModel:()=>y.CamembertPreTrainedModel,CamembertTokenizer:()=>lr.CamembertTokenizer,CausalLMOutput:()=>y.CausalLMOutput,CausalLMOutputWithPast:()=>y.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Jt.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>y.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>y.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>y.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Jt.ClapFeatureExtractor,ClapModel:()=>y.ClapModel,ClapPreTrainedModel:()=>y.ClapPreTrainedModel,ClapTextModelWithProjection:()=>y.ClapTextModelWithProjection,CodeGenForCausalLM:()=>y.CodeGenForCausalLM,CodeGenModel:()=>y.CodeGenModel,CodeGenPreTrainedModel:()=>y.CodeGenPreTrainedModel,CodeGenTokenizer:()=>lr.CodeGenTokenizer,CodeLlamaTokenizer:()=>lr.CodeLlamaTokenizer,CohereForCausalLM:()=>y.CohereForCausalLM,CohereModel:()=>y.CohereModel,CoherePreTrainedModel:()=>y.CoherePreTrainedModel,CohereTokenizer:()=>lr.CohereTokenizer,ConvBertForMaskedLM:()=>y.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>y.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>y.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>y.ConvBertForTokenClassification,ConvBertModel:()=>y.ConvBertModel,ConvBertPreTrainedModel:()=>y.ConvBertPreTrainedModel,ConvBertTokenizer:()=>lr.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Jt.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>y.ConvNextForImageClassification,ConvNextImageProcessor:()=>Jt.ConvNextImageProcessor,ConvNextModel:()=>y.ConvNextModel,ConvNextPreTrainedModel:()=>y.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>y.ConvNextV2ForImageClassification,ConvNextV2Model:()=>y.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>y.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Jt.DPTFeatureExtractor,DPTForDepthEstimation:()=>y.DPTForDepthEstimation,DPTImageProcessor:()=>Jt.DPTImageProcessor,DPTModel:()=>y.DPTModel,DPTPreTrainedModel:()=>y.DPTPreTrainedModel,DebertaForMaskedLM:()=>y.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>y.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>y.DebertaForSequenceClassification,DebertaForTokenClassification:()=>y.DebertaForTokenClassification,DebertaModel:()=>y.DebertaModel,DebertaPreTrainedModel:()=>y.DebertaPreTrainedModel,DebertaTokenizer:()=>lr.DebertaTokenizer,DebertaV2ForMaskedLM:()=>y.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>y.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>y.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>y.DebertaV2ForTokenClassification,DebertaV2Model:()=>y.DebertaV2Model,DebertaV2PreTrainedModel:()=>y.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>lr.DebertaV2Tokenizer,DecisionTransformerModel:()=>y.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>y.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>Jt.DeiTFeatureExtractor,DeiTForImageClassification:()=>y.DeiTForImageClassification,DeiTModel:()=>y.DeiTModel,DeiTPreTrainedModel:()=>y.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>y.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>y.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>Hr.DepthEstimationPipeline,DepthProForDepthEstimation:()=>y.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>y.DepthProPreTrainedModel,DetrFeatureExtractor:()=>Jt.DetrFeatureExtractor,DetrForObjectDetection:()=>y.DetrForObjectDetection,DetrForSegmentation:()=>y.DetrForSegmentation,DetrModel:()=>y.DetrModel,DetrObjectDetectionOutput:()=>y.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>y.DetrPreTrainedModel,DetrSegmentationOutput:()=>y.DetrSegmentationOutput,Dinov2ForImageClassification:()=>y.Dinov2ForImageClassification,Dinov2Model:()=>y.Dinov2Model,Dinov2PreTrainedModel:()=>y.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>y.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>y.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>y.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>y.DistilBertForTokenClassification,DistilBertModel:()=>y.DistilBertModel,DistilBertPreTrainedModel:()=>y.DistilBertPreTrainedModel,DistilBertTokenizer:()=>lr.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>Hr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Jt.DonutFeatureExtractor,DonutImageProcessor:()=>Jt.DonutImageProcessor,DonutSwinModel:()=>y.DonutSwinModel,DonutSwinPreTrainedModel:()=>y.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>y.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Jt.EfficientNetImageProcessor,EfficientNetModel:()=>y.EfficientNetModel,EfficientNetPreTrainedModel:()=>y.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>y.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>y.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>y.ElectraForSequenceClassification,ElectraForTokenClassification:()=>y.ElectraForTokenClassification,ElectraModel:()=>y.ElectraModel,ElectraPreTrainedModel:()=>y.ElectraPreTrainedModel,ElectraTokenizer:()=>lr.ElectraTokenizer,EosTokenCriteria:()=>ao.EosTokenCriteria,EsmForMaskedLM:()=>y.EsmForMaskedLM,EsmForSequenceClassification:()=>y.EsmForSequenceClassification,EsmForTokenClassification:()=>y.EsmForTokenClassification,EsmModel:()=>y.EsmModel,EsmPreTrainedModel:()=>y.EsmPreTrainedModel,EsmTokenizer:()=>lr.EsmTokenizer,FFT:()=>Pn.FFT,FalconForCausalLM:()=>y.FalconForCausalLM,FalconModel:()=>y.FalconModel,FalconPreTrainedModel:()=>y.FalconPreTrainedModel,FalconTokenizer:()=>lr.FalconTokenizer,FastViTForImageClassification:()=>y.FastViTForImageClassification,FastViTModel:()=>y.FastViTModel,FastViTPreTrainedModel:()=>y.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>Hr.FeatureExtractionPipeline,FeatureExtractor:()=>Jt.FeatureExtractor,FillMaskPipeline:()=>Hr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>y.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>y.Florence2PreTrainedModel,Florence2Processor:()=>Jt.Florence2Processor,GLPNFeatureExtractor:()=>Jt.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>y.GLPNForDepthEstimation,GLPNModel:()=>y.GLPNModel,GLPNPreTrainedModel:()=>y.GLPNPreTrainedModel,GPT2LMHeadModel:()=>y.GPT2LMHeadModel,GPT2Model:()=>y.GPT2Model,GPT2PreTrainedModel:()=>y.GPT2PreTrainedModel,GPT2Tokenizer:()=>lr.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>y.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>y.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>y.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>y.GPTJForCausalLM,GPTJModel:()=>y.GPTJModel,GPTJPreTrainedModel:()=>y.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>y.GPTNeoForCausalLM,GPTNeoModel:()=>y.GPTNeoModel,GPTNeoPreTrainedModel:()=>y.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>y.GPTNeoXForCausalLM,GPTNeoXModel:()=>y.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>y.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>lr.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>y.Gemma2ForCausalLM,Gemma2Model:()=>y.Gemma2Model,Gemma2PreTrainedModel:()=>y.Gemma2PreTrainedModel,GemmaForCausalLM:()=>y.GemmaForCausalLM,GemmaModel:()=>y.GemmaModel,GemmaPreTrainedModel:()=>y.GemmaPreTrainedModel,GemmaTokenizer:()=>lr.GemmaTokenizer,GraniteForCausalLM:()=>y.GraniteForCausalLM,GraniteModel:()=>y.GraniteModel,GranitePreTrainedModel:()=>y.GranitePreTrainedModel,Grok1Tokenizer:()=>lr.Grok1Tokenizer,GroupViTModel:()=>y.GroupViTModel,GroupViTPreTrainedModel:()=>y.GroupViTPreTrainedModel,HerbertTokenizer:()=>lr.HerbertTokenizer,HieraForImageClassification:()=>y.HieraForImageClassification,HieraModel:()=>y.HieraModel,HieraPreTrainedModel:()=>y.HieraPreTrainedModel,HubertForCTC:()=>y.HubertForCTC,HubertForSequenceClassification:()=>y.HubertForSequenceClassification,HubertModel:()=>y.HubertModel,HubertPreTrainedModel:()=>y.HubertPreTrainedModel,ImageClassificationPipeline:()=>Hr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>Hr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Jt.ImageFeatureExtractor,ImageMattingOutput:()=>y.ImageMattingOutput,ImageSegmentationPipeline:()=>Hr.ImageSegmentationPipeline,ImageToImagePipeline:()=>Hr.ImageToImagePipeline,ImageToTextPipeline:()=>Hr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>ao.InterruptableStoppingCriteria,JAISLMHeadModel:()=>y.JAISLMHeadModel,JAISModel:()=>y.JAISModel,JAISPreTrainedModel:()=>y.JAISPreTrainedModel,LlamaForCausalLM:()=>y.LlamaForCausalLM,LlamaModel:()=>y.LlamaModel,LlamaPreTrainedModel:()=>y.LlamaPreTrainedModel,LlamaTokenizer:()=>lr.LlamaTokenizer,LlavaForConditionalGeneration:()=>y.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>y.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>y.LongT5ForConditionalGeneration,LongT5Model:()=>y.LongT5Model,LongT5PreTrainedModel:()=>y.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>y.M2M100ForConditionalGeneration,M2M100Model:()=>y.M2M100Model,M2M100PreTrainedModel:()=>y.M2M100PreTrainedModel,M2M100Tokenizer:()=>lr.M2M100Tokenizer,MBart50Tokenizer:()=>lr.MBart50Tokenizer,MBartForCausalLM:()=>y.MBartForCausalLM,MBartForConditionalGeneration:()=>y.MBartForConditionalGeneration,MBartForSequenceClassification:()=>y.MBartForSequenceClassification,MBartModel:()=>y.MBartModel,MBartPreTrainedModel:()=>y.MBartPreTrainedModel,MBartTokenizer:()=>lr.MBartTokenizer,MPNetForMaskedLM:()=>y.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>y.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>y.MPNetForSequenceClassification,MPNetForTokenClassification:()=>y.MPNetForTokenClassification,MPNetModel:()=>y.MPNetModel,MPNetPreTrainedModel:()=>y.MPNetPreTrainedModel,MPNetTokenizer:()=>lr.MPNetTokenizer,MT5ForConditionalGeneration:()=>y.MT5ForConditionalGeneration,MT5Model:()=>y.MT5Model,MT5PreTrainedModel:()=>y.MT5PreTrainedModel,MarianMTModel:()=>y.MarianMTModel,MarianModel:()=>y.MarianModel,MarianPreTrainedModel:()=>y.MarianPreTrainedModel,MarianTokenizer:()=>lr.MarianTokenizer,MaskFormerFeatureExtractor:()=>Jt.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>y.MaskFormerForInstanceSegmentation,MaskFormerModel:()=>y.MaskFormerModel,MaskFormerPreTrainedModel:()=>y.MaskFormerPreTrainedModel,MaskedLMOutput:()=>y.MaskedLMOutput,MaxLengthCriteria:()=>ao.MaxLengthCriteria,MistralForCausalLM:()=>y.MistralForCausalLM,MistralModel:()=>y.MistralModel,MistralPreTrainedModel:()=>y.MistralPreTrainedModel,MobileBertForMaskedLM:()=>y.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>y.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>y.MobileBertForSequenceClassification,MobileBertModel:()=>y.MobileBertModel,MobileBertPreTrainedModel:()=>y.MobileBertPreTrainedModel,MobileBertTokenizer:()=>lr.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>Jt.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>y.MobileNetV1ForImageClassification,MobileNetV1Model:()=>y.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>y.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Jt.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>y.MobileNetV2ForImageClassification,MobileNetV2Model:()=>y.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>y.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Jt.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>y.MobileNetV3ForImageClassification,MobileNetV3Model:()=>y.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>y.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Jt.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>y.MobileNetV4ForImageClassification,MobileNetV4Model:()=>y.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>y.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Jt.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>y.MobileViTForImageClassification,MobileViTImageProcessor:()=>Jt.MobileViTImageProcessor,MobileViTModel:()=>y.MobileViTModel,MobileViTPreTrainedModel:()=>y.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>y.MobileViTV2ForImageClassification,MobileViTV2Model:()=>y.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>y.MobileViTV2PreTrainedModel,ModelOutput:()=>y.ModelOutput,Moondream1ForConditionalGeneration:()=>y.Moondream1ForConditionalGeneration,MptForCausalLM:()=>y.MptForCausalLM,MptModel:()=>y.MptModel,MptPreTrainedModel:()=>y.MptPreTrainedModel,MusicgenForCausalLM:()=>y.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>y.MusicgenForConditionalGeneration,MusicgenModel:()=>y.MusicgenModel,MusicgenPreTrainedModel:()=>y.MusicgenPreTrainedModel,NllbTokenizer:()=>lr.NllbTokenizer,NomicBertModel:()=>y.NomicBertModel,NomicBertPreTrainedModel:()=>y.NomicBertPreTrainedModel,NougatImageProcessor:()=>Jt.NougatImageProcessor,NougatTokenizer:()=>lr.NougatTokenizer,OPTForCausalLM:()=>y.OPTForCausalLM,OPTModel:()=>y.OPTModel,OPTPreTrainedModel:()=>y.OPTPreTrainedModel,ObjectDetectionPipeline:()=>Hr.ObjectDetectionPipeline,OpenELMForCausalLM:()=>y.OpenELMForCausalLM,OpenELMModel:()=>y.OpenELMModel,OpenELMPreTrainedModel:()=>y.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Jt.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>y.OwlViTForObjectDetection,OwlViTModel:()=>y.OwlViTModel,OwlViTPreTrainedModel:()=>y.OwlViTPreTrainedModel,OwlViTProcessor:()=>Jt.OwlViTProcessor,Owlv2ForObjectDetection:()=>y.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Jt.Owlv2ImageProcessor,Owlv2Model:()=>y.Owlv2Model,Owlv2PreTrainedModel:()=>y.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>y.Phi3ForCausalLM,Phi3Model:()=>y.Phi3Model,Phi3PreTrainedModel:()=>y.Phi3PreTrainedModel,PhiForCausalLM:()=>y.PhiForCausalLM,PhiModel:()=>y.PhiModel,PhiPreTrainedModel:()=>y.PhiPreTrainedModel,Pipeline:()=>Hr.Pipeline,PreTrainedModel:()=>y.PreTrainedModel,PreTrainedTokenizer:()=>lr.PreTrainedTokenizer,PretrainedConfig:()=>wc.PretrainedConfig,PretrainedMixin:()=>y.PretrainedMixin,Processor:()=>Jt.Processor,PvtForImageClassification:()=>y.PvtForImageClassification,PvtImageProcessor:()=>Jt.PvtImageProcessor,PvtModel:()=>y.PvtModel,PvtPreTrainedModel:()=>y.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>Jt.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>y.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>y.PyAnnoteModel,PyAnnotePreTrainedModel:()=>y.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Jt.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>y.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>Hr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>y.Qwen2ForCausalLM,Qwen2Model:()=>y.Qwen2Model,Qwen2PreTrainedModel:()=>y.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>lr.Qwen2Tokenizer,RTDetrForObjectDetection:()=>y.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Jt.RTDetrImageProcessor,RTDetrModel:()=>y.RTDetrModel,RTDetrObjectDetectionOutput:()=>y.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>y.RTDetrPreTrainedModel,RawImage:()=>Af.RawImage,ResNetForImageClassification:()=>y.ResNetForImageClassification,ResNetModel:()=>y.ResNetModel,ResNetPreTrainedModel:()=>y.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>y.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>y.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>y.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>y.RoFormerForTokenClassification,RoFormerModel:()=>y.RoFormerModel,RoFormerPreTrainedModel:()=>y.RoFormerPreTrainedModel,RoFormerTokenizer:()=>lr.RoFormerTokenizer,RobertaForMaskedLM:()=>y.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>y.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>y.RobertaForSequenceClassification,RobertaForTokenClassification:()=>y.RobertaForTokenClassification,RobertaModel:()=>y.RobertaModel,RobertaPreTrainedModel:()=>y.RobertaPreTrainedModel,RobertaTokenizer:()=>lr.RobertaTokenizer,SamImageProcessor:()=>Jt.SamImageProcessor,SamImageSegmentationOutput:()=>y.SamImageSegmentationOutput,SamModel:()=>y.SamModel,SamPreTrainedModel:()=>y.SamPreTrainedModel,SamProcessor:()=>Jt.SamProcessor,SapiensFeatureExtractor:()=>Jt.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>y.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>y.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>y.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>y.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Jt.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Jt.SegformerFeatureExtractor,SegformerForImageClassification:()=>y.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>y.SegformerForSemanticSegmentation,SegformerModel:()=>y.SegformerModel,SegformerPreTrainedModel:()=>y.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>y.Seq2SeqLMOutput,SequenceClassifierOutput:()=>y.SequenceClassifierOutput,SiglipImageProcessor:()=>Jt.SiglipImageProcessor,SiglipModel:()=>y.SiglipModel,SiglipPreTrainedModel:()=>y.SiglipPreTrainedModel,SiglipTextModel:()=>y.SiglipTextModel,SiglipTokenizer:()=>lr.SiglipTokenizer,SiglipVisionModel:()=>y.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Jt.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>y.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>y.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>y.SpeechT5HifiGan,SpeechT5Model:()=>y.SpeechT5Model,SpeechT5PreTrainedModel:()=>y.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Jt.SpeechT5Processor,SpeechT5Tokenizer:()=>lr.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>y.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>y.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>y.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>y.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>y.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>lr.SqueezeBertTokenizer,StableLmForCausalLM:()=>y.StableLmForCausalLM,StableLmModel:()=>y.StableLmModel,StableLmPreTrainedModel:()=>y.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>y.Starcoder2ForCausalLM,Starcoder2Model:()=>y.Starcoder2Model,Starcoder2PreTrainedModel:()=>y.Starcoder2PreTrainedModel,StoppingCriteria:()=>ao.StoppingCriteria,StoppingCriteriaList:()=>ao.StoppingCriteriaList,SummarizationPipeline:()=>Hr.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>y.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Jt.Swin2SRImageProcessor,Swin2SRModel:()=>y.Swin2SRModel,Swin2SRPreTrainedModel:()=>y.Swin2SRPreTrainedModel,SwinForImageClassification:()=>y.SwinForImageClassification,SwinModel:()=>y.SwinModel,SwinPreTrainedModel:()=>y.SwinPreTrainedModel,T5ForConditionalGeneration:()=>y.T5ForConditionalGeneration,T5Model:()=>y.T5Model,T5PreTrainedModel:()=>y.T5PreTrainedModel,T5Tokenizer:()=>lr.T5Tokenizer,TableTransformerForObjectDetection:()=>y.TableTransformerForObjectDetection,TableTransformerModel:()=>y.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>y.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>y.TableTransformerPreTrainedModel,Tensor:()=>on.Tensor,Text2TextGenerationPipeline:()=>Hr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>Hr.TextClassificationPipeline,TextGenerationPipeline:()=>Hr.TextGenerationPipeline,TextStreamer:()=>yc.TextStreamer,TextToAudioPipeline:()=>Hr.TextToAudioPipeline,TokenClassificationPipeline:()=>Hr.TokenClassificationPipeline,TokenClassifierOutput:()=>y.TokenClassifierOutput,TokenizerModel:()=>lr.TokenizerModel,TrOCRForCausalLM:()=>y.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>y.TrOCRPreTrainedModel,TranslationPipeline:()=>Hr.TranslationPipeline,UniSpeechForCTC:()=>y.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>y.UniSpeechForSequenceClassification,UniSpeechModel:()=>y.UniSpeechModel,UniSpeechPreTrainedModel:()=>y.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>y.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>y.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>y.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>y.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>y.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>Jt.ViTFeatureExtractor,ViTForImageClassification:()=>y.ViTForImageClassification,ViTImageProcessor:()=>Jt.ViTImageProcessor,ViTMAEModel:()=>y.ViTMAEModel,ViTMAEPreTrainedModel:()=>y.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>y.ViTMSNForImageClassification,ViTMSNModel:()=>y.ViTMSNModel,ViTMSNPreTrainedModel:()=>y.ViTMSNPreTrainedModel,ViTModel:()=>y.ViTModel,ViTPreTrainedModel:()=>y.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>y.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>y.VitMatteForImageMatting,VitMatteImageProcessor:()=>Jt.VitMatteImageProcessor,VitMattePreTrainedModel:()=>y.VitMattePreTrainedModel,VitsModel:()=>y.VitsModel,VitsModelOutput:()=>y.VitsModelOutput,VitsPreTrainedModel:()=>y.VitsPreTrainedModel,VitsTokenizer:()=>lr.VitsTokenizer,Wav2Vec2BertForCTC:()=>y.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>y.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>y.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>y.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>lr.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Jt.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>y.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>y.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>y.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>y.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>y.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Jt.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>y.WavLMForAudioFrameClassification,WavLMForCTC:()=>y.WavLMForCTC,WavLMForSequenceClassification:()=>y.WavLMForSequenceClassification,WavLMForXVector:()=>y.WavLMForXVector,WavLMModel:()=>y.WavLMModel,WavLMPreTrainedModel:()=>y.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Jt.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>y.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>y.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Jt.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>y.WhisperForConditionalGeneration,WhisperModel:()=>y.WhisperModel,WhisperPreTrainedModel:()=>y.WhisperPreTrainedModel,WhisperProcessor:()=>Jt.WhisperProcessor,WhisperTextStreamer:()=>yc.WhisperTextStreamer,WhisperTokenizer:()=>lr.WhisperTokenizer,XLMForQuestionAnswering:()=>y.XLMForQuestionAnswering,XLMForSequenceClassification:()=>y.XLMForSequenceClassification,XLMForTokenClassification:()=>y.XLMForTokenClassification,XLMModel:()=>y.XLMModel,XLMPreTrainedModel:()=>y.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>y.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>y.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>y.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>y.XLMRobertaForTokenClassification,XLMRobertaModel:()=>y.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>y.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>lr.XLMRobertaTokenizer,XLMTokenizer:()=>lr.XLMTokenizer,XLMWithLMHeadModel:()=>y.XLMWithLMHeadModel,XVectorOutput:()=>y.XVectorOutput,YolosFeatureExtractor:()=>Jt.YolosFeatureExtractor,YolosForObjectDetection:()=>y.YolosForObjectDetection,YolosModel:()=>y.YolosModel,YolosObjectDetectionOutput:()=>y.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>y.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>Hr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>Hr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>Hr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>Hr.ZeroShotObjectDetectionPipeline,bankers_round:()=>Pn.bankers_round,cat:()=>on.cat,cos_sim:()=>Pn.cos_sim,dot:()=>Pn.dot,dynamic_time_warping:()=>Pn.dynamic_time_warping,env:()=>Pf.env,full:()=>on.full,full_like:()=>on.full_like,getKeyValueShapes:()=>wc.getKeyValueShapes,hamming:()=>vi.hamming,hanning:()=>vi.hanning,interpolate:()=>on.interpolate,interpolate_4d:()=>on.interpolate_4d,interpolate_data:()=>Pn.interpolate_data,is_chinese_char:()=>lr.is_chinese_char,layer_norm:()=>on.layer_norm,log_softmax:()=>Pn.log_softmax,magnitude:()=>Pn.magnitude,matmul:()=>on.matmul,max:()=>Pn.max,mean:()=>on.mean,mean_pooling:()=>on.mean_pooling,medianFilter:()=>Pn.medianFilter,mel_filter_bank:()=>vi.mel_filter_bank,min:()=>Pn.min,ones:()=>on.ones,ones_like:()=>on.ones_like,permute:()=>on.permute,permute_data:()=>Pn.permute_data,pipeline:()=>Hr.pipeline,quantize_embeddings:()=>on.quantize_embeddings,read_audio:()=>vi.read_audio,rfft:()=>on.rfft,round:()=>Pn.round,softmax:()=>Pn.softmax,spectrogram:()=>vi.spectrogram,stack:()=>on.stack,std_mean:()=>on.std_mean,topk:()=>on.topk,window_function:()=>vi.window_function,zeros:()=>on.zeros,zeros_like:()=>on.zeros_like});var Pf=qr("./src/env.js"),Hr=qr("./src/pipelines.js"),y=qr("./src/models.js"),lr=qr("./src/tokenizers.js"),Jt=qr("./src/processors.js"),wc=qr("./src/configs.js"),vi=qr("./src/utils/audio.js"),Af=qr("./src/utils/image.js"),on=qr("./src/utils/tensor.js"),Pn=qr("./src/utils/maths.js"),yc=qr("./src/generation/streamers.js"),ao=qr("./src/generation/stopping_criteria.js");p.ASTFeatureExtractor,p.ASTForAudioClassification,p.ASTModel,p.ASTPreTrainedModel,p.AlbertForMaskedLM,p.AlbertForQuestionAnswering,p.AlbertForSequenceClassification,p.AlbertModel,p.AlbertPreTrainedModel,p.AlbertTokenizer,p.AudioClassificationPipeline,p.AutoConfig,p.AutoModel,p.AutoModelForAudioClassification,p.AutoModelForAudioFrameClassification,p.AutoModelForCTC,p.AutoModelForCausalLM,p.AutoModelForDepthEstimation,p.AutoModelForDocumentQuestionAnswering,p.AutoModelForImageClassification,p.AutoModelForImageFeatureExtraction,p.AutoModelForImageMatting,p.AutoModelForImageSegmentation,p.AutoModelForImageToImage,p.AutoModelForMaskGeneration,p.AutoModelForMaskedLM,p.AutoModelForNormalEstimation,p.AutoModelForObjectDetection,p.AutoModelForQuestionAnswering,p.AutoModelForSemanticSegmentation,p.AutoModelForSeq2SeqLM,p.AutoModelForSequenceClassification,p.AutoModelForSpeechSeq2Seq,p.AutoModelForTextToSpectrogram,p.AutoModelForTextToWaveform,p.AutoModelForTokenClassification,p.AutoModelForUniversalSegmentation,p.AutoModelForVision2Seq,p.AutoModelForXVector,p.AutoModelForZeroShotObjectDetection,p.AutoProcessor;var If=p.AutoTokenizer;p.AutomaticSpeechRecognitionPipeline,p.BartForConditionalGeneration,p.BartForSequenceClassification,p.BartModel,p.BartPretrainedModel,p.BartTokenizer,p.BaseModelOutput,p.BaseStreamer,p.BeitFeatureExtractor,p.BeitForImageClassification,p.BeitModel,p.BeitPreTrainedModel,p.BertForMaskedLM,p.BertForQuestionAnswering,p.BertForSequenceClassification,p.BertForTokenClassification,p.BertModel,p.BertPreTrainedModel,p.BertTokenizer,p.BitImageProcessor,p.BlenderbotForConditionalGeneration,p.BlenderbotModel,p.BlenderbotPreTrainedModel,p.BlenderbotSmallForConditionalGeneration,p.BlenderbotSmallModel,p.BlenderbotSmallPreTrainedModel,p.BlenderbotSmallTokenizer,p.BlenderbotTokenizer,p.BloomForCausalLM,p.BloomModel,p.BloomPreTrainedModel,p.BloomTokenizer,p.CLIPFeatureExtractor,p.CLIPImageProcessor,p.CLIPModel,p.CLIPPreTrainedModel,p.CLIPSegForImageSegmentation,p.CLIPSegModel,p.CLIPSegPreTrainedModel,p.CLIPTextModel,p.CLIPTextModelWithProjection,p.CLIPTokenizer,p.CLIPVisionModel,p.CLIPVisionModelWithProjection,p.CamembertForMaskedLM,p.CamembertForQuestionAnswering,p.CamembertForSequenceClassification,p.CamembertForTokenClassification,p.CamembertModel,p.CamembertPreTrainedModel,p.CamembertTokenizer,p.CausalLMOutput,p.CausalLMOutputWithPast,p.ChineseCLIPFeatureExtractor,p.ChineseCLIPModel,p.ChineseCLIPPreTrainedModel,p.ClapAudioModelWithProjection,p.ClapFeatureExtractor,p.ClapModel,p.ClapPreTrainedModel,p.ClapTextModelWithProjection,p.CodeGenForCausalLM,p.CodeGenModel,p.CodeGenPreTrainedModel,p.CodeGenTokenizer,p.CodeLlamaTokenizer,p.CohereForCausalLM,p.CohereModel,p.CoherePreTrainedModel,p.CohereTokenizer,p.ConvBertForMaskedLM,p.ConvBertForQuestionAnswering,p.ConvBertForSequenceClassification,p.ConvBertForTokenClassification,p.ConvBertModel,p.ConvBertPreTrainedModel,p.ConvBertTokenizer,p.ConvNextFeatureExtractor,p.ConvNextForImageClassification,p.ConvNextImageProcessor,p.ConvNextModel,p.ConvNextPreTrainedModel,p.ConvNextV2ForImageClassification,p.ConvNextV2Model,p.ConvNextV2PreTrainedModel,p.DPTFeatureExtractor,p.DPTForDepthEstimation,p.DPTImageProcessor,p.DPTModel,p.DPTPreTrainedModel,p.DebertaForMaskedLM,p.DebertaForQuestionAnswering,p.DebertaForSequenceClassification,p.DebertaForTokenClassification,p.DebertaModel,p.DebertaPreTrainedModel,p.DebertaTokenizer,p.DebertaV2ForMaskedLM,p.DebertaV2ForQuestionAnswering,p.DebertaV2ForSequenceClassification,p.DebertaV2ForTokenClassification,p.DebertaV2Model,p.DebertaV2PreTrainedModel,p.DebertaV2Tokenizer,p.DecisionTransformerModel,p.DecisionTransformerPreTrainedModel,p.DeiTFeatureExtractor,p.DeiTForImageClassification,p.DeiTModel,p.DeiTPreTrainedModel,p.DepthAnythingForDepthEstimation,p.DepthAnythingPreTrainedModel,p.DepthEstimationPipeline,p.DepthProForDepthEstimation,p.DepthProPreTrainedModel,p.DetrFeatureExtractor,p.DetrForObjectDetection,p.DetrForSegmentation,p.DetrModel,p.DetrObjectDetectionOutput,p.DetrPreTrainedModel,p.DetrSegmentationOutput,p.Dinov2ForImageClassification,p.Dinov2Model,p.Dinov2PreTrainedModel,p.DistilBertForMaskedLM,p.DistilBertForQuestionAnswering,p.DistilBertForSequenceClassification,p.DistilBertForTokenClassification,p.DistilBertModel,p.DistilBertPreTrainedModel,p.DistilBertTokenizer,p.DocumentQuestionAnsweringPipeline,p.DonutFeatureExtractor,p.DonutImageProcessor,p.DonutSwinModel,p.DonutSwinPreTrainedModel,p.EfficientNetForImageClassification,p.EfficientNetImageProcessor,p.EfficientNetModel,p.EfficientNetPreTrainedModel,p.ElectraForMaskedLM,p.ElectraForQuestionAnswering,p.ElectraForSequenceClassification,p.ElectraForTokenClassification,p.ElectraModel,p.ElectraPreTrainedModel,p.ElectraTokenizer,p.EosTokenCriteria,p.EsmForMaskedLM,p.EsmForSequenceClassification,p.EsmForTokenClassification,p.EsmModel,p.EsmPreTrainedModel,p.EsmTokenizer,p.FFT,p.FalconForCausalLM,p.FalconModel,p.FalconPreTrainedModel,p.FalconTokenizer,p.FastViTForImageClassification,p.FastViTModel,p.FastViTPreTrainedModel,p.FeatureExtractionPipeline,p.FeatureExtractor,p.FillMaskPipeline,p.Florence2ForConditionalGeneration,p.Florence2PreTrainedModel,p.Florence2Processor,p.GLPNFeatureExtractor,p.GLPNForDepthEstimation,p.GLPNModel,p.GLPNPreTrainedModel,p.GPT2LMHeadModel,p.GPT2Model,p.GPT2PreTrainedModel,p.GPT2Tokenizer,p.GPTBigCodeForCausalLM,p.GPTBigCodeModel,p.GPTBigCodePreTrainedModel,p.GPTJForCausalLM,p.GPTJModel,p.GPTJPreTrainedModel,p.GPTNeoForCausalLM,p.GPTNeoModel,p.GPTNeoPreTrainedModel,p.GPTNeoXForCausalLM,p.GPTNeoXModel,p.GPTNeoXPreTrainedModel,p.GPTNeoXTokenizer,p.Gemma2ForCausalLM,p.Gemma2Model,p.Gemma2PreTrainedModel,p.GemmaForCausalLM,p.GemmaModel,p.GemmaPreTrainedModel,p.GemmaTokenizer,p.GraniteForCausalLM,p.GraniteModel,p.GranitePreTrainedModel,p.Grok1Tokenizer,p.GroupViTModel,p.GroupViTPreTrainedModel,p.HerbertTokenizer,p.HieraForImageClassification,p.HieraModel,p.HieraPreTrainedModel,p.HubertForCTC,p.HubertForSequenceClassification,p.HubertModel,p.HubertPreTrainedModel,p.ImageClassificationPipeline,p.ImageFeatureExtractionPipeline,p.ImageFeatureExtractor,p.ImageMattingOutput,p.ImageSegmentationPipeline,p.ImageToImagePipeline,p.ImageToTextPipeline,p.InterruptableStoppingCriteria,p.JAISLMHeadModel,p.JAISModel,p.JAISPreTrainedModel,p.LlamaForCausalLM,p.LlamaModel,p.LlamaPreTrainedModel,p.LlamaTokenizer,p.LlavaForConditionalGeneration,p.LlavaPreTrainedModel,p.LongT5ForConditionalGeneration,p.LongT5Model,p.LongT5PreTrainedModel,p.M2M100ForConditionalGeneration,p.M2M100Model,p.M2M100PreTrainedModel,p.M2M100Tokenizer,p.MBart50Tokenizer,p.MBartForCausalLM,p.MBartForConditionalGeneration,p.MBartForSequenceClassification,p.MBartModel,p.MBartPreTrainedModel,p.MBartTokenizer,p.MPNetForMaskedLM,p.MPNetForQuestionAnswering,p.MPNetForSequenceClassification,p.MPNetForTokenClassification,p.MPNetModel,p.MPNetPreTrainedModel,p.MPNetTokenizer,p.MT5ForConditionalGeneration,p.MT5Model,p.MT5PreTrainedModel,p.MarianMTModel,p.MarianModel,p.MarianPreTrainedModel,p.MarianTokenizer,p.MaskFormerFeatureExtractor,p.MaskFormerForInstanceSegmentation,p.MaskFormerModel,p.MaskFormerPreTrainedModel,p.MaskedLMOutput,p.MaxLengthCriteria,p.MistralForCausalLM,p.MistralModel,p.MistralPreTrainedModel,p.MobileBertForMaskedLM,p.MobileBertForQuestionAnswering,p.MobileBertForSequenceClassification,p.MobileBertModel,p.MobileBertPreTrainedModel,p.MobileBertTokenizer,p.MobileNetV1FeatureExtractor,p.MobileNetV1ForImageClassification,p.MobileNetV1Model,p.MobileNetV1PreTrainedModel,p.MobileNetV2FeatureExtractor,p.MobileNetV2ForImageClassification,p.MobileNetV2Model,p.MobileNetV2PreTrainedModel,p.MobileNetV3FeatureExtractor,p.MobileNetV3ForImageClassification,p.MobileNetV3Model,p.MobileNetV3PreTrainedModel,p.MobileNetV4FeatureExtractor,p.MobileNetV4ForImageClassification,p.MobileNetV4Model,p.MobileNetV4PreTrainedModel,p.MobileViTFeatureExtractor,p.MobileViTForImageClassification,p.MobileViTImageProcessor,p.MobileViTModel,p.MobileViTPreTrainedModel,p.MobileViTV2ForImageClassification,p.MobileViTV2Model,p.MobileViTV2PreTrainedModel,p.ModelOutput,p.Moondream1ForConditionalGeneration,p.MptForCausalLM,p.MptModel,p.MptPreTrainedModel,p.MusicgenForCausalLM,p.MusicgenForConditionalGeneration,p.MusicgenModel,p.MusicgenPreTrainedModel,p.NllbTokenizer,p.NomicBertModel,p.NomicBertPreTrainedModel,p.NougatImageProcessor,p.NougatTokenizer,p.OPTForCausalLM,p.OPTModel,p.OPTPreTrainedModel,p.ObjectDetectionPipeline,p.OpenELMForCausalLM,p.OpenELMModel,p.OpenELMPreTrainedModel,p.OwlViTFeatureExtractor,p.OwlViTForObjectDetection,p.OwlViTModel,p.OwlViTPreTrainedModel,p.OwlViTProcessor,p.Owlv2ForObjectDetection,p.Owlv2ImageProcessor,p.Owlv2Model,p.Owlv2PreTrainedModel,p.Phi3ForCausalLM,p.Phi3Model,p.Phi3PreTrainedModel,p.PhiForCausalLM,p.PhiModel,p.PhiPreTrainedModel,p.Pipeline,p.PreTrainedModel,p.PreTrainedTokenizer,p.PretrainedConfig,p.PretrainedMixin,p.Processor,p.PvtForImageClassification,p.PvtImageProcessor,p.PvtModel,p.PvtPreTrainedModel,p.PyAnnoteFeatureExtractor,p.PyAnnoteForAudioFrameClassification,p.PyAnnoteModel,p.PyAnnotePreTrainedModel,p.PyAnnoteProcessor,p.QuestionAnsweringModelOutput,p.QuestionAnsweringPipeline,p.Qwen2ForCausalLM,p.Qwen2Model,p.Qwen2PreTrainedModel,p.Qwen2Tokenizer,p.RTDetrForObjectDetection,p.RTDetrImageProcessor,p.RTDetrModel,p.RTDetrObjectDetectionOutput,p.RTDetrPreTrainedModel,p.RawImage,p.ResNetForImageClassification,p.ResNetModel,p.ResNetPreTrainedModel,p.RoFormerForMaskedLM,p.RoFormerForQuestionAnswering,p.RoFormerForSequenceClassification,p.RoFormerForTokenClassification,p.RoFormerModel,p.RoFormerPreTrainedModel,p.RoFormerTokenizer,p.RobertaForMaskedLM,p.RobertaForQuestionAnswering,p.RobertaForSequenceClassification,p.RobertaForTokenClassification,p.RobertaModel,p.RobertaPreTrainedModel,p.RobertaTokenizer,p.SamImageProcessor,p.SamImageSegmentationOutput,p.SamModel,p.SamPreTrainedModel,p.SamProcessor,p.SapiensFeatureExtractor,p.SapiensForDepthEstimation,p.SapiensForNormalEstimation,p.SapiensForSemanticSegmentation,p.SapiensPreTrainedModel,p.SeamlessM4TFeatureExtractor,p.SegformerFeatureExtractor,p.SegformerForImageClassification,p.SegformerForSemanticSegmentation,p.SegformerModel,p.SegformerPreTrainedModel,p.Seq2SeqLMOutput,p.SequenceClassifierOutput,p.SiglipImageProcessor,p.SiglipModel,p.SiglipPreTrainedModel,p.SiglipTextModel,p.SiglipTokenizer,p.SiglipVisionModel,p.SpeechT5FeatureExtractor,p.SpeechT5ForSpeechToText,p.SpeechT5ForTextToSpeech,p.SpeechT5HifiGan,p.SpeechT5Model,p.SpeechT5PreTrainedModel,p.SpeechT5Processor,p.SpeechT5Tokenizer,p.SqueezeBertForMaskedLM,p.SqueezeBertForQuestionAnswering,p.SqueezeBertForSequenceClassification,p.SqueezeBertModel,p.SqueezeBertPreTrainedModel,p.SqueezeBertTokenizer,p.StableLmForCausalLM,p.StableLmModel,p.StableLmPreTrainedModel,p.Starcoder2ForCausalLM,p.Starcoder2Model,p.Starcoder2PreTrainedModel,p.StoppingCriteria,p.StoppingCriteriaList,p.SummarizationPipeline,p.Swin2SRForImageSuperResolution,p.Swin2SRImageProcessor,p.Swin2SRModel,p.Swin2SRPreTrainedModel,p.SwinForImageClassification,p.SwinModel,p.SwinPreTrainedModel,p.T5ForConditionalGeneration,p.T5Model,p.T5PreTrainedModel,p.T5Tokenizer,p.TableTransformerForObjectDetection,p.TableTransformerModel,p.TableTransformerObjectDetectionOutput,p.TableTransformerPreTrainedModel,p.Tensor,p.Text2TextGenerationPipeline,p.TextClassificationPipeline,p.TextGenerationPipeline,p.TextStreamer,p.TextToAudioPipeline,p.TokenClassificationPipeline,p.TokenClassifierOutput,p.TokenizerModel,p.TrOCRForCausalLM,p.TrOCRPreTrainedModel,p.TranslationPipeline,p.UniSpeechForCTC,p.UniSpeechForSequenceClassification,p.UniSpeechModel,p.UniSpeechPreTrainedModel,p.UniSpeechSatForAudioFrameClassification,p.UniSpeechSatForCTC,p.UniSpeechSatForSequenceClassification,p.UniSpeechSatModel,p.UniSpeechSatPreTrainedModel,p.ViTFeatureExtractor,p.ViTForImageClassification,p.ViTImageProcessor,p.ViTMAEModel,p.ViTMAEPreTrainedModel,p.ViTMSNForImageClassification,p.ViTMSNModel,p.ViTMSNPreTrainedModel,p.ViTModel,p.ViTPreTrainedModel,p.VisionEncoderDecoderModel,p.VitMatteForImageMatting,p.VitMatteImageProcessor,p.VitMattePreTrainedModel,p.VitsModel,p.VitsModelOutput,p.VitsPreTrainedModel,p.VitsTokenizer,p.Wav2Vec2BertForCTC,p.Wav2Vec2BertForSequenceClassification,p.Wav2Vec2BertModel,p.Wav2Vec2BertPreTrainedModel,p.Wav2Vec2CTCTokenizer,p.Wav2Vec2FeatureExtractor,p.Wav2Vec2ForAudioFrameClassification,p.Wav2Vec2ForCTC,p.Wav2Vec2ForSequenceClassification,p.Wav2Vec2Model,p.Wav2Vec2PreTrainedModel,p.Wav2Vec2ProcessorWithLM,p.WavLMForAudioFrameClassification,p.WavLMForCTC,p.WavLMForSequenceClassification,p.WavLMForXVector,p.WavLMModel,p.WavLMPreTrainedModel,p.WeSpeakerFeatureExtractor,p.WeSpeakerResNetModel,p.WeSpeakerResNetPreTrainedModel,p.WhisperFeatureExtractor,p.WhisperForConditionalGeneration,p.WhisperModel,p.WhisperPreTrainedModel,p.WhisperProcessor,p.WhisperTextStreamer,p.WhisperTokenizer,p.XLMForQuestionAnswering,p.XLMForSequenceClassification,p.XLMForTokenClassification,p.XLMModel,p.XLMPreTrainedModel,p.XLMRobertaForMaskedLM,p.XLMRobertaForQuestionAnswering,p.XLMRobertaForSequenceClassification,p.XLMRobertaForTokenClassification,p.XLMRobertaModel,p.XLMRobertaPreTrainedModel,p.XLMRobertaTokenizer,p.XLMTokenizer,p.XLMWithLMHeadModel,p.XVectorOutput,p.YolosFeatureExtractor,p.YolosForObjectDetection,p.YolosModel,p.YolosObjectDetectionOutput,p.YolosPreTrainedModel,p.ZeroShotAudioClassificationPipeline,p.ZeroShotClassificationPipeline,p.ZeroShotImageClassificationPipeline,p.ZeroShotObjectDetectionPipeline,p.bankers_round,p.cat,p.cos_sim,p.dot,p.dynamic_time_warping,p.env,p.full,p.full_like,p.getKeyValueShapes,p.hamming,p.hanning,p.interpolate,p.interpolate_4d,p.interpolate_data,p.is_chinese_char,p.layer_norm,p.log_softmax,p.magnitude,p.matmul,p.max,p.mean,p.mean_pooling,p.medianFilter,p.mel_filter_bank,p.min,p.ones,p.ones_like,p.permute,p.permute_data,p.pipeline,p.quantize_embeddings,p.read_audio,p.rfft,p.round,p.softmax,p.spectrogram,p.stack,p.std_mean,p.topk,p.window_function,p.zeros,p.zeros_like;const pp=new Map;self.addEventListener("message",async Dt=>{const{model_id:Ee,text:V}=Dt.data;let F=pp.get(Ee);F||(F=If.from_pretrained(Ee).then(L=>{switch(L.constructor.name){case"LlamaTokenizer":case"Grok1Tokenizer":L.decoder.decoders.pop();break;case"T5Tokenizer":L.decoder.addPrefixSpace=!1;break}return L}),pp.set(Ee,F));const ce=await F,we=ce.encode(V);let ye=we.map(L=>ce.decode([L])),Te=[];switch(ce.constructor.name){case"BertTokenizer":Te=ye.map((L,P)=>P===0||L.startsWith("##")?0:8),ye=ye.map(L=>L.replace("##",""));break;case"T5Tokenizer":ye.length>0&&ye!==" "&&(ye[0]=ye[0].replace(/^ /,""));break}self.postMessage({token_ids:we,decoded:ye,margins:Te})})})();