diff --git "a/assets/worker-D60LmNTA.js" "b/assets/worker-D60LmNTA.js" new file mode 100644--- /dev/null +++ "b/assets/worker-D60LmNTA.js" @@ -0,0 +1,2648 @@ +var T_=Object.defineProperty;var C_=(Cn,es,ti)=>es in Cn?T_(Cn,es,{enumerable:!0,configurable:!0,writable:!0,value:ti}):Cn[es]=ti;var be=(Cn,es,ti)=>C_(Cn,typeof es!="symbol"?es+"":es,ti);(function(){"use strict";var Cn={},es={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(xt,ye,O)=>{xt.exports=O.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{Environment:()=>Ve,Interpreter:()=>ut,Template:()=>Tt,parse:()=>Te,tokenize:()=>B});var P=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"}),le=Object.freeze({set:P.Set,for:P.For,in:P.In,is:P.Is,if:P.If,else:P.Else,endif:P.EndIf,elif:P.ElseIf,endfor:P.EndFor,and:P.And,or:P.Or,not:P.Not,"not in":P.NotIn,macro:P.Macro,endmacro:P.EndMacro,true:P.BooleanLiteral,false:P.BooleanLiteral,True:P.BooleanLiteral,False:P.BooleanLiteral}),we=class{constructor(v,H){this.value=v,this.type=H}};function xe(v){return/\w/.test(v)}function Ce(v){return/[0-9]/.test(v)}var U=[["{%",P.OpenStatement],["%}",P.CloseStatement],["{{",P.OpenExpression],["}}",P.CloseExpression],["(",P.OpenParen],[")",P.CloseParen],["{",P.OpenCurlyBracket],["}",P.CloseCurlyBracket],["[",P.OpenSquareBracket],["]",P.CloseSquareBracket],[",",P.Comma],[".",P.Dot],[":",P.Colon],["|",P.Pipe],["<=",P.ComparisonBinaryOperator],[">=",P.ComparisonBinaryOperator],["==",P.ComparisonBinaryOperator],["!=",P.ComparisonBinaryOperator],["<",P.ComparisonBinaryOperator],[">",P.ComparisonBinaryOperator],["+",P.AdditiveBinaryOperator],["-",P.AdditiveBinaryOperator],["*",P.MultiplicativeBinaryOperator],["/",P.MultiplicativeBinaryOperator],["%",P.MultiplicativeBinaryOperator],["=",P.Equals]],I=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function L(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=L(v,H);let he=0;const nt=bt=>{let Dt="";for(;bt(Y[he]);){if(Y[he]==="\\"){if(++he,he>=Y.length)throw new SyntaxError("Unexpected end of input");const At=Y[he++],dr=I.get(At);if(dr===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);Dt+=dr;continue}if(Dt+=Y[he++],he>=Y.length)throw new SyntaxError("Unexpected end of input")}return Dt};e:for(;he0){$.push(new we(At,P.Text));continue}}nt(At=>/\s/.test(At));const Dt=Y[he];if(Dt==="-"||Dt==="+"){const At=(Nt=$.at(-1))==null?void 0:Nt.type;if(At===P.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${Dt}`);switch(At){case P.Identifier:case P.NumericLiteral:case P.BooleanLiteral:case P.StringLiteral:case P.CloseParen:case P.CloseSquareBracket:break;default:{++he;const dr=nt(Ce);$.push(new we(`${Dt}${dr}`,dr.length>0?P.NumericLiteral:P.UnaryOperator));continue}}}for(const[At,dr]of U)if(Y.slice(he,he+At.length)===At){$.push(new we(At,dr)),he+=At.length;continue e}if(Dt==="'"||Dt==='"'){++he;const At=nt(dr=>dr!==Dt);$.push(new we(At,P.StringLiteral)),++he;continue}if(Ce(Dt)){const At=nt(Ce);$.push(new we(At,P.NumericLiteral));continue}if(xe(Dt)){const At=nt(xe),dr=Object.hasOwn(le,At)?le[At]:P.Identifier;dr===P.In&&((yt=$.at(-1))==null?void 0:yt.type)===P.Not?($.pop(),$.push(new we("not in",P.NotIn))):$.push(new we(At,dr));continue}throw new SyntaxError(`Unexpected character: ${Dt}`)}return $}var q=class{constructor(){be(this,"type","Statement")}},re=class extends q{constructor(H){super();be(this,"type","Program");this.body=H}},fe=class extends q{constructor(H,$,Y){super();be(this,"type","If");this.test=H,this.body=$,this.alternate=Y}},de=class extends q{constructor(H,$,Y,he){super();be(this,"type","For");this.loopvar=H,this.iterable=$,this.body=Y,this.defaultBlock=he}},z=class extends q{constructor(H,$){super();be(this,"type","Set");this.assignee=H,this.value=$}},J=class extends q{constructor(H,$,Y){super();be(this,"type","Macro");this.name=H,this.args=$,this.body=Y}},pe=class extends q{constructor(){super(...arguments);be(this,"type","Expression")}},X=class extends pe{constructor(H,$,Y){super();be(this,"type","MemberExpression");this.object=H,this.property=$,this.computed=Y}},K=class extends pe{constructor(H,$){super();be(this,"type","CallExpression");this.callee=H,this.args=$}},j=class extends pe{constructor(H){super();be(this,"type","Identifier");this.value=H}},k=class extends pe{constructor(H){super();be(this,"type","Literal");this.value=H}},N=class extends k{constructor(){super(...arguments);be(this,"type","NumericLiteral")}},E=class extends k{constructor(){super(...arguments);be(this,"type","StringLiteral")}},ue=class extends k{constructor(){super(...arguments);be(this,"type","BooleanLiteral")}},Me=class extends k{constructor(){super(...arguments);be(this,"type","ArrayLiteral")}},$e=class extends k{constructor(){super(...arguments);be(this,"type","TupleLiteral")}},De=class extends k{constructor(){super(...arguments);be(this,"type","ObjectLiteral")}},ze=class extends pe{constructor(H,$,Y){super();be(this,"type","BinaryExpression");this.operator=H,this.left=$,this.right=Y}},it=class extends pe{constructor(H,$){super();be(this,"type","FilterExpression");this.operand=H,this.filter=$}},rt=class extends pe{constructor(H,$){super();be(this,"type","SelectExpression");this.iterable=H,this.test=$}},lt=class extends pe{constructor(H,$,Y){super();be(this,"type","TestExpression");this.operand=H,this.negate=$,this.test=Y}},me=class extends pe{constructor(H,$){super();be(this,"type","UnaryExpression");this.operator=H,this.argument=$}},W=class extends pe{constructor(H=void 0,$=void 0,Y=void 0){super();be(this,"type","SliceExpression");this.start=H,this.stop=$,this.step=Y}},ce=class extends pe{constructor(H,$){super();be(this,"type","KeywordArgumentExpression");this.key=H,this.value=$}};function Te(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 P.Text:return Nt();case P.OpenStatement:return yt();case P.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(P.Text,"Expected text token").value)}function yt(){Y(P.OpenStatement,"Expected opening statement token");let Fe;switch(v[$].type){case P.Set:++$,Fe=Dt(),Y(P.CloseStatement,"Expected closing statement token");break;case P.If:++$,Fe=At(),Y(P.OpenStatement,"Expected {% token"),Y(P.EndIf,"Expected endif token"),Y(P.CloseStatement,"Expected %} token");break;case P.Macro:++$,Fe=dr(),Y(P.OpenStatement,"Expected {% token"),Y(P.EndMacro,"Expected endmacro token"),Y(P.CloseStatement,"Expected %} token");break;case P.For:++$,Fe=Yr(),Y(P.OpenStatement,"Expected {% token"),Y(P.EndFor,"Expected endfor token"),Y(P.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${v[$].type}`)}return Fe}function bt(){Y(P.OpenExpression,"Expected opening expression token");const Fe=Rr();return Y(P.CloseExpression,"Expected closing expression token"),Fe}function Dt(){const Fe=Rr();if(Je(P.Equals)){++$;const Oe=Dt();return new z(Fe,Oe)}return Fe}function At(){var Ut,sr,br,Nr,mr,kr,wr,$n;const Fe=Rr();Y(P.CloseStatement,"Expected closing statement token");const Oe=[],ct=[];for(;!(((Ut=v[$])==null?void 0:Ut.type)===P.OpenStatement&&(((sr=v[$+1])==null?void 0:sr.type)===P.ElseIf||((br=v[$+1])==null?void 0:br.type)===P.Else||((Nr=v[$+1])==null?void 0:Nr.type)===P.EndIf));)Oe.push(he());if(((mr=v[$])==null?void 0:mr.type)===P.OpenStatement&&((kr=v[$+1])==null?void 0:kr.type)!==P.EndIf)if(++$,Je(P.ElseIf))Y(P.ElseIf,"Expected elseif token"),ct.push(At());else for(Y(P.Else,"Expected else token"),Y(P.CloseStatement,"Expected closing statement token");!(((wr=v[$])==null?void 0:wr.type)===P.OpenStatement&&(($n=v[$+1])==null?void 0:$n.type)===P.EndIf);)ct.push(he());return new fe(Fe,Oe,ct)}function dr(){const Fe=Ot();if(Fe.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Oe=tt();Y(P.CloseStatement,"Expected closing statement token");const ct=[];for(;nt(P.OpenStatement,P.EndMacro);)ct.push(he());return new J(Fe,Oe,ct)}function Cr(Fe=!1){const Oe=Fe?Ot:Rr,ct=[Oe()],Ut=Je(P.Comma);for(;Ut&&(++$,ct.push(Oe()),!!Je(P.Comma)););return Ut?new $e(ct):ct[0]}function Yr(){const Fe=Cr(!0);if(!(Fe instanceof j||Fe instanceof $e))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Fe.type} instead`);Y(P.In,"Expected `in` keyword following loop variable");const Oe=Rr();Y(P.CloseStatement,"Expected closing statement token");const ct=[];for(;nt(P.OpenStatement,P.EndFor)&&nt(P.OpenStatement,P.Else);)ct.push(he());const Ut=[];if(Je(P.OpenStatement,P.Else))for(++$,++$,Y(P.CloseStatement,"Expected closing statement token");nt(P.OpenStatement,P.EndFor);)Ut.push(he());return new de(Fe,Oe,ct,Ut)}function Rr(){return Jr()}function Jr(){const Fe=yn();if(Je(P.If)){++$;const Oe=yn();if(Je(P.Else)){++$;const ct=yn();return new fe(Oe,[Fe],[ct])}else return new rt(Fe,Oe)}return Fe}function yn(){let Fe=at();for(;Je(P.Or);){const Oe=v[$];++$;const ct=at();Fe=new ze(Oe,Fe,ct)}return Fe}function at(){let Fe=G();for(;Je(P.And);){const Oe=v[$];++$;const ct=G();Fe=new ze(Oe,Fe,ct)}return Fe}function G(){let Fe;for(;Je(P.Not);){const Oe=v[$];++$;const ct=G();Fe=new me(Oe,ct)}return Fe??ge()}function ge(){let Fe=Ie();for(;Je(P.ComparisonBinaryOperator)||Je(P.In)||Je(P.NotIn);){const Oe=v[$];++$;const ct=Ie();Fe=new ze(Oe,Fe,ct)}return Fe}function Ie(){let Fe=ft();for(;Je(P.AdditiveBinaryOperator);){const Oe=v[$];++$;const ct=ft();Fe=new ze(Oe,Fe,ct)}return Fe}function Se(){const Fe=$t();return Je(P.OpenParen)?Ne(Fe):Fe}function Ne(Fe){let Oe=new K(Fe,tt());return Je(P.OpenParen)&&(Oe=Ne(Oe)),Oe}function tt(){Y(P.OpenParen,"Expected opening parenthesis for arguments list");const Fe=wt();return Y(P.CloseParen,"Expected closing parenthesis for arguments list"),Fe}function wt(){const Fe=[];for(;!Je(P.CloseParen);){let Oe=Rr();if(Je(P.Equals)){if(++$,!(Oe instanceof j))throw new SyntaxError("Expected identifier for keyword argument");const ct=Rr();Oe=new ce(Oe,ct)}Fe.push(Oe),Je(P.Comma)&&++$}return Fe}function mt(){const Fe=[];let Oe=!1;for(;!Je(P.CloseSquareBracket);)Je(P.Colon)?(Fe.push(void 0),++$,Oe=!0):(Fe.push(Rr()),Je(P.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 $t(){let Fe=Ot();for(;Je(P.Dot)||Je(P.OpenSquareBracket);){const Oe=v[$];++$;let ct;const Ut=Oe.type!==P.Dot;if(Ut)ct=mt(),Y(P.CloseSquareBracket,"Expected closing square bracket");else if(ct=Ot(),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(P.MultiplicativeBinaryOperator);){const Oe=v[$];++$;const ct=Lt();Fe=new ze(Oe,Fe,ct)}return Fe}function Lt(){let Fe=jt();for(;Je(P.Is);){++$;const Oe=Je(P.Not);Oe&&++$;let ct=Ot();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(P.Pipe);){++$;let Oe=Ot();if(!(Oe instanceof j))throw new SyntaxError("Expected identifier for the filter");Je(P.OpenParen)&&(Oe=Ne(Oe)),Fe=new it(Fe,Oe)}return Fe}function Ot(){const Fe=v[$];switch(Fe.type){case P.NumericLiteral:return++$,new N(Number(Fe.value));case P.StringLiteral:return++$,new E(Fe.value);case P.BooleanLiteral:return++$,new ue(Fe.value.toLowerCase()==="true");case P.Identifier:return++$,new j(Fe.value);case P.OpenParen:{++$;const Oe=Cr();if(v[$].type!==P.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${v[$].type} instead`);return++$,Oe}case P.OpenSquareBracket:{++$;const Oe=[];for(;!Je(P.CloseSquareBracket);)Oe.push(Rr()),Je(P.Comma)&&++$;return++$,new Me(Oe)}case P.OpenCurlyBracket:{++$;const Oe=new Map;for(;!Je(P.CloseCurlyBracket);){const ct=Rr();Y(P.Colon,"Expected colon between key and value in object literal");const Ut=Rr();Oe.set(ct,Ut),Je(P.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){be(this,"type","RuntimeValue");be(this,"value");be(this,"builtins",new Map);this.value=v}__bool__(){return new ht(!!this.value)}},dt=class extends Ze{constructor(){super(...arguments);be(this,"type","NumericValue")}},Re=class extends Ze{constructor(){super(...arguments);be(this,"type","StringValue");be(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(ne(this.value)))],["length",new dt(this.value.length)]]))}},ht=class extends Ze{constructor(){super(...arguments);be(this,"type","BooleanValue")}},Mt=class extends Ze{constructor(){super(...arguments);be(this,"type","ObjectValue");be(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);be(this,"type","KeywordArgumentsValue")}},Z=class extends Ze{constructor(){super(...arguments);be(this,"type","ArrayValue");be(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);be(this,"type","TupleValue")}},Ke=class extends Ze{constructor(){super(...arguments);be(this,"type","FunctionValue")}},et=class extends Ze{constructor(){super(...arguments);be(this,"type","NullValue")}},je=class extends Ze{constructor(){super(...arguments);be(this,"type","UndefinedValue")}},Ve=class{constructor(v){be(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]})]]));be(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){be(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(Pt($));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(ne($.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(Pt($,Je.value))}if($ instanceof Z){switch(he){case"selectattr":{if($.value.some(Dt=>!(Dt instanceof Mt)))throw new Error("`selectattr` can only be applied to array of objects");if(Y.args.some(Dt=>Dt.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[nt,Je,Nt]=Y.args.map(Dt=>this.evaluate(Dt,H));let yt;if(Je){const Dt=H.tests.get(Je.value);if(!Dt)throw new Error(`Unknown test: ${Je.value}`);yt=Dt}else yt=(...Dt)=>Dt[0].__bool__().value;const bt=$.value.filter(Dt=>{const At=Dt.value.get(nt.value);return At?yt(At,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),Dt=$.value.split(` +`),At=" ".repeat(Nt.value),dr=Dt.map((Cr,Yr)=>!yt.value&&Yr===0||!bt.value&&Cr.length===0?Cr:At+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,At);else if(v.loopvar.type==="TupleLiteral"){const Cr=v.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const Yr=At;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 Pt(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=>Pt(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 Dt=`"${yt}": ${Pt(bt,H,Y+1)}`;return H?`${Je}${Dt}`:Dt});return H?`{${Nt.join(",")}${nt}}`:`{${Nt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${v.type}`)}}var Tt=class{constructor(v){be(this,"parsed");const H=B(v,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Te(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":(xt,ye,O)=>{O.r(ye),O.d(ye,{registerBackend:()=>we,resolveBackendAndExecutionProviders:()=>Ce});const P=new Map,le=[],we=(U,I,L)=>{if(I&&typeof I.init=="function"&&typeof I.createInferenceSessionHandler=="function"){const B=P.get(U);if(B===void 0)P.set(U,{backend:I,priority:L});else{if(B.priority>L)return;if(B.priority===L&&B.backend!==I)throw new Error(`cannot register backend "${U}" using priority ${L}`)}if(L>=0){const q=le.indexOf(U);q!==-1&&le.splice(q,1);for(let re=0;re{const I=P.get(U);if(!I)return"backend not found.";if(I.initialized)return I.backend;if(I.aborted)return I.error;{const L=!!I.initPromise;try{return L||(I.initPromise=I.backend.init(U)),await I.initPromise,I.initialized=!0,I.backend}catch(B){return L||(I.error=`${B}`,I.aborted=!0),I.error}finally{delete I.initPromise}}},Ce=async U=>{const I=U.executionProviders||[],L=I.map(z=>typeof z=="string"?z:z.name),B=L.length===0?le:L;let q;const re=[],fe=new Set;for(const z of B){const J=await xe(z);typeof J=="string"?re.push({name:z,err:J}):(q||(q=J),q===J&&fe.add(z))}if(!q)throw new Error(`no available backend found. ERR: ${re.map(z=>`[${z.name}] ${z.err}`).join(", ")}`);for(const{name:z,err:J}of re)L.includes(z)&&console.warn(`removing requested execution provider "${z}" from session options because it is not available: ${J}`);const de=I.filter(z=>fe.has(typeof z=="string"?z:z.name));return[q,new Proxy(U,{get:(z,J)=>J==="executionProviders"?de:Reflect.get(z,J)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{registerBackend:()=>P.registerBackend});var P=O("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{env:()=>we});var P=O("./node_modules/onnxruntime-common/dist/esm/version.js");let le="warning";const we={wasm:{},webgl:{},webgpu:{},versions:{common:P.version},set logLevel(xe){if(xe!==void 0){if(typeof xe!="string"||["verbose","info","warning","error","fatal"].indexOf(xe)===-1)throw new Error(`Unsupported logging level: ${xe}`);le=xe}},get logLevel(){return le}};Object.defineProperty(we,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{env:()=>le});var P=O("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const le=P.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{InferenceSession:()=>we.InferenceSession,TRACE:()=>Ce.TRACE,TRACE_FUNC_BEGIN:()=>Ce.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Ce.TRACE_FUNC_END,Tensor:()=>xe.Tensor,TrainingSession:()=>U.TrainingSession,env:()=>le.env,registerBackend:()=>P.registerBackend});var P=O("./node_modules/onnxruntime-common/dist/esm/backend.js"),le=O("./node_modules/onnxruntime-common/dist/esm/env.js"),we=O("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),xe=O("./node_modules/onnxruntime-common/dist/esm/tensor.js");O("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),O("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Ce=O("./node_modules/onnxruntime-common/dist/esm/trace.js");O("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),O("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var U=O("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{InferenceSession:()=>xe});var P=O("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),le=O("./node_modules/onnxruntime-common/dist/esm/tensor.js"),we=O("./node_modules/onnxruntime-common/dist/esm/trace.js");class xe{constructor(U){this.handler=U}async run(U,I,L){(0,we.TRACE_FUNC_BEGIN)();const B={};let q={};if(typeof U!="object"||U===null||U instanceof le.Tensor||Array.isArray(U))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let re=!0;if(typeof I=="object"){if(I===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(I instanceof le.Tensor)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.");re=!1;for(const z of I){if(typeof z!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(z)===-1)throw new RangeError(`'fetches' contains invalid output name: ${z}.`);B[z]=null}if(typeof L=="object"&&L!==null)q=L;else if(typeof L<"u")throw new TypeError("'options' must be an object.")}else{let z=!1;const J=Object.getOwnPropertyNames(I);for(const pe of this.outputNames)if(J.indexOf(pe)!==-1){const X=I[pe];(X===null||X instanceof le.Tensor)&&(z=!0,re=!1,B[pe]=X)}if(z){if(typeof L=="object"&&L!==null)q=L;else if(typeof L<"u")throw new TypeError("'options' must be an object.")}else q=I}}else if(typeof I<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const z of this.inputNames)if(typeof U[z]>"u")throw new Error(`input '${z}' is missing in 'feeds'.`);if(re)for(const z of this.outputNames)B[z]=null;const fe=await this.handler.run(U,B,q),de={};for(const z in fe)if(Object.hasOwnProperty.call(fe,z)){const J=fe[z];J instanceof le.Tensor?de[z]=J:de[z]=new le.Tensor(J.type,J.data,J.dims)}return(0,we.TRACE_FUNC_END)(),de}async release(){return this.handler.dispose()}static async create(U,I,L,B){(0,we.TRACE_FUNC_BEGIN)();let q,re={};if(typeof U=="string"){if(q=U,typeof I=="object"&&I!==null)re=I;else if(typeof I<"u")throw new TypeError("'options' must be an object.")}else if(U instanceof Uint8Array){if(q=U,typeof I=="object"&&I!==null)re=I;else if(typeof I<"u")throw new TypeError("'options' must be an object.")}else if(U instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&U instanceof SharedArrayBuffer){const J=U;let pe=0,X=U.byteLength;if(typeof I=="object"&&I!==null)re=I;else if(typeof I=="number"){if(pe=I,!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=U.byteLength-pe,typeof L=="number"){if(X=L,!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 L<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof I<"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,de]=await(0,P.resolveBackendAndExecutionProviders)(re),z=await fe.createInferenceSessionHandler(q,de);return(0,we.TRACE_FUNC_END)(),new xe(z)}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":(xt,ye,O)=>{O.r(ye),O.d(ye,{InferenceSession:()=>le});var P=O("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const le=P.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(xt,ye,O)=>{O.r(ye)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(xt,ye,O)=>{O.r(ye)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{tensorToDataURL:()=>P,tensorToImageData:()=>le});const P=(we,xe)=>{const Ce=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Ce.width=we.dims[3],Ce.height=we.dims[2];const U=Ce.getContext("2d");if(U!=null){let I,L;(xe==null?void 0:xe.tensorLayout)!==void 0&&xe.tensorLayout==="NHWC"?(I=we.dims[2],L=we.dims[3]):(I=we.dims[3],L=we.dims[2]);const B=(xe==null?void 0:xe.format)!==void 0?xe.format:"RGB",q=xe==null?void 0:xe.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 de=L*I;let z=0,J=de,pe=de*2,X=-1;B==="RGBA"?(z=0,J=de,pe=de*2,X=de*3):B==="RGB"?(z=0,J=de,pe=de*2):B==="RBG"&&(z=0,pe=de,J=de*2);for(let K=0;K{const Ce=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let U;if(Ce!=null){let I,L,B;(xe==null?void 0:xe.tensorLayout)!==void 0&&xe.tensorLayout==="NHWC"?(I=we.dims[2],L=we.dims[1],B=we.dims[3]):(I=we.dims[3],L=we.dims[2],B=we.dims[1]);const q=xe!==void 0&&xe.format!==void 0?xe.format:"RGB",re=xe==null?void 0:xe.norm;let fe,de;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?de=[0,0,0,0]:typeof re.bias=="number"?de=[re.bias,re.bias,re.bias,re.bias]:(de=[re.bias[0],re.bias[1],re.bias[2],0],re.bias[3]!==void 0&&(de[3]=re.bias[3]));const z=L*I;if(xe!==void 0&&(xe.format!==void 0&&B===4&&xe.format!=="RGBA"||B===3&&xe.format!=="RGB"&&xe.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=z,E=z*2,ue=-1;q==="RGBA"?(k=0,N=z,E=z*2,ue=z*3):q==="RGB"?(k=0,N=z,E=z*2):q==="RBG"&&(k=0,E=z,N=z*2),U=Ce.createImageData(I,L);for(let Me=0;Me{O.r(ye)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{bufferToTensor:()=>le,tensorFromGpuBuffer:()=>Ce,tensorFromImage:()=>we,tensorFromPinnedBuffer:()=>U,tensorFromTexture:()=>xe});var P=O("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const le=(I,L)=>{if(I===void 0)throw new Error("Image buffer must be defined");if(L.height===void 0||L.width===void 0)throw new Error("Image height and width must be defined");if(L.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:B,width:q}=L,re=L.norm??{mean:255,bias:0};let fe,de;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"?de=[re.bias,re.bias,re.bias,re.bias]:de=[re.bias[0],re.bias[1],re.bias[2],re.bias[3]??0];const z=L.format!==void 0?L.format:"RGBA",J=L.tensorFormat!==void 0&&L.tensorFormat!==void 0?L.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,Me=pe,$e=pe*2,De=-1;z==="RGB"&&(K=3,j=0,k=1,N=2,E=-1),J==="RGBA"?De=pe*3:J==="RBG"?(ue=0,$e=pe,Me=pe*2):J==="BGR"&&($e=0,Me=pe,ue=pe*2);for(let it=0;it{const B=typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement,q=typeof ImageData<"u"&&I instanceof ImageData,re=typeof ImageBitmap<"u"&&I instanceof ImageBitmap,fe=typeof I=="string";let de,z=L??{};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=I.width,X.height=I.height;const K=pe(X);if(K!=null){let j=I.height,k=I.width;if(L!==void 0&&L.resizedHeight!==void 0&&L.resizedWidth!==void 0&&(j=L.resizedHeight,k=L.resizedWidth),L!==void 0){if(z=L,L.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");z.tensorFormat="RGBA",z.height=j,z.width=k}else z.tensorFormat="RGBA",z.height=j,z.width=k;K.drawImage(I,0,0),de=K.getImageData(0,0,k,j).data}else throw new Error("Can not access image data")}else if(q){let X,K;if(L!==void 0&&L.resizedWidth!==void 0&&L.resizedHeight!==void 0?(X=L.resizedHeight,K=L.resizedWidth):(X=I.height,K=I.width),L!==void 0&&(z=L),z.format="RGBA",z.height=X,z.width=K,L!==void 0){const j=J();j.width=K,j.height=X;const k=pe(j);if(k!=null)k.putImageData(I,0,0),de=k.getImageData(0,0,K,X).data;else throw new Error("Can not access image data")}else de=I.data}else if(re){if(L===void 0)throw new Error("Please provide image config with format for Imagebitmap");const X=J();X.width=I.width,X.height=I.height;const K=pe(X);if(K!=null){const j=I.height,k=I.width;return K.drawImage(I,0,0,k,j),de=K.getImageData(0,0,k,j).data,z.height=j,z.width=k,le(de,z)}else throw new Error("Can not access image data")}else{if(fe)return new Promise((X,K)=>{const j=J(),k=pe(j);if(!I||!k)return K();const N=new Image;N.crossOrigin="Anonymous",N.src=I,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);z.height=j.height,z.width=j.width,X(le(E.data,z))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(de!==void 0)return le(de,z);throw new Error("Input data provided is not supported - aborted tensor creation")},xe=(I,L)=>{const{width:B,height:q,download:re,dispose:fe}=L,de=[1,q,B,4];return new P.Tensor({location:"texture",type:"float32",texture:I,dims:de,download:re,dispose:fe})},Ce=(I,L)=>{const{dataType:B,dims:q,download:re,dispose:fe}=L;return new P.Tensor({location:"gpu-buffer",type:B??"float32",gpuBuffer:I,dims:q,download:re,dispose:fe})},U=(I,L,B)=>new P.Tensor({location:"cpu-pinned",type:I,data:L,dims:B??[L.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(xt,ye,O)=>{O.r(ye)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>le,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>P,checkTypedArray:()=>xe});const P=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),le=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let we=!1;const xe=()=>{if(!we){we=!0;const Ce=typeof BigInt64Array<"u"&&BigInt64Array.from,U=typeof BigUint64Array<"u"&&BigUint64Array.from,I=typeof Float16Array<"u"&&Float16Array.from;Ce&&(P.set("int64",BigInt64Array),le.set(BigInt64Array,"int64")),U&&(P.set("uint64",BigUint64Array),le.set(BigUint64Array,"uint64")),I?(P.set("float16",Float16Array),le.set(Float16Array,"float16")):P.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{Tensor:()=>Ce});var P=O("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),le=O("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),we=O("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),xe=O("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Ce{constructor(I,L,B){(0,we.checkTypedArray)();let q,re;if(typeof I=="object"&&"location"in I)switch(this.dataLocation=I.location,q=I.type,re=I.dims,I.location){case"cpu-pinned":{const de=we.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(q);if(!de)throw new TypeError(`unsupported type "${q}" to create tensor from pinned buffer`);if(!(I.data instanceof de))throw new TypeError(`buffer should be of type ${de.name}`);this.cpuData=I.data;break}case"texture":{if(q!=="float32")throw new TypeError(`unsupported type "${q}" to create tensor from texture`);this.gpuTextureData=I.texture,this.downloader=I.download,this.disposer=I.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=I.gpuBuffer,this.downloader=I.download,this.disposer=I.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let de,z;if(typeof I=="string")if(q=I,z=B,I==="string"){if(!Array.isArray(L))throw new TypeError("A string tensor's data must be a string array.");de=L}else{const J=we.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(I);if(J===void 0)throw new TypeError(`Unsupported tensor type: ${I}.`);if(Array.isArray(L)){if(I==="float16"&&J===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");I==="uint64"||I==="int64"?de=J.from(L,BigInt):de=J.from(L)}else if(L instanceof J)de=L;else throw new TypeError(`A ${q} tensor's data must be type of ${J}`)}else if(z=L,Array.isArray(I)){if(I.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const J=typeof I[0];if(J==="string")q="string",de=I;else if(J==="boolean")q="bool",de=Uint8Array.from(I);else throw new TypeError(`Invalid element type of data array: ${J}.`)}else{const J=we.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(I.constructor);if(J===void 0)throw new TypeError(`Unsupported type for tensor data: ${I.constructor}.`);q=J,de=I}if(z===void 0)z=[de.length];else if(!Array.isArray(z))throw new TypeError("A tensor's dims must be a number array");re=z,this.cpuData=de,this.dataLocation="cpu"}const fe=(0,xe.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(I,L){return(0,le.tensorFromImage)(I,L)}static fromTexture(I,L){return(0,le.tensorFromTexture)(I,L)}static fromGpuBuffer(I,L){return(0,le.tensorFromGpuBuffer)(I,L)}static fromPinnedBuffer(I,L,B){return(0,le.tensorFromPinnedBuffer)(I,L,B)}toDataURL(I){return(0,P.tensorToDataURL)(this,I)}toImageData(I){return(0,P.tensorToImageData)(this,I)}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(I){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 L=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=L,I&&this.disposer&&(this.disposer(),this.disposer=void 0),L}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(I){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,xe.tensorReshape)(this,I)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{calculateSize:()=>le,tensorReshape:()=>we});var P=O("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const le=xe=>{let Ce=1;for(let U=0;U{switch(xe.location){case"cpu":return new P.Tensor(xe.type,xe.data,Ce);case"cpu-pinned":return new P.Tensor({location:"cpu-pinned",data:xe.data,type:xe.type,dims:Ce});case"texture":return new P.Tensor({location:"texture",texture:xe.texture,type:xe.type,dims:Ce});case"gpu-buffer":return new P.Tensor({location:"gpu-buffer",gpuBuffer:xe.gpuBuffer,type:xe.type,dims:Ce});default:throw new Error(`tensorReshape: tensor location ${xe.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{Tensor:()=>le});var P=O("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const le=P.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{TRACE:()=>le,TRACE_FUNC_BEGIN:()=>xe,TRACE_FUNC_END:()=>Ce});var P=O("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const le=(U,I)=>{(typeof P.env.trace>"u"?!P.env.wasm.trace:!P.env.trace)||console.timeStamp(`${U}::ORT::${I}`)},we=(U,I)=>{var q;const L=((q=new Error().stack)==null?void 0:q.split(/\r\n|\r|\n/g))||[];let B=!1;for(let re=0;re{(typeof P.env.trace>"u"?!P.env.wasm.trace:!P.env.trace)||we("BEGIN",U)},Ce=U=>{(typeof P.env.trace>"u"?!P.env.wasm.trace:!P.env.trace)||we("END",U)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{TrainingSession:()=>xe});var P=O("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),le=O("./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 xe{constructor(U,I,L){this.handler=U,this.hasOptimizerModel=I,this.hasEvalModel=L}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(U,I){const L=U.evalModel||"",B=U.optimizerModel||"",q=I||{},[re,fe]=await(0,P.resolveBackendAndExecutionProviders)(q);if(re.createTrainingSessionHandler){const de=await re.createTrainingSessionHandler(U.checkpointState,U.trainModel,L,B,fe);return new xe(de,!!U.optimizerModel,!!U.evalModel)}else throw new Error(we)}typeNarrowingForRunStep(U,I,L,B,q){const re={};let fe={};if(typeof L!="object"||L===null||L instanceof le.Tensor||Array.isArray(L))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let de=!0;if(typeof B=="object"){if(B===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(B instanceof le.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.");de=!1;for(const z of B){if(typeof z!="string")throw new TypeError("'fetches' must be a string array or an object.");if(I.indexOf(z)===-1)throw new RangeError(`'fetches' contains invalid output name: ${z}.`);re[z]=null}if(typeof q=="object"&&q!==null)fe=q;else if(typeof q<"u")throw new TypeError("'options' must be an object.")}else{let z=!1;const J=Object.getOwnPropertyNames(B);for(const pe of I)if(J.indexOf(pe)!==-1){const X=B[pe];(X===null||X instanceof le.Tensor)&&(z=!0,de=!1,re[pe]=X)}if(z){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 z of U)if(typeof L[z]>"u")throw new Error(`input '${z}' is missing in 'feeds'.`);if(de)for(const z of I)re[z]=null;return[re,fe]}convertHandlerReturnTypeToMapOfTensors(U){const I={};for(const L in U)if(Object.hasOwnProperty.call(U,L)){const B=U[L];B instanceof le.Tensor?I[L]=B:I[L]=new le.Tensor(B.type,B.data,B.dims)}return I}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(U,I,L){const[B,q]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,U,I,L),re=await this.handler.runTrainStep(U,B,q);return this.convertHandlerReturnTypeToMapOfTensors(re)}async runOptimizerStep(U){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(U||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(U,I,L){if(this.hasEvalModel){const[B,q]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,U,I,L),re=await this.handler.runEvalStep(U,B,q);return this.convertHandlerReturnTypeToMapOfTensors(re)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(U=!0){return this.handler.getParametersSize(U)}async loadParametersBuffer(U,I=!0){const L=await this.getParametersSize(I);if(U.length!==4*L)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(U,I)}async getContiguousParameters(U=!0){return this.handler.getContiguousParameters(U)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{TrainingSession:()=>le});var P=O("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const le=P.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{version:()=>P});const P="1.19.2"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(xt,ye,O)=>{O.r(ye),O.d(ye,{InferenceSession:()=>Tt,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>je,TRACE_FUNC_END:()=>Ve,Tensor:()=>Z,TrainingSession:()=>yt,default:()=>am,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 P=Object.defineProperty,le=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyNames,xe=Object.prototype.hasOwnProperty,Ce=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),U=(e,t)=>()=>(e&&(t=e(e=0)),t),I=(e,t)=>{for(var r in t)P(e,r,{get:t[r],enumerable:!0})},L=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of we(t))!xe.call(e,i)&&i!==r&&P(e,i,{get:()=>t[i],enumerable:!(n=le(t,i))||n.enumerable});return e},B=e=>L(P({},"__esModule",{value:!0}),e),q,re,fe,de,z,J=U(()=>{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}}},z=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 de(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=U(()=>{J()}),X,K=U(()=>{X="1.20.0-dev.20241016-2b8fc5529b"}),j,k,N=U(()=>{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=U(()=>{N(),E=k}),Me,$e,De=U(()=>{Me=(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,D=3,V=0,A=m,ee=m*2,te=-1;u==="RGBA"?(V=0,A=m,ee=m*2,te=m*3):u==="RGB"?(V=0,A=m,ee=m*2):u==="RBG"&&(V=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,D=0,V=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"?(D=0,A=c,V=c*2):d==="BGR"&&(A=0,V=c,D=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]})}),Te,We,ot,ne,Ze=U(()=>{Te=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,ne=()=>{if(!ot){ot=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(Te.set("int64",BigInt64Array),We.set(BigInt64Array,"int64")),t&&(Te.set("uint64",BigUint64Array),We.set(BigUint64Array,"uint64")),r?(Te.set("float16",Float16Array),We.set(Float16Array,"float16")):Te.set("float16",Uint16Array)}}}),dt,Re,ht=U(()=>{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=U(()=>{De(),ce(),Ze(),ht(),Mt=class{constructor(e,t,r){ne();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=Te.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=Te.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 Me(this,e)}toImageData(e){return $e(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Re(this,e)}}}),Z,Ae=U(()=>{Xe(),Z=Mt}),Ke,et,je,Ve,ut=U(()=>{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,Pt=U(()=>{J(),Ae(),ut(),_t=class zf{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 z(s),c=await u.createInferenceSessionHandler(a,d);return Ve(),new zf(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Tt,v=U(()=>{Pt(),Tt=_t}),H=U(()=>{}),$=U(()=>{}),Y=U(()=>{}),he=U(()=>{}),nt,Je,Nt=U(()=>{J(),Ae(),nt="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Je=class Df{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 z(a);if(s.createTrainingSessionHandler){let d=await s.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,i,u);return new Df(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=U(()=>{Nt(),yt=Je}),Dt={};I(Dt,{InferenceSession:()=>Tt,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>je,TRACE_FUNC_END:()=>Ve,Tensor:()=>Z,TrainingSession:()=>yt,env:()=>E,registerBackend:()=>fe});var At=U(()=>{pe(),ue(),v(),Ae(),H(),$(),ut(),Y(),he(),bt()}),dr=U(()=>{}),Cr={};I(Cr,{default:()=>Jr});var Yr,Rr,Jr,yn=U(()=>{var e;rh(),kr(),Ot(),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(()=>{jc(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;Vc(a,i).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})});break}case"copy-from":{let{buffer:i}=n,a=cc(i);postMessage({type:r,out:a});break}case"create":{let{model:i,options:a}=n;Uc(i,a).then(s=>{postMessage({type:r,out:s})},s=>{postMessage({type:r,err:s})});break}case"release":Wc(n),postMessage({type:r});break;case"run":{let{sessionId:i,inputIndices:a,inputs:s,outputIndices:u,options:d}=n;qc(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},Kc([...s,...c]))},c=>{postMessage({type:r,err:c})});break}case"end-profiling":Hc(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={};I(at,{default:()=>Ie});var G,ge,Ie,Se=U(()=>{var e;ge=(G=self.location.href,async function(t={}){function r(){return hr.buffer!=Qt.buffer&&fn(),Qt}function n(){return hr.buffer!=Qt.buffer&&fn(),xr}function i(){return hr.buffer!=Qt.buffer&&fn(),qe}function a(){return hr.buffer!=Qt.buffer&&fn(),vt}function s(){return hr.buffer!=Qt.buffer&&fn(),rr}function u(){return hr.buffer!=Qt.buffer&&fn(),Br}function d(){return hr.buffer!=Qt.buffer&&fn(),nn}function c(){return hr.buffer!=Qt.buffer&&fn(),fc}var g,m,l=Object.assign({},t),T=new Promise((o,h)=>{g=o,m=h}),x=typeof window=="object",C=typeof importScripts=="function",D=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 V=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let A=()=>{let o=(w,M,S)=>(...se)=>{let He=ds,st=M==null?void 0:M();se=w(...se);let It=M==null?void 0:M();return st!==It&&(w=It,S(st),M=S=null),ds!=He?new Promise((Rt,Zt)=>{fp={resolve:Rt,reject:Zt}}):se},h=w=>async(...M)=>{var S;try{if(l.Fb)throw Error("Session already started");let se=l.Fb={fc:M[0],errors:[]},He=await w(...M);if(l.Fb!==se)throw Error("Session mismatch");(S=l.Gb)==null||S.flush();let st=se.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,se,He)=>w.registerBuffer(M,S,se,He),l.jsepGetBuffer=M=>w.getBuffer(M),l.jsepCreateDownloader=(M,S,se)=>w.createDownloader(M,S,se),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,se)=>w.registerMLTensor(M,S,se),l.qc=(M,S,se,He,st)=>w.registerMLConstant(M,S,se,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 Ft,Bt=console.log.bind(console),ar=console.error.bind(console),nr=Bt,Ht=ar;if(Object.assign(l,ie),ie=null,D){let o=function(h){try{var w=h.data,M=w.cmd;if(M==="load"){let S=[];self.onmessage=se=>S.push(se),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let se of S)o(se);self.onmessage=o};for(let se of w.handlers)l[se]&&!l[se].proxy||(l[se]=(...He)=>{postMessage({Mb:"callHandler",oc:se,args:He})},se=="print"&&(nr=l[se]),se=="printErr"&&(Ht=l[se]));hr=w.wasmMemory,fn(),Er(w.wasmModule)}else if(M==="run"){wp(w.pthread_ptr,0,0,1,0,0),cp(w.pthread_ptr),um(),Ch(),jr||(xf(),jr=!0);try{dm(w.start_routine,w.arg)}catch(S){if(S!="unwind")throw S}}else M==="cancel"?lo()&&$c(-1):w.target!=="setimmediate"&&(M==="checkMailbox"?jr&&gc():M&&(Ht(`worker: received unknown command ${M}`),Ht(w)))}catch(S){throw Tf(),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:lo()})},l.instantiateWasm=(h,w)=>new Promise(M=>{Er=S=>{S=new WebAssembly.Instance(S,bh()),w(S),M()}}),self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=o}l.wasmBinary&&(Ft=l.wasmBinary);var hr,Fr,Gt,Qt,xr,qe,vt,rr,Br,nn,an,Xs,fc,Sn=!1;function fn(){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=nn=new Float32Array(o),l.HEAPF64=fc=new Float64Array(o),l.HEAP64=an=new BigInt64Array(o),l.HEAPU64=Xs=new BigUint64Array(o)}if(!D){if(!((hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof V))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");fn()}var yi=[],cn=[],vn=[],Gn=0,Qs=null;function mc(){if(--Gn==0&&Qs){var o=Qs;Qs=null,o()}}function io(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 Jc,_h=o=>o.startsWith("data:application/octet-stream;base64,"),gh=o=>o.startsWith("file://");function wh(o){if(o==Jc&&Ft)return new Uint8Array(Ft);if(te)return te(o);throw"both async and sync fetching of the wasm failed"}function yh(o,h,w){return function(M){if(!Ft&&(x||C)){if(typeof fetch=="function"&&!gh(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(()=>wh(M));if(ee)return new Promise((S,se)=>{ee(M,He=>S(new Uint8Array(He)),se)})}return Promise.resolve().then(()=>wh(M))}(o).then(M=>WebAssembly.instantiate(M,h)).then(w,M=>{Ht(`failed to asynchronously prepare wasm: ${M}`),io(M)})}function bh(){return{a:{O:lm,Aa:om,b:pm,aa:Sh,B:Ih,qa:Fh,Y:zh,_:Dh,ra:Lh,oa:Bh,ha:Rh,na:Nh,L:jh,Z:Vh,W:Uh,pa:Wh,X:Gh,wa:hm,F:fm,Q:mm,P:gm,E:ym,u:bm,q:Mm,G:vm,A:Sm,R:Pm,ua:Am,ka:Im,U:Fm,ba:Om,H:zm,ja:cp,ta:Dm,t:Lm,x:Nm,n:jm,l:Um,c:up,o:Wm,j:Hm,w:Km,p:Xm,g:Qm,s:Ym,m:Zm,e:Jm,k:e_,i:t_,h:r_,d:n_,ea:s_,fa:i_,ga:a_,ca:af,da:of,T:o_,f:l_,D:u_,I:d_,M:c_,y:p_,sa:h_,V:f_,v:uf,z:m_,N:__,S:g_,za:w_,ya:y_,la:pf,ma:hf,$:sp,C:ff,K:mf,ia:_f,J:gf,a:hr,xa:np,va:bf,r:v_}}}var ep={867364:(o,h,w,M,S)=>{if(l===void 0||!l.Eb)return 1;if((o=wn(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 se=o.subarray(h,h+w);switch(S){case 0:n().set(se,M>>>0);break;case 1:l.cc(M,se);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:wn(w),format:M?"NHWC":"NCHW"})},872645:(o,h,w,M)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:wn(w),format:M?"NHWC":"NCHW"})},872778:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be,Mr)=>{l.jb("ConvTranspose",o,{format:It?"NHWC":"NCHW",autoPad:h,dilations:[w],group:M,kernelShape:[S],pads:[se,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:wn(Mr)})},873179:(o,h,w,M,S,se,He,st,It,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(se>>>0,4+(se>>>0)>>>0)),strides:Array.from(s().subarray(He>>>0,2+(He>>>0)>>>0)),wIsConst:()=>!!r()[It>>>0],outputPadding:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],outputShape:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[],activation:wn(Be)})},873744:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be,Mr)=>{l.jb("ConvTranspose",o,{format:It?"NHWC":"NCHW",autoPad:h,dilations:[w],group:M,kernelShape:[S],pads:[se,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:wn(Mr)})},874145:(o,h,w,M,S,se,He,st,It,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(se>>>0,4+(se>>>0)>>>0)),strides:Array.from(s().subarray(He>>>0,2+(He>>>0)>>>0)),wIsConst:()=>!!r()[It>>>0],outputPadding:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],outputShape:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[],activation:wn(Be)})},874710:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},874801:(o,h,w,M,S,se,He,st,It,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:se?Array.from(s().subarray(se>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,It>>>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,se,He,st,It,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:se?Array.from(s().subarray(se>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,It>>>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,se,He,st,It,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:se?Array.from(s().subarray(se>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,It>>>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,se,He,st,It,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:se?Array.from(s().subarray(se>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,It>>>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,se,He,st,It,Rt,Zt)=>{l.jb("Resize",o,{antialias:h,axes:w?Array.from(s().subarray(w>>>0,M>>>0)):[],coordinateTransformMode:wn(S),cubicCoeffA:se,excludeOutside:He,extrapolationValue:st,keepAspectRatioPolicy:wn(It),mode:wn(Rt),nearestMode:wn(Zt)})},877905:(o,h,w,M,S,se,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:se?Array.from(s().subarray(se>>>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:wn(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,se)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:w,spatial:!!S,trainingMode:!!M,format:se?"NHWC":"NCHW"})},878831:(o,h,w,M,S,se)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:w,spatial:!!S,trainingMode:!!M,format:se?"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,se,He,st,It)=>{l.jb("Attention",o,{numHeads:h,isUnidirectional:w,maskFilterValue:M,scale:S,doRotary:se,qkvHiddenSizes:He?Array.from(s().subarray(Number(st)>>>0,Number(st)+He>>>0)):[],pastPresentShareBuffer:!!It})},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,se,He,st,It,Rt,Zt,Tr,Vr,Be,Mr,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:se?Array.from(s().subarray(se>>>0,He>>>0)):[],pads:st?Array.from(s().subarray(st>>>0,It>>>0)):[],strides:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],w_is_const:()=>!!r()[Vr>>>0],activation:wn(Be),activation_params:Mr?Array.from(d().subarray(Mr>>>0,rn>>>0)):[]})},880127:o=>{l.jb("Gelu",o,void 0)},880179:(o,h,w,M,S,se,He,st,It)=>{l.jb("GroupQueryAttention",o,{numHeads:h,kvNumHeads:w,scale:M,softcap:S,doRotary:se,rotaryInterleaved:He,smoothSoftmax:st,localWindowSize:It})},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,se)=>{l.jb("MatMulNBits",o,{k:h,n:w,accuracyLevel:M,bits:S,blockSize:se})},880745:(o,h,w,M,S,se)=>{l.jb("MultiHeadAttention",o,{numHeads:h,isUnidirectional:w,maskFilterValue:M,scale:S,doRotary:se})},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 om(o,h,w){return ef(async()=>{await l.Xb(o,h,w)})}function lm(){return typeof wasmOffsetConverter<"u"}function tp(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var rp=o=>{o.terminate(),o.onmessage=()=>{}},Mh=o=>{Ys.length==0&&(Eh(),$h(Ys[0]));var h=Ys.pop();if(!h)return 6;Mi.push(h),ls[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},bi=0,Zr=(o,h,...w)=>{for(var M=2*w.length,S=Mp(),se=bp(8*M),He=se>>>3,st=0;st>>0]=It)}return o=Cf(o,0,M,se,h),Ec(S),o};function np(o){if(D)return Zr(0,1,o);if(Gt=o,!(0{if(Gt=o,D)throw vh(o),"unwind";np(o)},Ys=[],Mi=[],xh=[],ls={},Th=o=>{var h=o.Ab;delete ls[h],Ys.push(o),Mi.splice(Mi.indexOf(o),1),o.Ab=0,yp(h)};function Ch(){xh.forEach(o=>o())}var $h=o=>new Promise(h=>{o.onmessage=S=>{var se=(S=S.data).cmd;if(S.targetThread&&S.targetThread!=lo()){var He=ls[S.targetThread];He?He.postMessage(S,S.transferList):Ht(`Internal error! Worker sent a message "${se}" to target pthread ${S.targetThread}, but that thread no longer exists!`)}else se==="checkMailbox"?gc():se==="spawnThread"?Mh(S):se==="cleanupThread"?Th(ls[S.thread]):se==="killThread"?(S=S.thread,se=ls[S],delete ls[S],rp(se),yp(S),Mi.splice(Mi.indexOf(se),1),se.Ab=0):se==="cancelThread"?ls[S.thread].postMessage({cmd:"cancel"}):se==="loaded"?(o.loaded=!0,h(o)):se==="alert"?alert(`Thread ${S.threadId}: ${S.text}`):S.target==="setimmediate"?o.postMessage(S):se==="callHandler"?l[S.handler](...S.args):se&&Ht(`worker sent an unknown command ${se}`)},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:Fr})});function Eh(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ys.push(o)}var _c=o=>{for(;0{var o=lo(),h=u()[o+52>>>2>>>0];o=u()[o+56>>>2>>>0],Ef(h,h-o),Ec(h)},dm=(o,h)=>{bi=0,o=kf(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 kh(o,h,w,M){return D?Zr(2,1,o,h,w,M):Sh(o,h,w,M)}function Sh(o,h,w,M){if(o>>>=0,h>>>=0,w>>>=0,M>>>=0,V===void 0)return Ht("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var S=[];return D&&S.length===0?kh(o,h,w,M):(o={hc:w,Ab:o,Qb:M,mc:S},D?(o.Mb="spawnThread",postMessage(o,S),0):Mh(o))}var Ph=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ah=(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|se<<6|He:(7&S)<<18|se<<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},wn=(o,h)=>(o>>>=0)?Ah(n(),o,h):"";function Ih(o,h,w){return D?Zr(3,1,o,h,w):0}function Fh(o,h){if(D)return Zr(4,1,o,h)}var ip=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},Oh=(o,h,w,M)=>{if(!(0>>=0;M=w+M-1;for(var se=0;se=He&&(He=65536+((1023&He)<<10)|1023&o.charCodeAt(++se)),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},ao=(o,h,w)=>Oh(o,n(),h,w);function zh(o,h){if(D)return Zr(5,1,o,h)}function Dh(o,h,w){if(D)return Zr(6,1,o,h,w)}function Lh(o,h,w){return D?Zr(7,1,o,h,w):0}function Bh(o,h){if(D)return Zr(8,1,o,h)}function Rh(o,h,w){if(D)return Zr(9,1,o,h,w)}function Nh(o,h,w,M){if(D)return Zr(10,1,o,h,w,M)}function jh(o,h,w,M){if(D)return Zr(11,1,o,h,w,M)}function Vh(o,h,w,M){if(D)return Zr(12,1,o,h,w,M)}function Uh(o){if(D)return Zr(13,1,o)}function Wh(o,h){if(D)return Zr(14,1,o,h)}function Gh(o,h,w){if(D)return Zr(15,1,o,h,w)}var qh,Zs,hm=()=>{io("")},us=o=>{for(var h="";n()[o>>>0];)h+=qh[n()[o++>>>0]];return h},ap={},op={};function Ts(o,h,w={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(M,S,se={}){var He=S.name;if(!M)throw new Zs(`type "${He}" must have a positive integer typeid pointer`);if(op.hasOwnProperty(M)){if(se.Sb)return;throw new Zs(`Cannot register type '${He}' twice`)}op[M]=S,ap.hasOwnProperty(M)&&(S=ap[M],delete ap[M],S.forEach(st=>st()))}(o,h,w)}var Hh=(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=>Xs[M>>>3];default:throw new TypeError(`invalid integer width (${h}): ${o}`)}};function fm(o,h,w){w>>>=0,Ts(o>>>=0,{name:h=us(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:Js,readValueFromPointer:Hh(h,w,h.indexOf("u")==-1),Db:null})}var Js=8;function mm(o,h,w,M){Ts(o>>>=0,{name:h=us(h>>>0),fromWireType:function(S){return!!S},toWireType:function(S,se){return se?w:M},argPackAdvance:Js,readValueFromPointer:function(S){return this.fromWireType(n()[S>>>0])},Db:null})}var lp=[],Cs=[];function up(o){9<(o>>>=0)&&--Cs[o+1]==0&&(Cs[o]=void 0,lp.push(o))}var qn=o=>{if(!o)throw new Zs("Cannot use deleted val. handle = "+o);return Cs[o]},Hn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=lp.pop()||Cs.length;return Cs[h]=o,Cs[h+1]=1,h}};function dp(o){return this.fromWireType(u()[o>>>2>>>0])}var _m={name:"emscripten::val",fromWireType:o=>{var h=qn(o);return up(o),h},toWireType:(o,h)=>Hn(h),argPackAdvance:Js,readValueFromPointer:dp,Db:null};function gm(o){return Ts(o>>>0,_m)}var wm=(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 ym(o,h,w){w>>>=0,Ts(o>>>=0,{name:h=us(h>>>0),fromWireType:M=>M,toWireType:(M,S)=>S,argPackAdvance:Js,readValueFromPointer:wm(h,w),Db:null})}function bm(o,h,w,M,S){if(o>>>=0,w>>>=0,h=us(h>>>0),S===-1&&(S=4294967295),S=st=>st,M===0){var se=32-8*w;S=st=>st<>>se}var He=h.includes("unsigned")?function(st,It){return It>>>0}:function(st,It){return It};Ts(o,{name:h,fromWireType:S,toWireType:He,argPackAdvance:Js,readValueFromPointer:Hh(h,w,M!==0),Db:null})}function Mm(o,h,w){function M(se){var He=u()[se>>>2>>>0];return se=u()[se+4>>>2>>>0],new S(r().buffer,se,He)}var S=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];Ts(o>>>=0,{name:w=us(w>>>0),fromWireType:M,argPackAdvance:Js,readValueFromPointer:M},{Sb:!0})}function vm(o,h){o>>>=0;var w=(h=us(h>>>0))==="std::string";Ts(o,{name:h,fromWireType:function(M){var S=u()[M>>>2>>>0],se=M+4;if(w)for(var He=se,st=0;st<=S;++st){var It=se+st;if(st==S||n()[It>>>0]==0){if(He=wn(He,It-He),Rt===void 0)var Rt=He;else Rt+="\0",Rt+=He;He=It+1}}else{for(Rt=Array(S),st=0;st>>0]);Rt=Rt.join("")}return cs(M),Rt},toWireType:function(M,S){S instanceof ArrayBuffer&&(S=new Uint8Array(S));var se=typeof S=="string";if(!(se||S instanceof Uint8Array||S instanceof Uint8ClampedArray||S instanceof Int8Array))throw new Zs("Cannot pass non-string to std::string");var He=w&&se?ip(S):S.length,st=Cc(4+He+1),It=st+4;if(u()[st>>>2>>>0]=He,w&&se)ao(S,It,He+1);else if(se)for(se=0;se>>0]=Rt}else for(se=0;se>>0]=S[se];return M!==null&&M.push(cs,st),st},argPackAdvance:Js,readValueFromPointer:dp,Db(M){cs(M)}})}var Kh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,xm=(o,h)=>{for(var w=o>>1,M=w+h/2;!(w>=M)&&a()[w>>>0];)++w;if(32<(w<<=1)-o&&Kh)return Kh.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},Tm=(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]=se,h+=2}return i()[h>>>1>>>0]=0,h-M},Cm=o=>2*o.length,$m=(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},Em=(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=se&&(se=65536+((1023&se)<<10)|1023&o.charCodeAt(++S)),s()[h>>>2>>>0]=se,(h+=4)+4>w)break}return s()[h>>>2>>>0]=0,h-M},km=o=>{for(var h=0,w=0;w=M&&++w,h+=4}return h};function Sm(o,h,w){if(o>>>=0,h>>>=0,w=us(w>>>=0),h===2)var M=xm,S=Tm,se=Cm,He=st=>a()[st>>>1>>>0];else h===4&&(M=$m,S=Em,se=km,He=st=>u()[st>>>2>>>0]);Ts(o,{name:w,fromWireType:st=>{for(var It,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),It===void 0?It=Zt:(It+="\0",It+=Zt),Zt=Vr+h)}return cs(st),It},toWireType:(st,It)=>{if(typeof It!="string")throw new Zs(`Cannot pass non-string to C++ string type ${w}`);var Rt=se(It),Zt=Cc(4+Rt+h);return u()[Zt>>>2>>>0]=Rt/h,S(It,Zt+4,Rt+h),st!==null&&st.push(cs,Zt),Zt},argPackAdvance:Js,readValueFromPointer:dp,Db(st){cs(st)}})}function Pm(o,h){Ts(o>>>=0,{Tb:!0,name:h=us(h>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Am=()=>1;function Im(o){wp(o>>>0,!C,1,!x,131072,!1),Ch()}var Xh=o=>{if(!Sn)try{if(o(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(s(),o>>>2,o).value.then(gc),o+=128,Atomics.store(s(),o>>>2,1))}var gc=()=>{var o=lo();o&&(cp(o),Xh($f))};function Fm(o,h){(o>>>=0)==h>>>0?setTimeout(gc):D?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=ls[o])&&o.postMessage({cmd:"checkMailbox"})}var pp=[];function Om(o,h,w,M,S){for(h>>>=0,M/=2,pp.length=M,w=S>>>0>>>3,S=0;S>>0];return(h?ep[h]:x_[o])(...pp)}function zm(o){o>>>=0,D?postMessage({cmd:"cleanupThread",thread:o}):Th(ls[o])}function Dm(o){}var hp=(o,h)=>{var w=op[o];if(w===void 0)throw o=vf(o),w=us(o),cs(o),new Zs(`${h} has unknown type ${w}`);return w},Qh=(o,h,w)=>{var M=[];return o=o.toWireType(M,w),M.length&&(u()[h>>>2>>>0]=Hn(M)),o};function Lm(o,h,w){return h>>>=0,w>>>=0,o=qn(o>>>0),h=hp(h,"emval::as"),Qh(h,w,o)}var wc=o=>{try{o()}catch(h){io(h)}},ei=0,ds=null,Yh=0,yc=[],Zh={},Jh={},Bm=0,fp=null,Rm=[];function ef(o){return function(h){if(!Sn){if(ei===0){var w=!1,M=!1;h((S=0)=>{if(!Sn&&(Yh=S,w=!0,M)){ei=2,wc(()=>Af(ds)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),S=!1;try{var se=function(){var It=s()[ds+8>>>2>>>0];return It=Xt[Jh[It]],--bi,It()}()}catch(It){se=It,S=!0}var He=!1;if(!ds){var st=fp;st&&(fp=null,(S?st.reject:st.resolve)(se),He=!0)}if(S&&!He)throw se}}),M=!0,w||(ei=1,ds=function(){var S=Cc(65548),se=S+12;u()[S>>>2>>>0]=se,u()[S+4>>>2>>>0]=se+65536,se=yc[0];var He=Zh[se];return He===void 0&&(He=Bm++,Zh[se]=He,Jh[He]=se),se=He,s()[S+8>>>2>>>0]=se,S}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),wc(()=>Sf(ds)))}else ei===2?(ei=0,wc(If),cs(ds),ds=null,Rm.forEach(Xh)):io(`invalid state: ${ei}`);return Yh}}(h=>{o().then(h)})}function Nm(o){return o>>>=0,ef(()=>(o=qn(o)).then(Hn))}var bc=[];function jm(o,h,w,M){return w>>>=0,M>>>=0,(o=bc[o>>>0])(null,h=qn(h>>>0),w,M)}var Vm={},Mc=o=>{var h=Vm[o];return h===void 0?us(o):h};function Um(o,h,w,M,S){return w>>>=0,M>>>=0,S>>>=0,(o=bc[o>>>0])(h=qn(h>>>0),h[w=Mc(w)],M,S)}var tf=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Wm(o){return(o>>>=0)==0?Hn(tf()):(o=Mc(o),Hn(tf()[o]))}var Gm=o=>{var h=bc.length;return bc.push(o),h},qm=(o,h)=>{for(var w=Array(o),M=0;M>>2>>>0],"parameter "+M);return w},rf=(o,h)=>Object.defineProperty(h,"name",{value:o});function Hm(o,h,w){var M=(h=qm(o,h>>>0)).shift();o--;var S=`return function (obj, func, destructorsRef, args) { +`,se=0,He=[];w===0&&He.push("obj");for(var st=["retType"],It=[M],Rt=0;RtZt.name).join(", ")}) => ${M.name}>`,Gm(rf(w,o))}function Km(o){return o=Mc(o>>>0),Hn(l[o])}function Xm(o,h){return h>>>=0,o=qn(o>>>0),h=qn(h),Hn(o[h])}function Qm(o){9<(o>>>=0)&&(Cs[o+1]+=1)}function Ym(){return Hn([])}function Zm(o){o=qn(o>>>0);for(var h=Array(o.length),w=0;w>>0))}function e_(){return Hn({})}function t_(o){for(var h=qn(o>>>=0);h.length;){var w=h.pop();h.pop()(w)}up(o)}function r_(o,h,w){h>>>=0,w>>>=0,o=qn(o>>>0),h=qn(h),w=qn(w),o[h]=w}function n_(o,h){return h>>>=0,o=(o=hp(o>>>0,"_emval_take_value")).readValueFromPointer(h),Hn(o)}function s_(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 oo=o=>o%4==0&&(o%100!=0||o%400==0),nf=[0,31,60,91,121,152,182,213,244,274,305,335],sf=[0,31,59,90,120,151,181,212,243,273,304,334];function i_(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=(oo(o.getFullYear())?nf:sf)[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 a_(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(),se=new Date(h.getFullYear(),0,1).getTimezoneOffset(),He=Math.min(se,S);return 0>w?s()[o+32>>>2>>>0]=+(S!=se&&He==M):0>>2>>>0]=h.getDay(),w=(oo(h.getFullYear())?nf:sf)[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 af(o,h,w,M,S,se,He){return D?Zr(16,1,o,h,w,M,S,se,He):-52}function of(o,h,w,M,S,se){if(D)return Zr(17,1,o,h,w,M,S,se)}function o_(o,h,w,M){o>>>=0,h>>>=0,w>>>=0,M>>>=0;var S=new Date().getFullYear(),se=new Date(S,0,1),He=new Date(S,6,1);S=se.getTimezoneOffset();var st=He.getTimezoneOffset(),It=Math.max(S,st);u()[o>>>2>>>0]=60*It,s()[h>>>2>>>0]=+(S!=st),se=(o=Rt=>Rt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(se),He=o(He),st{mp.length=0;for(var w;w=n()[o++>>>0];){var M=w!=105;h+=(M&=w!=112)&&h%8?4:0,mp.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 mp};function l_(o,h,w){return o>>>=0,h=lf(h>>>0,w>>>0),ep[o](...h)}function u_(o,h,w){return o>>>=0,h=lf(h>>>0,w>>>0),ep[o](...h)}var d_=()=>{},c_=()=>Date.now();function p_(o,h){return Ht(wn(o>>>0,h>>>0))}var uf,h_=()=>{throw bi+=1,"unwind"};function f_(){return 4294901760}uf=()=>performance.timeOrigin+performance.now();var m_=()=>navigator.hardwareConcurrency;function __(){return io("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function g_(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),fn();var se=1;break e}catch{}se=void 0}if(se)return!0}return!1}var vc=()=>(io("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Sd={},df=o=>{o.forEach(h=>{vc()})};function w_(){var o=Error().stack.toString().split(` +`);return o[0]=="Error"&&o.shift(),df(o),Sd.Pb=vc(),Sd.ec=o,Sd.Pb}function y_(o,h,w){if(o>>>=0,h>>>=0,Sd.Pb==o)var M=Sd.ec;else(M=Error().stack.toString().split(` +`))[0]=="Error"&&M.shift(),df(M);for(var S=3;M[S]&&vc()!=o;)++S;for(o=0;o>>2>>>0]=vc();return o}var _p,gp={},cf=()=>{if(!_p){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 gp)gp[o]===void 0?delete h[o]:h[o]=gp[o];var w=[];for(o in h)w.push(`${o}=${h[o]}`);_p=w}return _p};function pf(o,h){if(D)return Zr(18,1,o,h);o>>>=0,h>>>=0;var w=0;return cf().forEach((M,S)=>{var se=h+w;for(S=u()[o+4*S>>>2>>>0]=se,se=0;se>>0]=M.charCodeAt(se);r()[S>>>0]=0,w+=M.length+1}),0}function hf(o,h){if(D)return Zr(19,1,o,h);o>>>=0,h>>>=0;var w=cf();u()[o>>>2>>>0]=w.length;var M=0;return w.forEach(S=>M+=S.length+1),u()[h>>>2>>>0]=M,0}function ff(o){return D?Zr(20,1,o):52}function mf(o,h,w,M){return D?Zr(21,1,o,h,w,M):52}function _f(o,h,w,M){return D?Zr(22,1,o,h,w,M):70}var b_=[null,[],[]];function gf(o,h,w,M){if(D)return Zr(23,1,o,h,w,M);h>>>=0,w>>>=0,M>>>=0;for(var S=0,se=0;se>>2>>>0],st=u()[h+4>>>2>>>0];h+=8;for(var It=0;It>>0],Zt=b_[o];Rt===0||Rt===10?((o===1?nr:Ht)(Ah(Zt,0)),Zt.length=0):Zt.push(Rt)}S+=st}return u()[M>>>2>>>0]=S,0}var wf=[31,29,31,30,31,30,31,31,30,31,30,31],yf=[31,28,31,30,31,30,31,31,30,31,30,31],M_=(o,h)=>{r().set(o,h>>>0)};function bf(o,h,w,M){function S(Be,Mr,rn){for(Be=typeof Be=="number"?Be.toString():Be||"";Be.lengthOf?-1:0vi-Be.getDate())){Be.setDate(Be.getDate()+Mr);break}Mr-=vi-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),Mr=st(new Date(Be.getFullYear(),0,4)),rn=st(rn),0>=He(Mr,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?wn(Rt):""},w=wn(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=>se((Be.Cb+1900)/100|0,2),"%d":Be=>se(Be.Lb,2),"%e":Be=>S(Be.Lb,2," "),"%g":Be=>It(Be).toString().substring(2),"%G":It,"%H":Be=>se(Be.Hb,2),"%I":Be=>((Be=Be.Hb)==0?Be=12:12{for(var Mr=0,rn=0;rn<=Be.Ib-1;Mr+=(oo(Be.Cb+1900)?wf:yf)[rn++]);return se(Be.Lb+Mr,3)},"%m":Be=>se(Be.Ib+1,2),"%M":Be=>se(Be.jc,2),"%n":()=>` +`,"%p":Be=>0<=Be.Hb&&12>Be.Hb?"AM":"PM","%S":Be=>se(Be.kc,2),"%t":()=>" ","%u":Be=>Be.ub||7,"%U":Be=>se(Math.floor((Be.Bb+7-Be.ub)/7),2),"%V":Be=>{var Mr=Math.floor((Be.Bb+7-(Be.ub+6)%7)/7);if(2>=(Be.ub+371-Be.Bb-2)%7&&Mr++,Mr)Mr==53&&((rn=(Be.ub+371-Be.Bb)%7)==4||rn==3&&oo(Be.Cb)||(Mr=1));else{Mr=52;var rn=(Be.ub+7-Be.Bb-1)%7;(rn==4||rn==5&&oo(Be.Cb%400-1))&&Mr++}return se(Mr,2)},"%w":Be=>Be.ub,"%W":Be=>se(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 Mr=0<=(Be=Be.ic);return Be=Math.abs(Be)/60,(Mr?"+":"-")+("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 Mr=Array(ip(Be)+1);return Oh(Be,Mr,0,Mr.length),Mr}(w=w.replace(/\0\0/g,"%")),Zt.length>h?0:(M_(Zt,o),Zt.length-1)}function v_(o,h,w,M){return bf(o>>>0,h>>>0,w>>>0,M>>>0)}D||function(){for(var o=l.numThreads-1;o--;)Eh();yi.unshift(()=>{Gn++,function(h){D?h():Promise.all(Ys.map($h)).then(h)}(()=>mc())})}();for(var Mf=Array(256),xc=0;256>xc;++xc)Mf[xc]=String.fromCharCode(xc);qh=Mf,Zs=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-lp.length;var x_=[np,vh,kh,Ih,Fh,zh,Dh,Lh,Bh,Rh,Nh,jh,Vh,Uh,Wh,Gh,af,of,pf,hf,ff,mf,_f,gf],Xt=function(){function o(w,M){return Xt=w.exports,Xt=function(){var S=Xt,se={};for(let[He,st]of Object.entries(S))se[He]=typeof st=="function"?(...It)=>{yc.push(He);try{return st(...It)}finally{Sn||(yc.pop(),ds&&ei===1&&yc.length===0&&(ei=0,bi+=1,wc(Pf),typeof Fibers<"u"&&Fibers.tc()))}}:st;return se}(),Xt=function(){var S=Xt,se=st=>It=>st(It)>>>0,He=st=>()=>st()>>>0;return(S=Object.assign({},S)).Ca=se(S.Ca),S.fb=He(S.fb),S.hb=se(S.hb),S.emscripten_main_runtime_thread_id=He(S.emscripten_main_runtime_thread_id),S.sb=se(S.sb),S.tb=He(S.tb),S}(),xh.push(Xt.ib),cn.unshift(Xt.Ba),Fr=M,mc(),Xt}var h=bh();if(Gn++,l.instantiateWasm)try{return l.instantiateWasm(h,o)}catch(w){Ht(`Module.instantiateWasm callback failed with error: ${w}`),m(w)}return Jc||(Jc=l.locateFile?_h("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(O("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),O.b).href),function(w,M){var S=Jc;return Ft||typeof WebAssembly.instantiateStreaming!="function"||_h(S)||gh(S)||typeof fetch!="function"?yh(S,w,M):fetch(S,{credentials:"same-origin"}).then(se=>WebAssembly.instantiateStreaming(se,w).then(M,function(He){return Ht(`wasm streaming compile failed: ${He}`),Ht("falling back to ArrayBuffer instantiation"),yh(S,w,M)}))}(h,function(w){o(w.instance,w.module)}).catch(m),{}}(),vf=o=>(vf=Xt.Ca)(o),xf=()=>(xf=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,se,He,st,It,Rt)=>(l._OrtCreateSessionOptions=Xt.Ga)(o,h,w,M,S,se,He,st,It,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,se)=>(l._OrtCreateTensor=Xt.Ra)(o,h,w,M,S,se),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,se,He,st)=>(l._OrtRun=Xt.bb)(o,h,w,M,S,se,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 Tc,lo=()=>(lo=Xt.fb)(),cs=l._free=o=>(cs=l._free=Xt.gb)(o),Cc=l._malloc=o=>(Cc=l._malloc=Xt.hb)(o),wp=(o,h,w,M,S,se)=>(wp=Xt.kb)(o,h,w,M,S,se),Tf=()=>(Tf=Xt.lb)(),Cf=(o,h,w,M,S)=>(Cf=Xt.mb)(o,h,w,M,S),yp=o=>(yp=Xt.nb)(o),$c=o=>($c=Xt.ob)(o),$f=()=>($f=Xt.pb)(),Ef=(o,h)=>(Ef=Xt.qb)(o,h),Ec=o=>(Ec=Xt.rb)(o),bp=o=>(bp=Xt.sb)(o),Mp=()=>(Mp=Xt.tb)(),kf=l.dynCall_ii=(o,h)=>(kf=l.dynCall_ii=Xt.vb)(o,h),Sf=o=>(Sf=Xt.wb)(o),Pf=()=>(Pf=Xt.xb)(),Af=o=>(Af=Xt.yb)(o),If=()=>(If=Xt.zb)();function Ff(){0Mp(),l.stackRestore=o=>Ec(o),l.stackAlloc=o=>bp(o),l.UTF8ToString=wn,l.stringToUTF8=ao,l.lengthBytesUTF8=ip,Qs=function o(){Tc||Ff(),Tc||(Qs=o)},Ff(),T}),Ie=ge,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&ge()}),Ne,tt,wt,mt,$t,ft,Lt,jt,Ot=U(()=>{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)},$t=(yn(),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,$t()];let r=await mt(Ne);return[r,$t(r)]},Lt=(Se(),B(at)).default,jt=async(r,n,i)=>[void 0,Lt]}),Fe,Oe,ct,Ut,sr,br,Nr,mr,kr=U(()=>{Ot(),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,D)=>{let V={numThreads:r};g?V.wasmBinary=g:(c||a)&&(V.locateFile=(A,ee)=>c??(a??ee)+A),l(V).then(A=>{ct=!1,Oe=!0,Fe=A,C(),m&&URL.revokeObjectURL(m)},A=>{ct=!1,Ut=!0,D(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.")}}),wr,$n,Ur,hs=U(()=>{kr(),wr=(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)}}}),Es,Kn=U(()=>{kr(),hs(),Es=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=wr(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=wr(s,n),c=wr(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}}}),ks,Ss,Ps,As,Is,ts=U(()=>{kr(),hs(),ks=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}`)}},Ss=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ps=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)},As=(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=wr("deviceType",r),d=wr(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=wr("preferredLayout",r),d=wr(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=wr(i,r);mr()._OrtAppendExecutionProvider(e,a)!==0&&Ur(`Can't append execution provider: ${i}.`)}},Is=e=>{let t=mr(),r=0,n=[],i=e||{};Ps(i);try{let a=ks(i.graphOptimizationLevel??"all"),s=Ss(i.executionMode??"sequential"),u=typeof i.logId=="string"?wr(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"?wr(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&&As(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=wr("enableGraphCapture",n),l=wr(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=wr(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=wr(m,n),x=wr(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}}}),Xn,An,Bn,fs,Ln,ms,_s,gs,Yt=U(()=>{Xn=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}`)}},Bn=(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},fs=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}`)}},ms=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",_s=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool",gs=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}`)}}}),rs,Fs=U(()=>{dr(),rs=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let 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)}}),Os,ws,zs,Ds,ns,Ls,ae,_=U(()=>{Yt(),Os=["V","I","W","E","F"],ws=(e,t)=>{console.log(`[${Os[e]},${new Date().toISOString()}]${t}`)},ns=(e,t)=>{zs=e,Ds=t},Ls=(e,t)=>{let r=Ln(e),n=Ln(zs);r>=n&&ws(r,typeof t=="function"?t():t)},ae=(...e)=>{Ds&&Ls(...e)}}),F,Q=U(()=>{Yt(),F=(e,t)=>new(fs(t))(e)}),oe=U(()=>{}),_e,Ge,gt,Et,Ct,zt,er,Sr,ur,Wr=U(()=>{_(),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,Et=e=>{for(let t=0;tCt++,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=zt();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=Et(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:zt(),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=U(()=>{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)}),mn,bn,Ee,tn,ln,In,Rn,Kt=U(()=>{mn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},bn=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=mn.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}},Ee=class kc{static size(t){return kc.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 kc.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 kc.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 Pd{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,Kr=(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=Kr(e,t);return typeof r=="string"?r:r[0]},Or=(e,t=1)=>{let r=Kr(e,t);return typeof r=="string"?r:r[1]},kt=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:Ee.computeStrides(r)})}),t},_r=e=>e%4===0?4:e%2===0?2:1,ss=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Qn=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Nn=(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,ri=(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=Kr(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.":"",D=`${C}${e}_shape`,V=`${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(V,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(",")})`,Ft=(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 nn=s-1;nn>=0;nn--){let an=vt.indicesGet("outputIndices",nn+vt.rank-s);Br.push(`${Ft(V,nn)} * (${an} % ${Ft(D,nn)})`)}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)}); + }`})(),Fr=(...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 ${D} = ${l.indices}(${r.join(",")});`,`const ${V} = ${l.indices}(${Ee.computeStrides(r).join(",")});`),qe.join(` +`)},type:l,offsetToIndices:te,indicesToOffset:Pe,broadcastedIndicesToOffset:nr,indices:Ye,indicesGet:Ft,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:Fr,getByOffset:Er,getByIndices:Gt,usage:n,name:e,strides:V,shape:D,rank:s}},Qe=(e,t,r,n=1)=>ri(e,t,r,"input",n),qt=(e,t,r,n=1)=>ri(e,t,r,"output",n),Ti=(e,t,r,n=1)=>ri(e,t,r,"internal",n),Ci=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])}},co=(e,t)=>new Ci(e,t),ys=(e,t)=>{let r=e.length,n=[];for(let i=0;i1&&s===1&&n.unshift(a)}return n}}),po,$i,is,ho,Id,xn,Fd,fo,jn=U(()=>{Yt(),Kt(),Pr(),pr(),po=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},$i=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,is=(e,t)=>Ee.sortBasedOnPerm(e,$i(e.length,t)),ho=(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=$i(n,t),a=is(e.dims,i),{newShape:s,newPerm:u}=Id(e.dims,i),d=Ee.areEqual(u,[2,3,1]),c=Ee.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,D;return g?D=V=>` + ${V.registerUniform("output_size","u32").declareVariables(T,x)} + var tile : array, ${C}>; + ${V.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]")} + } + }`:D=V=>` + ${V.registerUniform("output_size","u32").declareVariables(T,x)} + + ${ho(i,n,T,x)} + + ${V.mainStart()} + ${V.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 V=Ee.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(V/64)},programUniforms:[{type:12,data:V},...kt(m,l)]}},getShaderSource:D}},Fd=(e,t)=>{po(e.inputs),e.compute(xn(e.inputs[0],t.perm))},fo=e=>or({perm:e.perm})}),mo,_o,go,wo,yo,Ei,bo,Mo,ki,vo,Fn,Si,xo,To,Pi,Co,$o,Ai,Eo,ko,Ii,Od=U(()=>{Yt(),Kt(),pr(),Vi(),jn(),mo={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"},_o={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"},go={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},wo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},yo=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,i]},bo=(e,t)=>{let r=e.length+t.length,n=[],i=0;for(let a=0;a{for(let r=0;r{let r=[];if(!Mo(e,t)){for(let n=0;nr.push(n))}return r},vo=(e,t,r,n,i,a,s)=>{let u=r[0].dims,d=Ee.size(a),c=Ee.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(${go[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${l}) { + let candidate = f32(${g.getByOffset("offset + k")}); + bestValue = ${mo[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 = ${_o[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}(${wo[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:Oi(e.inputs,r),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((T,x)=>x));let s=Ee.normalizeAxes(a,e.inputs[0].dims.length),u=s,d=e.inputs[0],c=ki(u,e.inputs[0].dims.length);c.length>0&&(d=e.compute(xn(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],u=yo(u.length,d.dims.length));let[g,m]=Ei(d.dims,u),l=g;i.keepDims&&(l=bo(g,s)),e.compute(vo(t,{hint:i.cacheKey,inputDependencies:["type"]},[d],n,e.inputs[0].dataType,l,m),{inputs:[d]})},Si=(e,t)=>{Fn(e,"ReduceMeanShared",t,"mean")},xo=(e,t)=>{Fn(e,"ReduceL1Shared",t,"l1")},To=(e,t)=>{Fn(e,"ReduceL2Shared",t,"l2")},Pi=(e,t)=>{Fn(e,"ReduceLogSumExpShared",t,"logSumExp")},Co=(e,t)=>{Fn(e,"ReduceMaxShared",t,"max")},$o=(e,t)=>{Fn(e,"ReduceMinShared",t,"min")},Ai=(e,t)=>{Fn(e,"ReduceProdShared",t,"prod")},Eo=(e,t)=>{Fn(e,"ReduceSumShared",t,"sum")},ko=(e,t)=>{Fn(e,"ReduceSumSquareShared",t,"sumSquare")},Ii=(e,t)=>{Fn(e,"ReduceLogSumShared",t,"logSum")}}),On,Fi,ni,Oi,En,So,Po,zi,Ao,Io,Di,Fo,Oo,Li,zo,zn,Bi,Do,Lo,Ri,Bo,Ro,Ni,No,jo,ji,Vi=U(()=>{Yt(),Kt(),Pr(),pr(),Od(),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.")},Fi=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ni=(e,t,r,n,i,a,s=!1,u=!1)=>{let d=[],c=r[0].dims,g=c.length,m=Ee.normalizeAxes(i,g),l=!u&&m.length===0;c.forEach((C,D)=>{l||m.indexOf(D)>=0?s&&d.push(1):d.push(C)});let T=d.length,x=Ee.size(d);return{name:e,shaderCache:t,getShaderSource:C=>{let D=[],V=Qe("_A",r[0].dataType,g),A=qt("output",a,T),ee=n(V,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};`:""} + ${V.indicesSet("input_indices",ie,`j${ie}`)} + ${te} + }`):(D.push(`${V.indicesSet("input_indices",ie,A.indicesGet("output_indices",ke))};`),ke++);return` + + ${C.registerUniform("output_size","u32").declareVariables(V,A)} + + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${V.type.indices}; + let output_indices = ${A.offsetToIndices("global_idx")}; + + ${D.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},...kt(c,d)]})}},Oi=(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:Oi(i,r);e.compute(ni(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?Fi:n,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},So=(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);"])},Po=(e,t)=>{On(e.inputs),En(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},zi=(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);"])},Ao=(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);"])},Io=(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")});`,""]})},Di=(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});`]})},Fo=(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")});`,""]})},Oo=(e,t)=>{On(e.inputs),En(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Li=(e,t)=>{On(e.inputs),En(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},zo=(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},Bi=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Di(e,t):Si(e,t)},Do=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Po(e,t):xo(e,t)},Lo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zi(e,t):To(e,t)},Ri=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ao(e,t):Pi(e,t)},Bo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Io(e,t):Co(e,t)},Ro=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fo(e,t):$o(e,t)},Ni=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Oo(e,t):Ai(e,t)},No=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Li(e,t):Eo(e,t)},jo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zo(e,t):ko(e,t)},ji=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?So(e,t):Ii(e,t)}}),Ui,Wi,Vo,Gi,Uo=U(()=>{Yt(),Pr(),Vi(),Ui=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.")},Wi=(e,t)=>{Ui(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(ni("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Vo=(e,t)=>{Ui(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(ni("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Gi=e=>or(e)}),Wo,si,qi,Go,qo,bs,Ho,Ko,ii=U(()=>{Yt(),Kt(),oe(),pr(),Wo=(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 D=x+C,V=-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]!==D)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:D,maxSequenceLength:V,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}},si=(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; + `,qi=(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=Or(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; + ${V.registerUniforms(Pe).declareVariables(...ee)} + ${V.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; + ${si(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:D,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/c),y:i,z:t*r},programUniforms:l})}},Go=(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,D=_r(a.headSize),V=a.headSize/D,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:V},{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&&Ee.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=Ft=>{let Bt=Qe("q",t.dataType,t.dims,D),ar=Qe("key",r.dataType,r.dims,D),nr=[Bt,ar];if(ie){let Qt=Qe("past_key",n.dataType,n.dims,D);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,D));let Fr=Or(1,D),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}>; + ${Ft.registerUniforms(Gt).declareVariables(...nr,...hr)} + ${Ft.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; + ${si(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 = ${Fr}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${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 += ${Fr}(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(D){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: ${D}`)}})()}; + output[outputIdx] = ${jr.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${D};${i!==void 0};${n!==void 0};${e}`,inputDependencies:ke},getRunData:()=>({outputs:Pe,dispatchGroup:ee,programUniforms:te}),getShaderSource:Ye}},qo=(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,D={x:Math.ceil(i.vHeadSize/C),y:Math.ceil(i.sequenceLength/C),z:i.batchSize*i.numHeads},V=[{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&&Ee.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),Ft=[Pe,Ye];A&&Ft.push(Qe("past_value",n.dataType,n.dims));let Bt=s?Qe("seq_lens",s.dataType,s.dims):void 0;s&&Ft.push(Bt);let ar=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&Ft.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(...Ft,...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; + ${si(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:D,programUniforms:V}),getShaderSource:ie}},bs=(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&&Ee.size(d.dims)>0?d:void 0,D=[t,r];l>1&&s&&Ee.size(s.dims)>0&&D.push(s),C&&D.push(C),g&&D.push(g),m&&D.push(m);let V=e.compute(Go(l,t,r,s,C,c,T,g,m),{inputs:D,outputs:l>1?[-1,1]:[-1]})[0];e.compute(qi(V,c.batchSize,c.numHeads,T,c.sequenceLength,x,g,m),{inputs:g&&m?[V,g,m]:[V],outputs:[]});let A=[V,n];l>1&&u&&Ee.size(u.dims)>0&&A.push(u),g&&A.push(g),m&&A.push(m),e.compute(qo(l,V,n,u,c,T,g,m),{inputs:A,outputs:l>1?[0,2]:[0]})},Ho=(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),D=Qe("weight",d[1].dataType,d[1].dims),V=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,D,V,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]})},Ko=(e,t)=>{let r=Wo(e.inputs,t),[n,i,a]=Ho(e,r);return bs(e,n,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}}),Xo,Qo,Hi,Yo,zd=U(()=>{At(),Yt(),Kt(),Pr(),pr(),Xo=(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")},Qo=(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=Ee.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),D=qt("y",e[0].dataType,g,s),V=()=>{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=` + ${D.indicesSet("outputIndices","0","0")} + let cOffset = ${D.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,D)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${D.offsetToIndices(`global_idx * ${s}`)}; + ${V()} + 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; + ${D.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},...kt(a)]:[{type:12,data:d}]})}},Hi=e=>or(e),Yo=(e,t)=>{let{inputs:r,outputCount:n}=e,i=Hi({...t,outputCount:n});if(E.webgpu.validateInputContent&&Xo(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Qo(r,i))}}),Ki,Zo,Jo,el=U(()=>{Kt(),pr(),Ki=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")},Zo=e=>{let t=e[0].dims,r=e[0].dims[2],n=Ee.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")} + }`}},Jo=e=>{Ki(e.inputs),e.compute(Zo(e.inputs))}}),tl,vr,Xi,rl,nl,sl,il,Qi,al,ol,ll,ul,Yi,dl,cl,pl,Bs,Zi,ai,hl,Ji,fl,ml,ea,_l,gl,ta,wl,yl,ra,bl,Ml,oi,vl,xl,li,na,sa,ui,Tl,Cl,$l,ia,El,kl,aa=U(()=>{Yt(),Kt(),Pr(),pr(),tl=(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)} + }`},vr=(e,t,r,n,i,a=e.dataType,s,u)=>{let d=[{type:12,data:Math.ceil(Ee.size(e.dims)/4)}];return s&&d.push(...s),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:c=>tl(c,Ee.size(e.dims),e.dataType,a,r,n,u),getRunData:c=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Ee.size(c[0].dims)/64/4)},programUniforms:d})}},Xi=e=>{e.compute(vr(e.inputs[0],"Abs","abs"))},rl=e=>{e.compute(vr(e.inputs[0],"Acos","acos"))},nl=e=>{e.compute(vr(e.inputs[0],"Acosh","acosh"))},sl=e=>{e.compute(vr(e.inputs[0],"Asin","asin"))},il=e=>{e.compute(vr(e.inputs[0],"Asinh","asinh"))},Qi=e=>{e.compute(vr(e.inputs[0],"Atan","atan"))},al=e=>{e.compute(vr(e.inputs[0],"Atanh","atanh"))},ol=e=>or(e),ll=(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(vr(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},ul=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})},Yi=(e,t)=>{let r=t||ul(e.inputs),n=Or(e.inputs[0].dataType);e.compute(vr(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]})},dl=e=>{e.compute(vr(e.inputs[0],"Ceil","ceil"))},cl=e=>{e.compute(vr(e.inputs[0],"Cos","cos"))},pl=e=>{e.compute(vr(e.inputs[0],"Cosh","cosh"))},Bs=e=>or(e),Zi=(e,t)=>{let r=Or(e.inputs[0].dataType);e.compute(vr(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))},ai=(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)); +}`,hl=e=>{let t=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,ai(t)))},Ji=e=>{e.compute(vr(e.inputs[0],"Exp","exp"))},fl=e=>{e.compute(vr(e.inputs[0],"Floor","floor"))},ml=e=>{let t=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,ai(t)))},ea=(e,t)=>{let r=Or(e.inputs[0].dataType);e.compute(vr(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))},_l=e=>{e.compute(vr(e.inputs[0],"Not",t=>`!${t}`))},gl=e=>{e.compute(vr(e.inputs[0],"Neg",t=>`-${t}`))},ta=e=>{e.compute(vr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},wl=e=>{let t=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},yl=e=>{e.compute(vr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ra=e=>or(e),bl=(e,t)=>{let r=Or(e.inputs[0].dataType);e.compute(vr(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))},Ml=e=>{e.compute(vr(e.inputs[0],"Sin","sin"))},oi=e=>{e.compute(vr(e.inputs[0],"Sinh","sinh"))},vl=e=>{e.compute(vr(e.inputs[0],"Sqrt","sqrt"))},xl=e=>{e.compute(vr(e.inputs[0],"Tan","tan"))},li=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,na=e=>{e.compute(vr(e.inputs[0],"Tanh",li))},sa=(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 ${li("v")}; +} +`,ui=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Tl=e=>{let t=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"FastGelu",ui,sa(t),void 0,e.inputs[0].dataType))},Cl=(e,t)=>{let r=Or(e.inputs[0].dataType);return e.compute(vr(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},$l=e=>{e.compute(vr(e.inputs[0],"Log","log"))},ia=(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; +} +`,El=e=>`quick_gelu_impl(${e})`,kl=(e,t)=>{let r=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"QuickGelu",El,ia(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),oa,Sl,Pl,Al=U(()=>{Kt(),pr(),aa(),oa=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")},Sl=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=Ee.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)} + + ${ai(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")} + }`}},Pl=e=>{oa(e.inputs),e.compute(Sl(e.inputs))}}),Il,Fl,kn,Ol,zl,la,Dl,Ll,ua,Bl,Rl,da,Nl,Dd=U(()=>{Yt(),Kt(),pr(),Il=(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),D=Qe("bData",c,r.length,4),V;if(i)if(a){let A=Ee.size(t)===1,ee=Ee.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?V=x.setByOffset("global_idx",T(A?`${C.type.value}(${C.getByOffset("0")}.x)`:C.getByOffset("global_idx"),ee?`${D.type.value}(${D.getByOffset("0")}.x)`:D.getByOffset("global_idx"))):V=` + let outputIndices = ${x.offsetToIndices("global_idx * 4u")}; + let offsetA = ${C.broadcastedIndicesToOffset("outputIndices",x)}; + let offsetB = ${D.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?D.getByOffset("offsetB / 4u"):`${D.type.value}(${D.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else V=x.setByOffset("global_idx",T(C.getByOffset("global_idx"),D.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} = ${D.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?V=` + 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));`:V=` + ${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,D,x)} + + ${m??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${V} + }`},Fl=(e,t,r,n,i,a,s=r.dataType)=>{let u=!Ee.areEqual(r.dims,n.dims),d=r.dims,c=Ee.size(r.dims),g=!1,m=!1,l=[u];if(u){let T=bn.calcShape(r.dims,n.dims,!1);if(!T)throw new Error("Can't perform binary op on the given tensors");d=T,c=Ee.size(d);let x=Ee.size(r.dims)===1,C=Ee.size(n.dims)===1,D=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,V=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;l.push(x),l.push(C),l.push(D),l.push(V);let A=1;for(let ee=1;eeT.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:T=>Il(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(Ee.size(d)/4)},...kt(r.dims,n.dims,d)]})}},kn=(e,t,r,n,i,a)=>{e.compute(Fl(t,i??"",e.inputs[0],e.inputs[1],r,n,a))},Ol=e=>{kn(e,"Add",(t,r)=>`${t}+${r}`)},zl=e=>{kn(e,"Div",(t,r)=>`${t}/${r}`)},la=e=>{kn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Dl=e=>{kn(e,"Mul",(t,r)=>`${t}*${r}`)},Ll=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)); + } + `)},ua=e=>{kn(e,"Sub",(t,r)=>`${t}-${r}`)},Bl=e=>{kn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Rl=e=>{kn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},da=e=>{kn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Nl=e=>{kn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),jl,Vl,di,Ul,Wl,Gl,Ld=U(()=>{Yt(),Kt(),Pr(),pr(),jl=(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")})}})},Vl=(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; + }`,di=(e,t)=>{let r=e.length,n=[];for(let i=0;i{let i=Ee.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 D=0;D(${T}); + ${l} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${di(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}},Wl=(e,t)=>{let r=e.inputs,n=r[0].dims,i=Ee.normalizeAxis(t.axis,n.length);jl(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=>Ee.size(u.dims)>0);e.compute(Ul(s,i,a,r[0].dataType),{inputs:s})},Gl=e=>or({axis:e.axis})}),Yn,Vn,Zn,ca,Un=U(()=>{Yt(),Kt(),Yn=(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}`)}},Vn=(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})},Zn=(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"})},ca=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,Rn];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,pa,ci=U(()=>{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.`)}},pa=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),ha,fa=U(()=>{ha=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)); +} +`}),ql,Hl,Rs,ma,Kl,Ns,Xl,_a,js=U(()=>{Yt(),Kt(),pr(),Un(),ci(),ql=(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":""}); + `,Hl=(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];"} + }`,Rs=(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; + ${ql(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];"} + + ${Hl(i,l)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},ma=(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":""}); + `,Kl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ns=(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],D=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]}) { + ${ma(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; + ${ma(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) { + ${Kl(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>; + ${D} + } +`},Xl=(e,t,r,n,i,a=!1)=>{let[s,u,d]=i,[c,g,m,l]=n,T=ys(s,d),x=ys(u,d),C=fr(n[0].type.tensor),D=()=>{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},V=()=>{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) + { + ${D()} + 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) + { + ${V()} + 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")} + } + } + `},_a=(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=Ee.size(g),l=s[s.length-2],T=s[s.length-1],x=u[u.length-1],C=T%4===0&&x%4===0,D=l<=8?[4,1,1]:[4,4,1],V=[8,8,1],A=[Math.ceil(x/V[0]/D[0]),Math.ceil(l/V[1]/D[1]),Math.ceil(m/V[2]/D[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],Ft=[{type:6,data:l},{type:6,data:x},{type:6,data:T}];Vn(t,Ft),Ft.push(...kt(g,te,ke));let Bt=["rank","rank"],ar=e.length>2;ar&&(Ft.push(...kt(e[2].dims)),Bt.push("rank")),Ft.push(...kt(Ye));let nr=Ht=>{let Er=g.length,jr=Ti("batchDims",e[0].dataType,Er,1),hr=fr(e[0].dataType),Fr=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=[Fr,Gt];if(ar){let nn=i?ee:1;xr.push(Qe("bias",e[2].dataType,e[2].dims.length,nn))}let qe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Zn(t,qe);let vt=fr(Qt.type.tensor),rr=Yn(t,Qt.type.value,vt),Br=Xl(ee,ar,rr,[jr,Fr,Gt,Qt],[d,c,g],i);return` + ${Ht.registerUniforms(qe).registerInternalVariables(jr).declareVariables(...xr,Qt)} + ${Br} + ${C?Rs(D,V,hr,jr):Ns(D,V,hr,jr)} + `};return{name:"MatMul",shaderCache:{hint:`${D};${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:Ft}),getShaderSource:nr}}}),Ql,Yl,Bd=U(()=>{Yt(),_(),pr(),Un(),ci(),fa(),js(),Ql=(e,t,r,n,i=!1,a,s=4,u=4,d=4,c="f32")=>{let g=Ft=>{switch(Ft){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 ${Ft} is not supported.`)}},m=Ft=>{switch(Ft){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 ${Ft} 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])",D=e?"row":"col",V=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 = ${D} / outWidth; + let outCol = ${D} % outWidth; + + let WRow = ${V} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${V} / 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 = ${V} % 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=Yn(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} + ${pa(i)} + ${Ye} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Yl=(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,D=c?x:l*T,V=c?l*T:x,A=[8,8,1],ee=n<=8?[4,1,1]:[4,4,1],te=[Math.ceil(D/A[0]/ee[0]),Math.ceil(V/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]),Ft=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}];Vn(t,Ht),Ht.push(...kt(e[0].dims,e[1].dims));let Er=["rank","rank"];s&&(Ht.push(...kt(e[2].dims)),Er.push("rank")),Ht.push(...kt(r));let jr=hr=>{let Fr=[{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}];Zn(t,Fr);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 nn=Qe("bias",e[2].dataType,e[2].dims.length,Gt);rr.push(nn),xr+=` + fn getBiasByOutputCoords(coords : vec4) -> ${C?`vec4<${Qt}>`:Qt} { + return bias[coords.${c?"w":"y"}${C?"/ 4":""}]; + }`}return` + ${ha("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(Fr).declareVariables(...rr,Br)} + ${xr} + ${Ql(c,Ft,Bt,ar,s,t,nr[0],nr[1],nr[2],Qt)} + ${C?Rs(ee,A,Qt,void 0,!c,Ye):Ns(ee,A,Qt,void 0,!c,Ye,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${ie};${C};${Ft};${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}}}),Zl,ga,Vs,wa,ya,Jl,ba,eu,Rd=U(()=>{Yt(),_(),Kt(),pr(),Un(),ci(),Zl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Vs=(e,t)=>t<=1?e:e+(e-1)*(t-1),wa=(e,t,r,n=1)=>{let i=Vs(t,n);return Math.floor((e[0]*(r-1)-r+i)/2)},ya=(e,t,r,n,i)=>{i==null&&(i=wa(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},Jl=(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=ya([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,D,V)=>C===V[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=ya([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,D=(T-1)*s+c-n,V=Math.floor(x/2),A=x-V,ee=Math.floor(C/2),te=C-ee,ie=Math.floor(D/2),ke=D-ie;g={top:ee,bottom:te,left:ie,right:ke,front:V,back:A}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:g,outDepth:m,outHeight:l,outWidth:T}},ba=(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,[D,V,A]=ga(r),[ee,te,ie]=ga(n),ke=Vs(T,ee),Pe=Vs(x,te),Ye=Vs(C,ie),{padInfo:Ft,outDepth:Bt,outHeight:ar,outWidth:nr}=Jl(i,d,c,g,D,V,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:Ft,strideDepth:D,strideHeight:V,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}},eu=(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((D,V)=>V)},c=[Math.ceil(Zl(d.x.map(D=>r[D]))/u[0]),1,1];ae("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let g=1,m=Ee.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}];Vn(t,l),l.push(...kt(e[0].dims,e[1].dims));let T=["rank","rank"],x=e.length===3;x&&(l.push(...kt(e[2].dims)),T.push("rank")),l.push(...kt(r));let C=D=>{let V=[{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}];Zn(t,V);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 Ft=hn(g,ee),Bt=Yn(t,Ft,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")}; + } + ${D.registerUniforms(V).declareVariables(...ke,Pe)} + ${D.mainStart()} + ${D.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}}}),Jn,tu,Nd=U(()=>{Yt(),Kt(),pr(),Un(),Jn=(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=Ee.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}];Vn(t,T),T.push(...kt(s,[u[0],u[1],u[2],u[3]/m]));let x=i?["rank","rank","rank"]:["rank","rank"];T.push(...kt([r[0],r[1],r[2],r[3]/m]));let C=D=>{let V=qt("output",e[0].dataType,r.length,m),A=fr(V.type.tensor),ee=Yn(t,V.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"}];Zn(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` + ${D.registerUniforms(Pe).declareVariables(...ke,V)} + + ${D.mainStart()} + ${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${V.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: ${V.type.value} = ${V.type.value}(0); + ${Ye} + ${a} + ${ee} + ${V.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}},tu=(e,t,r,n)=>{let i=e.length>2,a=_r(r[3]),s=_r(r[2]),u=Ee.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]]}];Vn(t,m),m.push(...kt(d,c,g));let l=(s-1)*t.strides[1]+c[1],T=x=>{let C=qt("output",e[0].dataType,g.length,a),D=fr(C.type.tensor),V=Yn(t,C.type.value,D),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 Zn(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} + ${V} + ${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}}}),Ma,ru,va,nu=U(()=>{Yt(),Kt(),js(),pr(),Un(),Ma=(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=Ee.size(r)/m/T,C=e.length>2,D=n?n.slice(0,-2):r.slice(0,-2),V=[Ee.size(D),d,c],A=[{type:12,data:x},{type:12,data:d},{type:12,data:c},{type:12,data:g}];Vn(t,A),A.push(...kt(D,s,u)),C&&A.push(...kt(e[2].dims)),A.push(...kt(V));let ee=te=>{let ie=Ti("batch_dims",e[0].dataType,D.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,V.length,m),Ft=fr(Ye.type.tensor),Bt=Yn(t,Ye.type.value,Ft),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=ys(Ht,D),hr=ys(Er,D),Fr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Zn(t,Fr);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,nn=`var ${rr}_indices: ${xr.type.indices};`;for(let an=vt-2-1,Xs=Br-1;an>=0;an--,Xs--)nn+=` +${rr}_indices[${an}] = ${Br>1?`batch_indices[${Xs}]`:"batch_indices"};`;return qe.forEach(an=>{nn+=` +${rr}_indices[${an}] = 0;`}),nn+=`${rr}_indices[${vt-2}] = 0u; + ${rr}_indices[${vt-1}] = 0u;`,nn},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}},ru=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.")},va=e=>{ru(e.inputs);let t=bn.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(Ma(e.inputs,{activation:""},t)):e.compute(_a(e.inputs,{activation:""},t))}}),su,pi,iu,Ms,xa,Ta,au,Us,Ca,jd=U(()=>{Kt(),Bd(),Rd(),js(),Nd(),Un(),nu(),jn(),su=(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},pi=[2,3,1,0],iu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>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")},Ms=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=ca(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=su(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],pi),{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(tu(ke,r,a,n),{inputs:ke}):e.compute(Jn(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,Ft,Bt=[];if(i){let Ht=e.kernelCustomData.wT??e.compute(xn(t[1],pi),{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]),Ft=[1,ke,x]}else Pe=t[0].reshape([ke,u*d,c]),Ye=Ht.reshape([1,c,x]),Ft=[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]),Ft=[ke,x,l*T],Bt.push(Ye),Bt.push(Pe);s&&Bt.push(t[2]);let ar=Ft[2],nr=Bt[0].dims[Bt[0].dims.length-1];ar<8&&nr<8?e.compute(Ma(Bt,r,a,Ft,i,n),{inputs:Bt}):e.compute(_a(Bt,r,a,Ft,i,n),{inputs:Bt});return}let D=!0,V=e.kernelCustomData.wT??e.compute(xn(t[1],pi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=V);let A=[t[0],V];s&&A.push(t[2]);let ee=i?l*T:x,te=i?x:l*T,ie=g*m*c;e.compute(Yl(A,r,a,ee,te,ie,s,D,n),{inputs:A})},au=(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=Ms({...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]])},Us=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",i=Ms(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,s=ba(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(eu(t,i,s.outShape,[s.filterDepth,s.filterHeight,s.filterWidth],[s.padInfo.front,s.padInfo.top,s.padInfo.left],n))},Ca=(e,t)=>{if(iu(e.inputs,t),e.inputs[0].dims.length===3)au(e,t);else if(e.inputs[0].dims.length===5)Us(e,e.inputs,t);else{let r=Ms(t,e.inputs);Ta(e,e.inputs,r)}}}),ou,lu,$a=U(()=>{Yt(),_(),pr(),Un(),ci(),fa(),js(),ou=(e,t=!1,r,n,i=4)=>{let a=D=>{switch(D){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 ${D} 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=Yn(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} + ${pa(t)} + ${C} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value; + } + }`},lu=(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,D=d?m*l:T,V=[8,8,1],A=n<=8?[4,1,1]:[4,4,1],ee=[Math.ceil(C/V[0]/A[0]),Math.ceil(D/V[1]/A[1]),Math.ceil(g/V[2]/A[2])];ae("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ee}`);let te=x?4:1,ie=Math.max(V[0]*te,V[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))],Ft=[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:Ft}];Vn(t,Bt),Bt.push(...kt(e[0].dims,e[1].dims));let ar=["rank","rank"];s&&(Bt.push(...kt(e[2].dims)),ar.push("rank")),Bt.push(...kt(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),Fr=[Er,jr],Gt="";if(s){let qe=Qe("bias",e[2].dataType,e[2].dims.length,ke);Fr.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:Ft.length}];Zn(t,Qt);let xr=fr(e[0].dataType,1);if(xr!=="f16"&&xr!=="f32")throw new Error(`elemType ${xr} is not supported.`);return` + ${ha("uniforms.result_strides")} + ${Ht.registerUniforms(Qt).declareVariables(...Fr,hr)}; + ${Gt} + ${ou(d,s,t,Er.type.value,te)} + ${x?Rs(A,V,xr,void 0,!d,ie):Ns(A,V,xr,void 0,!d,ie,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${A};${V};${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}}}),uu,Ea,Vd=U(()=>{Yt(),_(),Kt(),pr(),uu=(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),D=Qe("Dy",t[0].dataType,t[0].dims.length,x),V=[D,C];n&&V.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 = ${D.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 = ${D.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 = ${D.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 = ${D.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?D.get("batch","idyR","idyC","inputChannel"):D.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(...V,A)} + ${T} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${a?ee:te}}`},Ea=(e,t,r)=>{let n=e.length>2,i=t.outputShape,a=Ee.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,D=e[1].dims,V=D[0]/C,A=D[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:V},{type:12,data:A},...kt(e[0].dims,e[1].dims)];n&&(ee.push(...kt(e[2].dims)),d.push("rank")),ee.push(...kt(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`${uu(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}}}),Ud,du,cu,ka,vs,pu,hu,fu,mu,_u,Sa=U(()=>{$a(),Vd(),Un(),jn(),Ud=(e,t,r,n,i,a)=>(e-1)*t+r+(n-1)*i+1-a,du=(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)},cu=(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)}cu(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},vs=e=>{let t=ca(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};`}},pu=(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")},hu=[2,3,1,0],fu=(e,t,r)=>{let n=ka(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(Ea(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,D=e.kernelCustomData.wT??e.compute(xn(t[1],hu),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=D);let V=[t[0],D],A=t.length===3;A&&(!i&&t[2].dims.length===1?V.push(t[2].reshape([t[2].dims[0],1,1])):V.push(t[2])),e.compute(lu(V,n,a,l,T,x,A,C),{inputs:V})},mu=(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=ka({...t,pads:u,strides:s,dilations:a,kernelShape:i},n);e.compute(Ea(n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]]))},_u=(e,t)=>{pu(e.inputs,t),e.inputs[0].dims.length===3?mu(e,t):fu(e,e.inputs,t)}}),Wd,gu,wu,Gd=U(()=>{Yt(),Kt(),Pr(),pr(),Wd=(e,t,r,n)=>{let i=Ee.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=Ee.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},...kt(t,t)]}),getShaderSource:g}},gu=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(Wd(n,r,i,t),{inputs:[0]})},wu=e=>{let t=e.exclusive===1,r=e.reverse===1;return or({exclusive:t,reverse:r})}}),yu,bu,Pa,Mu,vu,xu=U(()=>{Yt(),Kt(),Pr(),pr(),yu=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.")},bu=(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),D=V=>` + ${V.registerUniform("output_size","u32").declareVariables(x,C)} + + ${bu(u,l,x,C)} + + ${V.mainStart()} + ${V.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:V=>{let A=d?[r,n*c,i*c,a/c**2]:[r,a/c**2,n*c,i*c],ee=Ee.size(A),te=m.dims,ie=Ee.sortBasedOnPerm(te,u);return{outputs:[{dims:A,dataType:V[0].dataType}],dispatchGroup:{x:Math.ceil(ee/64)},programUniforms:[{type:12,data:ee},...kt(te,ie)]}},getShaderSource:D}},Mu=(e,t)=>{yu(e.inputs),e.compute(Pa(e.inputs[0],t))},vu=e=>or({blocksize:e.blocksize,mode:e.mode,format:e.format})}),hi,Ws,fi,Tu,Cu,mi,$u,Aa,Eu,ku,Ia,Fa=U(()=>{Yt(),Kt(),Pr(),pr(),hi="[a-zA-Z]|\\.\\.\\.",Ws="("+hi+")+",fi="^"+Ws+"$",Tu="("+Ws+",)*"+Ws,Cu="^"+Tu+"$",mi=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)}},$u=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(Cu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,s)=>{let u=e[s].dims.slice();if(!a.match(RegExp(fi)))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(Ws)))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(fi))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(hi,"g")),c=new mi(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",Eu=(e,t,r,n)=>{let i=e.map(c=>c.length).map((c,g)=>Qe(`input${g}`,t,c)),a=Ee.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=[],D=[],V=[],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,Ft)=>{if(te.inputIndices.includes(Ft)){let Bt=Ye.symbolToIndices.get(ie);if(Bt===void 0)throw new Error("Invalid symbol error");Bt.forEach(ar=>{g.push(`${i[Ft].indicesSet(`input${Ft}Indices`,ar,s.indicesGet("outputIndices",Pe))}`)})}})}else r.lhs.forEach((Pe,Ye)=>{if(te.inputIndices.includes(Ye)){let Ft=Pe.symbolToIndices.get(ie);if(Ft===void 0)throw new Error("Invalid symbol error");Ft.forEach(Bt=>{x.push(`${i[Ye].indicesSet(`input${Ye}Indices`,Bt,`${ie}`)}`)}),V.push(`prod *= ${i[Ye].getByIndices(`input${Ye}Indices`)};`)}}),C.push(`for(var ${ie}: u32 = 0; ${ie} < uniforms.${Aa(ie)}; ${ie}++) {`),D.push("}")});let ee=A?[...g,`let sum = ${i.map((te,ie)=>te.getByIndices(`input${ie}Indices`)).join(" * ")};`]:[...g,l,...C,...x,m,...V,T,...D];return` + ${c.registerUniforms(u.map(te=>({name:`${Aa(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)=>[...kt(m)]).reduce((m,l)=>m.concat(l),c);return g.push(...kt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:g}},getShaderSource:d}},ku=(e,t)=>{let r=new $u(e.inputs,t.equation),n=r.outputDims,i=e.inputs.map((a,s)=>a.dims);e.compute(Eu(i,e.inputs[0].dataType,r,n))},Ia=e=>{let t=e.equation.replace(/\s+/g,"");return or({equation:t})}}),qd,Oa,Su,za,Pu,Hd=U(()=>{Yt(),Kt(),pr(),qd=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?Oa(e,t):Oa(t,e),za=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Su(t,r),i=e[0].dataType,a=i===9?4:1,s=Math.ceil(Ee.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,D="")=>` + 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}] = ${D}(${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},...kt(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})}},Pu=e=>{qd(e.inputs),e.compute(za(e.inputs),{inputs:[0]})}}),Da,Au,Kd=U(()=>{Yt(),Kt(),pr(),aa(),Da=e=>{let t=e[0].dataType,r=Ee.size(e[0].dims),n=Ee.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)} + + ${sa(Or(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",ui("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)}})}},Au=e=>{e.inputs.length<2||Ee.size(e.inputs[1].dims)===0?Tl(e):e.compute(Da(e.inputs))}}),La,Xd,Qd,Ba,Iu=U(()=>{Yt(),Kt(),Pr(),pr(),La=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Xd=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,a=Ee.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(Ee.size(s)/d),g=[{type:12,data:c},{type:6,data:u},{type:12,data:a},...kt(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),D=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},V;if(e[0].dataType===9){let A=(ee,te,ie="")=>` + let outputIndices${te} = ${C.offsetToIndices(`outputOffset + ${te}u`)}; + ${D(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}]); + `;V=` + 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 V=` + let outputIndices = ${C.offsetToIndices("global_idx")}; + ${D("")}; + 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")} + ${V} + }`};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}},Qd=e=>or({axis:e.axis}),Ba=(e,t)=>{let r=e.inputs;La(r),e.compute(Xd(e.inputs,t))}}),Fu,Ou,Ra,zu,Yd=U(()=>{Yt(),Kt(),Pr(),pr(),Fu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=Ee.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.")}},Ou=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,a=Ee.normalizeAxis(t.gatherAxis,i),s=Ee.normalizeAxis(t.quantizeAxis,i),u=r.slice(0);u.splice(a,1,...n);let d=Ee.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},...kt(...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),D=Qe("scales",e[2].dataType,e[2].dims.length),V=e.length>3?Qe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,A=qt("output",c,u.length),ee=[x,C,D];V&&ee.push(V);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 = ${D.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${D.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${D.getByIndices("scale_indices")}; + ${V?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${V.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${V.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 = ${Or(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}},Ra=(e,t)=>{let r=e.inputs;Fu(r,t),e.compute(Ou(e.inputs,t))},zu=e=>or({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Na,Du,Lu,ja,Zd=U(()=>{Yt(),Kt(),Pr(),pr(),Na=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.`)},Du=(e,t)=>{let r=e[0].dims,n=e[0].dataType,i=r.length,a=e[1].dims,s=e[1].dataType,u=Ee.normalizeAxis(t.axis,i),d=r[u],c=a.slice(0),g=Ee.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(...kt(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")}; + }`}},Lu=e=>or({axis:e.axis}),ja=(e,t)=>{let r=e.inputs;Na(r),e.compute(Du(e.inputs,t))}}),Bu,Ru,Nu,zr,Ic=U(()=>{Yt(),Kt(),pr(),Bu=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")},Ru=(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=Ee.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(...kt(e[2].dims)),g.push("rank")),c.push(...kt(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),D=Qe("b",e[1].dataType,e[1].dims),V=C.type.value,A=null,ee=[C,D];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 = ${V}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${T} + } + + ${x} + ${A!=null?`let cOffset = ${A.broadcastedIndicesToOffset("vec2(m, n)",te)}; value += ${V}(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}},Nu=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}`}},zr=(e,t)=>{Bu(e.inputs),e.compute(Ru(e.inputs,t))}}),Mn,Jd,Va,Ua,ju,Gs,Vu,Wa=U(()=>{Yt(),Kt(),Pr(),oe(),ii(),pr(),jn(),Mn=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Jd=(e,t)=>{let r=e[0],n=Mn(e,1),i=Mn(e,2),a=Mn(e,3),s=Mn(e,4),u=Mn(e,5),d=Mn(e,6),c=Mn(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,D=Math.floor(l/t.numHeads);if(d&&c&&Ee.size(d.dims)&&Ee.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]!==D)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]!==D)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&&Ee.size(d.dims)||c&&Ee.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let V;if(n&&Ee.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)');V=2,T=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==D)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.');V=5,T=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==D)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');V=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');V=3}if(a&&Ee.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&&Ee.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&&Ee.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&&Ee.size(s.dims)>0)throw new Error("Key padding mask is not supported");if(u&&Ee.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:D,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:V}},Va=e=>or({...e}),Ua=or({perm:[0,2,1,3]}),ju=(e,t,r,n,i,a,s)=>{let u=[n,i,a],d=Ee.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]},Gs=(e,t,r,n,i,a,s,u)=>{let d=a;if(s&&Ee.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=ju(e,a,s,t,n,r*i,u),d=d.reshape([t,n,r,i]),r===1||n===1?d:e.compute(xn(d,Ua.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,Ua.perm),{inputs:[d],outputs:[-1]})[0]},Vu=(e,t)=>{let r=Jd(e.inputs,t),n=e.inputs[0],i=Mn(e.inputs,1),a=Mn(e.inputs,2),s=Mn(e.inputs,3),u=Mn(e.inputs,4),d=Mn(e.inputs,5),c=Mn(e.inputs,6),g=Mn(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=Gs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,s,0);if(m)return bs(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=Gs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,s,r.hiddenSize),x=Gs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,s,2*r.hiddenSize);bs(e,l,T,x,u,void 0,c,g,d,r)}}),Ga,Uu,Wu,qa,Gu,ec,qu,Hu=U(()=>{Yt(),Kt(),Pr(),pr(),Ga=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Uu=(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})},Wu=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; +}`,qa=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=Ee.size(r),i=e[0].dataType,a=Ee.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)} + ${Wu(d.length)} + ${qa(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})}},ec=(e,t)=>{Ga(e.inputs);let r=e.inputs.length===1?t:Uu(e.inputs,t);e.compute(Gu(e.inputs,r),{inputs:[0]})},qu=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})}}),Ku,Xu,Ha,Qu,tc=U(()=>{Pr(),ii(),Wa(),Hu(),jn(),Ku=(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,D=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&&D){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||D)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let V=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');V=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:V}},Xu=or({perm:[0,2,1,3]}),Ha=(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,Xu.perm),{inputs:[n],outputs:[-1]})[0]),n},Qu=(e,t)=>{var D;let r=Ku(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((D=e.inputs[1])==null?void 0:D.dims.length)===5)throw new Error("Packed KV is not implemented");let n=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(Gu([n],m),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,a],C=Gs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,l,void 0,0);bs(e,C,Ha(e,T,r),Ha(e,x,r),void 0,void 0,s,u,void 0,r,d,c)}}),Ka,Yu,Zu,Ju,rc=U(()=>{Yt(),Kt(),jn(),pr(),Ka=(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(...kt(l,T));let D=V=>{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; + ${V.declareVariables(...ke)} + ${V.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 = ${Nn("workgroup_shared[0][0]",d)} / f32(hight * ${d}); + let squared_sum_final = ${Nn("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:D},{inputs:[t,r,n],outputs:[-1]})[0]},Yu=(e,t,r)=>{let n=t[0].dims,i=n,a=2,s=n[0],u=n[1],d=Ee.sizeFromDimension(n,a),c=_r(d),g=Ee.size(i)/c,m=Ka(e,t[0],t[1],t[2],s,d,u,r.epsilon),l=[s,u,d/c],T=[s,u],x=["type","none"],C=D=>{let V=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=[V,A,ee];return` + ${D.registerUniform("output_size","u32").declareVariables(...te)} + ${D.mainStart()} + ${D.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 = ${V.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},...kt(l,T,l)]}),getShaderSource:C},{inputs:[t[0],m]})},Zu=(e,t,r)=>{let n=t[0].dims,i=n,a=n[0],s=n[n.length-1],u=Ee.sizeFromDimension(n,1)/s,d=_r(s),c=Ee.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 D=0;D{let V=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`${V}(${Ye}(scale.${Pe}))`;case 2:return`vec2<${V}>(${Ye}(scale[0].${Pe}, scale[1].${Pe}))`;case 4:return`vec4<${V}>(${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; + + ${D.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]})},Ju=(e,t)=>{t.format==="NHWC"?Zu(e,e.inputs,t):Yu(e,e.inputs,t)}}),ed,td,rd,nc=U(()=>{Yt(),Kt(),pr(),ed=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},td=(e,t,r)=>{let n=t.simplified,i=e[0].dims,a=e[1],s=!n&&e[2],u=i,d=Ee.normalizeAxis(t.axis,i.length),c=Ee.sizeToDimension(i,d),g=Ee.sizeFromDimension(i,d),m=Ee.size(a.dims),l=s?Ee.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)),V&&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 = ${ss("f32",x)}; + var mean_square_vector = ${ss("f32",x)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Qn(ke,x,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Nn("mean_vector",x)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Nn("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 = ${Qn(ke,x,"x[j + offset]")}; + let f32scale = ${Qn(ke,x,"scale[j]")}; + output[j + offset] = ${Pe[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${s?`+ ${Qn(ke,x,"bias[j]")}`:""} + ); + } + + ${V?"mean_data_output[global_idx] = mean":""}; + ${A?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},te=[{dims:u,dataType:e[0].dataType}];return V&&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:D}),getShaderSource:ee}},rd=(e,t)=>{ed(e.inputs),e.compute(td(e.inputs,t,e.outputCount))}}),nd,sc,Xa,sd,id,ic=U(()=>{Yt(),Kt(),Pr(),pr(),nd=(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(!Ee.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(Ee.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(Ee.size(d)!==c)throw new Error("zeroPoints input size error.")}},sc=(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=Ee.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,D=Ee.size(x)/T/C,V=64,A=[],ee=[d,i,a/m],te=Ee.convertShape(e[1].dims).slice();te.splice(-1,1,c/l),A.push(...kt(ee)),A.push(...kt(te)),A.push(...kt(e[2].dims)),e.length===4&&A.push(...kt(Ee.convertShape(e[3].dims)));let ie=[d,i,s/T];A.push(...kt(ie));let ke=Pe=>{let Ye=ee.length,Ft=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=[Ft,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),Fr=(()=>{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 = ${Ft.indicesToOffset(`${Ft.type.indices}(batch, row, word_offset)`)}; + var a_data: ${Fr}; + for (var j: u32 = 0; j < ${8/m}; j++) { + a_data[j] = ${Ft.getByOffset("input_offset")}; + input_offset++; + } + `;for(let vt=0;vt> 4) & b_mask); + b_quantized_values = ${Fr}(${Array.from({length:4},(rr,Br)=>`${hr}(b_value_lower[${Br}]), ${hr}(b_value_upper[${Br}])`).join(", ")}); + b_dequantized_values = ${m===1?`${Fr}(${Array.from({length:8},(rr,Br)=>`(b_quantized_values[${Br}] - ${Ht?`zero_point${vt}`:"zero_point"}) * scale${vt}`).join(", ")});`:`(b_quantized_values - ${Fr}(${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: ${Fr}; + var b_dequantized_values: ${Fr};`,qe};return` + var workgroup_shared: array<${jr.type.value}, ${C*V}>; + ${Pe.declareVariables(...nr,jr)} + ${Pe.mainStart([V,1,1])} + let output_indices = ${jr.offsetToIndices(`(global_idx / ${V}) * ${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 += ${V}) { + //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 < ${V}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};${V}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:x,dataType:g}],dispatchGroup:{x:D},programUniforms:A}),getShaderSource:ke}},Xa=(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=Ee.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,D=x/C,V=D*l*8,A=V/m,ee=V/t.blockSize,te=Ee.size(T)/C,ie=[],ke=[d,i,a/m],Pe=Ee.convertShape(e[1].dims).slice();Pe.splice(-1,1,c/l),ie.push(...kt(ke)),ie.push(...kt(Pe)),ie.push(...kt(e[2].dims)),e.length===4&&ie.push(...kt(Ee.convertShape(e[3].dims)));let Ye=[d,i,s];ie.push(...kt(Ye));let Ft=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 Fr=Ye.length,Gt=qt("output",e[0].dataType,Fr),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([D,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 < ${D}; 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};${D};${C}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:T,dataType:g}],dispatchGroup:{x:te},programUniforms:ie}),getShaderSource:Ft}},sd=(e,t)=>{nd(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Xa(e.inputs,t)):e.compute(sc(e.inputs,t))},id=e=>or(e)}),ad,od,ld,ud,dd,cd,pd,hd,fd,ac=U(()=>{Yt(),Kt(),pr(),ad=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].")}},od=(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]; + } + `},ld=(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]; + `},ud=(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]; + `},dd=(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]; + `},cd=(e,t,r)=>{switch(r.mode){case 0:return od(e,t,r.pads.length);case 1:return ld(e,t,r.pads.length);case 2:return ud(e,t,r.pads.length);case 3:return dd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},pd=(e,t)=>{let r=Ee.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=Ee.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(...kt(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=cd(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(Ee.size(r)/64)},programUniforms:a}),getShaderSource:d}},hd=(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},fd=(e,t)=>{ad(e.inputs);let r=hd(e.inputs,t);e.compute(pd(e.inputs,r),{inputs:[0]})}}),qs,Qa,Ya,Za,Ja,md,_d,eo,to,gd,wd,ro,yd,bd,Md,cr,vd,sn,un,_n=U(()=>{At(),Yt(),Kt(),pr(),qs=e=>{if(E.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Qa=(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]},Ya=(e,t)=>{let r=t.format==="NHWC",n=Ee.size(e),i=Ee.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],D=t.pads[t.pads.length-2];l=!!(C+D),a.push({type:12,data:T},{type:12,data:x},{type:12,data:C},{type:12,data:D}),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=Ee.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]}},Za=(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="",D="",V="",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?D=` + 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; + } + `:D=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ee}] = indices[${ee}] * uniforms.sh - uniforms.phStart + j; + `,V=` + } + `}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; + ${D} + ${C} + ${V} + ${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,D=i.pads.length,V="";return c?V=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:V=` + } + 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",D)}; + ${V} + } + ${s} + + output[global_idx] = value; + }`}},Ja=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,md=e=>`${Ja(e)};${e.countIncludePad}`,_d=e=>`${Ja(e)};${e.storageOrder};${e.dilations}`,eo=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}),to=(e,t,r,n)=>{let[i,a]=Qa(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]=Ya(a,i);g.push(...kt(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(Ee.size(a)/64)},programUniforms:g}),getShaderSource:D=>Za(D,s,t.dims.length,a.length,i,d,c,0,m,l,T,x)}},gd=e=>{let t=e.count_include_pad!==0,r=eo(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:md(n)}},wd=(e,t)=>{qs(e.inputs),e.compute(to("AveragePool",e.inputs[0],!1,t))},ro={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},yd=e=>{let t=e.format;return{format:t,...ro,cacheKey:t}},bd=(e,t)=>{qs(e.inputs),e.compute(to("GlobalAveragePool",e.inputs[0],!0,t))},Md=(e,t,r,n)=>{let[i,a]=Qa(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]=Ya(a,i);return g.push(...kt(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(Ee.size(a)/64)},programUniforms:g}),getShaderSource:C=>Za(C,d,t.dims.length,a.length,i,s,u,t.dataType===10?-65504:-1e5,m,l,T,x)}},cr=(e,t)=>{qs(e.inputs),e.compute(Md("MaxPool",e.inputs[0],!1,t))},vd=e=>{let t=e.storage_order,r=e.dilations,n=eo(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:_d(i)}},sn=e=>{let t=e.format;return{format:t,...ro,cacheKey:t}},un=(e,t)=>{qs(e.inputs),e.compute(Md("GlobalMaxPool",e.inputs[0],!0,t))}}),as,oc,xd,Td,f=U(()=>{Yt(),Kt(),Pr(),pr(),as=(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)].")}},oc=(e,t)=>{let r=Ee.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,a=e[0].dims,s=e[1].dataType,u=Ee.size(a),d=n===3||n===2,c=d?[Math.ceil(Ee.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(Ee.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),D=T&&(!d||C===4),V=D?C:1,A=D&&!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,V),Pe=[ee,te];ie&&Pe.push(ie);let Ye=[c,g];m&&Ye.push(l);let Ft=[{type:12,data:u/V},{type:12,data:r},{type:12,data:t.blockSize},...kt(...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 = ${V===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/V/64),y:1,z:1},programUniforms:Ft})}},xd=(e,t)=>{as(e.inputs,t),e.compute(oc(e.inputs,t))},Td=e=>or({axis:e.axis,blockSize:e.blockSize})}),b,R,ve,Ue=U(()=>{At(),Yt(),pr(),b=(e,t,r)=>{let n=e===t,i=et&&r>0;if(n||i||a)throw new Error("Range these inputs' contents are invalid.")},R=(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},...kt(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})}},ve=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&&b(t,r,n),e.compute(R(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),Le,pt,St,Vt,tr,Ar,Dr,yr,ir,Ir,$r,gr,Lr,Tn,dn,Gr,Xr,Qr,gn,os=U(()=>{Yt(),Kt(),Pr(),pr(),Le=(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")}},pt=(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},St=(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");Le(n,t),t.axes.length>0&&pt(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")},Vt=(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`)}})()+"}",tr=(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`)}})()+"}",Ar=(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},Dr=(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},yr=(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},ir=(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; + }`,Ir=(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; + }`,$r=(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; + }`,gr=(e,t,r,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",r,"batch")}; +`:"",Lr=(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))`)}; + ${gr(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); + }`},Tn=(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 D=C===m?"row":"col";return` + fn ${D}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 ${D}: ${T} = originalIdx + ${T}(i); + if (${D} < 0 || ${D} >= ${r[C]}) { + ${c?`coefs[i + 1] = 0.0; + continue;`:u?`return ${d};`:`${D} = max(0, min(${D}, ${r[C]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",C,`u32(${D})`)}; + 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); + } + `},dn=(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))`)}; + ${gr(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); + }`},Gr=(e,t,r,n,i,a)=>{let s=e.dims,u=Ar(a,t.axes,s.length),d=Dr(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=yr(s,c,t)));let g=qt("output",e.dataType,d.length),m=Qe("input",e.dataType,s.length),l=Ee.size(d),T=s.length===d.length&&s.every((A,ee)=>A===d[ee]),x=t.coordinateTransformMode==="tf_crop_and_resize",C=t.extrapolationValue,D=m.type.value,V=A=>` + ${T?"":` + ${Vt(t.coordinateTransformMode,D)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${$r(m,s)}; + ${tr(t.nearestMode,r,D)}; + ${Ir(m,g,s,d,c.length,u.length,x)}; + `;case"linear":return` + ${ir(g,s,d,c.length,u.length)}; + ${(()=>{if(s.length===2||s.length===4)return`${Lr(m,g,s,x,C)}`;if(s.length===3||s.length===5)return`${dn(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`${Tn(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:V,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},...kt(s,d)]})}},Xr=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Qr=(e,t)=>{let r=[],n=[],i=[],a=Xr(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");St(e.inputs,t,a,r,n,i),e.compute(Gr(e.inputs[0],t,a,r,n,i),{inputs:[0]})},gn=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})}}),_i,no,Fc,Wn=U(()=>{Yt(),Kt(),Pr(),pr(),_i=(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(!Ee.areEqual(n.dims,[])&&!Ee.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(!Ee.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=Ee.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")},no=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:i,scale:a}=t,s=e[0].dims[0],u=Ee.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=Ee.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]}):[],...kt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],C=D=>{let V=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 D.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}]),` + ${D.declareVariables(V,A,ee,te,ie)} + + ${D.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]; + ${D.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 = ${V.getByOffset("i")} * ${ee.get("position_id","bsnh[3]")} - + ${V.getByOffset("j")} * ${te.get("position_id","bsnh[3]")}; + ${ie.setByOffset("i","re")} + let im = ${V.getByOffset("i")} * ${te.get("position_id","bsnh[3]")} + + ${V.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",V.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(Ee.size(l)/pn)},programUniforms:x})}},Fc=(e,t)=>{_i(e.inputs,t),e.compute(no(e.inputs,t))}}),xs,lc,uc,Oc=U(()=>{Yt(),Kt(),pr(),xs=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")}},lc=(e,t,r,n)=>{let i=t.simplified,a=e[0].dims,s=Ee.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,D=64,V=_r(c),A=[{type:12,data:d},{type:12,data:V},{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,V),Qe("skip",e[1].dataType,e[1].dims,V),Qe("gamma",e[2].dataType,e[2].dims,V)];m&&Pe.push(Qe("beta",e[3].dataType,e[3].dims,V)),l&&Pe.push(Qe("bias",e[4].dataType,e[4].dims,V)),Pe.push(qt("output",e[0].dataType,u,V)),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,V));let Ye=fr(e[0].dataType),Ft=fr(1,V);return` + + ${ie.registerUniforms(ke).declareVariables(...Pe)} + var sum_shared : array<${Ft}, ${D}>; + var sum_squared_shared : array<${Ft}, ${D}>; + + ${ie.mainStart([D,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${D}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${D}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${D-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 = ${Qn(Ye,V,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${D}; + 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 = ${Nn("sum",V)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Nn("square_sum",V)} / 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:`${V};${T};${x};${C}`,inputDependencies:e.map((ie,ke)=>"type")},getShaderSource:ee,getRunData:()=>({outputs:te,dispatchGroup:{x:Math.ceil(d/c)},programUniforms:A})}},uc=(e,t)=>{xs(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(lc(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Cd,$d,Cp,zc,$p,Ep,kp,Sp,Hf=U(()=>{Yt(),Kt(),Pr(),pr(),Cd=(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},Cp=(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},zc=(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]]))},$p=(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; + }`,Ep=(e,t)=>{let r=e[0].dims,n=Ee.size(r),i=t.axes.length>0?Ee.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=$d(e,4);a.forEach(V=>V!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let s=t.starts.map((V,A)=>zc(V,A,r,i,a)),u=t.ends.map((V,A)=>zc(V,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 V=0;VMath.sign(V));a.forEach((V,A,ee)=>{if(V<0){let te=(u[A]-s[A])/V,ie=s[A],ke=ie+te*a[A];s[A]=ke,u[A]=ie,ee[A]=-V}});let c=r.slice(0);i.forEach((V,A)=>{c[V]=Math.ceil((u[V]-s[V])/a[V])});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=Ee.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},...kt(e[0].dims,c)],D=V=>` + ${V.registerUniforms(x).declareVariables(l,m)} + ${$p(l,m,r)} + ${V.mainStart()} + ${V.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:D,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:C})}},kp=(e,t)=>{Cd(e.inputs,t);let r=Cp(e.inputs,t);e.compute(Ep(e.inputs,r),{inputs:[0]})},Sp=e=>{let t=e.starts,r=e.ends,n=e.axes;return or({starts:t,ends:r,axes:n})}}),Pp,Ap,Ip,Fp,Kf=U(()=>{Yt(),Kt(),Pr(),jn(),pr(),Pp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Ap=(e,t)=>{let r=e.inputs[0],n=r.dims,i=Ee.size(n),a=64,s=n.length,u=Ee.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,D=(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,V=Qe("x",c.dataType,c.dims,x),A=qt("result",c.dataType,c.dims,x),ee=V.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(V,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}(${D("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}(${Nn("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]})},Ip=(e,t)=>{Pp(e.inputs),Ap(e,t)},Fp=e=>or({axis:e.axis})}),Dc,Op,zp,Dp,Lp,Xf=U(()=>{Yt(),Kt(),pr(),Dc=e=>Array.from(e.getBigInt64Array(),Number),Op=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(Dc(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")},zp=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Dc(e[1]),i=zp(r,n),a=Ee.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},...kt(e[0].dims,i)]}),getShaderSource:c}},Lp=e=>{Op(e.inputs),e.compute(Dp(e.inputs),{inputs:[0]})}}),Bp,Rp,Np,Qf=U(()=>{Yt(),Kt(),pr(),Bp=(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}]`,D=`b_data[index_b${T}][component_b${T}]`,V=`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,D,V)}); + `};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} + }`},Rp=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,i=e[1].dataType,a=!(Ee.areEqual(t,r)&&Ee.areEqual(r,n)),s=t,u=Ee.size(t);if(a){let c=bn.calcShape(bn.calcShape(t,r,!1),n,!1);if(!c)throw new Error("Can't perform where op on the given tensors");s=c,u=Ee.size(s)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Bp(c,e,s,a,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...kt(n,t,r,s)]})}},Np=e=>{e.compute(Rp(e.inputs))}}),jp,Yf=U(()=>{Uo(),ii(),zd(),el(),Al(),Dd(),Ld(),jd(),Sa(),Gd(),xu(),Fa(),Hd(),Kd(),Iu(),Yd(),Zd(),Ic(),tc(),rc(),nc(),nu(),ic(),Wa(),ac(),_n(),f(),Ue(),Vi(),os(),Wn(),Oc(),Hf(),Kf(),Hu(),Xf(),jn(),aa(),Qf(),jp=new Map([["Abs",[Xi]],["Acos",[rl]],["Acosh",[nl]],["Add",[Ol]],["ArgMax",[Vo,Gi]],["ArgMin",[Wi,Gi]],["Asin",[sl]],["Asinh",[il]],["Atan",[Qi]],["Atanh",[al]],["Attention",[Ko]],["AveragePool",[wd,gd]],["BatchNormalization",[Yo]],["BiasAdd",[Jo]],["BiasSplitGelu",[Pl]],["Cast",[ll,ol]],["Ceil",[dl]],["Clip",[Yi]],["Concat",[Wl,Gl]],["Conv",[Ca,xa]],["ConvTranspose",[_u,vs]],["Cos",[cl]],["Cosh",[pl]],["CumSum",[gu,wu]],["DepthToSpace",[Mu,vu]],["DequantizeLinear",[xd,Td]],["Div",[zl]],["Einsum",[ku,Ia]],["Elu",[Zi,Bs]],["Equal",[la]],["Erf",[hl]],["Exp",[Ji]],["Expand",[Pu]],["FastGelu",[Au]],["Floor",[fl]],["FusedConv",[Ca,xa]],["Gather",[Ba,Qd]],["GatherElements",[ja,Lu]],["GatherBlockQuantized",[Ra,zu]],["Gelu",[ml]],["Gemm",[zr,Nu]],["GlobalAveragePool",[bd,yd]],["GlobalMaxPool",[un,sn]],["Greater",[Bl]],["GreaterOrEqual",[da]],["GroupQueryAttention",[Qu]],["HardSigmoid",[bl,ra]],["InstanceNormalization",[Ju]],["LayerNormalization",[rd]],["LeakyRelu",[ea,Bs]],["Less",[Rl]],["LessOrEqual",[Nl]],["Log",[$l]],["MatMul",[va]],["MatMulNBits",[sd,id]],["MaxPool",[cr,vd]],["Mul",[Dl]],["MultiHeadAttention",[Vu,Va]],["Neg",[gl]],["Not",[_l]],["Pad",[fd]],["Pow",[Ll]],["QuickGelu",[kl,Bs]],["Range",[ve]],["Reciprocal",[ta]],["ReduceMin",[Ro]],["ReduceMean",[Bi]],["ReduceMax",[Bo]],["ReduceSum",[No]],["ReduceProd",[Ni]],["ReduceL1",[Do]],["ReduceL2",[Lo]],["ReduceLogSum",[ji]],["ReduceLogSumExp",[Ri]],["ReduceSumSquare",[jo]],["Relu",[wl]],["Resize",[Qr,gn]],["RotaryEmbedding",[Fc]],["Sigmoid",[yl]],["Sin",[Ml]],["Sinh",[oi]],["Slice",[kp,Sp]],["SkipLayerNormalization",[uc]],["Split",[ec,qu]],["Sqrt",[vl]],["Softmax",[Ip,Fp]],["Sub",[ua]],["Tan",[xl]],["Tanh",[na]],["ThresholdedRelu",[Cl,Bs]],["Tile",[Lp]],["Transpose",[Fd,fo]],["Where",[Np]]])}),Vp,Zf=U(()=>{At(),_(),pr(),Vp=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=co(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]}}}),Up,Wp,Gp,qp,Jf=U(()=>{At(),Yt(),_(),Q(),Wr(),Yf(),Zf(),Up=(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+`:${Up(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Gp=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},qp=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 Gp(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ur(this),this.programManager=new Vp(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ns(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),D=Number(x-this.queryTimeBase);if(!Number.isSafeInteger(C)||!Number.isSafeInteger(D))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(V=>({dims:V.dims,dataType:An(V.dataType)})),outputsMetadata:l.map(V=>({dims:V.dims,dataType:An(V.dataType)})),kernelId:s,kernelType:d,kernelName:c,programName:g,startTime:C,endTime:D});else{let V="";m.forEach((ee,te)=>{V+=`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}" ${V}${A}execution time: ${D-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 Ft=Pe.type===10?2:4,Bt,ar;Pe.type===10?(ar=Ye.length>4?16:Ye.length>2?8:Ye.length*Ft,Bt=Ye.length>4?16:Ft*Ye.length):(ar=Ye.length<=2?Ye.length*Ft: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*Ft});let te=16;A=Math.ceil(A/te)*te;let ie=new ArrayBuffer(A);c.forEach((Pe,Ye)=>{let Ft=ee[Ye],Bt=typeof Pe.data=="number"?[Pe.data]:Pe.data;if(Pe.type===6)new Int32Array(ie,Ft,Bt.length).set(Bt);else if(Pe.type===12)new Uint32Array(ie,Ft,Bt.length).set(Bt);else if(Pe.type===10)new Uint16Array(ie,Ft,Bt.length).set(Bt);else if(Pe.type===1)new Float32Array(ie,Ft,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,D=Wp(e,t,C),V=this.programManager.getArtifact(D);if(V||(V=this.programManager.build(e,x),this.programManager.setArtifact(D,V),ae("info",()=>`[artifact] key: ${D}, programName: ${e.name}`)),c&&V.uniformVariablesInfo){if(c.length!==V.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${V.uniformVariablesInfo.length}, got ${c.length} in program "${V.programInfo.name}".`);for(let A=0;A`[ProgramManager] run "${e.name}" (key=${D}) with ${x[0]}x${x[1]}x${x[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let A={kernelId:this.currentKernelId,programName:V.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push(A),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(A)}return this.programManager.run(V,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=jp.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 F(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()}}}),Hp,Lc,Bc,Rc,Kp,Xp,em=U(()=>{_(),Hp=1,Lc=()=>Hp++,Bc=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])}},Rc=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()}},Kp=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Lc();return this.tensorTrackersById.set(e,new Rc(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=Lc(),a=new Bc({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(i,new Rc(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 Bc({sessionId:a,context:s,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Xp=(...e)=>new Kp(...e)}),Nc,Qp,tm=U(()=>{Yt(),kr(),Q(),em(),_(),Nc=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Qp=class{constructor(e){this.tensorManager=Xp(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,ns(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=Nc.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 F(r,t)}}registerMLTensor(e,t,r){let n=Nc.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(){}}}),Yp={};I(Yp,{init:()=>Jp});var dc,Zp,Jp,rm=U(()=>{Yt(),Jf(),_(),Kt(),tm(),dc=class Lf{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=Ee.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=Ee.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=Ee.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=Ee.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Ee.size(t)!==Ee.size(this.dims))throw new Error("Invalid new shape");return new Lf(this.module,this.dataType,this.data,t)}},Zp=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 dc(this.module,d,this.output(u,c),c),a=(u,d)=>{let c=Bn(u,d);if(!c)throw new Error(`Unsupported data type: ${u}`);let g=c>0?this.backend.gpuDataManager.create(c).id:0;return new dc(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 qp;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 Zp(t,a,u);return a.computeKernel(s,g,c)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new Qp(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)])}}}),eh,jc,Vc,Hs,th,cc,Uc,Wc,Gc,qc,Hc,Kc,rh=U(()=>{Kn(),ts(),Yt(),kr(),hs(),Fs(),eh=(e,t)=>{mr()._OrtInit(e,t)!==0&&Ur("Can't initialize onnxruntime.")},jc=async e=>{eh(e.wasm.numThreads,Ln(e.logLevel))},Vc=async(e,t)=>{{let r=(rm(),B(Yp)).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)}}},Hs=new Map,th=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)}},cc=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]},Uc=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]=cc(e);let a=0,s=0,u=0,d=[],c=[],g=[];try{if([s,d]=Is(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(rs(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,Ft=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:Ft,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]=th(a),D=!!(t!=null&&t.enableGraphCapture),V=[],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=>gs(ie))}),Hs.set(a,[a,c,g,te,D,!1]),[a,V,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)}},Wc=e=>{var d;let t=mr(),r=Hs.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),Hs.delete(e)},Gc=(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=Bn(Xn(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=Bn(Xn(u),d);let C=s.jsepRegisterMLTensor;if(!C)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=C(x,Xn(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 D=0;Ds.HEAP32[x++]=D);let C=s._OrtCreateTensor(Xn(u),g,m,T,d.length,gs(c));C===0&&Ur(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(C)}finally{s.stackRestore(l)}},qc=async(e,t,r,n,i,a)=>{var Bt,ar;let s=mr(),u=Hs.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,D=0,V=[],A=[],ee=[],te=[],ie=s.stackSave(),ke=s.stackAlloc(x*4),Pe=s.stackAlloc(x*4),Ye=s.stackAlloc(C*4),Ft=s.stackAlloc(C*4);try{(Bt=s.jsepOnRunStart)==null||Bt.call(s,d),[D,V]=Es(a);for(let Gt=0;Gtcn*vn,1);rr=An(an);let yi=m==null?void 0:m.outputPreferredLocations[n[Gt]];if(rr==="string"){if(yi==="gpu-buffer"||yi==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let cn=[],vn=Br/4;for(let Gn=0;Gn0){let cn=s.jsepGetBuffer;if(!cn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let vn=cn(Br),Gn=Bn(an,fn);if(Gn===void 0||!ms(rr))throw new Error(`Unsupported data type: ${rr}`);vt=!0,Fr.push([rr,Sn,{gpuBuffer:vn,download:s.jsepCreateDownloader(vn,Gn,rr),dispose:()=>{s._OrtReleaseTensor(Qt)}},"gpu-buffer"])}else if(yi==="ml-tensor"&&fn>0){let cn=s.jsepEnsureTensor;if(!cn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Bn(an,fn)===void 0||!_s(rr))throw new Error(`Unsupported data type: ${rr}`);let vn=await cn(Br,an,Sn,!1);vt=!0,Fr.push([rr,Sn,{mlTensor:vn,download:s.jsepCreateMLTensorDownloader(Br,rr),dispose:()=>{s.jsepReleaseTensorId(Br),s._OrtReleaseTensor(Qt)}},"ml-tensor"])}else{let cn=fs(rr),vn=new cn(fn);new Uint8Array(vn.buffer,vn.byteOffset,vn.byteLength).set(s.HEAPU8.subarray(Br,Br+vn.byteLength)),Fr.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),Hs.set(e,[d,c,g,m,l,!1])),Fr}finally{s.stackRestore(ie),A.forEach(nr=>s._OrtReleaseTensor(nr)),ee.forEach(nr=>s._OrtReleaseTensor(nr)),te.forEach(nr=>s._free(nr)),D!==0&&s._OrtReleaseRunOptions(D),V.forEach(nr=>s._free(nr))}},Hc=e=>{let t=mr(),r=Hs.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)},Kc=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Ks,Dn,so,Ed,kd,pc,Xc,hc,gi,wi,nh,sh,ih,ah,oh,lh,uh,dh,ch=U(()=>{At(),rh(),kr(),Ot(),Ks=()=>!!E.wasm.proxy&&typeof document<"u",so=!1,Ed=!1,kd=!1,hc=new Map,gi=(e,t)=>{let r=hc.get(e);r?r.push(t):hc.set(e,[t])},wi=()=>{if(so||!Ed||kd||!Dn)throw new Error("worker not ready")},nh=e=>{switch(e.data.type){case"init-wasm":so=!1,e.data.err?(kd=!0,Xc[1](e.data.err)):(Ed=!0,Xc[0]()),pc&&(URL.revokeObjectURL(pc),pc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=hc.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},sh=async()=>{if(!Ed){if(so)throw new Error("multiple calls to 'initWasm()' detected.");if(kd)throw new Error("previous call to 'initWasm()' failed.");if(so=!0,Ks())return new Promise((e,t)=>{Dn==null||Dn.terminate(),ft().then(([r,n])=>{try{Dn=n,Dn.onerror=a=>t(a),Dn.onmessage=nh,Xc=[e,t];let i={type:"init-wasm",in:E};Dn.postMessage(i),pc=r}catch(i){t(i)}},t)});try{await Nr(E.wasm),await jc(E),Ed=!0}catch(e){throw kd=!0,e}finally{so=!1}}},ih=async e=>{if(Ks())return wi(),new Promise((t,r)=>{gi("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:E}};Dn.postMessage(n)});await Vc(E,e)},ah=async e=>Ks()?(wi(),new Promise((t,r)=>{gi("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Dn.postMessage(n,[e.buffer])})):cc(e),oh=async(e,t)=>{if(Ks()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return wi(),new Promise((r,n)=>{gi("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 Uc(e,t)},lh=async e=>{if(Ks())return wi(),new Promise((t,r)=>{gi("release",[t,r]);let n={type:"release",in:e};Dn.postMessage(n)});Wc(e)},uh=async(e,t,r,n,i,a)=>{if(Ks()){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 wi(),new Promise((s,u)=>{gi("run",[s,u]);let d=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:a}};Dn.postMessage(c,Kc(d))})}else return qc(e,t,r,n,i,a)},dh=async e=>{if(Ks())return wi(),new Promise((t,r)=>{gi("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Dn.postMessage(n)});Hc(e)}}),Qc,ph,hh,nm=U(()=>{At(),ch(),Yt(),dr(),Fs(),Qc=(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()}`)}},ph=e=>{switch(e[3]){case"cpu":return new Z(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ms(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(!_s(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]}`)}},hh=class{async fetchModelAndCopyToWasmMemory(e){return ah(await rs(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 oh(r,t),Ve()}async dispose(){return lh(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)=>Qc(m,()=>`input "${this.inputNames[i[l]]}"`)),d=a.map((m,l)=>m?Qc(m,()=>`output "${this.outputNames[s[l]]}"`):null),c=await uh(this.sessionId,i,u,s,d,r),g={};for(let m=0;mZc,initializeFlags:()=>Yc,wasmBackend:()=>mh});var Yc,Zc,mh,sm=U(()=>{At(),ch(),nm(),Ot(),Yc=()=>{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"?Ce("node:os").cpus().length:navigator.hardwareConcurrency;E.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Zc=class{async init(e){Yc(),await sh(),await ih(e)}async createInferenceSessionHandler(e,t){let r=new hh;return await r.loadModel(e,t),Promise.resolve(r)}},mh=new Zc});At(),At(),At();var im="1.21.0-dev.20241024-d9ca84ef96",am=Dt;{let e=(sm(),B(fh)).wasmBackend;fe("webgpu",e,5),fe("webnn",e,5),fe("cpu",e,10),fe("wasm",e,10)}Object.defineProperty(E.versions,"web",{value:im,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":(xt,ye,O)=>{var P;O.r(ye),O.d(ye,{Tensor:()=>Ce.Tensor,createInferenceSession:()=>z,deviceToExecutionProviders:()=>fe,isONNXProxy:()=>X,isONNXTensor:()=>J});var le=O("./src/env.js"),we=O("?2ce3"),xe=O("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Ce=O("./node_modules/onnxruntime-common/dist/esm/index.js");const U=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"}}),I=[];let L,B;const q=Symbol.for("onnxruntime");if(q in globalThis)B=globalThis[q];else if(le.apis.IS_NODE_ENV){switch(B=we??(P||(P=O.t(we,2))),process.platform){case"win32":I.push("dml");break;case"linux":process.arch==="x64"&&I.push("cuda");break}I.push("cpu"),L=["cpu"]}else B=xe,le.apis.IS_WEBNN_AVAILABLE&&I.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),le.apis.IS_WEBGPU_AVAILABLE&&I.push("webgpu"),I.push("wasm"),L=["wasm"];const re=B.InferenceSession;function fe(K=null){if(!K)return L;switch(K){case"auto":return I;case"gpu":return I.filter(j=>["webgpu","cuda","dml","webnn-gpu"].includes(j))}if(I.includes(K))return[U[K]??K];throw new Error(`Unsupported device: "${K}". Should be one of: ${I.join(", ")}.`)}let de=null;async function z(K,j,k){de&&await de;const N=re.create(K,j);de??(de=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@${le.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}le.env.backends.onnx=pe},"./src/configs.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{AutoConfig:()=>I,PretrainedConfig:()=>U,getKeyValueShapes:()=>Ce});var P=O("./src/utils/core.js"),le=O("./src/utils/hub.js");async function we(L,B){return await(0,le.getModelJSON)(L,"config.json",!0,B)}function xe(L){const B={};let q={};switch(L.model_type){case"llava":case"paligemma":case"florence2":q=xe(L.text_config);break;case"moondream1":q=xe(L.phi_config);break;case"musicgen":q=xe(L.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"olmo":case"mobilellm":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=xe(L.decoder),de="num_decoder_layers"in fe,z=(0,P.pick)(L,["model_type","is_encoder_decoder"]);return de?(z.num_decoder_layers=fe.num_decoder_layers,z.num_decoder_heads=fe.num_decoder_heads,z.decoder_hidden_size=fe.decoder_hidden_size,z.num_encoder_layers=fe.num_encoder_layers,z.num_encoder_heads=fe.num_encoder_heads,z.encoder_hidden_size=fe.encoder_hidden_size):(z.num_layers=fe.num_layers,z.num_heads=fe.num_heads,z.hidden_size=fe.hidden_size),z}const re={...q,...(0,P.pick)(L,["model_type","multi_query","is_encoder_decoder"])};for(const fe in B)re[fe]=L[B[fe]];return re}function Ce(L,{prefix:B="past_key_values"}={}){const q={},re=L.normalized_config,fe=1;if(re.is_encoder_decoder&&"num_encoder_heads"in re&&"num_decoder_heads"in re){const de=re.encoder_dim_kv??re.encoder_hidden_size/re.num_encoder_heads,z=re.decoder_dim_kv??re.decoder_hidden_size/re.num_decoder_heads,J=[fe,re.num_encoder_heads,0,de],pe=[fe,re.num_decoder_heads,0,z];for(let X=0;X{var E;O.r(ye),O.d(ye,{apis:()=>z,env:()=>k});var P=O("?569f"),le=O("?3f59"),we=O("?154a");const xe="3.0.2",Ce=typeof self<"u",U=Ce&&self.constructor.name==="DedicatedWorkerGlobalScope",I=Ce&&"caches"in self,L=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(P),de=!N(le),z=Object.freeze({IS_BROWSER_ENV:Ce,IS_WEBWORKER_ENV:U,IS_WEB_CACHE_AVAILABLE:I,IS_WEBGPU_AVAILABLE:L,IS_WEBNN_AVAILABLE:B,IS_PROCESS_AVAILABLE:q,IS_NODE_ENV:re,IS_FS_AVAILABLE:fe,IS_PATH_AVAILABLE:de}),J=fe&&de;let pe="./";if(J){const ue=Object({url:self.location.href}).url;ue?pe=le.dirname(le.dirname(we.fileURLToPath(ue))):typeof __dirname<"u"&&(pe=le.dirname(__dirname))}const X=J?le.join(pe,"/.cache/"):null,K="/models/",j=J?le.join(pe,K):K,k={version:xe,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ce,localModelPath:j,useFS:fe,useBrowserCache:I,useFSCache:fe,cacheDir:X,useCustomCache:!1,customCache:null};function N(ue){return Object.keys(ue).length===0}},"./src/generation/configuration_utils.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{GenerationConfig:()=>le});var P=O("./src/utils/core.js");class le{constructor(xe){be(this,"max_length",20);be(this,"max_new_tokens",null);be(this,"min_length",0);be(this,"min_new_tokens",null);be(this,"early_stopping",!1);be(this,"max_time",null);be(this,"do_sample",!1);be(this,"num_beams",1);be(this,"num_beam_groups",1);be(this,"penalty_alpha",null);be(this,"use_cache",!0);be(this,"temperature",1);be(this,"top_k",50);be(this,"top_p",1);be(this,"typical_p",1);be(this,"epsilon_cutoff",0);be(this,"eta_cutoff",0);be(this,"diversity_penalty",0);be(this,"repetition_penalty",1);be(this,"encoder_repetition_penalty",1);be(this,"length_penalty",1);be(this,"no_repeat_ngram_size",0);be(this,"bad_words_ids",null);be(this,"force_words_ids",null);be(this,"renormalize_logits",!1);be(this,"constraints",null);be(this,"forced_bos_token_id",null);be(this,"forced_eos_token_id",null);be(this,"remove_invalid_values",!1);be(this,"exponential_decay_length_penalty",null);be(this,"suppress_tokens",null);be(this,"begin_suppress_tokens",null);be(this,"forced_decoder_ids",null);be(this,"guidance_scale",null);be(this,"num_return_sequences",1);be(this,"output_attentions",!1);be(this,"output_hidden_states",!1);be(this,"output_scores",!1);be(this,"return_dict_in_generate",!1);be(this,"pad_token_id",null);be(this,"bos_token_id",null);be(this,"eos_token_id",null);be(this,"encoder_no_repeat_ngram_size",0);be(this,"decoder_start_token_id",null);be(this,"generation_kwargs",{});Object.assign(this,(0,P.pick)(xe,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{ClassifierFreeGuidanceLogitsProcessor:()=>J,ForcedBOSTokenLogitsProcessor:()=>U,ForcedEOSTokenLogitsProcessor:()=>I,LogitsProcessor:()=>we,LogitsProcessorList:()=>Ce,LogitsWarper:()=>xe,MinLengthLogitsProcessor:()=>fe,MinNewTokensLengthLogitsProcessor:()=>de,NoBadWordsLogitsProcessor:()=>z,NoRepeatNGramLogitsProcessor:()=>q,RepetitionPenaltyLogitsProcessor:()=>re,SuppressTokensAtBeginLogitsProcessor:()=>L,TemperatureLogitsWarper:()=>pe,TopKLogitsWarper:()=>K,TopPLogitsWarper:()=>X,WhisperTimeStampLogitsProcessor:()=>B});var P=O("./src/utils/generic.js");O("./src/utils/tensor.js");var le=O("./src/utils/maths.js");class we extends P.Callable{_call(k,N){throw Error("`_call` should be implemented in a subclass")}}class xe extends P.Callable{_call(k,N){throw Error("`_call` should be implemented in a subclass")}}class Ce extends P.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 U extends we{constructor(k){super(),this.bos_token_id=k}_call(k,N){for(let E=0;E=1&&Me[Me.length-1]>=this.timestamp_begin,De=Me.length<2||Me[Me.length-2]>=this.timestamp_begin;if($e&&(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,le.log_softmax)(ue),it=Math.log(ze.subarray(this.timestamp_begin).map(Math.exp).reduce((lt,me)=>lt+me)),rt=(0,le.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 Me=0;Me1 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),Me=N.slice([E,N.dims[0]],null);for(let $e=0;$e1)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 xe{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":(xt,ye,O)=>{O.r(ye),O.d(ye,{LogitsSampler:()=>xe});var P=O("./src/utils/generic.js"),le=O("./src/utils/tensor.js"),we=O("./src/utils/maths.js");O("./src/generation/configuration_utils.js");class xe extends P.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 de=q*re;fe=fe.slice(de,de+re)}return fe}randomSelect(B){let q=0;for(let fe=0;fe1)return new I(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 Ce(B)}}class Ce extends xe{async sample(B){const q=(0,we.max)(B.data)[1];return[[BigInt(q),0]]}}class U extends xe{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,le.topk)(B,q),de=(0,we.softmax)(re.data);return Array.from({length:this.generation_config.num_beams},()=>{const z=this.randomSelect(de);return[fe.data[z],Math.log(de[z])]})}}class I extends xe{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,le.topk)(B,q),de=(0,we.softmax)(re.data);return Array.from({length:this.generation_config.num_beams},(z,J)=>[fe.data[J],Math.log(de[J])])}}},"./src/generation/stopping_criteria.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{EosTokenCriteria:()=>Ce,InterruptableStoppingCriteria:()=>U,MaxLengthCriteria:()=>xe,StoppingCriteria:()=>le,StoppingCriteriaList:()=>we});var P=O("./src/utils/generic.js");class le extends P.Callable{_call(L,B){throw Error("StoppingCriteria needs to be subclassed")}}class we extends P.Callable{constructor(){super(),this.criteria=[]}push(L){this.criteria.push(L)}extend(L){L instanceof we?L=L.criteria:L instanceof le&&(L=[L]),this.criteria.push(...L)}_call(L,B){const q=new Array(L.length).fill(!1);for(const re of this.criteria){const fe=re(L,B);for(let de=0;deB.length>=this.max_length)}}class Ce extends le{constructor(L){super(),Array.isArray(L)||(L=[L]),this.eos_token_id=L}_call(L,B){return L.map(q=>{const re=q.at(-1);return this.eos_token_id.some(fe=>re==fe)})}}class U extends le{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(L,B){return new Array(L.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{BaseStreamer:()=>xe,TextStreamer:()=>U,WhisperTextStreamer:()=>I});var P=O("./src/utils/core.js"),le=O("./src/tokenizers.js"),we=O("./src/env.js");class xe{put(B){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Ce=we.apis.IS_PROCESS_AVAILABLE?L=>process.stdout.write(L):L=>console.log(L);class U extends xe{constructor(B,{skip_prompt:q=!1,callback_function:re=null,token_callback_function:fe=null,decode_kwargs:de={},...z}={}){super(),this.tokenizer=B,this.skip_prompt=q,this.callback_function=re??Ce,this.token_callback_function=fe,this.decode_kwargs={...de,...z},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(B){var de;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];(de=this.token_callback_function)==null||de.call(this,q),this.token_cache=(0,P.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,le.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===Ce&&we.apis.IS_PROCESS_AVAILABLE&&((fe=this.callback_function)==null||fe.call(this,` +`))}}class I extends U{constructor(B,{skip_prompt:q=!1,callback_function:re=null,token_callback_function:fe=null,on_chunk_start:de=null,on_chunk_end:z=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=de,this.on_chunk_end=z,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 de=Number(q[0])-this.timestamp_begin;if(de>=0){const z=de*this.time_precision;this.waiting_for_timestamp?(re=this.on_chunk_end)==null||re.call(this,z):(fe=this.on_chunk_start)==null||fe.call(this,z),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":(xt,ye,O)=>{O.r(ye),O.d(ye,{ASTForAudioClassification:()=>ri,ASTModel:()=>Wt,ASTPreTrainedModel:()=>Nn,AlbertForMaskedLM:()=>Yt,AlbertForQuestionAnswering:()=>gs,AlbertForSequenceClassification:()=>_s,AlbertModel:()=>ms,AlbertPreTrainedModel:()=>Ln,AutoModel:()=>Xa,AutoModelForAudioClassification:()=>md,AutoModelForAudioFrameClassification:()=>eo,AutoModelForCTC:()=>Ja,AutoModelForCausalLM:()=>ud,AutoModelForDepthEstimation:()=>ro,AutoModelForDocumentQuestionAnswering:()=>to,AutoModelForImageClassification:()=>hd,AutoModelForImageFeatureExtraction:()=>bd,AutoModelForImageMatting:()=>gd,AutoModelForImageSegmentation:()=>fd,AutoModelForImageToImage:()=>wd,AutoModelForMaskGeneration:()=>Za,AutoModelForMaskedLM:()=>dd,AutoModelForNormalEstimation:()=>yd,AutoModelForObjectDetection:()=>Qa,AutoModelForQuestionAnswering:()=>cd,AutoModelForSemanticSegmentation:()=>ac,AutoModelForSeq2SeqLM:()=>ic,AutoModelForSequenceClassification:()=>sd,AutoModelForSpeechSeq2Seq:()=>ad,AutoModelForTextToSpectrogram:()=>od,AutoModelForTextToWaveform:()=>ld,AutoModelForTokenClassification:()=>id,AutoModelForUniversalSegmentation:()=>qs,AutoModelForVision2Seq:()=>pd,AutoModelForXVector:()=>_d,AutoModelForZeroShotObjectDetection:()=>Ya,BartForConditionalGeneration:()=>Q,BartForSequenceClassification:()=>oe,BartModel:()=>F,BartPretrainedModel:()=>_,BaseModelOutput:()=>dt,BeitForImageClassification:()=>Ml,BeitModel:()=>bl,BeitPreTrainedModel:()=>ra,BertForMaskedLM:()=>Mt,BertForQuestionAnswering:()=>Ae,BertForSequenceClassification:()=>Xe,BertForTokenClassification:()=>Z,BertModel:()=>ht,BertPreTrainedModel:()=>Re,BlenderbotForConditionalGeneration:()=>Sr,BlenderbotModel:()=>er,BlenderbotPreTrainedModel:()=>zt,BlenderbotSmallForConditionalGeneration:()=>en,BlenderbotSmallModel:()=>Wr,BlenderbotSmallPreTrainedModel:()=>ur,BloomForCausalLM:()=>Qo,BloomModel:()=>Xo,BloomPreTrainedModel:()=>ii,CLIPModel:()=>ho,CLIPPreTrainedModel:()=>is,CLIPSegForImageSegmentation:()=>Mo,CLIPSegModel:()=>bo,CLIPSegPreTrainedModel:()=>Ei,CLIPTextModel:()=>Id,CLIPTextModelWithProjection:()=>xn,CLIPVisionModel:()=>Fd,CLIPVisionModelWithProjection:()=>fo,CamembertForMaskedLM:()=>Yr,CamembertForQuestionAnswering:()=>yn,CamembertForSequenceClassification:()=>Rr,CamembertForTokenClassification:()=>Jr,CamembertModel:()=>Cr,CamembertPreTrainedModel:()=>dr,CausalLMOutput:()=>as,CausalLMOutputWithPast:()=>oc,ChineseCLIPModel:()=>yo,ChineseCLIPPreTrainedModel:()=>wo,ClapAudioModelWithProjection:()=>Eu,ClapModel:()=>$u,ClapPreTrainedModel:()=>mi,ClapTextModelWithProjection:()=>Aa,CodeGenForCausalLM:()=>Po,CodeGenModel:()=>So,CodeGenPreTrainedModel:()=>En,CohereForCausalLM:()=>Ro,CohereModel:()=>Bo,CoherePreTrainedModel:()=>Ri,ConvBertForMaskedLM:()=>$,ConvBertForQuestionAnswering:()=>nt,ConvBertForSequenceClassification:()=>Y,ConvBertForTokenClassification:()=>he,ConvBertModel:()=>H,ConvBertPreTrainedModel:()=>v,ConvNextForImageClassification:()=>Hl,ConvNextModel:()=>ql,ConvNextPreTrainedModel:()=>fa,ConvNextV2ForImageClassification:()=>Kl,ConvNextV2Model:()=>ma,ConvNextV2PreTrainedModel:()=>Rs,DPTForDepthEstimation:()=>Dd,DPTModel:()=>Nl,DPTPreTrainedModel:()=>da,DebertaForMaskedLM:()=>ge,DebertaForQuestionAnswering:()=>Ne,DebertaForSequenceClassification:()=>Ie,DebertaForTokenClassification:()=>Se,DebertaModel:()=>G,DebertaPreTrainedModel:()=>at,DebertaV2ForMaskedLM:()=>mt,DebertaV2ForQuestionAnswering:()=>Lt,DebertaV2ForSequenceClassification:()=>$t,DebertaV2ForTokenClassification:()=>ft,DebertaV2Model:()=>wt,DebertaV2PreTrainedModel:()=>tt,DecisionTransformerModel:()=>Nu,DecisionTransformerPreTrainedModel:()=>Ru,DeiTForImageClassification:()=>Pl,DeiTModel:()=>Sl,DeiTPreTrainedModel:()=>oa,DepthAnythingForDepthEstimation:()=>Vl,DepthAnythingPreTrainedModel:()=>jl,DepthProForDepthEstimation:()=>Yn,DepthProPreTrainedModel:()=>Ld,DetrForObjectDetection:()=>xl,DetrForSegmentation:()=>li,DetrModel:()=>vl,DetrObjectDetectionOutput:()=>na,DetrPreTrainedModel:()=>oi,DetrSegmentationOutput:()=>sa,Dinov2ForImageClassification:()=>_a,Dinov2Model:()=>Xl,Dinov2PreTrainedModel:()=>Ns,DistilBertForMaskedLM:()=>Ut,DistilBertForQuestionAnswering:()=>ct,DistilBertForSequenceClassification:()=>Fe,DistilBertForTokenClassification:()=>Oe,DistilBertModel:()=>Ot,DistilBertPreTrainedModel:()=>jt,DonutSwinModel:()=>ha,DonutSwinPreTrainedModel:()=>ci,EfficientNetForImageClassification:()=>Kd,EfficientNetModel:()=>Au,EfficientNetPreTrainedModel:()=>Da,ElectraForMaskedLM:()=>yt,ElectraForQuestionAnswering:()=>At,ElectraForSequenceClassification:()=>bt,ElectraForTokenClassification:()=>Dt,ElectraModel:()=>Nt,ElectraPreTrainedModel:()=>Je,EsmForMaskedLM:()=>Nr,EsmForSequenceClassification:()=>mr,EsmForTokenClassification:()=>kr,EsmModel:()=>br,EsmPreTrainedModel:()=>sr,FalconForCausalLM:()=>Cu,FalconModel:()=>Tu,FalconPreTrainedModel:()=>fi,FastViTForImageClassification:()=>cl,FastViTModel:()=>dl,FastViTPreTrainedModel:()=>Yi,Florence2ForConditionalGeneration:()=>$i,Florence2PreTrainedModel:()=>po,GLPNForDepthEstimation:()=>pa,GLPNModel:()=>hn,GLPNPreTrainedModel:()=>Un,GPT2LMHeadModel:()=>Fn,GPT2Model:()=>vo,GPT2PreTrainedModel:()=>ki,GPTBigCodeForCausalLM:()=>Oi,GPTBigCodeModel:()=>ni,GPTBigCodePreTrainedModel:()=>Fi,GPTJForCausalLM:()=>On,GPTJModel:()=>Od,GPTJPreTrainedModel:()=>Ii,GPTNeoForCausalLM:()=>$o,GPTNeoModel:()=>Co,GPTNeoPreTrainedModel:()=>Pi,GPTNeoXForCausalLM:()=>ko,GPTNeoXModel:()=>Eo,GPTNeoXPreTrainedModel:()=>Ai,Gemma2ForCausalLM:()=>Ui,Gemma2Model:()=>Vi,Gemma2PreTrainedModel:()=>ji,GemmaForCausalLM:()=>jo,GemmaModel:()=>No,GemmaPreTrainedModel:()=>Ni,GraniteForCausalLM:()=>Lo,GraniteModel:()=>Do,GranitePreTrainedModel:()=>Bi,GroupViTModel:()=>ul,GroupViTPreTrainedModel:()=>ll,HieraForImageClassification:()=>Fl,HieraModel:()=>Il,HieraPreTrainedModel:()=>Al,HubertForCTC:()=>cu,HubertForSequenceClassification:()=>ka,HubertModel:()=>du,HubertPreTrainedModel:()=>Ud,ImageMattingOutput:()=>xd,JAISLMHeadModel:()=>To,JAISModel:()=>xo,JAISPreTrainedModel:()=>Si,LlamaForCausalLM:()=>Io,LlamaModel:()=>Ao,LlamaPreTrainedModel:()=>zi,LlavaForConditionalGeneration:()=>ys,LlavaPreTrainedModel:()=>co,LongT5ForConditionalGeneration:()=>Ds,LongT5Model:()=>zs,LongT5PreTrainedModel:()=>ws,M2M100ForConditionalGeneration:()=>Rd,M2M100Model:()=>eu,M2M100PreTrainedModel:()=>ba,MBartForCausalLM:()=>Ct,MBartForConditionalGeneration:()=>gt,MBartForSequenceClassification:()=>Et,MBartModel:()=>Ge,MBartPreTrainedModel:()=>_e,MPNetForMaskedLM:()=>Ss,MPNetForQuestionAnswering:()=>Is,MPNetForSequenceClassification:()=>Ps,MPNetForTokenClassification:()=>As,MPNetModel:()=>ks,MPNetPreTrainedModel:()=>Kn,MT5ForConditionalGeneration:()=>ae,MT5Model:()=>Ls,MT5PreTrainedModel:()=>ns,MarianMTModel:()=>Jl,MarianModel:()=>ya,MarianPreTrainedModel:()=>wa,MaskFormerForInstanceSegmentation:()=>ca,MaskFormerModel:()=>Zn,MaskFormerPreTrainedModel:()=>Vn,MaskedLMOutput:()=>un,MistralForCausalLM:()=>vu,MistralModel:()=>Mu,MistralPreTrainedModel:()=>Pa,MobileBertForMaskedLM:()=>Ur,MobileBertForQuestionAnswering:()=>Es,MobileBertForSequenceClassification:()=>hs,MobileBertModel:()=>$n,MobileBertPreTrainedModel:()=>wr,MobileLLMForCausalLM:()=>Oo,MobileLLMModel:()=>Fo,MobileLLMPreTrainedModel:()=>Di,MobileNetV1ForImageClassification:()=>Ou,MobileNetV1Model:()=>Fu,MobileNetV1PreTrainedModel:()=>Iu,MobileNetV2ForImageClassification:()=>Yd,MobileNetV2Model:()=>zu,MobileNetV2PreTrainedModel:()=>Ra,MobileNetV3ForImageClassification:()=>Lu,MobileNetV3Model:()=>Du,MobileNetV3PreTrainedModel:()=>Na,MobileNetV4ForImageClassification:()=>Bu,MobileNetV4Model:()=>Zd,MobileNetV4PreTrainedModel:()=>ja,MobileViTForImageClassification:()=>hl,MobileViTModel:()=>ai,MobileViTPreTrainedModel:()=>Zi,MobileViTV2ForImageClassification:()=>ml,MobileViTV2Model:()=>fl,MobileViTV2PreTrainedModel:()=>Ji,ModelOutput:()=>Ze,Moondream1ForConditionalGeneration:()=>pr,MptForCausalLM:()=>zd,MptModel:()=>Yo,MptPreTrainedModel:()=>Hi,MusicgenForCausalLM:()=>Qd,MusicgenForConditionalGeneration:()=>Ba,MusicgenModel:()=>Xd,MusicgenPreTrainedModel:()=>La,NomicBertModel:()=>et,NomicBertPreTrainedModel:()=>Ke,OPTForCausalLM:()=>Jo,OPTModel:()=>Zo,OPTPreTrainedModel:()=>Ki,OlmoForCausalLM:()=>zn,OlmoModel:()=>zo,OlmoPreTrainedModel:()=>Li,OpenELMForCausalLM:()=>Gi,OpenELMModel:()=>Vo,OpenELMPreTrainedModel:()=>Wi,OwlViTForObjectDetection:()=>gl,OwlViTModel:()=>_l,OwlViTPreTrainedModel:()=>ea,Owlv2ForObjectDetection:()=>yl,Owlv2Model:()=>wl,Owlv2PreTrainedModel:()=>ta,Phi3ForCausalLM:()=>Ko,Phi3Model:()=>Ho,Phi3PreTrainedModel:()=>bs,PhiForCausalLM:()=>qo,PhiModel:()=>Go,PhiPreTrainedModel:()=>qi,PreTrainedModel:()=>ne,PretrainedMixin:()=>zr,PvtForImageClassification:()=>nl,PvtModel:()=>rl,PvtPreTrainedModel:()=>Xi,PyAnnoteForAudioFrameClassification:()=>su,PyAnnoteModel:()=>nu,PyAnnotePreTrainedModel:()=>va,QuestionAnsweringModelOutput:()=>_n,Qwen2ForCausalLM:()=>si,Qwen2Model:()=>Wo,Qwen2PreTrainedModel:()=>Uo,RTDetrForObjectDetection:()=>Cl,RTDetrModel:()=>Tl,RTDetrObjectDetectionOutput:()=>$l,RTDetrPreTrainedModel:()=>ui,ResNetForImageClassification:()=>zl,ResNetModel:()=>Ol,ResNetPreTrainedModel:()=>kn,RoFormerForMaskedLM:()=>ut,RoFormerForQuestionAnswering:()=>Tt,RoFormerForSequenceClassification:()=>_t,RoFormerForTokenClassification:()=>Pt,RoFormerModel:()=>Ve,RoFormerPreTrainedModel:()=>je,RobertaForMaskedLM:()=>mn,RobertaForQuestionAnswering:()=>tn,RobertaForSequenceClassification:()=>bn,RobertaForTokenClassification:()=>Ee,RobertaModel:()=>Pr,RobertaPreTrainedModel:()=>or,SamImageSegmentationOutput:()=>Vs,SamModel:()=>ga,SamPreTrainedModel:()=>Zl,SapiensForDepthEstimation:()=>Wl,SapiensForNormalEstimation:()=>Gl,SapiensForSemanticSegmentation:()=>Ul,SapiensPreTrainedModel:()=>di,SegformerForImageClassification:()=>Oa,SegformerForSemanticSegmentation:()=>Su,SegformerModel:()=>qd,SegformerPreTrainedModel:()=>Fa,Seq2SeqLMOutput:()=>Md,SequenceClassifierOutput:()=>cr,SiglipModel:()=>mo,SiglipPreTrainedModel:()=>jn,SiglipTextModel:()=>_o,SiglipVisionModel:()=>go,SpeechT5ForSpeechToText:()=>gu,SpeechT5ForTextToSpeech:()=>wu,SpeechT5HifiGan:()=>Gd,SpeechT5Model:()=>Wd,SpeechT5PreTrainedModel:()=>Sa,SqueezeBertForMaskedLM:()=>An,SqueezeBertForQuestionAnswering:()=>fs,SqueezeBertForSequenceClassification:()=>Bn,SqueezeBertModel:()=>Xn,SqueezeBertPreTrainedModel:()=>ts,StableLmForCausalLM:()=>Hd,StableLmModel:()=>Pu,StableLmPreTrainedModel:()=>za,Starcoder2ForCausalLM:()=>Ws,Starcoder2Model:()=>hi,Starcoder2PreTrainedModel:()=>xu,Swin2SRForImageSuperResolution:()=>Rl,Swin2SRModel:()=>Bl,Swin2SRPreTrainedModel:()=>ua,SwinForImageClassification:()=>Ll,SwinModel:()=>Dl,SwinPreTrainedModel:()=>la,T5ForConditionalGeneration:()=>Os,T5Model:()=>Fs,T5PreTrainedModel:()=>rs,TableTransformerForObjectDetection:()=>kl,TableTransformerModel:()=>El,TableTransformerObjectDetectionOutput:()=>aa,TableTransformerPreTrainedModel:()=>ia,TokenClassifierOutput:()=>sn,TrOCRForCausalLM:()=>bu,TrOCRPreTrainedModel:()=>yu,UniSpeechForCTC:()=>Ta,UniSpeechForSequenceClassification:()=>au,UniSpeechModel:()=>xa,UniSpeechPreTrainedModel:()=>Ms,UniSpeechSatForAudioFrameClassification:()=>lu,UniSpeechSatForCTC:()=>jd,UniSpeechSatForSequenceClassification:()=>ou,UniSpeechSatModel:()=>Ca,UniSpeechSatPreTrainedModel:()=>Us,ViTForImageClassification:()=>vr,ViTMAEModel:()=>il,ViTMAEPreTrainedModel:()=>sl,ViTMSNForImageClassification:()=>ol,ViTMSNModel:()=>al,ViTMSNPreTrainedModel:()=>Qi,ViTModel:()=>tl,ViTPreTrainedModel:()=>el,VisionEncoderDecoderModel:()=>Ci,VitMatteForImageMatting:()=>Bs,VitMattePreTrainedModel:()=>pl,VitsModel:()=>Ia,VitsModelOutput:()=>Td,VitsPreTrainedModel:()=>ku,Wav2Vec2BertForCTC:()=>Ea,Wav2Vec2BertForSequenceClassification:()=>Vd,Wav2Vec2BertModel:()=>uu,Wav2Vec2BertPreTrainedModel:()=>$a,Wav2Vec2ForAudioFrameClassification:()=>ru,Wav2Vec2ForCTC:()=>Nd,Wav2Vec2ForSequenceClassification:()=>Ma,Wav2Vec2Model:()=>tu,Wav2Vec2PreTrainedModel:()=>Jn,WavLMForAudioFrameClassification:()=>_u,WavLMForCTC:()=>hu,WavLMForSequenceClassification:()=>fu,WavLMForXVector:()=>mu,WavLMModel:()=>pu,WavLMPreTrainedModel:()=>vs,WeSpeakerResNetModel:()=>iu,WeSpeakerResNetPreTrainedModel:()=>pi,WhisperForConditionalGeneration:()=>Ti,WhisperModel:()=>qt,WhisperPreTrainedModel:()=>Qe,XLMForQuestionAnswering:()=>Kr,XLMForSequenceClassification:()=>Kt,XLMForTokenClassification:()=>pn,XLMModel:()=>In,XLMPreTrainedModel:()=>ln,XLMRobertaForMaskedLM:()=>kt,XLMRobertaForQuestionAnswering:()=>Qn,XLMRobertaForSequenceClassification:()=>_r,XLMRobertaForTokenClassification:()=>ss,XLMRobertaModel:()=>Or,XLMRobertaPreTrainedModel:()=>fr,XLMWithLMHeadModel:()=>Rn,XVectorOutput:()=>vd,YolosForObjectDetection:()=>Yl,YolosModel:()=>Ql,YolosObjectDetectionOutput:()=>Bd,YolosPreTrainedModel:()=>js});var P=O("./src/configs.js"),le=O("./src/backends/onnx.js"),we=O("./src/utils/dtypes.js"),xe=O("./src/utils/generic.js"),Ce=O("./src/utils/core.js"),U=O("./src/utils/hub.js"),I=O("./src/utils/constants.js"),L=O("./src/generation/logits_process.js"),B=O("./src/generation/configuration_utils.js"),q=O("./src/utils/tensor.js"),re=O("./src/utils/maths.js"),fe=O("./src/generation/stopping_criteria.js"),de=O("./src/generation/logits_sampler.js"),z=O("./src/env.js"),J=O("./src/models/whisper/generation_whisper.js"),pe=O("./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 ve=((dn=R.config)==null?void 0:dn["transformers.js_config"])??{};let Ue=R.device??ve.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??(z.apis.IS_NODE_ENV?"cpu":"wasm"),pt=(0,le.deviceToExecutionProviders)(Le);let St=R.dtype??ve.dtype;typeof St!="string"&&(St&&St.hasOwnProperty(b)?St=St[b]:(St=we.DEFAULT_DEVICE_DTYPE_MAPPING[Le]??we.DATA_TYPES.fp32,console.warn(`dtype not specified for "${b}". Using the default dtype (${St}) for this device (${Le}).`)));const Vt=St;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=ve.kv_cache_dtype?typeof ve.kv_cache_dtype=="string"?ve.kv_cache_dtype:ve.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 Ar={dtype:Vt,kv_cache_dtype:tr},Dr=we.DEFAULT_DTYPE_SUFFIX_MAPPING[Vt],yr=`${R.subfolder??""}/${b}${Dr}.onnx`,ir={...R.session_options};ir.executionProviders??(ir.executionProviders=pt);const Ir=ve.free_dimension_overrides;Ir?ir.freeDimensionOverrides??(ir.freeDimensionOverrides=Ir):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,U.getModelFile)(f,yr,!0,R),gr=R.use_external_data_format??ve.use_external_data_format;let Lr=[];if(gr&&(gr===!0||typeof gr=="object"&&gr.hasOwnProperty(b)&&gr[b]===!0)){if(z.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const Gr=`${b}${Dr}.onnx_data`,Xr=`${R.subfolder??""}/${Gr}`;Lr.push(new Promise(async(Qr,gn)=>{const os=await(0,U.getModelFile)(f,Xr,!0,R);Qr({path:Gr,data:os})}))}else ir.externalData!==void 0&&(Lr=ir.externalData.map(async Gr=>{if(typeof Gr.data=="string"){const Xr=await(0,U.getModelFile)(f,Gr.data,!0,R);return{...Gr,data:Xr}}return Gr}));if(Lr.length>0&&(ir.externalData=await Promise.all(Lr)),Le==="webgpu"){const Gr=(0,P.getKeyValueShapes)(R.config,{prefix:"present"});if(Object.keys(Gr).length>0&&!(0,le.isONNXProxy)()){const Xr={};for(const Qr in Gr)Xr[Qr]="gpu-buffer";ir.preferredOutputLocation=Xr}}return{buffer:await $r,session_options:ir,session_config:Ar}}async function E(f,b,R){return Object.fromEntries(await Promise.all(Object.keys(b).map(async ve=>{const{buffer:Ue,session_options:Le,session_config:pt}=await N(f,b[ve],R),St=await(0,le.createInferenceSession)(Ue,Le,pt);return[ve,St]})))}async function ue(f,b,R){return Object.fromEntries(await Promise.all(Object.keys(b).map(async ve=>{const Ue=await(0,U.getModelJSON)(f,b[ve],!1,R);return[ve,Ue]})))}function Me(f,b){const R=Object.create(null),ve=[];for(const pt of f.inputNames){const St=b[pt];if(!(St instanceof q.Tensor)){ve.push(pt);continue}R[pt]=(0,le.isONNXProxy)()?St.clone():St}if(ve.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ve.join(", ")}.`);const Ue=Object.keys(b).length,Le=f.inputNames.length;if(Ue>Le){let pt=Object.keys(b).filter(St=>!f.inputNames.includes(St));console.warn(`WARNING: Too many inputs were provided (${Ue} > ${Le}). The following inputs will be ignored: "${pt.join(", ")}".`)}return R}async function $e(f,b){const R=Me(f,b);try{const ve=Object.fromEntries(Object.entries(R).map(([Le,pt])=>[Le,pt.ort_tensor]));let Ue=await f.run(ve);return Ue=De(Ue),Ue}catch(ve){throw console.error(`An error occurred during model execution: "${ve}".`),console.error("Inputs given to model:",R),ve}}function De(f){for(let b in f)(0,le.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:ve,decoder_input_ids:Ue,...Le}=b;if(!R){const St=(0,Ce.pick)(b,f.sessions.model.inputNames);R=(await lt(f,St)).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,ve=(0,Ce.pick)(b,R.inputNames);if(R.inputNames.includes("inputs_embeds")&&!ve.inputs_embeds){if(!b.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ve.inputs_embeds=await f.encode_text({input_ids:b.input_ids})}return R.inputNames.includes("token_type_ids")&&!ve.token_type_ids&&(ve.token_type_ids=new q.Tensor("int64",new BigInt64Array(ve.input_ids.data.length),ve.input_ids.dims)),await $e(R,ve)}async function me(f,b,R=!1){const ve=f.sessions[R?"decoder_model_merged":"model"],{past_key_values:Ue,...Le}=b;ve.inputNames.includes("use_cache_branch")&&(Le.use_cache_branch=it(!!Ue)),ve.inputNames.includes("position_ids")&&Le.attention_mask&&!Le.position_ids&&(Le.position_ids=ce(Le,Ue)),f.addPastKeyValues(Le,Ue);const pt=(0,Ce.pick)(Le,ve.inputNames);return await $e(ve,pt)}async function W(f,{input_ids:b=null,attention_mask:R=null,pixel_values:ve=null,position_ids:Ue=null,inputs_embeds:Le=null,past_key_values:pt=null,generation_config:St=null,logits_processor:Vt=null,...tr}){if(!Le){if(Le=await f.encode_text({input_ids:b}),ve&&b.dims[1]!==1){const Dr=await f.encode_image({pixel_values:ve});({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&&ve&&b.dims[1]===1){const Dr=b.dims[1],yr=Object.values(pt)[0].dims.at(-2);R=(0,q.cat)([(0,q.ones)([b.dims[0],yr]),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:St,logits_processor:Vt},!0)}function ce(f,b=null){const{input_ids:R,inputs_embeds:ve,attention_mask:Ue}=f,[Le,pt]=Ue.dims,St=new BigInt64Array(Ue.data.length);for(let tr=0;trLe.dims[1])){if(UeSt==f.config.image_token_index)){const St=f.config.num_image_tokens;if(!St)throw new Error("`num_image_tokens` is missing in the model configuration.");const Vt=Le.dims[1]-(Ue-St);R.input_ids=Le.slice(null,[-Vt,null]),R.attention_mask=(0,q.ones)([1,Ue+Vt])}}}return R}function We(f,b,R,ve){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):Te(f,...b)}class ne extends xe.Callable{constructor(R,ve,Ue){super();be(this,"main_input_name","input_ids");be(this,"forward_params",["input_ids","attention_mask"]);this.config=R,this.sessions=ve,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=Te;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 ve;const R=[];for(const Ue of Object.values(this.sessions))(ve=Ue==null?void 0:Ue.handler)!=null&&ve.dispose&&R.push(Ue.handler.dispose());return await Promise.all(R)}static async from_pretrained(R,{progress_callback:ve=null,config:Ue=null,cache_dir:Le=null,local_files_only:pt=!1,revision:St="main",model_file_name:Vt=null,subfolder:tr="onnx",device:Ar=null,dtype:Dr=null,use_external_data_format:yr=null,session_options:ir={}}={}){let Ir={progress_callback:ve,config:Ue,cache_dir:Le,local_files_only:pt,revision:St,model_file_name:Vt,subfolder:tr,device:Ar,dtype:Dr,use_external_data_format:yr,session_options:ir};const $r=k.get(this),gr=K.get($r);Ue=Ir.config=await P.AutoConfig.from_pretrained(R,Ir);let Lr;if(gr===X.DecoderOnly)Lr=await Promise.all([E(R,{model:Ir.model_file_name??"model"},Ir),ue(R,{generation_config:"generation_config.json"},Ir)]);else if(gr===X.Seq2Seq||gr===X.Vision2Seq)Lr=await Promise.all([E(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Ir),ue(R,{generation_config:"generation_config.json"},Ir)]);else if(gr===X.MaskGeneration)Lr=await Promise.all([E(R,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Ir)]);else if(gr===X.EncoderDecoder)Lr=await Promise.all([E(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Ir)]);else if(gr===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,Ir),ue(R,{generation_config:"generation_config.json"},Ir)])}else gr===X.Musicgen?Lr=await Promise.all([E(R,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Ir),ue(R,{generation_config:"generation_config.json"},Ir)]):(gr!==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 ${I.GITHUB_ISSUE_URL}.`),Lr=await Promise.all([E(R,{model:Ir.model_file_name??"model"},Ir)]));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 ve=new L.LogitsProcessorList;return R.temperature!==null&&R.temperature!==1&&ve.push(new L.TemperatureLogitsWarper(R.temperature)),R.top_k!==null&&R.top_k!==0&&ve.push(new L.TopKLogitsWarper(R.top_k)),R.top_p!==null&&R.top_p<1&&ve.push(new L.TopPLogitsWarper(R.top_p)),ve}_get_logits_processor(R,ve,Ue=null){const Le=new L.LogitsProcessorList;if(R.repetition_penalty!==null&&R.repetition_penalty!==1&&Le.push(new L.RepetitionPenaltyLogitsProcessor(R.repetition_penalty)),R.no_repeat_ngram_size!==null&&R.no_repeat_ngram_size>0&&Le.push(new L.NoRepeatNGramLogitsProcessor(R.no_repeat_ngram_size)),R.bad_words_ids!==null&&Le.push(new L.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 L.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 L.MinNewTokensLengthLogitsProcessor(ve,R.min_new_tokens,R.eos_token_id)),R.forced_bos_token_id!==null&&Le.push(new L.ForcedBOSTokenLogitsProcessor(R.forced_bos_token_id)),R.forced_eos_token_id!==null&&Le.push(new L.ForcedEOSTokenLogitsProcessor(R.max_length,R.forced_eos_token_id)),R.begin_suppress_tokens!==null){const pt=ve>1||R.forced_bos_token_id===null?ve:ve+1;Le.push(new L.SuppressTokensAtBeginLogitsProcessor(R.begin_suppress_tokens,pt))}return R.guidance_scale!==null&&R.guidance_scale>1&&Le.push(new L.ClassifierFreeGuidanceLogitsProcessor(R.guidance_scale)),Ue!==null&&Le.extend(Ue),Le}_prepare_generation_config(R,ve,Ue=B.GenerationConfig){const Le={...this.config};for(const St of["decoder","generator","text_config"])St in Le&&Object.assign(Le,Le[St]);const pt=new Ue(Le);return Object.assign(pt,this.generation_config??{}),R&&Object.assign(pt,R),ve&&Object.assign(pt,(0,Ce.pick)(ve,Object.getOwnPropertyNames(pt))),pt}_get_stopping_criteria(R,ve=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)),ve&&Ue.extend(ve),Ue}_validate_model_class(){if(!this.can_generate){const R=[Ga,qa,Wa,Va],ve=k.get(this.constructor),Ue=new Set,Le=this.config.model_type;for(const St of R){const Vt=St.get(Le);Vt&&Ue.add(Vt[0])}let pt=`The current model class (${ve}) 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:ve,model_inputs:Ue,is_encoder_decoder:Le}){return Ue.past_key_values=this.getPastKeyValues(ve,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:ve,model_kwargs:Ue}){const Le=(0,Ce.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:ve,model_input_name:Ue,generation_config:Le}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ve.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:St,pixel_values:Vt,attention_mask:tr,...Ar}=ve,Dr=await this._prepare_inputs_embeds(ve);ve={...Ar,...(0,Ce.pick)(Dr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:pt}=await lt(this,ve);if(Le.guidance_scale!==null&&Le.guidance_scale>1)pt=(0,q.cat)([pt,(0,q.full_like)(pt,0)],0),"attention_mask"in ve&&(ve.attention_mask=(0,q.cat)([ve.attention_mask,(0,q.zeros_like)(ve.attention_mask)],0));else if(ve.decoder_input_ids){const St=ze(ve.decoder_input_ids).dims[0];if(St!==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 (${St}).`);pt=(0,q.cat)(Array.from({length:St},()=>pt),0)}}return ve.encoder_outputs=pt,ve}_prepare_decoder_input_ids_for_generation({batch_size:R,model_input_name:ve,model_kwargs:Ue,decoder_start_token_id:Le,bos_token_id:pt,generation_config:St}){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:ve=null,logits_processor:Ue=null,stopping_criteria:Le=null,streamer:pt=null,...St}){this._validate_model_class(),ve=this._prepare_generation_config(ve,St);let{inputs_tensor:Vt,model_inputs:tr,model_input_name:Ar}=this._prepare_model_inputs({inputs:R,model_kwargs:St});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:Ar,generation_config:ve})));let yr;Dr?{input_ids:yr,model_inputs:tr}=this._prepare_decoder_input_ids_for_generation({batch_size:tr[Ar].dims.at(0),model_input_name:Ar,model_kwargs:tr,decoder_start_token_id:ve.decoder_start_token_id,bos_token_id:ve.bos_token_id,generation_config:ve}):yr=tr[Ar];let ir=yr.dims.at(-1);ve.max_new_tokens!==null&&(ve.max_length=ir+ve.max_new_tokens);const Ir=this._get_logits_processor(ve,ir,Ue),$r=this._get_stopping_criteria(ve,Le),gr=tr[Ar].dims.at(0),Lr=de.LogitsSampler.getSampler(ve),Tn=new Array(gr).fill(0),dn=yr.tolist();pt&&pt.put(dn);let Gr,Xr={};for(;;){if(tr=this.prepare_inputs_for_generation(dn,tr,ve),Gr=await this.forward(tr),ve.output_attentions&&ve.return_dict_in_generate){const Wn=this.getAttentions(Gr);for(const xs in Wn)xs in Xr||(Xr[xs]=[]),Xr[xs].push(Wn[xs])}const os=Gr.logits.slice(null,-1,null),_i=Ir(dn,os),no=[];for(let Wn=0;Wn<_i.dims.at(0);++Wn){const xs=_i[Wn],lc=await Lr(xs);for(const[uc,Oc]of lc){const Cd=BigInt(uc);Tn[Wn]+=Oc,dn[Wn].push(Cd),no.push([Cd]);break}}if(pt&&pt.put(no),$r(dn).every(Wn=>Wn))break;tr=this._update_model_kwargs_for_generation({generated_input_ids:no,outputs:Gr,model_inputs:tr,is_encoder_decoder:Dr})}pt&&pt.end();const Qr=this.getPastKeyValues(Gr,tr.past_key_values,!0),gn=new q.Tensor("int64",dn.flat(),[dn.length,dn[0].length]);if(ve.return_dict_in_generate)return{sequences:gn,past_key_values:Qr,...Xr};for(const os of Object.values(Gr))os.location==="gpu-buffer"&&os.dispose();return gn}getPastKeyValues(R,ve,Ue=!1){const Le=Object.create(null);for(const pt in R)if(pt.startsWith("present")){const St=pt.replace("present","past_key_values"),Vt=pt.includes("encoder");if(Vt&&ve?Le[St]=ve[St]:Le[St]=R[pt],ve&&(!Vt||Ue)){const tr=ve[St];tr.location==="gpu-buffer"&&tr.dispose()}}return Le}getAttentions(R){const ve={};for(const Ue of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Le in R)Le.startsWith(Ue)&&(Ue in ve||(ve[Ue]=[]),ve[Ue].push(R[Le]));return ve}addPastKeyValues(R,ve){var Ue;if(ve)Object.assign(R,ve);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",St=pt==="float16"?new Uint16Array:[],Vt=(0,P.getKeyValueShapes)(this.config);for(const tr in Vt)R[tr]=new q.Tensor(pt,St,Vt[tr])}}async encode_image({pixel_values:R}){const ve=(await $e(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 (${ve.dims[1]}).`),this.config.num_image_tokens=ve.dims[1]),ve}async encode_text({input_ids:R}){return(await $e(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:ve=null}){super(),this.last_hidden_state=b,this.hidden_states=R,this.attentions=ve}}class Re extends ne{}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 sn(await super._call(b))}}class Ae extends Re{async _call(b){return new _n(await super._call(b))}}class Ke extends ne{}class et extends Ke{}class je extends ne{}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 Pt extends je{async _call(b){return new sn(await super._call(b))}}class Tt extends je{async _call(b){return new _n(await super._call(b))}}class v extends ne{}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 sn(await super._call(b))}}class nt extends v{async _call(b){return new _n(await super._call(b))}}class Je extends ne{}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 Dt extends Je{async _call(b){return new sn(await super._call(b))}}class At extends Je{async _call(b){return new _n(await super._call(b))}}class dr extends ne{}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 sn(await super._call(b))}}class yn extends dr{async _call(b){return new _n(await super._call(b))}}class at extends ne{}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 sn(await super._call(b))}}class Ne extends at{async _call(b){return new _n(await super._call(b))}}class tt extends ne{}class wt extends tt{}class mt extends tt{async _call(b){return new un(await super._call(b))}}class $t extends tt{async _call(b){return new cr(await super._call(b))}}class ft extends tt{async _call(b){return new sn(await super._call(b))}}class Lt extends tt{async _call(b){return new _n(await super._call(b))}}class jt extends ne{}class Ot 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 sn(await super._call(b))}}class ct extends jt{async _call(b){return new _n(await super._call(b))}}class Ut extends jt{async _call(b){return new un(await super._call(b))}}class sr extends ne{}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 sn(await super._call(b))}}class wr extends ne{}class $n extends wr{}class Ur extends wr{async _call(b){return new un(await super._call(b))}}class hs extends wr{async _call(b){return new cr(await super._call(b))}}class Es extends wr{async _call(b){return new _n(await super._call(b))}}class Kn extends ne{}class ks extends Kn{}class Ss extends Kn{async _call(b){return new un(await super._call(b))}}class Ps extends Kn{async _call(b){return new cr(await super._call(b))}}class As extends Kn{async _call(b){return new sn(await super._call(b))}}class Is extends Kn{async _call(b){return new _n(await super._call(b))}}class ts extends ne{}class Xn extends ts{}class An extends ts{async _call(b){return new un(await super._call(b))}}class Bn extends ts{async _call(b){return new cr(await super._call(b))}}class fs extends ts{async _call(b){return new _n(await super._call(b))}}class Ln extends ne{}class ms extends Ln{}class _s extends Ln{async _call(b){return new cr(await super._call(b))}}class gs extends Ln{async _call(b){return new _n(await super._call(b))}}class Yt extends Ln{async _call(b){return new un(await super._call(b))}}class rs extends ne{constructor(){super(...arguments);be(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Fs extends rs{}class Os extends rs{}class ws extends ne{}class zs extends ws{}class Ds extends ws{}class ns extends ne{}class Ls extends ns{}class ae extends ns{}class _ extends ne{}class F extends _{}class Q extends _{}class oe extends _{async _call(b){return new cr(await super._call(b))}}class _e extends ne{}class Ge extends _e{}class gt extends _e{}class Et extends _e{async _call(b){return new cr(await super._call(b))}}class Ct extends _e{}class zt extends ne{}class er extends zt{}class Sr extends zt{}class ur extends ne{}class Wr extends ur{}class en extends ur{}class or extends ne{}class Pr extends or{}class mn extends or{async _call(b){return new un(await super._call(b))}}class bn extends or{async _call(b){return new cr(await super._call(b))}}class Ee extends or{async _call(b){return new sn(await super._call(b))}}class tn extends or{async _call(b){return new _n(await super._call(b))}}class ln extends ne{}class In extends ln{}class Rn 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 sn(await super._call(b))}}class Kr extends ln{async _call(b){return new _n(await super._call(b))}}class fr extends ne{}class Or extends fr{}class kt 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 ss extends fr{async _call(b){return new sn(await super._call(b))}}class Qn extends fr{async _call(b){return new _n(await super._call(b))}}class Nn extends ne{}class Wt extends Nn{}class ri extends Nn{}class Qe extends ne{constructor(){super(...arguments);be(this,"requires_attention_mask",!1);be(this,"main_input_name","input_features");be(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class qt extends Qe{}class Ti 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 ve=b.language;const Ue=b.task;if(b.is_multilingual){ve||(console.warn("No language specified - defaulting to English (en)."),ve="en");const pt=`<|${(0,pe.whisper_language_to_code)(ve)}|>`;R.push(b.lang_to_id[pt]),R.push(b.task_to_id[Ue??"transcribe"])}else if(ve||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:ve=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&&(ve??(ve=new L.LogitsProcessorList),ve.push(new L.WhisperTimeStampLogitsProcessor(R,pt))),R.begin_suppress_tokens&&(ve??(ve=new L.LogitsProcessorList),ve.push(new L.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 St=await super.generate({inputs:b,generation_config:R,logits_processor:ve,decoder_input_ids:pt,...Le});return R.return_token_timestamps&&(St.token_timestamps=this._extract_token_timestamps(St,R.alignment_heads,R.num_frames)),St}_extract_token_timestamps(b,R,ve=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`.");ve==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let 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,St=Array.from({length:this.config.decoder_layers},($r,gr)=>(0,q.cat)(pt.map(Lr=>Lr[gr]),2)),Vt=(0,q.stack)(R.map(([$r,gr])=>{if($r>=St.length)throw new Error(`Layer index ${$r} is out of bounds for cross attentions (length ${St.length}).`);return ve?St[$r].slice(null,gr,null,[0,ve]):St[$r].slice(null,gr)})).transpose(1,0,2,3),[tr,Ar]=(0,q.std_mean)(Vt,-2,0,!0),Dr=Vt.clone();for(let $r=0;$rLr[gn+1]-Lr[gn]),Gr=(0,Ce.mergeArrays)([1],dn).map(Qr=>!!Qr),Xr=[];for(let Qr=0;Qryr.findIndex(ir=>ir==Le)),Vt=St.every(yr=>yr===-1),tr=St.every(yr=>yr!==-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 Ar=[],Dr=[];for(let yr=0;yrLe*pt,1);b.input_labels=new q.Tensor("int64",new BigInt64Array(Ue).fill(1n),ve)}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 $e(this.sessions.prompt_encoder_mask_decoder,R)}async _call(b){return new Vs(await super._call(b))}}class Vs extends Ze{constructor({iou_scores:b,pred_masks:R}){super(),this.iou_scores=b,this.pred_masks=R}}class wa extends ne{}class ya extends wa{}class Jl extends wa{}class ba extends ne{}class eu extends ba{}class Rd extends ba{}class Jn extends ne{}class tu extends Jn{}class Nd extends Jn{async _call(b){return new as(await super._call(b))}}class Ma extends Jn{async _call(b){return new cr(await super._call(b))}}class ru extends Jn{async _call(b){return new sn(await super._call(b))}}class va extends ne{}class nu extends va{}class su extends va{async _call(b){return new sn(await super._call(b))}}class pi extends ne{}class iu extends pi{}class Ms extends ne{}class xa extends Ms{}class Ta extends Ms{async _call(b){return new as(await super._call(b))}}class au extends Ms{async _call(b){return new cr(await super._call(b))}}class Us extends ne{}class Ca extends Us{}class jd extends Us{async _call(b){return new as(await super._call(b))}}class ou extends Us{async _call(b){return new cr(await super._call(b))}}class lu extends Us{async _call(b){return new sn(await super._call(b))}}class $a extends ne{}class uu extends $a{}class Ea extends $a{async _call(b){return new as(await super._call(b))}}class Vd extends $a{async _call(b){return new cr(await super._call(b))}}class Ud extends ne{}class du extends Jn{}class cu extends Jn{async _call(b){return new as(await super._call(b))}}class ka extends Jn{async _call(b){return new cr(await super._call(b))}}class vs extends ne{}class pu extends vs{}class hu extends vs{async _call(b){return new as(await super._call(b))}}class fu extends vs{async _call(b){return new cr(await super._call(b))}}class mu extends vs{async _call(b){return new vd(await super._call(b))}}class _u extends vs{async _call(b){return new sn(await super._call(b))}}class Sa extends ne{}class Wd extends Sa{}class gu extends Sa{}class wu extends Sa{async generate_speech(b,R,{threshold:ve=.5,minlenratio:Ue=0,maxlenratio:Le=20,vocoder:pt=null}={}){const St={input_ids:b},{encoder_outputs:Vt,encoder_attention_mask:tr}=await lt(this,St),Ar=Vt.dims[1]/this.config.reduction_factor,Dr=Math.floor(Ar*Le),yr=Math.floor(Ar*Ue),ir=this.config.num_mel_bins;let Ir=[],$r=null,gr=null,Lr=0;for(;;){++Lr;const Gr=it(!!gr);let Xr;gr?Xr=gr.output_sequence_out:Xr=new q.Tensor("float32",new Float32Array(ir),[1,1,ir]);let Qr={use_cache_branch:Gr,output_sequence:Xr,encoder_attention_mask:tr,speaker_embeddings:R,encoder_hidden_states:Vt};this.addPastKeyValues(Qr,$r),gr=await $e(this.sessions.decoder_model_merged,Qr),$r=this.getPastKeyValues(gr,$r);const{prob:gn,spectrum:os}=gr;if(Ir.push(os),Lr>=yr&&(Array.from(gn.data).filter(_i=>_i>=ve).length>0||Lr>=Dr))break}const Tn=(0,q.cat)(Ir),{waveform:dn}=await $e(pt.sessions.model,{spectrogram:Tn});return{spectrogram:Tn,waveform:dn}}}class Gd extends ne{constructor(){super(...arguments);be(this,"main_input_name","spectrogram")}}class yu extends ne{}class bu extends yu{}class Pa extends ne{}class Mu extends Pa{}class vu extends Pa{}class xu extends ne{}class hi extends xu{}class Ws extends xu{}class fi extends ne{}class Tu extends fi{}class Cu extends fi{}class mi extends ne{}class $u extends mi{}class Aa extends mi{static async from_pretrained(b,R={}){return R.model_file_name??(R.model_file_name="text_model"),super.from_pretrained(b,R)}}class Eu extends mi{static async from_pretrained(b,R={}){return R.model_file_name??(R.model_file_name="audio_model"),super.from_pretrained(b,R)}}class ku extends ne{}class Ia extends ku{async _call(b){return new Td(await super._call(b))}}class Fa extends ne{}class qd extends Fa{}class Oa extends Fa{}class Su extends Fa{}class za extends ne{}class Pu extends za{}class Hd extends za{}class Da extends ne{}class Au extends Da{}class Kd extends Da{async _call(b){return new cr(await super._call(b))}}class La extends ne{}class Xd extends La{}class Qd extends La{}class Ba extends ne{constructor(){super(...arguments);be(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[ve,Ue]=R.dims,Le=this.config.decoder.num_codebooks,pt=Ue-Le;let St=0;for(let Ar=0;Ar0&&ir<=pt&&(R.data[St++]=R.data[Ar])}const Vt=Math.floor(ve/Le),tr=St/(Vt*Le);return new q.Tensor(R.type,R.data.slice(0,St),[Vt,Le,tr])}prepare_inputs_for_generation(R,ve,Ue){let Le=structuredClone(R);for(let St=0;St=Vt&&(Le[St][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,ve,Ue)}async generate(R){const ve=await super.generate(R),Ue=this._apply_and_filter_by_delay_pattern_mask(ve).unsqueeze_(0),{audio_values:Le}=await $e(this.sessions.encodec_decode,{audio_codes:Ue});return Le}}class Iu extends ne{}class Fu extends Iu{}class Ou extends Iu{async _call(b){return new cr(await super._call(b))}}class Ra extends ne{}class zu extends Ra{}class Yd extends Ra{async _call(b){return new cr(await super._call(b))}}class Na extends ne{}class Du extends Na{}class Lu extends Na{async _call(b){return new cr(await super._call(b))}}class ja extends ne{}class Zd extends ja{}class Bu extends ja{async _call(b){return new cr(await super._call(b))}}class Ru extends ne{}class Nu extends Ru{}class zr{static async from_pretrained(b,{progress_callback:R=null,config:ve=null,cache_dir:Ue=null,local_files_only:Le=!1,revision:pt="main",model_file_name:St=null,subfolder:Vt="onnx",device:tr=null,dtype:Ar=null,use_external_data_format:Dr=null,session_options:yr={}}={}){const ir={progress_callback:R,config:ve,cache_dir:Ue,local_files_only:Le,revision:pt,model_file_name:St,subfolder:Vt,device:tr,dtype:Ar,use_external_data_format:Dr,session_options:yr};if(ir.config=await P.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 Ir of this.MODEL_CLASS_MAPPINGS){const $r=Ir.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 ne.from_pretrained(b,ir);throw Error(`Unsupported model type: ${ir.config.model_type}`)}}be(zr,"MODEL_CLASS_MAPPINGS",null),be(zr,"BASE_IF_FAIL",!1);const Ic=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",ks]],["albert",["AlbertModel",ms]],["distilbert",["DistilBertModel",Ot]],["roberta",["RobertaModel",Pr]],["xlm",["XLMModel",In]],["xlm-roberta",["XLMRobertaModel",Or]],["clap",["ClapModel",$u]],["clip",["CLIPModel",ho]],["clipseg",["CLIPSegModel",bo]],["chinese_clip",["ChineseCLIPModel",yo]],["siglip",["SiglipModel",mo]],["mobilebert",["MobileBertModel",$n]],["squeezebert",["SqueezeBertModel",Xn]],["wav2vec2",["Wav2Vec2Model",tu]],["wav2vec2-bert",["Wav2Vec2BertModel",uu]],["unispeech",["UniSpeechModel",xa]],["unispeech-sat",["UniSpeechSatModel",Ca]],["hubert",["HubertModel",du]],["wavlm",["WavLMModel",pu]],["audio-spectrogram-transformer",["ASTModel",Wt]],["vits",["VitsModel",Ia]],["pyannote",["PyAnnoteModel",nu]],["wespeaker-resnet",["WeSpeakerResNetModel",iu]],["detr",["DetrModel",vl]],["rt_detr",["RTDetrModel",Tl]],["table-transformer",["TableTransformerModel",El]],["vit",["ViTModel",tl]],["pvt",["PvtModel",rl]],["vit_msn",["ViTMSNModel",al]],["vit_mae",["ViTMAEModel",il]],["groupvit",["GroupViTModel",ul]],["fastvit",["FastViTModel",dl]],["mobilevit",["MobileViTModel",ai]],["mobilevitv2",["MobileViTV2Model",fl]],["owlvit",["OwlViTModel",_l]],["owlv2",["Owlv2Model",wl]],["beit",["BeitModel",bl]],["deit",["DeiTModel",Sl]],["hiera",["HieraModel",Il]],["convnext",["ConvNextModel",ql]],["convnextv2",["ConvNextV2Model",ma]],["dinov2",["Dinov2Model",Xl]],["resnet",["ResNetModel",Ol]],["swin",["SwinModel",Dl]],["swin2sr",["Swin2SRModel",Bl]],["donut-swin",["DonutSwinModel",ha]],["yolos",["YolosModel",Ql]],["dpt",["DPTModel",Nl]],["glpn",["GLPNModel",hn]],["hifigan",["SpeechT5HifiGan",Gd]],["efficientnet",["EfficientNetModel",Au]],["decision_transformer",["DecisionTransformerModel",Nu]],["mobilenet_v1",["MobileNetV1Model",Fu]],["mobilenet_v2",["MobileNetV2Model",zu]],["mobilenet_v3",["MobileNetV3Model",Du]],["mobilenet_v4",["MobileNetV4Model",Zd]],["maskformer",["MaskFormerModel",Zn]]]),Mn=new Map([["t5",["T5Model",Fs]],["longt5",["LongT5Model",zs]],["mt5",["MT5Model",Ls]],["bart",["BartModel",F]],["mbart",["MBartModel",Ge]],["marian",["MarianModel",ya]],["whisper",["WhisperModel",qt]],["m2m_100",["M2M100Model",eu]],["blenderbot",["BlenderbotModel",er]],["blenderbot-small",["BlenderbotSmallModel",Wr]]]),Jd=new Map([["bloom",["BloomModel",Xo]],["jais",["JAISModel",xo]],["gpt2",["GPT2Model",vo]],["gptj",["GPTJModel",Od]],["gpt_bigcode",["GPTBigCodeModel",ni]],["gpt_neo",["GPTNeoModel",Co]],["gpt_neox",["GPTNeoXModel",Eo]],["codegen",["CodeGenModel",So]],["llama",["LlamaModel",Ao]],["olmo",["OlmoModel",zo]],["mobilellm",["MobileLLMModel",Fo]],["granite",["GraniteModel",Do]],["cohere",["CohereModel",Bo]],["gemma",["GemmaModel",No]],["gemma2",["Gemma2Model",Vi]],["openelm",["OpenELMModel",Vo]],["qwen2",["Qwen2Model",Wo]],["phi",["PhiModel",Go]],["phi3",["Phi3Model",Ho]],["mpt",["MptModel",Yo]],["opt",["OPTModel",Zo]],["mistral",["MistralModel",Mu]],["starcoder2",["Starcoder2Model",hi]],["falcon",["FalconModel",Tu]],["stablelm",["StableLmModel",Pu]]]),Va=new Map([["speecht5",["SpeechT5ForSpeechToText",gu]],["whisper",["WhisperForConditionalGeneration",Ti]]]),Ua=new Map([["speecht5",["SpeechT5ForTextToSpeech",wu]]]),ju=new Map([["vits",["VitsModel",Ia]],["musicgen",["MusicgenForConditionalGeneration",Ba]]]),Gs=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",$t]],["mpnet",["MPNetForSequenceClassification",Ps]],["albert",["AlbertForSequenceClassification",_s]],["distilbert",["DistilBertForSequenceClassification",Fe]],["roberta",["RobertaForSequenceClassification",bn]],["xlm",["XLMForSequenceClassification",Kt]],["xlm-roberta",["XLMRobertaForSequenceClassification",_r]],["bart",["BartForSequenceClassification",oe]],["mbart",["MBartForSequenceClassification",Et]],["mobilebert",["MobileBertForSequenceClassification",hs]],["squeezebert",["SqueezeBertForSequenceClassification",Bn]]]),Vu=new Map([["bert",["BertForTokenClassification",Z]],["roformer",["RoFormerForTokenClassification",Pt]],["electra",["ElectraForTokenClassification",Dt]],["esm",["EsmForTokenClassification",kr]],["convbert",["ConvBertForTokenClassification",he]],["camembert",["CamembertForTokenClassification",Jr]],["deberta",["DebertaForTokenClassification",Se]],["deberta-v2",["DebertaV2ForTokenClassification",ft]],["mpnet",["MPNetForTokenClassification",As]],["distilbert",["DistilBertForTokenClassification",Oe]],["roberta",["RobertaForTokenClassification",Ee]],["xlm",["XLMForTokenClassification",pn]],["xlm-roberta",["XLMRobertaForTokenClassification",ss]]]),Wa=new Map([["t5",["T5ForConditionalGeneration",Os]],["longt5",["LongT5ForConditionalGeneration",Ds]],["mt5",["MT5ForConditionalGeneration",ae]],["bart",["BartForConditionalGeneration",Q]],["mbart",["MBartForConditionalGeneration",gt]],["marian",["MarianMTModel",Jl]],["m2m_100",["M2M100ForConditionalGeneration",Rd]],["blenderbot",["BlenderbotForConditionalGeneration",Sr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",en]]]),Ga=new Map([["bloom",["BloomForCausalLM",Qo]],["gpt2",["GPT2LMHeadModel",Fn]],["jais",["JAISLMHeadModel",To]],["gptj",["GPTJForCausalLM",On]],["gpt_bigcode",["GPTBigCodeForCausalLM",Oi]],["gpt_neo",["GPTNeoForCausalLM",$o]],["gpt_neox",["GPTNeoXForCausalLM",ko]],["codegen",["CodeGenForCausalLM",Po]],["llama",["LlamaForCausalLM",Io]],["olmo",["OlmoForCausalLM",zn]],["mobilellm",["MobileLLMForCausalLM",Oo]],["granite",["GraniteForCausalLM",Lo]],["cohere",["CohereForCausalLM",Ro]],["gemma",["GemmaForCausalLM",jo]],["gemma2",["Gemma2ForCausalLM",Ui]],["openelm",["OpenELMForCausalLM",Gi]],["qwen2",["Qwen2ForCausalLM",si]],["phi",["PhiForCausalLM",qo]],["phi3",["Phi3ForCausalLM",Ko]],["mpt",["MptForCausalLM",zd]],["opt",["OPTForCausalLM",Jo]],["mbart",["MBartForCausalLM",Ct]],["mistral",["MistralForCausalLM",vu]],["starcoder2",["Starcoder2ForCausalLM",Ws]],["falcon",["FalconForCausalLM",Cu]],["trocr",["TrOCRForCausalLM",bu]],["stablelm",["StableLmForCausalLM",Hd]]]),Uu=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",Ss]],["albert",["AlbertForMaskedLM",Yt]],["distilbert",["DistilBertForMaskedLM",Ut]],["roberta",["RobertaForMaskedLM",mn]],["xlm",["XLMWithLMHeadModel",Rn]],["xlm-roberta",["XLMRobertaForMaskedLM",kt]],["mobilebert",["MobileBertForMaskedLM",Ur]],["squeezebert",["SqueezeBertForMaskedLM",An]]]),Wu=new Map([["bert",["BertForQuestionAnswering",Ae]],["roformer",["RoFormerForQuestionAnswering",Tt]],["electra",["ElectraForQuestionAnswering",At]],["convbert",["ConvBertForQuestionAnswering",nt]],["camembert",["CamembertForQuestionAnswering",yn]],["deberta",["DebertaForQuestionAnswering",Ne]],["deberta-v2",["DebertaV2ForQuestionAnswering",Lt]],["mpnet",["MPNetForQuestionAnswering",Is]],["albert",["AlbertForQuestionAnswering",gs]],["distilbert",["DistilBertForQuestionAnswering",ct]],["roberta",["RobertaForQuestionAnswering",tn]],["xlm",["XLMForQuestionAnswering",Kr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Qn]],["mobilebert",["MobileBertForQuestionAnswering",Es]],["squeezebert",["SqueezeBertForQuestionAnswering",fs]]]),qa=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ci]]]),Gu=new Map([["llava",["LlavaForConditionalGeneration",ys]],["moondream1",["Moondream1ForConditionalGeneration",pr]],["florence2",["Florence2ForConditionalGeneration",$i]]]),ec=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ci]]]),qu=new Map([["vit",["ViTForImageClassification",vr]],["pvt",["PvtForImageClassification",nl]],["vit_msn",["ViTMSNForImageClassification",ol]],["fastvit",["FastViTForImageClassification",cl]],["mobilevit",["MobileViTForImageClassification",hl]],["mobilevitv2",["MobileViTV2ForImageClassification",ml]],["beit",["BeitForImageClassification",Ml]],["deit",["DeiTForImageClassification",Pl]],["hiera",["HieraForImageClassification",Fl]],["convnext",["ConvNextForImageClassification",Hl]],["convnextv2",["ConvNextV2ForImageClassification",Kl]],["dinov2",["Dinov2ForImageClassification",_a]],["resnet",["ResNetForImageClassification",zl]],["swin",["SwinForImageClassification",Ll]],["segformer",["SegformerForImageClassification",Oa]],["efficientnet",["EfficientNetForImageClassification",Kd]],["mobilenet_v1",["MobileNetV1ForImageClassification",Ou]],["mobilenet_v2",["MobileNetV2ForImageClassification",Yd]],["mobilenet_v3",["MobileNetV3ForImageClassification",Lu]],["mobilenet_v4",["MobileNetV4ForImageClassification",Bu]]]),Hu=new Map([["detr",["DetrForObjectDetection",xl]],["rt_detr",["RTDetrForObjectDetection",Cl]],["table-transformer",["TableTransformerForObjectDetection",kl]],["yolos",["YolosForObjectDetection",Yl]]]),Ku=new Map([["owlvit",["OwlViTForObjectDetection",gl]],["owlv2",["Owlv2ForObjectDetection",yl]]]),Xu=new Map([["detr",["DetrForSegmentation",li]],["clipseg",["CLIPSegForImageSegmentation",Mo]]]),Ha=new Map([["segformer",["SegformerForSemanticSegmentation",Su]],["sapiens",["SapiensForSemanticSegmentation",Ul]]]),Qu=new Map([["detr",["DetrForSegmentation",li]],["maskformer",["MaskFormerForInstanceSegmentation",ca]]]),tc=new Map([["sam",["SamModel",ga]]]),Ka=new Map([["wav2vec2",["Wav2Vec2ForCTC",Nd]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ea]],["unispeech",["UniSpeechForCTC",Ta]],["unispeech-sat",["UniSpeechSatForCTC",jd]],["wavlm",["WavLMForCTC",hu]],["hubert",["HubertForCTC",cu]]]),Yu=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Ma]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Vd]],["unispeech",["UniSpeechForSequenceClassification",au]],["unispeech-sat",["UniSpeechSatForSequenceClassification",ou]],["wavlm",["WavLMForSequenceClassification",fu]],["hubert",["HubertForSequenceClassification",ka]],["audio-spectrogram-transformer",["ASTForAudioClassification",ri]]]),Zu=new Map([["wavlm",["WavLMForXVector",mu]]]),Ju=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",lu]],["wavlm",["WavLMForAudioFrameClassification",_u]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ru]],["pyannote",["PyAnnoteForAudioFrameClassification",su]]]),rc=new Map([["vitmatte",["VitMatteForImageMatting",Bs]]]),ed=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Rl]]]),td=new Map([["dpt",["DPTForDepthEstimation",Dd]],["depth_anything",["DepthAnythingForDepthEstimation",Vl]],["glpn",["GLPNForDepthEstimation",pa]],["sapiens",["SapiensForDepthEstimation",Wl]],["depth_pro",["DepthProForDepthEstimation",Yn]]]),rd=new Map([["sapiens",["SapiensForNormalEstimation",Gl]]]),nc=new Map([["clip",["CLIPVisionModelWithProjection",fo]],["siglip",["SiglipVisionModel",go]]]),nd=[[Ic,X.EncoderOnly],[Mn,X.EncoderDecoder],[Jd,X.DecoderOnly],[Gs,X.EncoderOnly],[Vu,X.EncoderOnly],[Wa,X.Seq2Seq],[Va,X.Seq2Seq],[Ga,X.DecoderOnly],[Uu,X.EncoderOnly],[Wu,X.EncoderOnly],[qa,X.Vision2Seq],[Gu,X.ImageTextToText],[qu,X.EncoderOnly],[Xu,X.EncoderOnly],[Qu,X.EncoderOnly],[Ha,X.EncoderOnly],[rc,X.EncoderOnly],[ed,X.EncoderOnly],[td,X.EncoderOnly],[rd,X.EncoderOnly],[Hu,X.EncoderOnly],[Ku,X.EncoderOnly],[tc,X.MaskGeneration],[Ka,X.EncoderOnly],[Yu,X.EncoderOnly],[Ua,X.Seq2Seq],[ju,X.EncoderOnly],[Zu,X.EncoderOnly],[Ju,X.EncoderOnly],[nc,X.EncoderOnly]];for(const[f,b]of nd)for(const[R,ve]of f.values())K.set(R,b),k.set(ve,R),j.set(R,ve);const sc=[["MusicgenForConditionalGeneration",Ba,X.Musicgen],["CLIPTextModelWithProjection",xn,X.EncoderOnly],["SiglipTextModel",_o,X.EncoderOnly],["ClapTextModelWithProjection",Aa,X.EncoderOnly],["ClapAudioModelWithProjection",Eu,X.EncoderOnly]];for(const[f,b,R]of sc)K.set(f,R),k.set(b,f),j.set(f,b);class Xa extends zr{}be(Xa,"MODEL_CLASS_MAPPINGS",nd.map(b=>b[0])),be(Xa,"BASE_IF_FAIL",!0);class sd extends zr{}be(sd,"MODEL_CLASS_MAPPINGS",[Gs]);class id extends zr{}be(id,"MODEL_CLASS_MAPPINGS",[Vu]);class ic extends zr{}be(ic,"MODEL_CLASS_MAPPINGS",[Wa]);class ad extends zr{}be(ad,"MODEL_CLASS_MAPPINGS",[Va]);class od extends zr{}be(od,"MODEL_CLASS_MAPPINGS",[Ua]);class ld extends zr{}be(ld,"MODEL_CLASS_MAPPINGS",[ju]);class ud extends zr{}be(ud,"MODEL_CLASS_MAPPINGS",[Ga]);class dd extends zr{}be(dd,"MODEL_CLASS_MAPPINGS",[Uu]);class cd extends zr{}be(cd,"MODEL_CLASS_MAPPINGS",[Wu]);class pd extends zr{}be(pd,"MODEL_CLASS_MAPPINGS",[qa]);class hd extends zr{}be(hd,"MODEL_CLASS_MAPPINGS",[qu]);class fd extends zr{}be(fd,"MODEL_CLASS_MAPPINGS",[Xu]);class ac extends zr{}be(ac,"MODEL_CLASS_MAPPINGS",[Ha]);class qs extends zr{}be(qs,"MODEL_CLASS_MAPPINGS",[Qu]);class Qa extends zr{}be(Qa,"MODEL_CLASS_MAPPINGS",[Hu]);class Ya extends zr{}be(Ya,"MODEL_CLASS_MAPPINGS",[Ku]);class Za extends zr{}be(Za,"MODEL_CLASS_MAPPINGS",[tc]);class Ja extends zr{}be(Ja,"MODEL_CLASS_MAPPINGS",[Ka]);class md extends zr{}be(md,"MODEL_CLASS_MAPPINGS",[Yu]);class _d extends zr{}be(_d,"MODEL_CLASS_MAPPINGS",[Zu]);class eo extends zr{}be(eo,"MODEL_CLASS_MAPPINGS",[Ju]);class to extends zr{}be(to,"MODEL_CLASS_MAPPINGS",[ec]);class gd extends zr{}be(gd,"MODEL_CLASS_MAPPINGS",[rc]);class wd extends zr{}be(wd,"MODEL_CLASS_MAPPINGS",[ed]);class ro extends zr{}be(ro,"MODEL_CLASS_MAPPINGS",[td]);class yd extends zr{}be(yd,"MODEL_CLASS_MAPPINGS",[rd]);class bd extends zr{}be(bd,"MODEL_CLASS_MAPPINGS",[nc]);class Md extends Ze{constructor({logits:b,past_key_values:R,encoder_outputs:ve,decoder_attentions:Ue=null,cross_attentions:Le=null}){super(),this.logits=b,this.past_key_values=R,this.encoder_outputs=ve,this.decoder_attentions=Ue,this.cross_attentions=Le}}class cr extends Ze{constructor({logits:b}){super(),this.logits=b}}class vd extends Ze{constructor({logits:b,embeddings:R}){super(),this.logits=b,this.embeddings=R}}class sn extends Ze{constructor({logits:b}){super(),this.logits=b}}class un extends Ze{constructor({logits:b}){super(),this.logits=b}}class _n extends Ze{constructor({start_logits:b,end_logits:R}){super(),this.start_logits=b,this.end_logits=R}}class as extends Ze{constructor({logits:b}){super(),this.logits=b}}class oc extends Ze{constructor({logits:b,past_key_values:R}){super(),this.logits=b,this.past_key_values=R}}class xd extends Ze{constructor({alphas:b}){super(),this.alphas=b}}class Td extends Ze{constructor({waveform:b,spectrogram:R}){super(),this.waveform=b,this.spectrogram=R}}},"./src/models/whisper/common_whisper.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{WHISPER_LANGUAGE_MAPPING:()=>le,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>we,whisper_language_to_code:()=>xe});const P=[["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"]],le=new Map(P),we=new Map([...P.map(([Ce,U])=>[U,Ce]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function xe(Ce){Ce=Ce.toLowerCase();let U=we.get(Ce);if(U===void 0)if(le.has(Ce))U=Ce;else{const L=Ce.length===2?le.keys():le.values();throw new Error(`Language "${Ce}" is not supported. Must be one of: ${JSON.stringify(L)}`)}return U}},"./src/models/whisper/generation_whisper.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{WhisperGenerationConfig:()=>le});var P=O("./src/generation/configuration_utils.js");class le extends P.GenerationConfig{constructor(){super(...arguments);be(this,"return_timestamps",null);be(this,"return_token_timestamps",null);be(this,"num_frames",null);be(this,"alignment_heads",null);be(this,"task",null);be(this,"language",null);be(this,"no_timestamps_token_id",null);be(this,"prompt_ids",null);be(this,"is_multilingual",null);be(this,"lang_to_id",null);be(this,"task_to_id",null);be(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{TensorOpRegistry:()=>xe});var P=O("./src/backends/onnx.js"),le=O("./src/utils/tensor.js");const we=async(Ce,U,I)=>{const L=await(0,P.createInferenceSession)(new Uint8Array(Ce),U);return async B=>{const q=Object.fromEntries(Object.entries(B).map(([fe,de])=>[fe,de.ort_tensor])),re=await L.run(q);return Array.isArray(I)?I.map(fe=>new le.Tensor(re[fe])):new le.Tensor(re[I])}};class xe{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}}be(xe,"session_options",{})},"./src/pipelines.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{AudioClassificationPipeline:()=>De,AutomaticSpeechRecognitionPipeline:()=>it,DepthEstimationPipeline:()=>Ze,DocumentQuestionAnsweringPipeline:()=>We,FeatureExtractionPipeline:()=>Me,FillMaskPipeline:()=>X,ImageClassificationPipeline:()=>lt,ImageFeatureExtractionPipeline:()=>$e,ImageSegmentationPipeline:()=>me,ImageToImagePipeline:()=>ne,ImageToTextPipeline:()=>rt,ObjectDetectionPipeline:()=>ce,Pipeline:()=>de,QuestionAnsweringPipeline:()=>pe,SummarizationPipeline:()=>j,Text2TextGenerationPipeline:()=>K,TextClassificationPipeline:()=>z,TextGenerationPipeline:()=>E,TextToAudioPipeline:()=>ot,TokenClassificationPipeline:()=>J,TranslationPipeline:()=>k,ZeroShotAudioClassificationPipeline:()=>ze,ZeroShotClassificationPipeline:()=>ue,ZeroShotImageClassificationPipeline:()=>W,ZeroShotObjectDetectionPipeline:()=>Te,pipeline:()=>ht});var P=O("./src/tokenizers.js"),le=O("./src/models.js"),we=O("./src/processors.js"),xe=O("./src/utils/generic.js"),Ce=O("./src/utils/core.js"),U=O("./src/utils/maths.js"),I=O("./src/utils/audio.js"),L=O("./src/utils/tensor.js"),B=O("./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,I.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 de extends xe.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 z extends de{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 L.Tensor("float32",(0,U.softmax)(_t.data),_t.dims),Ve=this.model.config.id2label,ut=[];for(const _t of et.logits){const Pt=je(_t),Tt=await(0,L.topk)(Pt,Ae),v=Tt[0].tolist(),$=Tt[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 de{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 Pt=0;Ptyt==this.tokenizer.sep_token_id);_t[v].map((yt,bt)=>yt==1&&(bt===0||bt>$&&Pt.findIndex(Dt=>Dt==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,U.softmax)(Y).map((yt,bt)=>[yt,bt]),Je=(0,U.softmax)(he).map((yt,bt)=>[yt,bt]);nt[0][0]=0,Je[0][0]=0;const Nt=(0,Ce.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(Pt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Tt=et[ut][Pt],v=await(0,L.topk)(new L.Tensor("float32",(0,U.softmax)(Tt.data),Tt.dims),Ae),H=v[0].tolist(),$=v[1].tolist();je.push($.map((Y,he)=>{const nt=_t.slice();return nt[Pt]=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 de{constructor(Ae){super(Ae);be(this,"_key","generated_text")}async _call(Ae,Ke={}){Array.isArray(Ae)||(Ae=[Ae]),this.model.config.prefix&&(Ae=Ae.map(Pt=>this.model.config.prefix+Pt));const et=this.model.config.task_specific_params;et&&et[this.task]&&et[this.task].prefix&&(Ae=Ae.map(Pt=>et[this.task].prefix+Pt));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(Pt=>({[this._key]:Pt}))}}class j extends K{constructor(Ae){super(Ae);be(this,"_key","summary_text")}}class k extends K{constructor(Ae){super(Ae);be(this,"_key","translation_text")}}function N(Xe){return Array.isArray(Xe)&&Xe.every(Z=>"role"in Z&&"content"in Z)}class E extends de{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}),Pt=await this.model.generate({..._t,...Ae}),Tt=this.tokenizer.batch_decode(Pt,{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(Pt=>Ke.replace("{}",Pt)),ut=et||Ae.length===1,_t=[];for(const Pt of Z){const Tt=[];for(const $ of Ve){const Y=this.tokenizer(Pt,{text_pair:$,padding:!0,truncation:!0}),he=await this.model(Y);ut?Tt.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):Tt.push(he.logits.data[this.entailment_id])}const H=(ut?Tt.map($=>(0,U.softmax)($)[1]):(0,U.softmax)(Tt)).map(($,Y)=>[$,Y]).sort(($,Y)=>Y[0]-$[0]);_t.push({sequence:Pt,labels:H.map($=>Ae[$[1]]),scores:H.map($=>$[0])})}return je?_t:_t[0]}}class Me extends de{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,L.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,L.quantize_embeddings)(_t,je)),_t}}class $e extends de{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 de{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),Tt=(await this.model(_t)).logits[0],v=await(0,L.topk)(new L.Tensor("float32",(0,U.softmax)(Tt.data),Tt.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 de{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(Tt=>Ke.replace("{}",Tt)),Ve=this.tokenizer(je,{padding:!0,truncation:!0}),ut=this.processor.feature_extractor.config.sampling_rate,_t=await re(Z,ut),Pt=[];for(const Tt of _t){const v=await this.processor(Tt),H=await this.model({...Ve,...v}),$=(0,U.softmax)(H.logits_per_audio.data);Pt.push([...$].map((Y,he)=>({score:Y,label:Ae[he]})))}return et?Pt[0]:Pt}}class it extends de{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),Tt=(await this.model(_t)).logits[0],v=[];for(const $ of Tt)v.push((0,U.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 Pt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Tt=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 Dt=0;for(;;){const At=Dt+Nt,dr=Y.subarray(Dt,At),Cr=await this.processor(dr),Yr=Dt===0,Rr=At>=Y.length;if(he.push({stride:[dr.length,Yr?0:yt,Rr?0:yt],input_features:Cr.input_features,is_last:Rr}),Rr)break;Dt+=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]/Tt);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,U.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:Pt,return_timestamps:Ke,force_full_sequences:je});$.push({text:nt,...Je})}return _t?$[0]:$}}class rt extends de{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}),Pt=this.tokenizer.batch_decode(_t,{skip_special_tokens:!0}).map(Tt=>({generated_text:Tt.trim()}));Ve.push(Pt)}return Ke?Ve:Ve[0]}}class lt extends de{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 Pt=await(0,L.topk)(new L.Tensor("float32",(0,U.softmax)(_t.data),_t.dims),Ae),Tt=Pt[0].tolist(),H=Pt[1].tolist().map(($,Y)=>({label:Ve?Ve[$]:`LABEL_${$}`,score:Tt[Y]}));ut.push(H)}return Array.isArray(Z)?ut:ut[0]}}class me extends de{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 Pt=await q(Z),Tt=Pt.map(Je=>[Je.height,Je.width]),{pixel_values:v,pixel_mask:H}=await this.processor(Pt),$=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??Tt)[0],Nt=Je.segmentation;for(const yt of Je.segments_info){const bt=new Uint8ClampedArray(Nt.data.length);for(let At=0;AtKe.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),Pt=await this.model({...ut,pixel_values:_t}),Tt=this.model.config.model_type==="siglip"?H=>H.sigmoid().data:H=>(0,U.softmax)(H.data),v=[];for(const H of Pt.logits_per_image){const Y=[...Tt(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 ce extends de{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),Pt=await this.model({pixel_values:ut,pixel_mask:_t}),Tt=this.processor.feature_extractor.post_process_object_detection(Pt,Ae,Ve),v=this.model.config.id2label,H=Tt.map($=>$.boxes.map((Y,he)=>({score:$.scores[he],label:v[$.classes[he]],box:fe(Y,!Ke)})));return et?H:H[0]}}class Te extends de{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}),Pt=await this.processor(ut),Tt=[];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)),Tt.push(Je)}return Ve?Tt:Tt[0]}}class We extends de{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}),Tt=this.tokenizer.batch_decode(_t)[0].match(/(.*?)<\/s_answer>/);let v=null;return Tt&&Tt.length>=2&&(v=Tt[1].trim()),[{answer:v}]}}class ot extends de{constructor(Ae){super(Ae);be(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 le.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 L.Tensor("float32",Ke,[1,Ke.length]);else if(!(Ke instanceof L.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 ne extends de{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 de{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:P.AutoTokenizer,pipeline:z,model:le.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:P.AutoTokenizer,pipeline:J,model:le.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:P.AutoTokenizer,pipeline:pe,model:le.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:P.AutoTokenizer,pipeline:X,model:le.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:P.AutoTokenizer,pipeline:j,model:le.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:P.AutoTokenizer,pipeline:k,model:le.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:P.AutoTokenizer,pipeline:K,model:le.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:P.AutoTokenizer,pipeline:E,model:le.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:P.AutoTokenizer,pipeline:ue,model:le.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:De,model:le.AutoModelForAudioClassification,processor:we.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:P.AutoTokenizer,pipeline:ze,model:le.AutoModel,processor:we.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:P.AutoTokenizer,pipeline:it,model:[le.AutoModelForSpeechSeq2Seq,le.AutoModelForCTC],processor:we.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:P.AutoTokenizer,pipeline:ot,model:[le.AutoModelForTextToWaveform,le.AutoModelForTextToSpectrogram],processor:[we.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:P.AutoTokenizer,pipeline:rt,model:le.AutoModelForVision2Seq,processor:we.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:lt,model:le.AutoModelForImageClassification,processor:we.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:me,model:[le.AutoModelForImageSegmentation,le.AutoModelForSemanticSegmentation,le.AutoModelForUniversalSegmentation],processor:we.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:P.AutoTokenizer,pipeline:W,model:le.AutoModel,processor:we.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ce,model:le.AutoModelForObjectDetection,processor:we.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:P.AutoTokenizer,pipeline:Te,model:le.AutoModelForZeroShotObjectDetection,processor:we.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:P.AutoTokenizer,pipeline:We,model:le.AutoModelForDocumentQuestionAnswering,processor:we.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ne,model:le.AutoModelForImageToImage,processor:we.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ze,model:le.AutoModelForDepthEstimation,processor:we.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:P.AutoTokenizer,pipeline:Me,model:le.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:we.AutoProcessor,pipeline:$e,model:[le.AutoModelForImageFeatureExtraction,le.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:Pt=null,session_options:Tt={}}={}){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:Pt,session_options:Tt},$=new Map([["tokenizer",v.tokenizer],["model",v.model],["processor",v.processor]]),Y=await Mt($,Z,H);Y.task=Xe,(0,Ce.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,Pt)=>{var v,H;let Tt;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"))Tt=Y;else if((H=Y.message)!=null&&H.includes("Could not locate file"))Tt=Y;else{Pt(Y);return}}}Pt(Tt)}):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":(xt,ye,O)=>{O.r(ye),O.d(ye,{ASTFeatureExtractor:()=>he,AutoProcessor:()=>yn,BeitFeatureExtractor:()=>Ae,BitImageProcessor:()=>Me,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:()=>Te,FeatureExtractor:()=>X,Florence2Processor:()=>Jr,GLPNFeatureExtractor:()=>$e,ImageFeatureExtractor:()=>K,MaskFormerFeatureExtractor:()=>ut,MobileNetV1FeatureExtractor:()=>We,MobileNetV2FeatureExtractor:()=>ot,MobileNetV3FeatureExtractor:()=>ne,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:()=>Pt,SamProcessor:()=>Dt,SapiensFeatureExtractor:()=>j,SeamlessM4TFeatureExtractor:()=>Y,SegformerFeatureExtractor:()=>k,SiglipImageProcessor:()=>rt,SpeechT5FeatureExtractor:()=>yt,SpeechT5Processor:()=>Yr,Swin2SRImageProcessor:()=>Tt,ViTFeatureExtractor:()=>W,ViTImageProcessor:()=>ce,VitMatteImageProcessor:()=>v,Wav2Vec2FeatureExtractor:()=>$,Wav2Vec2ProcessorWithLM:()=>dr,WeSpeakerFeatureExtractor:()=>Nt,WhisperFeatureExtractor:()=>H,WhisperProcessor:()=>At,YolosFeatureExtractor:()=>_t});var P=O("./src/utils/generic.js"),le=O("./src/utils/core.js"),we=O("./src/utils/hub.js"),xe=O("./src/utils/maths.js"),Ce=O("./src/utils/tensor.js");O("./src/utils/image.js");var U=O("./src/utils/audio.js");function I([at,G,ge,Ie]){return[at-ge/2,G-Ie/2,at+ge/2,G+Ie/2]}function L(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 $t=[];for(let ft=0;ftG&&Ut.push(br)}else{let br=(0,xe.max)(ct.data)[1];if(br===mt-1||(sr=(0,xe.softmax)(ct.data),sr[br]mr*Lt[(kr+1)%2])),jt.boxes.push(Nr),jt.classes.push(br),jt.scores.push(sr[br])}}$t.push(jt)}return $t}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 Ot=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($t),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 $t=tt>0&&wt>0;return $t&&($t=tt/wt>Se),[$t,Ne]}function fe(at,G,ge,Ie,Se,Ne=null,tt=null){const[wt,mt]=tt??at[0].dims,$t=new Ce.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 Ot=0;const Fe=$t.data;for(let Oe=0;OeIe&&(Ne=Math.floor(Se)*G),NeNe?$t=Math.floor(Ne*mt/Se):Ne>Se&&(mt=Math.floor(Se*$t/Ne)),await G.resize($t,mt,{resample:Ie}))}async crop_margin(G,ge=200){const Ie=G.clone().grayscale(),Se=(0,xe.min)(Ie.data)[0],tt=(0,xe.max)(Ie.data)[0]-Se;if(tt===0)return G;const wt=ge/255;let mt=Ie.width,$t=Ie.height,ft=0,Lt=0;const jt=Ie.data;for(let Ot=0;Otthis.preprocess(Ne)));return{pixel_values:(0,Ce.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 Me extends K{}class $e 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 ce extends K{}class Te 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 ne extends K{}class Ze extends K{}class dt extends K{}class Re extends dt{}class ht extends K{post_process_object_detection(...G){return L(...G)}}class Mt extends ht{}class Xe extends K{post_process_object_detection(...G){return L(...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 $t=this.image_std;Array.isArray($t)||($t=new Array(wt).fill(mt));const ft=mt.map((Lt,jt)=>-Lt/$t[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,Ce.full)(Ie,1n);return{...ge,pixel_mask:Se}}post_process_object_detection(...G){return L(...G)}post_process_panoptic_segmentation(...G){return de(...G)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class ut extends K{post_process_panoptic_segmentation(...G){return de(...G)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class _t extends K{post_process_object_detection(...G){return L(...G)}}class Pt extends K{reshape_input_points(G,ge,Ie,Se=!1){G=structuredClone(G);let Ne=(0,le.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 Ce.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 $t=0;$tSe&&(Fe[Oe]=1);jt=new Ce.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 Tt 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,Ce.stack)(Ie.map((tt,wt)=>(0,Ce.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,U.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,U.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(G){const ge=await(0,U.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,xe.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){z(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 Ce.Tensor("float32",ge,Ie),attention_mask:new Ce.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,U.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,U.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}={}){z(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 Ce.Tensor(tt.type,sr,[br,Oe]),Ne&&(wt=new Ce.Tensor("int64",new BigInt64Array(br),[1,br]),wt.data.fill(1n,0,Fe))}}const[mt,$t]=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),$t*ft),Ot={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:$t*Ie,end:ft*Ie,confidence:Lt/(ft-$t)})))}return Se}}class Nt extends X{constructor(G){super(G);const ge=this.config.sampling_rate,Ie=(0,U.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,U.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){z(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=[],$t=[];for(const[ft,Lt,...jt]of wt)mt.push(Lt?Lt.trim():mt.at(-1)??""),$t.push(jt.map((Ot,Fe)=>(Number(Ot)+.5)/this.size_per_bin*Ie[Fe%2]));Ne={labels:mt,[tt]:$t};break;default:throw new Error(`Task "${ge}" (of type "${Se}") not yet implemented.`)}return{[ge]:Ne}}}class yn{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,$t=this.FEATURE_EXTRACTOR_CLASS_MAPPING[mt];if(!$t)if(wt.size!==void 0)console.warn(`Feature extractor type "${mt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),$t=K;else throw new Error(`Unknown Feature Extractor type: ${mt}`);let ft=this.PROCESSOR_CLASS_MAPPING[wt.processor_class]??bt,Lt=new $t(wt);return new ft(Lt)}}be(yn,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:K,WhisperFeatureExtractor:H,ViTFeatureExtractor:W,MobileViTFeatureExtractor:dt,MobileViTImageProcessor:Re,MobileNetV1FeatureExtractor:We,MobileNetV2FeatureExtractor:ot,MobileNetV3FeatureExtractor:ne,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:Me,DPTImageProcessor:ue,DPTFeatureExtractor:E,PvtImageProcessor:N,GLPNFeatureExtractor:$e,BeitFeatureExtractor:Ae,DeiTFeatureExtractor:Z,DetrFeatureExtractor:Ve,RTDetrImageProcessor:Xe,MaskFormerFeatureExtractor:ut,YolosFeatureExtractor:_t,DonutFeatureExtractor:Ke,DonutImageProcessor:et,NougatImageProcessor:je,EfficientNetImageProcessor:Te,ViTImageProcessor:ce,VitMatteImageProcessor:v,SamImageProcessor:Pt,Swin2SRImageProcessor:Tt,Wav2Vec2FeatureExtractor:$,SeamlessM4TFeatureExtractor:Y,SpeechT5FeatureExtractor:yt,ASTFeatureExtractor:he,ClapFeatureExtractor:nt,PyAnnoteFeatureExtractor:Je,WeSpeakerFeatureExtractor:Nt}),be(yn,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:At,Wav2Vec2ProcessorWithLM:dr,PyAnnoteProcessor:Cr,SamProcessor:Dt,SpeechT5Processor:Yr,OwlViTProcessor:Rr,Florence2Processor:Jr})},"./src/tokenizers.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{AlbertTokenizer:()=>tt,AutoTokenizer:()=>Ls,BartTokenizer:()=>Nr,BertTokenizer:()=>Ne,BlenderbotSmallTokenizer:()=>Os,BlenderbotTokenizer:()=>Fs,BloomTokenizer:()=>$n,CLIPTokenizer:()=>_s,CamembertTokenizer:()=>Oe,CodeGenTokenizer:()=>ms,CodeLlamaTokenizer:()=>Es,CohereTokenizer:()=>ns,ConvBertTokenizer:()=>jt,DebertaTokenizer:()=>$t,DebertaV2Tokenizer:()=>ft,DistilBertTokenizer:()=>Fe,ElectraTokenizer:()=>Ut,EsmTokenizer:()=>As,FalconTokenizer:()=>Ss,GPT2Tokenizer:()=>br,GPTNeoXTokenizer:()=>Ps,GemmaTokenizer:()=>ts,Grok1Tokenizer:()=>Xn,HerbertTokenizer:()=>Lt,LlamaTokenizer:()=>hs,M2M100Tokenizer:()=>fs,MBart50Tokenizer:()=>kr,MBartTokenizer:()=>mr,MPNetTokenizer:()=>ks,MarianTokenizer:()=>Yt,MobileBertTokenizer:()=>wt,NllbTokenizer:()=>Bn,NougatTokenizer:()=>zs,PreTrainedTokenizer:()=>Se,Qwen2Tokenizer:()=>Is,RoFormerTokenizer:()=>Ot,RobertaTokenizer:()=>wr,SiglipTokenizer:()=>gs,SpeechT5Tokenizer:()=>ws,SqueezeBertTokenizer:()=>mt,T5Tokenizer:()=>sr,TokenizerModel:()=>$e,VitsTokenizer:()=>Ds,Wav2Vec2CTCTokenizer:()=>rs,WhisperTokenizer:()=>Ln,XLMRobertaTokenizer:()=>Kn,XLMTokenizer:()=>ct,is_chinese_char:()=>X});var P=O("./src/utils/generic.js"),le=O("./src/utils/core.js"),we=O("./src/utils/hub.js"),xe=O("./src/utils/maths.js"),Ce=O("./src/utils/tensor.js"),U=O("./src/utils/data-structures.js"),I=O("./node_modules/@huggingface/jinja/dist/index.js"),L=O("./src/models/whisper/common_whisper.js");O("./src/utils/constants.js");async function B(ae,_){const F=await Promise.all([(0,we.getModelJSON)(ae,"tokenizer.json",!0,_),(0,we.getModelJSON)(ae,"tokenizer_config.json",!0,_)]);return _.legacy!==null&&(F[1].legacy=_.legacy),F}function q(ae,_){const F=[];let Q=0;for(const oe of ae.matchAll(_)){const _e=oe[0];Q0&&F.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,_,F){const Q=[];let oe=0;for(;oethis.tokens_to_ids.get(F)??this.unk_token_id)}convert_ids_to_tokens(_){return _.map(F=>this.vocab[F]??this.unk_token)}}class De extends $e{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[F,Q]of this.tokens_to_ids)this.vocab[Q]=F}encode(_){const F=[];for(const Q of _){const oe=[...Q];if(oe.length>this.max_input_chars_per_word){F.push(this.unk_token);continue}let _e=!1,Ge=0;const gt=[];for(;Ge0&&(zt=this.config.continuing_subword_prefix+zt),this.tokens_to_ids.has(zt)){Ct=zt;break}--Et}if(Ct===null){_e=!0;break}gt.push(Ct),Ge=Et}_e?F.push(this.unk_token):F.push(...gt)}return F}}class ze extends $e{constructor(_,F){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=F.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,xe.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new U.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(_){const F=_.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 F=0;for(let oe=0;oe<256;++oe)ae.includes(oe)||(ae.push(oe),_.push(256+F),F+=1);const Q=_.map(oe=>String.fromCharCode(oe));return Object.fromEntries(ae.map((oe,_e)=>[oe,Q[_e]]))})(),rt=(0,le.reverseDictionary)(it);class lt extends $e{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 F=Array.isArray(_.merges[0]);this.merges=F?_.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 F=this.cache.get(_);if(F!==void 0)return F;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 U.PriorityQueue((Et,Ct)=>Et.score`<0x${gt.toString(16).toUpperCase().padStart(2,"0")}>`);Ge.every(gt=>this.tokens_to_ids.has(gt))?F.push(...Ge):F.push(this.unk_token)}else F.push(this.unk_token)}return F}}class me extends $e{constructor(_,F){super(_),this.tokens_to_ids=fe(F.target_lang?_.vocab[F.target_lang]:_.vocab),this.bos_token=F.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=F.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=F.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=F.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 P.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 ce(_);case"NFC":return new Te(_);case"NFKC":return new We(_);case"NFKD":return new ot(_);case"Strip":return new ne(_);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 ce extends W{normalize(_){const F=re(this.config.pattern);return F===null?_:_.replaceAll(F,this.config.content)}}class Te extends W{normalize(_){return _=_.normalize("NFC"),_}}class We extends W{normalize(_){return _=_.normalize("NFKC"),_}}class ot extends W{normalize(_){return _=_.normalize("NFKD"),_}}class ne 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(F=>W.fromConfig(F))}normalize(_){return this.normalizers.reduce((F,Q)=>Q.normalize(F),_)}}class Mt extends W{_tokenize_chinese_chars(_){const F=[];for(let Q=0;Q<_.length;++Q){const oe=_[Q],_e=oe.charCodeAt(0);X(_e)?(F.push(" "),F.push(oe),F.push(" ")):F.push(oe)}return F.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 F=[];for(const Q of _){const oe=Q.charCodeAt(0);oe===0||oe===65533||this._is_control(Q)||(/^\s$/.test(Q)?F.push(" "):F.push(Q))}return F.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 P.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 yn(_);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(_,F){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(_,F){return(Array.isArray(_)?_.map(Q=>this.pre_tokenize_text(Q,F)):this.pre_tokenize_text(_,F)).flat()}_call(_,F){return this.pre_tokenize(_,F)}}class Z extends Xe{constructor(_){super(),this.pattern=new RegExp(`[^\\s${k}]+|[${k}]`,"gu")}pre_tokenize_text(_,F){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(_,F){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(_,F){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(_,F){return _.match(this.pattern)||[]}}class je extends Xe{constructor(_){super(),this.config=_;const F=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(F,"gu")}pre_tokenize_text(_,F){return _.match(this.pattern)||[]}}class Ve extends P.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"TemplateProcessing":return new Pt(_);case"ByteLevel":return new Tt(_);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(_,...F){throw Error("post_process should be implemented in subclass.")}_call(_,...F){return this.post_process(_,...F)}}class ut extends Ve{constructor(_){super(_),this.cls=_.cls[0],this.sep=_.sep[0]}post_process(_,F=null,{add_special_tokens:Q=!0}={}){Q&&(_=(0,le.mergeArrays)([this.cls],_,[this.sep]));let oe=new Array(_.length).fill(0);if(F!==null){const _e=Q&&this instanceof _t?[this.sep]:[],Ge=Q?[this.sep]:[];_=(0,le.mergeArrays)(_,_e,F,Ge),oe=(0,le.mergeArrays)(oe,new Array(F.length+_e.length+Ge.length).fill(1))}return{tokens:_,token_type_ids:oe}}}class _t extends ut{}class Pt extends Ve{constructor(_){super(_),this.single=_.single,this.pair=_.pair}post_process(_,F=null,{add_special_tokens:Q=!0}={}){const oe=F===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,le.mergeArrays)(_e,_),Ge=(0,le.mergeArrays)(Ge,new Array(_.length).fill(gt.Sequence.type_id))):gt.Sequence.id==="B"&&(_e=(0,le.mergeArrays)(_e,F),Ge=(0,le.mergeArrays)(Ge,new Array(F.length).fill(gt.Sequence.type_id))));return{tokens:_e,token_type_ids:Ge}}}class Tt extends Ve{post_process(_,F=null){return F&&(_=(0,le.mergeArrays)(_,F)),{tokens:_}}}class v extends Ve{constructor(_){super(_),this.processors=_.processors.map(F=>Ve.fromConfig(F))}post_process(_,F=null,Q={}){let oe;for(const _e of this.processors)if(_e instanceof Tt)_=_e.post_process(_).tokens,F&&(F=_e.post_process(F).tokens);else{const Ge=_e.post_process(_,F,Q);_=Ge.tokens,oe=Ge.token_type_ids}return{tokens:_,token_type_ids:oe}}}class H extends P.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 Dt(_);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 F=re(this.config.pattern);return F===null?_:_.map(Q=>Q.replaceAll(F,this.config.content))}}class Y extends H{constructor(_){super(_),this.text_decoder=new TextDecoder}decode_chain(_){const F=[];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));F.push(Ge),Q=[]}F.push(oe)}}if(Q.length>0){const oe=this.text_decoder.decode(Uint8Array.from(Q));F.push(oe),Q=[]}return F}}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(F=>{let Q=0;for(let _e=0;_e(Q!==0&&(F.startsWith(this.config.prefix)?F=F.replace(this.config.prefix,""):F=" "+F),this.cleanup&&(F=z(F)),F))}}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 F=_.join(""),Q=new Uint8Array([...F].map(_e=>this.byte_decoder[_e]));return this.text_decoder.decode(Q)}decode_chain(_){const F=[];let Q=[];for(const oe of _)this.added_tokens.find(_e=>_e.content===oe)!==void 0?(Q.length>0&&(F.push(this.convert_tokens_to_string(Q)),Q=[]),F.push(oe)):Q.push(oe);return Q.length>0&&F.push(this.convert_tokens_to_string(Q)),F}}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 F=[_[0]];for(let _e=1;_e<_.length;++_e)_[_e]!==F.at(-1)&&F.push(_[_e]);let oe=F.filter(_e=>_e!==this.pad_token).join("");return this.cleanup&&(oe=z(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(F=>H.fromConfig(F))}decode_chain(_){return this.decoders.reduce((F,Q)=>Q.decode_chain(F),_)}}class Dt extends H{constructor(_){super(_),this.suffix=this.config.suffix}decode_chain(_){return _.map((F,Q)=>F.replaceAll(this.suffix,Q===_.length-1?"":" "))}}class At extends H{decode_chain(_){let F="";for(let Q=1;Q<_.length;Q+=2)F+=_[Q];return[F]}}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:F=void 0}={}){let Q=_.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Q.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&F===0)&&(Q=this.strRep+Q),[Q]}}class Cr extends H{constructor(_){super(_),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement}decode_chain(_){const F=[];for(let Q=0;Q<_.length;++Q){let oe=_[Q].replaceAll(this.replacement," ");this.addPrefixSpace&&Q==0&&oe.startsWith(" ")&&(oe=oe.substring(1)),F.push(oe)}return F}}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(F=>Xe.fromConfig(F))}pre_tokenize_text(_,F){return this.tokenizers.reduce((Q,oe)=>oe.pre_tokenize(Q,F),[_])}}class Jr extends Xe{constructor(_){super()}pre_tokenize_text(_,F){return _.match(/\w+|[^\w\s]+/g)||[]}}class yn extends Xe{constructor(_){super()}pre_tokenize_text(_,F){return j(_)}}class at extends Xe{constructor(_){super(),this.config=_,this.pattern=re(this.config.pattern),this.content=this.config.content}pre_tokenize_text(_,F){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,_,F,Q){for(const oe of Object.keys(ae)){const _e=_-ae[oe].length,Ge=F(oe),gt=new Array(_e).fill(Ge);ae[oe]=Q==="right"?(0,le.mergeArrays)(ae[oe],gt):(0,le.mergeArrays)(gt,ae[oe])}}function Ie(ae,_){for(const F of Object.keys(ae))ae[F].length=_}class Se extends P.Callable{constructor(F,Q){super();be(this,"return_token_type_ids",!1);be(this,"padding_side","right");this._tokenizer_config=Q,this.normalizer=W.fromConfig(F.normalizer),this.pre_tokenizer=Xe.fromConfig(F.pre_tokenizer),this.model=$e.fromConfig(F.model,Q),this.post_processor=Ve.fromConfig(F.post_processor),this.decoder=H.fromConfig(F.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const oe of F.added_tokens){const _e=new Me(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,le.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(...F){for(const Q of F){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(F,{progress_callback:Q=null,config:oe=null,cache_dir:_e=null,local_files_only:Ge=!1,revision:gt="main",legacy:Et=null}={}){const Ct=await B(F,{progress_callback:Q,config:oe,cache_dir:_e,local_files_only:Ge,revision:gt,legacy:Et});return new this(...Ct)}_call(F,{text_pair:Q=null,add_special_tokens:oe=!0,padding:_e=!1,truncation:Ge=null,max_length:gt=null,return_tensor:Et=!0,return_token_type_ids:Ct=null}={}){const zt=Array.isArray(F);let er;if(zt){if(F.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(F.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=F.map((ur,Wr)=>this._encode_plus(ur,{text_pair:Q[Wr],add_special_tokens:oe,return_token_type_ids:Ct}))}else er=F.map(ur=>this._encode_plus(ur,{add_special_tokens:oe,return_token_type_ids:Ct}))}else{if(F==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(F,{text_pair:Q,add_special_tokens:oe,return_token_type_ids:Ct})]}if(gt===null?_e==="max_length"?gt=this.model_max_length:gt=(0,xe.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(Et){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 Ce.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(!zt)for(const ur of Object.keys(Sr))Sr[ur]=Sr[ur][0]}return Sr}_encode_text(F){return F===null?null:(this.added_tokens_regex?F.split(this.added_tokens_regex).filter(_e=>_e):[F]).map((_e,Ge)=>{if(this.added_tokens.find(Et=>Et.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 Et=this.pre_tokenizer!==null?this.pre_tokenizer(_e,{section_index:Ge}):[_e];return this.model(Et)}}).flat()}_encode_plus(F,{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(F,{pair:Q,add_special_tokens:oe}),Et=this.model.convert_tokens_to_ids(Ge),Ct={input_ids:Et,attention_mask:new Array(Et.length).fill(1)};return(_e??this.return_token_type_ids)&>&&(Ct.token_type_ids=gt),Ct}_tokenize_helper(F,{pair:Q=null,add_special_tokens:oe=!1}={}){const _e=this._encode_text(F),Ge=this._encode_text(Q);return this.post_processor?this.post_processor(_e,Ge,{add_special_tokens:oe}):{tokens:(0,le.mergeArrays)(_e??[],Ge??[])}}tokenize(F,{pair:Q=null,add_special_tokens:oe=!1}={}){return this._tokenize_helper(F,{pair:Q,add_special_tokens:oe}).tokens}encode(F,{text_pair:Q=null,add_special_tokens:oe=!0,return_token_type_ids:_e=null}={}){return this._encode_plus(F,{text_pair:Q,add_special_tokens:oe,return_token_type_ids:_e}).input_ids}batch_decode(F,Q={}){return F instanceof Ce.Tensor&&(F=F.tolist()),F.map(oe=>this.decode(oe,Q))}decode(F,Q={}){if(F instanceof Ce.Tensor&&(F=de(F)),!Array.isArray(F)||F.length===0||!(0,le.isIntegralNumber)(F[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(F,Q)}decode_single(F,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:oe=null}){let _e=this.model.convert_ids_to_tokens(F);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=z(Ge)),Ge}get_chat_template({chat_template:F=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const oe=this.chat_template;if(F!==null&&Object.hasOwn(oe,F))F=oe[F];else if(F===null)if(Q!==null&&"tool_use"in oe)F=oe.tool_use;else if("default"in oe)F=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(F===null)if(this.chat_template)F=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 F}apply_chat_template(F,{tools:Q=null,documents:oe=null,chat_template:_e=null,add_generation_prompt:Ge=!1,tokenize:gt=!0,padding:Et=!1,truncation:Ct=!1,max_length:zt=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 I.Template(_e),this._compiled_template_cache.set(_e,en));const or=Object.create(null);for(const mn of G){const bn=this.getToken(mn);bn&&(or[mn]=bn)}const Pr=en.render({messages:F,add_generation_prompt:Ge,tools:Q,documents:oe,...or,...Wr});if(gt){const mn=this._call(Pr,{add_special_tokens:!1,padding:Et,truncation:Ct,max_length:zt,return_tensor:er,...ur});return Sr?mn:mn.input_ids}return Pr}}class Ne extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class tt extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class wt extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class mt extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class $t extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class ft extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class Lt extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class jt extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class Ot extends Se{constructor(){super(...arguments);be(this,"return_token_type_ids",!0)}}class Fe extends Se{}class Oe extends Se{}class ct extends Se{constructor(F,Q){super(F,Q);be(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);be(this,"return_token_type_ids",!0)}}class sr extends Se{}class br extends Se{}class Nr extends Se{}class mr extends Se{constructor(_,F){super(_,F),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(_,F,Q){return An(this,_,F,Q)}}class kr extends mr{}class wr extends Se{}class $n extends Se{}const Ur="▁";class hs extends Se{constructor(F,Q){super(F,Q);be(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(F){if(F===null)return null;if(this.legacy||F.length===0)return super._encode_text(F);let Q=super._encode_text(Ur+F.replaceAll(Ur," "));return Q.length>1&&Q[0]===Ur&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class Es extends Se{}class Kn extends Se{}class ks extends Se{}class Ss extends Se{}class Ps extends Se{}class As extends Se{}class Is extends Se{}class ts extends Se{}class Xn extends Se{}function An(ae,_,F,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(_,F)}class Bn extends Se{constructor(_,F){super(_,F),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(_,F,Q){return An(this,_,F,Q)}}class fs extends Se{constructor(_,F){super(_,F),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(_,F,Q){return An(this,_,F,Q)}}class Ln extends Se{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(_,{return_timestamps:F=!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=F==="word";function Et(){return{language:Ge,timestamp:[null,null],text:""}}const Ct=[];let zt=Et(),er=0;const Sr=this.timestamp_begin;let ur=[],Wr=[],en=!1,or=null;const Pr=new Set(this.all_special_ids);for(const Ee of _){const tn=Ee.tokens,ln=gt?Ee.token_timestamps:null;let In=null,Rn=Sr;if("stride"in Ee){const[Kr,fr,Or]=Ee.stride;if(er-=fr,or=Kr-Or,fr&&(Rn=fr/oe+Sr),Or)for(let kt=tn.length-1;kt>=0;--kt){const _r=Number(tn[kt]);if(_r>=Sr){if(In!==null&&(_r-Sr)*oe=Sr){const Or=(fr-Sr)*oe+er,kt=(0,xe.round)(Or,2);if(In!==null&&fr>=In)en=!0;else if(en||ur.length>0&&fr0?(ur.push(Kt),gt&&Wr.push(pn)):ur.every(Kr=>Kr.length===0)&&(zt=Et(),ur=[],Kt=[],Wr=[],pn=[])}if(ur.length>0){if(_e&&F)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[Ee,tn]=this.findLongestCommonSequence(ur,Wr),ln=this.decode(Ee);zt.text=ln,gt&&(zt.words=this.collateWordTimestamps(Ee,tn,Ge)),Ct.push(zt)}let mn=Object.create(null);const bn=Ct.map(Ee=>Ee.text).join("");if(F||Q){for(let Ee=0;Ee0;let gt=Ge?[]:null,Et=Ge?F[0]:null;for(let Ct=1;Ct<_.length;++Ct){const zt=_[Ct];let er=0,Sr=[oe,oe,0,0];const ur=zt.length;for(let Ee=1;Eekt===pn[_r]&&Et[tn+_r]<=F[Ct][Rn+_r]).length:Kr=In.filter((kt,_r)=>kt===pn[_r]).length;const fr=Ee/1e4,Or=Kr/Ee+fr;Kr>1&&Or>er&&(er=Or,Sr=[tn,ln,Rn,Kt])}const[Wr,en,or,Pr]=Sr,mn=Math.floor((en+Wr)/2),bn=Math.floor((Pr+or)/2);_e.push(...Q.slice(0,mn)),Q=zt.slice(bn),oe=Q.length,Ge&&(gt.push(...Et.slice(0,mn)),Et=F[Ct].slice(bn))}return _e.push(...Q),Ge?(gt.push(...Et),[_e,gt]):[_e,[]]}collateWordTimestamps(_,F,Q){const[oe,_e,Ge]=this.combineTokensIntoWords(_,Q),gt=[];for(let Et=0;Et=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,F)),_e.join("")}splitTokensOnUnicode(_){const F=this.decode(_,{decode_with_timestamps:!0}),Q="�",oe=[],_e=[],Ge=[];let gt=[],Et=[],Ct=0;for(let zt=0;zt<_.length;++zt){const er=_[zt];gt.push(er),Et.push(zt);const Sr=this.decode(gt,{decode_with_timestamps:!0});(!Sr.includes(Q)||F[Ct+Sr.indexOf(Q)]===Q)&&(oe.push(Sr),_e.push(gt),Ge.push(Et),gt=[],Et=[],Ct+=Sr.length)}return[oe,_e,Ge]}splitTokensOnSpaces(_){const[F,Q,oe]=this.splitTokensOnUnicode(_),_e=[],Ge=[],gt=[],Et=new RegExp(`^[${k}]$`,"gu");for(let Ct=0;Ct=this.model.tokens_to_ids.get("<|endoftext|>"),Wr=zt.startsWith(" "),en=zt.trim(),or=Et.test(en);if(ur||Wr||or||_e.length===0)_e.push(zt),Ge.push(er),gt.push(Sr);else{const Pr=_e.length-1;_e[Pr]+=zt,Ge[Pr].push(...er),gt[Pr].push(...Sr)}}return[_e,Ge,gt]}mergePunctuations(_,F,Q,oe,_e){const Ge=structuredClone(_),gt=structuredClone(F),Et=structuredClone(Q);let Ct=Ge.length-2,zt=Ge.length-1;for(;Ct>=0;)Ge[Ct].startsWith(" ")&&oe.includes(Ge[Ct].trim())?(Ge[zt]=Ge[Ct]+Ge[zt],gt[zt]=(0,le.mergeArrays)(gt[Ct],gt[zt]),Et[zt]=(0,le.mergeArrays)(Et[Ct],Et[zt]),Ge[Ct]="",gt[Ct]=[],Et[Ct]=[]):zt=Ct,--Ct;for(Ct=0,zt=1;zter),gt.filter(er=>er.length>0),Et.filter(er=>er.length>0)]}}class ms extends Se{}class _s extends Se{}class gs extends Se{}class Yt extends Se{constructor(_,F){super(_,F),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[F,...Q]=_.trim().split(this.languageRegex);if(Q.length===0)return super._encode_text(F);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,le.mergeArrays)([oe],super._encode_text(_e))}}}class rs extends Se{}class Fs extends Se{}class Os extends Se{}class ws extends Se{}class zs extends Se{}class Ds extends Se{constructor(_,F){super(_,F),this.decoder=new At({})}}class ns extends Se{}class Ls{static async from_pretrained(_,{progress_callback:F=null,config:Q=null,cache_dir:oe=null,local_files_only:_e=!1,revision:Ge="main",legacy:gt=null}={}){var Sr;const[Et,Ct]=await B(_,{progress_callback:F,config:Q,cache_dir:oe,local_files_only:_e,revision:Ge,legacy:gt}),zt=((Sr=Ct.tokenizer_class)==null?void 0:Sr.replace(/Fast$/,""))??"PreTrainedTokenizer";let er=this.TOKENIZER_CLASS_MAPPING[zt];return er||(console.warn(`Unknown tokenizer class "${zt}", attempting to construct from base class.`),er=Se),new er(Et,Ct)}}be(Ls,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:sr,DistilBertTokenizer:Fe,CamembertTokenizer:Oe,DebertaTokenizer:$t,DebertaV2Tokenizer:ft,BertTokenizer:Ne,HerbertTokenizer:Lt,ConvBertTokenizer:jt,RoFormerTokenizer:Ot,XLMTokenizer:ct,ElectraTokenizer:Ut,MobileBertTokenizer:wt,SqueezeBertTokenizer:mt,AlbertTokenizer:tt,GPT2Tokenizer:br,BartTokenizer:Nr,MBartTokenizer:mr,MBart50Tokenizer:kr,RobertaTokenizer:wr,WhisperTokenizer:Ln,CodeGenTokenizer:ms,CLIPTokenizer:_s,SiglipTokenizer:gs,MarianTokenizer:Yt,BloomTokenizer:$n,NllbTokenizer:Bn,M2M100Tokenizer:fs,LlamaTokenizer:hs,CodeLlamaTokenizer:Es,XLMRobertaTokenizer:Kn,MPNetTokenizer:ks,FalconTokenizer:Ss,GPTNeoXTokenizer:Ps,EsmTokenizer:As,Wav2Vec2CTCTokenizer:rs,BlenderbotTokenizer:Fs,BlenderbotSmallTokenizer:Os,SpeechT5Tokenizer:ws,NougatTokenizer:zs,VitsTokenizer:Ds,Qwen2Tokenizer:Is,GemmaTokenizer:ts,Grok1Tokenizer:Xn,CohereTokenizer:ns,PreTrainedTokenizer:Se})},"./src/utils/audio.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{hamming:()=>L,hanning:()=>I,mel_filter_bank:()=>J,read_audio:()=>Ce,spectrogram:()=>k,window_function:()=>N});var P=O("./src/utils/hub.js"),le=O("./src/utils/maths.js"),we=O("./src/utils/core.js"),xe=O("./src/utils/tensor.js");async function Ce(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 Me=await(await(0,P.getFile)(E)).arrayBuffer(),$e=new AudioContext({sampleRate:ue});typeof ue>"u"&&console.warn(`No sampling rate provided, using default of ${$e.sampleRate}Hz.`);const De=await $e.decodeAudioData(Me);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,Me=15,$e=27/Math.log(6.4))=>E>=ue?Me+Math.log(E/ue)*$e:3*E/200};function q(E,ue="htk"){const Me=B[ue];if(!Me)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof E=="number"?Me(E):E.map($e=>Me($e))}const re={htk:E=>700*(10**(E/2595)-1),kaldi:E=>700*(Math.exp(E/1127)-1),slaney:(E,ue=1e3,Me=15,$e=Math.log(6.4)/27)=>E>=Me?ue*Math.exp($e*(E-Me)):200*E/3};function fe(E,ue="htk"){const Me=re[ue];if(!Me)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof E=="number"?Me(E):E.map($e=>Me($e))}function de(E,ue){const Me=Float64Array.from({length:ue.length-1},(it,rt)=>ue[rt+1]-ue[rt]),$e=Array.from({length:E.length},()=>new Array(ue.length));for(let it=0;itnew Array(E.length));for(let it=0;itE+$e*ze)}function J(E,ue,Me,$e,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(Me,it),me=q($e,it),W=z(lt,me,ue+2);let ce=fe(W,it),Te;if(rt){const ot=De/(E*2);Te=q(Float64Array.from({length:E},(ne,Ze)=>Ze*ot),it),ce=W}else Te=z(0,Math.floor(De/2),E);const We=de(Te,ce);if(ze!==null&&ze==="slaney")for(let ot=0;otDe)throw Error(`frame_length (${Me}) may not be larger than fft_length (${De})`);if(Xe!==Me)throw new Error(`Length of the window (${Xe}) must equal frame_length (${Me})`);if($e<=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-Me)/$e));dt!==null&&ZZ?ht&&(et=Re):et=Ke=Re);const je=new le.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(Me&&(it=it.subarray(0,E)),$e===null)return it;if(E>$e)throw new Error(`Length of the window (${E}) may not be larger than frame_length (${$e})`);return it}},"./src/utils/constants.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{GITHUB_ISSUE_URL:()=>P});const P="https://github.com/huggingface/transformers.js/issues/new/choose"},"./src/utils/core.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{calculateDimensions:()=>U,calculateReflectOffset:()=>q,dispatchCallback:()=>P,escapeRegExp:()=>we,isIntegralNumber:()=>Ce,isTypedArray:()=>xe,len:()=>fe,mergeArrays:()=>L,pick:()=>re,pop:()=>I,product:()=>B,reverseDictionary:()=>le});function P(de,z){de&&de(z)}function le(de){return Object.fromEntries(Object.entries(de).map(([z,J])=>[J,z]))}function we(de){return de.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xe(de){var z,J,pe;return((pe=(J=(z=de==null?void 0:de.prototype)==null?void 0:z.__proto__)==null?void 0:J.constructor)==null?void 0:pe.name)==="TypedArray"}function Ce(de){return Number.isInteger(de)||typeof de=="bigint"}function U(de){const z=[];let J=de;for(;Array.isArray(J);)z.push(J.length),J=J[0];return z}function I(de,z,J=void 0){const pe=de[z];if(pe!==void 0)return delete de[z],pe;if(J===void 0)throw Error(`Key ${z} does not exist in object.`);return J}function L(...de){return Array.prototype.concat.apply([],de)}function B(...de){return de.reduce((z,J)=>z.flatMap(pe=>J.map(X=>[pe,X])))}function q(de,z){return Math.abs((de+z)%(2*z)-z)}function re(de,z){return Object.assign({},...z.map(J=>{if(de[J]!==void 0)return{[J]:de[J]}}))}function fe(de){let z=0;for(const J of de)++z;return z}},"./src/utils/data-structures.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{CharTrie:()=>le,PriorityQueue:()=>P,TokenLattice:()=>xe});class P{constructor(I=(B,q)=>B>q,L=1/0){this._heap=[],this._comparator=I,this._maxSize=L}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...I){return this.extend(I)}extend(I){for(const L of I)if(this.size0&&this._swap(0,L),this._heap.pop(),this._siftDown(),I}replace(I){const L=this.peek();return this._heap[0]=I,this._siftDown(),L}_parent(I){return(I+1>>>1)-1}_left(I){return(I<<1)+1}_right(I){return I+1<<1}_greater(I,L){return this._comparator(this._heap[I],this._heap[L])}_swap(I,L){const B=this._heap[I];this._heap[I]=this._heap[L],this._heap[L]=B}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(I){for(;I>0&&this._greater(I,this._parent(I));)this._swap(I,this._parent(I)),I=this._parent(I)}_siftDown(){let I=0;for(;this._left(I)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const q=new Ce(this.bosTokenId,0,0,0,0),re=new Ce(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(I,L,B,q){const re=this.nodes.length,fe=new Ce(q,re,I,L,B);this.beginNodes[I].push(fe),this.endNodes[I+L].push(fe),this.nodes.push(fe)}viterbi(){const I=this.len;let L=0;for(;L<=I;){if(this.beginNodes[L].length==0)return[];for(let de of this.beginNodes[L]){de.prev=null;let z=0,J=null;for(let pe of this.endNodes[L]){const X=pe.backtraceScore+de.score;(J===null||X>z)&&(J=pe.clone(),z=X)}if(J!==null)de.prev=J,de.backtraceScore=z;else return[]}++L}const B=[],re=this.beginNodes[I][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(I){return this.chars.slice(I.pos,I.pos+I.length).join("")}tokens(){return this.viterbi().map(L=>this.piece(L))}tokenIds(){return this.viterbi().map(L=>L.tokenId)}}class Ce{constructor(I,L,B,q,re){this.tokenId=I,this.nodeId=L,this.pos=B,this.length=q,this.score=re,this.prev=null,this.backtraceScore=0}clone(){const I=new Ce(this.tokenId,this.nodeId,this.pos,this.length,this.score);return I.prev=this.prev,I.backtraceScore=this.backtraceScore,I}}},"./src/utils/devices.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{DEVICE_TYPES:()=>P});const P=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":(xt,ye,O)=>{O.r(ye),O.d(ye,{DATA_TYPES:()=>xe,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Ce,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>U,isWebGpuFp16Supported:()=>we});var P=O("./src/env.js"),le=O("./src/utils/devices.js");const we=function(){let I;return async function(){if(I===void 0)if(!P.apis.IS_WEBGPU_AVAILABLE)I=!1;else try{I=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{I=!1}return I}}(),xe=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Ce=Object.freeze({[le.DEVICE_TYPES.wasm]:xe.q8}),U=Object.freeze({[xe.fp32]:"",[xe.fp16]:"_fp16",[xe.int8]:"_int8",[xe.uint8]:"_uint8",[xe.q8]:"_quantized",[xe.q4]:"_q4",[xe.q4f16]:"_q4f16",[xe.bnb4]:"_bnb4"})},"./src/utils/generic.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{Callable:()=>P});const P=class{constructor(){let le=function(...we){return le._call(...we)};return Object.setPrototypeOf(le,new.target.prototype)}_call(...le){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{getFile:()=>L,getModelFile:()=>de,getModelJSON:()=>z});var P=O("?7a2c"),le=O("?a42a"),we=O("./src/env.js"),xe=O("./src/utils/core.js");const Ce={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class U{constructor(K){if(this.filePath=K,this.headers=new Headers,this.exists=P.existsSync(K),this.exists){this.status=200,this.statusText="OK";let j=P.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",Ce[K]??"application/octet-stream")}clone(){let K=new U(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 P.promises.readFile(this.filePath)).buffer}async blob(){const K=await P.promises.readFile(this.filePath);return new Blob([K],{type:this.headers.get("content-type")})}async text(){return await P.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function I(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 L(X){var K;if(we.env.useFS&&!I(X,["http:","https:","blob:"]))return new U(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};`),I(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=le.join(this.path,K),k=new U(j);if(k.exists)return k}async put(K,j){const k=Buffer.from(await j.arrayBuffer());let N=le.join(this.path,K);try{await P.promises.mkdir(le.dirname(N),{recursive:!0}),await P.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 de(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,xe.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(Te){console.warn("An error occurred while opening the browser cache:",Te)}}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),Me=pe(we.env.localModelPath,ue),$e=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:$e,rt=!1,lt;N&&(lt=await fe(N,Me,it));const me=lt!==void 0;if(lt===void 0){if(we.env.allowLocalModels)if(I(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 L(Me),ze=Me}catch(We){console.warn(`Unable to load from local path "${Me}": "${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 "${Me}".`);return null}if(lt=await L($e),lt.status!==200)return q(lt.status,$e,j);ze=it}rt=N&&typeof Response<"u"&< instanceof Response&<.status===200}(0,xe.dispatchCallback)(k.progress_callback,{status:"download",name:X,file:K});const W={status:"progress",name:X,file:K};let ce;return k.progress_callback?me&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ce=new Uint8Array(await lt.arrayBuffer()),(0,xe.dispatchCallback)(k.progress_callback,{...W,progress:100,loaded:ce.length,total:ce.length})):ce=await J(lt,Te=>{(0,xe.dispatchCallback)(k.progress_callback,{...W,...Te})}):ce=new Uint8Array(await lt.arrayBuffer()),rt&&ze&&await N.match(ze)===void 0&&await N.put(ze,new Response(ce,{headers:lt.headers})).catch(Te=>{console.warn(`Unable to add response to browser cache: ${Te}.`)}),(0,xe.dispatchCallback)(k.progress_callback,{status:"done",name:X,file:K}),ce}async function z(X,K,j=!0,k={}){let N=await de(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 Me(){const{done:$e,value:De}=await ue.read();if($e)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}),Me()}return await Me(),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":(xt,ye,O)=>{O.r(ye),O.d(ye,{RawImage:()=>fe});var P=O("./src/utils/hub.js"),le=O("./src/env.js"),we=O("./src/utils/tensor.js"),xe=O("?2b25");const Ce=typeof self<"u",U=Ce&&self.constructor.name==="DedicatedWorkerGlobalScope";let I,L,B;if(Ce)I=(de,z)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(de,z)},B=self.createImageBitmap,L=self.ImageData;else if(xe)B=async de=>{const J=(await de.metadata()).channels,{data:pe,info:X}=await de.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(z,J,pe,X){this.data=z,this.width=J,this.height=pe,this.channels=X}get size(){return[this.width,this.height]}static async read(z){if(z instanceof fe)return z;if(typeof z=="string"||z instanceof URL)return await this.fromURL(z);throw new Error(`Unsupported input type: ${typeof z}`)}static fromCanvas(z){if(!Ce)throw new Error("fromCanvas() is only supported in browser environments.");const pe=z.getContext("2d").getImageData(0,0,z.width,z.height).data;return new fe(pe,z.width,z.height,4)}static async fromURL(z){const J=await(0,P.getFile)(z);if(J.status!==200)throw new Error(`Unable to read image from "${z}" (${J.status} ${J.statusText})`);const pe=await J.blob();return this.fromBlob(pe)}static async fromBlob(z){if(Ce){const J=await B(z),pe=I(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=xe(await z.arrayBuffer());return await B(J)}}static fromTensor(z,J="CHW"){if(z.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${z.dims.length} dimensions.`);if(J==="CHW")z=z.transpose(1,2,0);else if(J!=="HWC")throw new Error(`Unsupported channel format: ${J}`);if(!(z.data instanceof Uint8ClampedArray||z.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${z.type}`);switch(z.dims[2]){case 1:case 2:case 3:case 4:return new fe(z.data,z.dims[1],z.dims[0],z.dims[2]);default:throw new Error(`Unsupported number of channels: ${z.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const z=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:Me=-X,k.drawImage(j,N,E,z,J,ue,Me,z,J),new fe(k.getImageData(0,0,z,J).data,z,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:z,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:z-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]=z-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:z,height:J})}return await B(K)}}async toBlob(z="image/png",J=1){if(!Ce)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:z,quality:J})}toTensor(z="CHW"){let J=new we.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(z!=="HWC")if(z==="CHW")J=J.permute(2,0,1);else throw new Error(`Unsupported channel format: ${z}`);return J}toCanvas(){if(!Ce)throw new Error("toCanvas() is only supported in browser environments.");const z=this.clone().rgba(),J=I(z.width,z.height),pe=new L(z.data,z.width,z.height);return J.getContext("2d").putImageData(pe,0,0),J}_update(z,J,pe,X=null){return this.data=z,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(z){if(this.channels===z)return this;switch(z){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(z){if(Ce){if(U)throw new Error("Unable to save an image from a Web Worker.");const J=z.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=z,j.click(),j.remove()}else{if(le.env.useFS)return await this.toSharp().toFile(z);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Ce)throw new Error("toSharp() is only supported in server-side environments.");return xe(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{FFT:()=>de,bankers_round:()=>pe,cos_sim:()=>U,dot:()=>Ce,dynamic_time_warping:()=>X,interpolate_data:()=>P,log_softmax:()=>xe,magnitude:()=>I,max:()=>B,medianFilter:()=>z,min:()=>L,permute_data:()=>le,round:()=>J,softmax:()=>we});function P(K,[j,k,N],[E,ue],Me="bilinear",$e=!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;--$e)E[$e]=De,N[$e]=j[k[$e]],De*=N[$e];const ue=k.map(($e,De)=>E[k.indexOf(De)]),Me=new K.constructor(K.length);for(let $e=0;$e=0;--ze)De+=it%j[ze]*ue[ze],it=Math.floor(it/j[ze]);Me[De]=K[$e]}return[Me,N]}function we(K){const j=B(K)[0],k=K.map(ue=>Math.exp(ue-j)),N=k.reduce((ue,Me)=>ue+Me,0);return k.map(ue=>ue/N)}function xe(K){const j=B(K)[0];let k=0;for(let ue=0;ueue-j-N)}function Ce(K,j){let k=0;for(let N=0;Nj+k*k,0))}function L(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;Me>=2;Me>>=2){$e=E/Me<<1;const lt=$e>>>2;for(De=0;De>>1,Me>>>1)}else for(De=0,ze=0;De>>1,Me>>>1,N)}const rt=this.table;for(Me>>=2;Me>=2;Me>>=2){$e=E/Me<<1;const me=$e>>>1,W=me>>>1,ce=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),Me[W]=ue[W],Me[W+1]=-ue[W+1]}this._slicedChirpBuffer=ue.subarray(k,N),this._f=new re(E>>1),this._f.transform(this._chirpBuffer,Me)}_transform(j,k,N){const E=this._buffer1,ue=this._buffer2,Me=this._outBuffer1,$e=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[Me++]=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||$e>0;)switch(De.push(Me-1),ze.push($e-1),ue[Me][$e]){case 0:--Me,--$e;break;case 1:--Me;break;case 2:--$e;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${Me}, ${$e}]. Please file a bug report.`)}return De.reverse(),ze.reverse(),[De,ze]}},"./src/utils/tensor.js":(xt,ye,O)=>{O.r(ye),O.d(ye,{Tensor:()=>Ce,cat:()=>K,full:()=>Me,full_like:()=>$e,interpolate:()=>L,interpolate_4d:()=>B,layer_norm:()=>z,matmul:()=>q,mean:()=>N,mean_pooling:()=>de,ones:()=>De,ones_like:()=>ze,permute:()=>I,quantize_embeddings:()=>lt,rfft:()=>re,stack:()=>j,std_mean:()=>k,topk:()=>fe,zeros:()=>it,zeros_like:()=>rt});var P=O("./src/utils/maths.js"),le=O("./src/backends/onnx.js"),we=O("./src/ops/registry.js");const xe=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class Ce{constructor(...W){be(this,"ort_tensor");return(0,le.isONNXTensor)(W[0])?this.ort_tensor=W[0]:this.ort_tensor=new le.Tensor(W[0],W[1],W[2]),new Proxy(this,{get:(ce,Te)=>{if(typeof Te=="string"){let We=Number(Te);if(Number.isInteger(We))return ce._getitem(We)}return ce[Te]},set:(ce,Te,We)=>ce[Te]=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,...ce]=this.dims;if(ce.length>0){const Te=ce.reduce((We,ot)=>We*ot);for(let We=0;We0){const We=Te.reduce((ot,ne)=>ot*ne);return this._subarray(W,We,Te)}else return new Ce(this.type,[this.data[W]],Te)}indexOf(W){const ce=this.data;for(let Te=0;TeXe)throw new Error(`Invalid slice: ${ht}`);const Z=[Math.max(Mt,0),Math.min(Xe,this.dims[Re])];Te.push(Z),ce.push(Z[1]-Z[0])}else throw new Error(`Invalid slice: ${ht}`)}const We=Te.map(([Re,ht])=>ht-Re),ot=We.reduce((Re,ht)=>Re*ht),ne=this.data,Ze=new ne.constructor(ot),dt=this.stride();for(let Re=0;Re=0;--Mt){const Z=We[Mt];ht+=(Xe%Z+Te[Mt][0])*dt[Mt],Xe=Math.floor(Xe/Z)}Ze[Re]=ne[ht]}return new Ce(this.type,Ze,ce)}permute(...W){return I(this,W)}transpose(...W){return this.permute(...W)}sum(W=null,ce=!1){return this.norm(1,W,ce)}norm(W="fro",ce=null,Te=!1){if(W==="fro")W=2;else if(typeof W=="string")throw Error(`Unsupported norm: ${W}`);const We=this.data;if(ce===null){let Ze=We.reduce((dt,Re)=>dt+Re**W,0)**(1/W);return new Ce(this.type,[Ze],[])}ce=X(ce,this.dims.length);const ot=this.dims.slice();ot[ce]=1;const ne=new We.constructor(We.length/this.dims[ce]);for(let Ze=0;Ze=0;--Re){const Xe=this.dims[Re];if(Re!==ce){const Z=ht%Xe;dt+=Z*Mt,Mt*=ot[Re]}ht=Math.floor(ht/Xe)}ne[dt]+=We[Ze]**W}if(W!==1)for(let Ze=0;Ze=0;--dt){const Mt=this.dims[dt];if(dt!==ce){const Xe=Re%Mt;Ze+=Xe*ht,ht*=this.dims[dt]}Re=Math.floor(Re/Mt)}We[ne]/=ot[Ze]}return this}normalize(W=2,ce=1){return this.clone().normalize_(W,ce)}stride(){return E(this.dims)}squeeze(W=null){return new Ce(this.type,this.data,J(this.dims,W))}squeeze_(W=null){return this.dims=J(this.dims,W),this}unsqueeze(W=null){return new Ce(this.type,this.data,pe(this.dims,W))}unsqueeze_(W=null){return this.dims=pe(this.dims,W),this}flatten_(W=0,ce=-1){ce=(ce+this.dims.length)%this.dims.length;let Te=this.dims.slice(0,W),We=this.dims.slice(W,ce+1),ot=this.dims.slice(ce+1);return this.dims=[...Te,We.reduce((ne,Ze)=>ne*Ze,1),...ot],this}flatten(W=0,ce=-1){return this.clone().flatten_(W,ce)}view(...W){let ce=-1;for(let We=0;WeZe!==ce?ot*ne:ot,1);W[ce]=Te.length/We}return new Ce(this.type,Te,W)}neg_(){const W=this.data;for(let ce=0;ceot*ne);if(ce!==Te)throw Error(`cannot reshape array of size ${ce} into shape (${W})`);let We=me;for(let ot=W.length-1;ot>=0;ot--)We=We.reduce((ne,Ze)=>{let dt=ne[ne.length-1];return dt.lengthce!==1):typeof W=="number"?me[W]===1&&me.splice(W,1):Array.isArray(W)&&(me=me.filter((ce,Te)=>ce!==1||!W.includes(Te))),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,ce=null,Te=!0){if(Te&&(me<-W||me>=W))throw new Error(`IndexError: index ${me} is out of bounds for dimension${ce===null?"":" "+ce} 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 ce=me[0].dims.slice();ce[W]=me.reduce((ne,Ze)=>ne+Ze.dims[W],0);const Te=ce.reduce((ne,Ze)=>ne*Ze,1),We=new me[0].data.constructor(Te),ot=me[0].type;if(W===0){let ne=0;for(const Ze of me){const dt=Ze.data;We.set(dt,ne),ne+=dt.length}}else{let ne=0;for(let Ze=0;Ze=0;--Xe){const Ke=Re[Xe];let et=Z%Ke;Xe===W&&(et+=ne),Mt+=et*Ae,Ae*=ce[Xe],Z=Math.floor(Z/Ke)}We[Mt]=dt[ht]}ne+=Re[W]}}return new Ce(ot,We,ce)}function j(me,W=0){return K(me.map(ce=>ce.unsqueeze(W)),W)}function k(me,W=null,ce=1,Te=!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-ce)),Ae=new Ce(me.type,[Xe],[]);return[new Ce(me.type,[Z],[]),Ae]}W=X(W,ot.length);const ne=N(me,W,Te),Ze=ne.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 Ce(me.type,[Ze/Te.length],[])}const We=me.dims;W=X(W,We.length);const ot=We.slice();ot[W]=1;const ne=new Te.constructor(Te.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)}ne[dt]+=Te[Ze]}if(We[W]!==1)for(let Ze=0;Ze=0;--ce)W[ce]=Te,Te*=me[ce];return W}function ue(me,W,ce,Te){const We=me.reduce((ot,ne)=>ot*ne,1);return new Ce(ce,new Te(We).fill(W),me)}function Me(me,W){let ce,Te;if(typeof W=="number")ce="float32",Te=Float32Array;else if(typeof W=="bigint")ce="int64",Te=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof W}`);return ue(me,W,ce,Te)}function $e(me,W){return Me(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 ce=W==="binary",Te=ce?"int8":"uint8",We=ce?Int8Array:Uint8Array,ot=me.data,ne=new We(ot.length/8);for(let Ze=0;Ze0?1:0,Re=Math.floor(Ze/8),ht=Ze%8;ne[Re]|=dt<<7-ht,ce&&ht===0&&(ne[Re]-=128)}return new Ce(Te,ne,[me.dims[0],me.dims[1]/8])}}},ti={};function qr(xt){var ye=ti[xt];if(ye!==void 0)return ye.exports;var O=ti[xt]={exports:{}};return es[xt](O,O.exports,qr),O.exports}qr.m=es,(()=>{var xt=Object.getPrototypeOf?O=>Object.getPrototypeOf(O):O=>O.__proto__,ye;qr.t=function(O,P){if(P&1&&(O=this(O)),P&8||typeof O=="object"&&O&&(P&4&&O.__esModule||P&16&&typeof O.then=="function"))return O;var le=Object.create(null);qr.r(le);var we={};ye=ye||[null,xt({}),xt([]),xt(xt)];for(var xe=P&2&&O;typeof xe=="object"&&!~ye.indexOf(xe);xe=xt(xe))Object.getOwnPropertyNames(xe).forEach(Ce=>we[Ce]=()=>O[Ce]);return we.default=()=>O,qr.d(le,we),le}})(),qr.d=(xt,ye)=>{for(var O in ye)qr.o(ye,O)&&!qr.o(xt,O)&&Object.defineProperty(xt,O,{enumerable:!0,get:ye[O]})},qr.o=(xt,ye)=>Object.prototype.hasOwnProperty.call(xt,ye),qr.r=xt=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(xt,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(xt,"__esModule",{value:!0})},(()=>{var xt;if(typeof self.location.href=="string"&&(xt=self.location.href),!xt)throw new Error("Automatic publicPath is not supported in this browser");xt=xt.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),qr.p=xt})(),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:()=>Sc.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:()=>Pc.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:()=>uo.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:()=>uo.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:()=>uo.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,MobileLLMForCausalLM:()=>y.MobileLLMForCausalLM,MobileLLMModel:()=>y.MobileLLMModel,MobileLLMPreTrainedModel:()=>y.MobileLLMPreTrainedModel,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,OlmoForCausalLM:()=>y.OlmoForCausalLM,OlmoModel:()=>y.OlmoModel,OlmoPreTrainedModel:()=>y.OlmoPreTrainedModel,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:()=>Sc.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:()=>Rf.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:()=>uo.StoppingCriteria,StoppingCriteriaList:()=>uo.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:()=>Pc.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:()=>Pc.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:()=>Bf.env,full:()=>on.full,full_like:()=>on.full_like,getKeyValueShapes:()=>Sc.getKeyValueShapes,hamming:()=>xi.hamming,hanning:()=>xi.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:()=>xi.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:()=>xi.read_audio,rfft:()=>on.rfft,round:()=>Pn.round,softmax:()=>Pn.softmax,spectrogram:()=>xi.spectrogram,stack:()=>on.stack,std_mean:()=>on.std_mean,topk:()=>on.topk,window_function:()=>xi.window_function,zeros:()=>on.zeros,zeros_like:()=>on.zeros_like});var Bf=qr("./src/env.js"),Hr=qr("./src/pipelines.js"),y=qr("./src/models.js"),lr=qr("./src/tokenizers.js"),Jt=qr("./src/processors.js"),Sc=qr("./src/configs.js"),xi=qr("./src/utils/audio.js"),Rf=qr("./src/utils/image.js"),on=qr("./src/utils/tensor.js"),Pn=qr("./src/utils/maths.js"),Pc=qr("./src/generation/streamers.js"),uo=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;var Nf=p.AutoProcessor,jf=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.MobileLLMForCausalLM,p.MobileLLMModel,p.MobileLLMPreTrainedModel,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.OlmoForCausalLM,p.OlmoModel,p.OlmoPreTrainedModel,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;var Vf=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;var vp=p.env,Uf=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,vp.allowLocalModels=!1,vp.allowRemoteModels=!0;const Wf=96;class ps{static async getInstance(ye,O=null){if(this.isInitialized&&this.model_id===ye)return[this.tokenizer,this.processor,this.model];try{return this.model_id=ye,this.tokenizer=await jf.from_pretrained(ye,{progress_callback:P=>{O==null||O({status:"initiate",file:"tokenizer",...P})}}),this.processor=await Nf.from_pretrained(ye,{progress_callback:P=>{O==null||O({status:"initiate",file:"processor",...P})}}),this.model=await Vf.from_pretrained(ye,{local:!1,device:"webgpu",dtype:"fp32",quantized:!1,progress_callback:P=>{O==null||O({status:"initiate",file:"model",...P})}}),this.isInitialized=!0,[this.tokenizer,this.processor,this.model]}catch(P){throw console.error("Pipeline initialization error:",P),P}}}be(ps,"model_id",null),be(ps,"tokenizer",null),be(ps,"processor",null),be(ps,"model",null),be(ps,"isInitialized",!1);let xp=!1,Ad=null,$s=new Map,Ac=!1;async function Gf(xt,ye){try{const[O,P,le]=await Ad,xe={...await P(xt),max_new_tokens:Wf,num_beams:1,temperature:0,return_dict_in_generate:!1,output_scores:!1};ps.model_id.endsWith(".en")||(xe.language=ye.language,xe.task="transcribe");const Ce=await le.generate(xe);return O.batch_decode(Ce,{skip_special_tokens:!0})[0]}catch(O){throw console.error("Transcription error:",O),O}}async function Tp(){if(!(Ac||$s.size===0)){Ac=!0;try{const[xt]=$s.keys(),ye=$s.get(xt);console.log("Processing task:",ye.data.segmentId);try{const O=await Gf(ye.data.audioData,{language:ye.data.language});self.postMessage({status:"complete",segmentId:ye.data.segmentId,output:O,isMerged:ye.data.isMerged})}catch(O){console.error("Error transcribing segment:",ye.data.segmentId,O),self.postMessage({status:"error",segmentId:ye.data.segmentId,error:O.message})}$s.delete(xt)}catch(xt){console.error("Queue processing error:",xt)}finally{Ac=!1,$s.size>0&&setTimeout(Tp,100)}}}async function qf(xt){if(xp){console.log("Model already loaded"),self.postMessage({status:"ready"});return}console.log("Loading Whisper model:",xt),self.postMessage({status:"loading",data:`Loading ${xt}...`});try{Ad=ps.getInstance(xt,we=>{self.postMessage(we)}),await Ad,console.log("Warming up model..."),self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const[ye,O,P]=await Ad,le={input_features:Uf([1,80,3e3],0),max_new_tokens:1,num_beams:1,temperature:0};xt.endsWith(".en")||(le.language="en",le.task="transcribe"),await P.generate(le),xp=!0,console.log("Model ready"),self.postMessage({status:"ready"})}catch(ye){throw console.error("Error loading model:",ye),ye}}self.addEventListener("message",async xt=>{var P;const{type:ye,data:O}=xt.data;switch(ye){case"load":await qf(O.modelId);break;case"transcribe":if($s.has(O.segmentId))console.log("Segment already in queue:",O.segmentId);else{const le={...O,isEnglishOnly:(P=ps.model_id)==null?void 0:P.endsWith(".en"),language:O.language||"en"};$s.set(O.segmentId,{type:ye,data:le}),console.log("Added to queue:",O.segmentId,"Queue size:",$s.size,"Language:",le.isEnglishOnly?"en (English-only model)":le.language,"Model:",ps.model_id),Tp()}break}})})();