diff --git "a/assets/worker-749W3JaX.js" "b/assets/worker-749W3JaX.js" new file mode 100644--- /dev/null +++ "b/assets/worker-749W3JaX.js" @@ -0,0 +1,2585 @@ +var f_=Object.defineProperty;var m_=(Tn,es,Ks)=>es in Tn?f_(Tn,es,{enumerable:!0,configurable:!0,writable:!0,value:Ks}):Tn[es]=Ks;var Me=(Tn,es,Ks)=>m_(Tn,typeof es!="symbol"?es+"":es,Ks);(function(){"use strict";var Tn={},es={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Ft,Ee,N)=>{Ft.exports=N.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{Environment:()=>je,Interpreter:()=>lt,Template:()=>Et,parse:()=>$e,tokenize:()=>P});var z=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"}),me=Object.freeze({set:z.Set,for:z.For,in:z.In,is:z.Is,if:z.If,else:z.Else,endif:z.EndIf,elif:z.ElseIf,endfor:z.EndFor,and:z.And,or:z.Or,not:z.Not,"not in":z.NotIn,macro:z.Macro,endmacro:z.EndMacro,true:z.BooleanLiteral,false:z.BooleanLiteral,True:z.BooleanLiteral,False:z.BooleanLiteral}),we=class{constructor(x,H){this.value=x,this.type=H}};function Te(x){return/\w/.test(x)}function Ce(x){return/[0-9]/.test(x)}var R=[["{%",z.OpenStatement],["%}",z.CloseStatement],["{{",z.OpenExpression],["}}",z.CloseExpression],["(",z.OpenParen],[")",z.CloseParen],["{",z.OpenCurlyBracket],["}",z.CloseCurlyBracket],["[",z.OpenSquareBracket],["]",z.CloseSquareBracket],[",",z.Comma],[".",z.Dot],[":",z.Colon],["|",z.Pipe],["<=",z.ComparisonBinaryOperator],[">=",z.ComparisonBinaryOperator],["==",z.ComparisonBinaryOperator],["!=",z.ComparisonBinaryOperator],["<",z.ComparisonBinaryOperator],[">",z.ComparisonBinaryOperator],["+",z.AdditiveBinaryOperator],["-",z.AdditiveBinaryOperator],["*",z.MultiplicativeBinaryOperator],["/",z.MultiplicativeBinaryOperator],["%",z.MultiplicativeBinaryOperator],["=",z.Equals]],S=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function V(x,H={}){return x.endsWith(` +`)&&(x=x.slice(0,-1)),x=x.replace(/{#.*?#}/gs,"{##}"),H.lstrip_blocks&&(x=x.replace(/^[ \t]*({[#%])/gm,"$1")),H.trim_blocks&&(x=x.replace(/([#%]})\n/g,"$1")),x.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function P(x,H={}){var Je,Bt,ct;const $=[],Q=V(x,H);let he=0;const Ye=Tt=>{let At="";for(;Tt(Q[he]);){if(Q[he]==="\\"){if(++he,he>=Q.length)throw new SyntaxError("Unexpected end of input");const Pt=Q[he++],cr=S.get(Pt);if(cr===void 0)throw new SyntaxError(`Unexpected escaped character: ${Pt}`);At+=cr;continue}if(At+=Q[he++],he>=Q.length)throw new SyntaxError("Unexpected end of input")}return At};e:for(;he0){$.push(new we(Pt,z.Text));continue}}Ye(Pt=>/\s/.test(Pt));const At=Q[he];if(At==="-"||At==="+"){const Pt=(Bt=$.at(-1))==null?void 0:Bt.type;if(Pt===z.Text||Pt===void 0)throw new SyntaxError(`Unexpected character: ${At}`);switch(Pt){case z.Identifier:case z.NumericLiteral:case z.BooleanLiteral:case z.StringLiteral:case z.CloseParen:case z.CloseSquareBracket:break;default:{++he;const cr=Ye(Ce);$.push(new we(`${At}${cr}`,cr.length>0?z.NumericLiteral:z.UnaryOperator));continue}}}for(const[Pt,cr]of R)if(Q.slice(he,he+Pt.length)===Pt){$.push(new we(Pt,cr)),he+=Pt.length;continue e}if(At==="'"||At==='"'){++he;const Pt=Ye(cr=>cr!==At);$.push(new we(Pt,z.StringLiteral)),++he;continue}if(Ce(At)){const Pt=Ye(Ce);$.push(new we(Pt,z.NumericLiteral));continue}if(Te(At)){const Pt=Ye(Te),cr=Object.hasOwn(me,Pt)?me[Pt]:z.Identifier;cr===z.In&&((ct=$.at(-1))==null?void 0:ct.type)===z.Not?($.pop(),$.push(new we("not in",z.NotIn))):$.push(new we(Pt,cr));continue}throw new SyntaxError(`Unexpected character: ${At}`)}return $}var re=class{constructor(){Me(this,"type","Statement")}},ne=class extends re{constructor(H){super();Me(this,"type","Program");this.body=H}},_e=class extends re{constructor(H,$,Q){super();Me(this,"type","If");this.test=H,this.body=$,this.alternate=Q}},ce=class extends re{constructor(H,$,Q,he){super();Me(this,"type","For");this.loopvar=H,this.iterable=$,this.body=Q,this.defaultBlock=he}},D=class extends re{constructor(H,$){super();Me(this,"type","Set");this.assignee=H,this.value=$}},q=class extends re{constructor(H,$,Q){super();Me(this,"type","Macro");this.name=H,this.args=$,this.body=Q}},te=class extends re{constructor(){super(...arguments);Me(this,"type","Expression")}},ie=class extends te{constructor(H,$,Q){super();Me(this,"type","MemberExpression");this.object=H,this.property=$,this.computed=Q}},X=class extends te{constructor(H,$){super();Me(this,"type","CallExpression");this.callee=H,this.args=$}},j=class extends te{constructor(H){super();Me(this,"type","Identifier");this.value=H}},I=class extends te{constructor(H){super();Me(this,"type","Literal");this.value=H}},L=class extends I{constructor(){super(...arguments);Me(this,"type","NumericLiteral")}},k=class extends I{constructor(){super(...arguments);Me(this,"type","StringLiteral")}},de=class extends I{constructor(){super(...arguments);Me(this,"type","BooleanLiteral")}},ve=class extends I{constructor(){super(...arguments);Me(this,"type","ArrayLiteral")}},ke=class extends I{constructor(){super(...arguments);Me(this,"type","TupleLiteral")}},ze=class extends I{constructor(){super(...arguments);Me(this,"type","ObjectLiteral")}},Ie=class extends te{constructor(H,$,Q){super();Me(this,"type","BinaryExpression");this.operator=H,this.left=$,this.right=Q}},Ze=class extends te{constructor(H,$){super();Me(this,"type","FilterExpression");this.operand=H,this.filter=$}},Ke=class extends te{constructor(H,$){super();Me(this,"type","SelectExpression");this.iterable=H,this.test=$}},ut=class extends te{constructor(H,$,Q){super();Me(this,"type","TestExpression");this.operand=H,this.negate=$,this.test=Q}},ye=class extends te{constructor(H,$){super();Me(this,"type","UnaryExpression");this.operator=H,this.argument=$}},W=class extends te{constructor(H=void 0,$=void 0,Q=void 0){super();Me(this,"type","SliceExpression");this.start=H,this.stop=$,this.step=Q}},fe=class extends te{constructor(H,$){super();Me(this,"type","KeywordArgumentExpression");this.key=H,this.value=$}};function $e(x){const H=new ne([]);let $=0;function Q(be,tt){const st=x[$++];if(!st||st.type!==be)throw new Error(`Parser Error: ${tt}. ${st.type} !== ${be}.`);return st}function he(){switch(x[$].type){case z.Text:return Bt();case z.OpenStatement:return ct();case z.OpenExpression:return Tt();default:throw new SyntaxError(`Unexpected token type: ${x[$].type}`)}}function Ye(...be){return $+be.length<=x.length&&be.some((tt,st)=>tt!==x[$+st].type)}function Je(...be){return $+be.length<=x.length&&be.every((tt,st)=>tt===x[$+st].type)}function Bt(){return new k(Q(z.Text,"Expected text token").value)}function ct(){Q(z.OpenStatement,"Expected opening statement token");let be;switch(x[$].type){case z.Set:++$,be=At(),Q(z.CloseStatement,"Expected closing statement token");break;case z.If:++$,be=Pt(),Q(z.OpenStatement,"Expected {% token"),Q(z.EndIf,"Expected endif token"),Q(z.CloseStatement,"Expected %} token");break;case z.Macro:++$,be=cr(),Q(z.OpenStatement,"Expected {% token"),Q(z.EndMacro,"Expected endmacro token"),Q(z.CloseStatement,"Expected %} token");break;case z.For:++$,be=Qr(),Q(z.OpenStatement,"Expected {% token"),Q(z.EndFor,"Expected endfor token"),Q(z.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${x[$].type}`)}return be}function Tt(){Q(z.OpenExpression,"Expected opening expression token");const be=Or();return Q(z.CloseExpression,"Expected closing expression token"),be}function At(){const be=Or();if(Je(z.Equals)){++$;const tt=At();return new D(be,tt)}return be}function Pt(){var qt,wr,Br,Kr,rr,Wr,Vr,Ln;const be=Or();Q(z.CloseStatement,"Expected closing statement token");const tt=[],st=[];for(;!(((qt=x[$])==null?void 0:qt.type)===z.OpenStatement&&(((wr=x[$+1])==null?void 0:wr.type)===z.ElseIf||((Br=x[$+1])==null?void 0:Br.type)===z.Else||((Kr=x[$+1])==null?void 0:Kr.type)===z.EndIf));)tt.push(he());if(((rr=x[$])==null?void 0:rr.type)===z.OpenStatement&&((Wr=x[$+1])==null?void 0:Wr.type)!==z.EndIf)if(++$,Je(z.ElseIf))Q(z.ElseIf,"Expected elseif token"),st.push(Pt());else for(Q(z.Else,"Expected else token"),Q(z.CloseStatement,"Expected closing statement token");!(((Vr=x[$])==null?void 0:Vr.type)===z.OpenStatement&&((Ln=x[$+1])==null?void 0:Ln.type)===z.EndIf);)st.push(he());return new _e(be,tt,st)}function cr(){const be=Gt();if(be.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const tt=gt();Q(z.CloseStatement,"Expected closing statement token");const st=[];for(;Ye(z.OpenStatement,z.EndMacro);)st.push(he());return new q(be,tt,st)}function Er(be=!1){const tt=be?Gt:Or,st=[tt()],qt=Je(z.Comma);for(;qt&&(++$,st.push(tt()),!!Je(z.Comma)););return qt?new ke(st):st[0]}function Qr(){const be=Er(!0);if(!(be instanceof j||be instanceof ke))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${be.type} instead`);Q(z.In,"Expected `in` keyword following loop variable");const tt=Or();Q(z.CloseStatement,"Expected closing statement token");const st=[];for(;Ye(z.OpenStatement,z.EndFor)&&Ye(z.OpenStatement,z.Else);)st.push(he());const qt=[];if(Je(z.OpenStatement,z.Else))for(++$,++$,Q(z.CloseStatement,"Expected closing statement token");Ye(z.OpenStatement,z.EndFor);)qt.push(he());return new ce(be,tt,st,qt)}function Or(){return Ur()}function Ur(){const be=at();if(Je(z.If)){++$;const tt=at();if(Je(z.Else)){++$;const st=at();return new _e(tt,[be],[st])}else return new Ke(be,tt)}return be}function at(){let be=U();for(;Je(z.Or);){const tt=x[$];++$;const st=U();be=new Ie(tt,be,st)}return be}function U(){let be=ge();for(;Je(z.And);){const tt=x[$];++$;const st=ge();be=new Ie(tt,be,st)}return be}function ge(){let be;for(;Je(z.Not);){const tt=x[$];++$;const st=ge();be=new ye(tt,st)}return be??Ae()}function Ae(){let be=et();for(;Je(z.ComparisonBinaryOperator)||Je(z.In)||Je(z.NotIn);){const tt=x[$];++$;const st=et();be=new Ie(tt,be,st)}return be}function et(){let be=zt();for(;Je(z.AdditiveBinaryOperator);){const tt=x[$];++$;const st=zt();be=new Ie(tt,be,st)}return be}function xe(){const be=ft();return Je(z.OpenParen)?Xe(be):be}function Xe(be){let tt=new X(be,gt());return Je(z.OpenParen)&&(tt=Xe(tt)),tt}function gt(){Q(z.OpenParen,"Expected opening parenthesis for arguments list");const be=mt();return Q(z.CloseParen,"Expected closing parenthesis for arguments list"),be}function mt(){const be=[];for(;!Je(z.CloseParen);){let tt=Or();if(Je(z.Equals)){if(++$,!(tt instanceof j))throw new SyntaxError("Expected identifier for keyword argument");const st=Or();tt=new fe(tt,st)}be.push(tt),Je(z.Comma)&&++$}return be}function $t(){const be=[];let tt=!1;for(;!Je(z.CloseSquareBracket);)Je(z.Colon)?(be.push(void 0),++$,tt=!0):(be.push(Or()),Je(z.Colon)&&(++$,tt=!0));if(be.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(tt){if(be.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new W(...be)}return be[0]}function ft(){let be=Gt();for(;Je(z.Dot)||Je(z.OpenSquareBracket);){const tt=x[$];++$;let st;const qt=tt.type!==z.Dot;if(qt)st=$t(),Q(z.CloseSquareBracket,"Expected closing square bracket");else if(st=Gt(),st.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");be=new ie(be,st,qt)}return be}function zt(){let be=Nt();for(;Je(z.MultiplicativeBinaryOperator);){const tt=x[$];++$;const st=Nt();be=new Ie(tt,be,st)}return be}function Nt(){let be=Rt();for(;Je(z.Is);){++$;const tt=Je(z.Not);tt&&++$;let st=Gt();if(st instanceof de&&(st=new j(st.value.toString())),!(st instanceof j))throw new SyntaxError("Expected identifier for the test");be=new ut(be,tt,st)}return be}function Rt(){let be=xe();for(;Je(z.Pipe);){++$;let tt=Gt();if(!(tt instanceof j))throw new SyntaxError("Expected identifier for the filter");Je(z.OpenParen)&&(tt=Xe(tt)),be=new Ze(be,tt)}return be}function Gt(){const be=x[$];switch(be.type){case z.NumericLiteral:return++$,new L(Number(be.value));case z.StringLiteral:return++$,new k(be.value);case z.BooleanLiteral:return++$,new de(be.value.toLowerCase()==="true");case z.Identifier:return++$,new j(be.value);case z.OpenParen:{++$;const tt=Er();if(x[$].type!==z.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${x[$].type} instead`);return++$,tt}case z.OpenSquareBracket:{++$;const tt=[];for(;!Je(z.CloseSquareBracket);)tt.push(Or()),Je(z.Comma)&&++$;return++$,new ve(tt)}case z.OpenCurlyBracket:{++$;const tt=new Map;for(;!Je(z.CloseCurlyBracket);){const st=Or();Q(z.Colon,"Expected colon between key and value in object literal");const qt=Or();tt.set(st,qt),Je(z.Comma)&&++$}return++$,new ze(tt)}default:throw new SyntaxError(`Unexpected token: ${be.type}`)}}for(;$=0?(H=(H??(H=0))<0?Math.max(x.length+H,0):Math.min(H,x.length),$=($??($=x.length))<0?Math.max(x.length+$,0):Math.min($,x.length)):(H=(H??(H=x.length-1))<0?Math.max(x.length+H,-1):Math.min(H,x.length-1),$=($??($=-1))<-1?Math.max(x.length+$,-1):Math.min($,x.length-1));const Ye=[];for(let Je=H;he*JeH.toUpperCase())}var nt=class{constructor(x=void 0){Me(this,"type","RuntimeValue");Me(this,"value");Me(this,"builtins",new Map);this.value=x}__bool__(){return new ht(!!this.value)}},ot=class extends nt{constructor(){super(...arguments);Me(this,"type","NumericValue")}},Re=class extends nt{constructor(){super(...arguments);Me(this,"type","StringValue");Me(this,"builtins",new Map([["upper",new Ne(()=>new Re(this.value.toUpperCase()))],["lower",new Ne(()=>new Re(this.value.toLowerCase()))],["strip",new Ne(()=>new Re(this.value.trim()))],["title",new Ne(()=>new Re(dt(this.value)))],["length",new ot(this.value.length)]]))}},ht=class extends nt{constructor(){super(...arguments);Me(this,"type","BooleanValue")}},bt=class extends nt{constructor(){super(...arguments);Me(this,"type","ObjectValue");Me(this,"builtins",new Map([["get",new Ne(([H,$])=>{if(!(H instanceof Re))throw new Error(`Object key must be a string: got ${H.type}`);return this.value.get(H.value)??$??new Qe})],["items",new Ne(()=>new ee(Array.from(this.value.entries()).map(([H,$])=>new ee([new Re(H),$]))))]]))}__bool__(){return new ht(this.value.size>0)}},qe=class extends bt{constructor(){super(...arguments);Me(this,"type","KeywordArgumentsValue")}},ee=class extends nt{constructor(){super(...arguments);Me(this,"type","ArrayValue");Me(this,"builtins",new Map([["length",new ot(this.value.length)]]))}__bool__(){return new ht(this.value.length>0)}},Pe=class extends ee{constructor(){super(...arguments);Me(this,"type","TupleValue")}},Ne=class extends nt{constructor(){super(...arguments);Me(this,"type","FunctionValue")}},Qe=class extends nt{constructor(){super(...arguments);Me(this,"type","NullValue")}},Ue=class extends nt{constructor(){super(...arguments);Me(this,"type","UndefinedValue")}},je=class{constructor(x){Me(this,"variables",new Map([["namespace",new Ne(x=>{if(x.length===0)return new bt(new Map);if(x.length!==1||!(x[0]instanceof bt))throw new Error("`namespace` expects either zero arguments or a single object argument");return x[0]})]]));Me(this,"tests",new Map([["boolean",x=>x.type==="BooleanValue"],["callable",x=>x instanceof Ne],["odd",x=>{if(x.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${x.type}`);return x.value%2!==0}],["even",x=>{if(x.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${x.type}`);return x.value%2===0}],["false",x=>x.type==="BooleanValue"&&!x.value],["true",x=>x.type==="BooleanValue"&&x.value],["string",x=>x.type==="StringValue"],["number",x=>x.type==="NumericValue"],["integer",x=>x.type==="NumericValue"&&Number.isInteger(x.value)],["iterable",x=>x instanceof ee||x instanceof Re],["lower",x=>{const H=x.value;return x.type==="StringValue"&&H===H.toLowerCase()}],["upper",x=>{const H=x.value;return x.type==="StringValue"&&H===H.toUpperCase()}],["none",x=>x.type==="NullValue"],["defined",x=>x.type!=="UndefinedValue"],["undefined",x=>x.type==="UndefinedValue"],["equalto",(x,H)=>x.value===H.value],["eq",(x,H)=>x.value===H.value]]));this.parent=x}set(x,H){return this.declareVariable(x,yt(H))}declareVariable(x,H){if(this.variables.has(x))throw new SyntaxError(`Variable already declared: ${x}`);return this.variables.set(x,H),H}setVariable(x,H){return this.variables.set(x,H),H}resolve(x){if(this.variables.has(x))return this;if(this.parent)return this.parent.resolve(x);throw new Error(`Unknown variable: ${x}`)}lookupVariable(x){try{return this.resolve(x).variables.get(x)??new Ue}catch{return new Ue}}},lt=class{constructor(x){Me(this,"global");this.global=x??new je}run(x){return this.evaluate(x,this.global)}evaluateBinaryExpression(x,H){const $=this.evaluate(x.left,H);switch(x.operator.value){case"and":return $.__bool__().value?this.evaluate(x.right,H):$;case"or":return $.__bool__().value?$:this.evaluate(x.right,H)}const Q=this.evaluate(x.right,H);switch(x.operator.value){case"==":return new ht($.value==Q.value);case"!=":return new ht($.value!=Q.value)}if($ instanceof Ue||Q instanceof Ue)throw new Error("Cannot perform operation on undefined values");if($ instanceof Qe||Q instanceof Qe)throw new Error("Cannot perform operation on null values");if($ instanceof ot&&Q instanceof ot)switch(x.operator.value){case"+":return new ot($.value+Q.value);case"-":return new ot($.value-Q.value);case"*":return new ot($.value*Q.value);case"/":return new ot($.value/Q.value);case"%":return new ot($.value%Q.value);case"<":return new ht($.value":return new ht($.value>Q.value);case">=":return new ht($.value>=Q.value);case"<=":return new ht($.value<=Q.value)}else if($ instanceof ee&&Q instanceof ee)switch(x.operator.value){case"+":return new ee($.value.concat(Q.value))}else if(Q instanceof ee){const he=Q.value.find(Ye=>Ye.value===$.value)!==void 0;switch(x.operator.value){case"in":return new ht(he);case"not in":return new ht(!he)}}if($ instanceof Re||Q instanceof Re)switch(x.operator.value){case"+":return new Re($.value.toString()+Q.value.toString())}if($ instanceof Re&&Q instanceof Re)switch(x.operator.value){case"in":return new ht(Q.value.includes($.value));case"not in":return new ht(!Q.value.includes($.value))}if($ instanceof Re&&Q instanceof bt)switch(x.operator.value){case"in":return new ht(Q.value.has($.value));case"not in":return new ht(!Q.value.has($.value))}throw new SyntaxError(`Unknown operator "${x.operator.value}" between ${$.type} and ${Q.type}`)}evaluateArguments(x,H){const $=[],Q=new Map;for(const he of x)if(he.type==="KeywordArgumentExpression"){const Ye=he;Q.set(Ye.key.value,this.evaluate(Ye.value,H))}else{if(Q.size>0)throw new Error("Positional arguments must come before keyword arguments");$.push(this.evaluate(he,H))}return[$,Q]}evaluateFilterExpression(x,H){const $=this.evaluate(x.operand,H);if(x.filter.type==="Identifier"){const Q=x.filter;if(Q.value==="tojson")return new Re(vt($));if($ instanceof ee)switch(Q.value){case"list":return $;case"first":return $.value[0];case"last":return $.value[$.value.length-1];case"length":return new ot($.value.length);case"reverse":return new ee($.value.reverse());case"sort":return new ee($.value.sort((he,Ye)=>{if(he.type!==Ye.type)throw new Error(`Cannot compare different types: ${he.type} and ${Ye.type}`);switch(he.type){case"NumericValue":return he.value-Ye.value;case"StringValue":return he.value.localeCompare(Ye.value);default:throw new Error(`Cannot compare type: ${he.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Q.value}`)}else if($ instanceof Re)switch(Q.value){case"length":return new ot($.value.length);case"upper":return new Re($.value.toUpperCase());case"lower":return new Re($.value.toLowerCase());case"title":return new Re(dt($.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,Ye)=>Ye===0||he.length===0?he:" "+he).join(` +`));case"string":return $;default:throw new Error(`Unknown StringValue filter: ${Q.value}`)}else if($ instanceof ot)switch(Q.value){case"abs":return new ot(Math.abs($.value));default:throw new Error(`Unknown NumericValue filter: ${Q.value}`)}else if($ instanceof bt)switch(Q.value){case"items":return new ee(Array.from($.value.entries()).map(([he,Ye])=>new ee([new Re(he),Ye])));case"length":return new ot($.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Q.value}`)}throw new Error(`Cannot apply filter "${Q.value}" to type: ${$.type}`)}else if(x.filter.type==="CallExpression"){const Q=x.filter;if(Q.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Q.callee.type}`);const he=Q.callee.value;if(he==="tojson"){const[,Ye]=this.evaluateArguments(Q.args,H),Je=Ye.get("indent")??new Qe;if(!(Je instanceof ot||Je instanceof Qe))throw new Error("If set, indent must be a number");return new Re(vt($,Je.value))}if($ instanceof ee){switch(he){case"selectattr":{if($.value.some(At=>!(At instanceof bt)))throw new Error("`selectattr` can only be applied to array of objects");if(Q.args.some(At=>At.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Ye,Je,Bt]=Q.args.map(At=>this.evaluate(At,H));let ct;if(Je){const At=H.tests.get(Je.value);if(!At)throw new Error(`Unknown test: ${Je.value}`);ct=At}else ct=(...At)=>At[0].__bool__().value;const Tt=$.value.filter(At=>{const Pt=At.value.get(Ye.value);return Pt?ct(Pt,Bt):!1});return new ee(Tt)}case"map":{const[,Ye]=this.evaluateArguments(Q.args,H);if(Ye.has("attribute")){const Je=Ye.get("attribute");if(!(Je instanceof Re))throw new Error("attribute must be a string");const Bt=Ye.get("default"),ct=$.value.map(Tt=>{if(!(Tt instanceof bt))throw new Error("items in map must be an object");return Tt.value.get(Je.value)??Bt??new Ue});return new ee(ct)}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[Ye,Je]=this.evaluateArguments(Q.args,H),Bt=Ye.at(0)??Je.get("width")??new ot(4);if(!(Bt instanceof ot))throw new Error("width must be a number");const ct=Ye.at(1)??Je.get("first")??new ht(!1),Tt=Ye.at(2)??Je.get("blank")??new ht(!1),At=$.value.split(` +`),Pt=" ".repeat(Bt.value),cr=At.map((Er,Qr)=>!ct.value&&Qr===0||!Tt.value&&Er.length===0?Er:Pt+Er);return new Re(cr.join(` +`))}}throw new Error(`Unknown StringValue filter: ${he}`)}else throw new Error(`Cannot apply filter "${he}" to type: ${$.type}`)}throw new Error(`Unknown filter: ${x.filter.type}`)}evaluateTestExpression(x,H){const $=this.evaluate(x.operand,H),Q=H.tests.get(x.test.value);if(!Q)throw new Error(`Unknown test: ${x.test.value}`);const he=Q($);return new ht(x.negate?!he:he)}evaluateUnaryExpression(x,H){const $=this.evaluate(x.argument,H);switch(x.operator.value){case"not":return new ht(!$.value);default:throw new SyntaxError(`Unknown operator: ${x.operator.value}`)}}evalProgram(x,H){return this.evaluateBlock(x.body,H)}evaluateBlock(x,H){let $="";for(const Q of x){const he=this.evaluate(Q,H);he.type!=="NullValue"&&he.type!=="UndefinedValue"&&($+=he.value)}return new Re($)}evaluateIdentifier(x,H){return H.lookupVariable(x.value)}evaluateCallExpression(x,H){const[$,Q]=this.evaluateArguments(x.args,H);Q.size>0&&$.push(new qe(Q));const he=this.evaluate(x.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(x,H,$){if(!(x instanceof ee||x instanceof Re))throw new Error("Slice object must be an array or string");const Q=this.evaluate(H.start,$),he=this.evaluate(H.stop,$),Ye=this.evaluate(H.step,$);if(!(Q instanceof ot||Q instanceof Ue))throw new Error("Slice start must be numeric or undefined");if(!(he instanceof ot||he instanceof Ue))throw new Error("Slice stop must be numeric or undefined");if(!(Ye instanceof ot||Ye instanceof Ue))throw new Error("Slice step must be numeric or undefined");return x instanceof ee?new ee(He(x.value,Q.value,he.value,Ye.value)):new Re(He(Array.from(x.value),Q.value,he.value,Ye.value).join(""))}evaluateMemberExpression(x,H){const $=this.evaluate(x.object,H);let Q;if(x.computed){if(x.property.type==="SliceExpression")return this.evaluateSliceExpression($,x.property,H);Q=this.evaluate(x.property,H)}else Q=new Re(x.property.value);let he;if($ instanceof bt){if(!(Q instanceof Re))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=$.value.get(Q.value)??$.builtins.get(Q.value)}else if($ instanceof ee||$ instanceof Re)if(Q instanceof ot)he=$.value.at(Q.value),$ instanceof Re&&(he=new Re($.value.at(Q.value)));else if(Q instanceof Re)he=$.builtins.get(Q.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Q.type}`);else{if(!(Q instanceof Re))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=$.builtins.get(Q.value)}return he instanceof nt?he:new Ue}evaluateSet(x,H){const $=this.evaluate(x.value,H);if(x.assignee.type==="Identifier"){const Q=x.assignee.value;H.setVariable(Q,$)}else if(x.assignee.type==="MemberExpression"){const Q=x.assignee,he=this.evaluate(Q.object,H);if(!(he instanceof bt))throw new Error("Cannot assign to member of non-object");if(Q.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");he.value.set(Q.property.value,$)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(x.assignee)}`);return new Qe}evaluateIf(x,H){const $=this.evaluate(x.test,H);return this.evaluateBlock($.__bool__().value?x.body:x.alternate,H)}evaluateFor(x,H){const $=new je(H);let Q,he;if(x.iterable.type==="SelectExpression"){const Tt=x.iterable;he=this.evaluate(Tt.iterable,$),Q=Tt.test}else he=this.evaluate(x.iterable,$);if(!(he instanceof ee))throw new Error(`Expected iterable type in for loop: got ${he.type}`);const Ye=[],Je=[];for(let Tt=0;TtEr.setVariable(x.loopvar.value,Pt);else if(x.loopvar.type==="TupleLiteral"){const Er=x.loopvar;if(Pt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Pt.type}`);const Qr=Pt;if(Er.value.length!==Qr.value.length)throw new Error(`Too ${Er.value.length>Qr.value.length?"few":"many"} items to unpack`);cr=Or=>{for(let Ur=0;Ur0?Ye[Tt-1]:new Ue],["nextitem",Tt{var Je;const he=new je(Q);$=$.slice();let Ye;((Je=$.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(Ye=$.pop());for(let Bt=0;Btthis.evaluate($,H)));case"TupleLiteral":return new Pe(x.value.map($=>this.evaluate($,H)));case"ObjectLiteral":{const $=new Map;for(const[Q,he]of x.value){const Ye=this.evaluate(Q,H);if(!(Ye instanceof Re))throw new Error(`Object keys must be strings: got ${Ye.type}`);$.set(Ye.value,this.evaluate(he,H))}return new bt($)}case"Identifier":return this.evaluateIdentifier(x,H);case"CallExpression":return this.evaluateCallExpression(x,H);case"MemberExpression":return this.evaluateMemberExpression(x,H);case"UnaryExpression":return this.evaluateUnaryExpression(x,H);case"BinaryExpression":return this.evaluateBinaryExpression(x,H);case"FilterExpression":return this.evaluateFilterExpression(x,H);case"TestExpression":return this.evaluateTestExpression(x,H);default:throw new SyntaxError(`Unknown node type: ${x.type}`)}}};function yt(x){switch(typeof x){case"number":return new ot(x);case"string":return new Re(x);case"boolean":return new ht(x);case"undefined":return new Ue;case"object":return x===null?new Qe:Array.isArray(x)?new ee(x.map(yt)):new bt(new Map(Object.entries(x).map(([H,$])=>[H,yt($)])));case"function":return new Ne((H,$)=>{const Q=x(...H.map(he=>he.value))??null;return yt(Q)});default:throw new Error(`Cannot convert to runtime value: ${x}`)}}function vt(x,H,$){const Q=$??0;switch(x.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(x.value);case"ArrayValue":case"ObjectValue":{const he=H?" ".repeat(H):"",Ye=` +`+he.repeat(Q),Je=Ye+he;if(x.type==="ArrayValue"){const Bt=x.value.map(ct=>vt(ct,H,Q+1));return H?`[${Je}${Bt.join(`,${Je}`)}${Ye}]`:`[${Bt.join(", ")}]`}else{const Bt=Array.from(x.value.entries()).map(([ct,Tt])=>{const At=`"${ct}": ${vt(Tt,H,Q+1)}`;return H?`${Je}${At}`:At});return H?`{${Bt.join(",")}${Ye}}`:`{${Bt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${x.type}`)}}var Et=class{constructor(x){Me(this,"parsed");const H=P(x,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=$e(H)}render(x){const H=new je;H.set("false",!1),H.set("true",!0),H.set("raise_exception",he=>{throw new Error(he)}),H.set("range",Y);for(const[he,Ye]of Object.entries(x))H.set(he,Ye);return new lt(H).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{registerBackend:()=>we,resolveBackendAndExecutionProviders:()=>Ce});const z=new Map,me=[],we=(R,S,V)=>{if(S&&typeof S.init=="function"&&typeof S.createInferenceSessionHandler=="function"){const P=z.get(R);if(P===void 0)z.set(R,{backend:S,priority:V});else{if(P.priority>V)return;if(P.priority===V&&P.backend!==S)throw new Error(`cannot register backend "${R}" using priority ${V}`)}if(V>=0){const re=me.indexOf(R);re!==-1&&me.splice(re,1);for(let ne=0;ne{const S=z.get(R);if(!S)return"backend not found.";if(S.initialized)return S.backend;if(S.aborted)return S.error;{const V=!!S.initPromise;try{return V||(S.initPromise=S.backend.init(R)),await S.initPromise,S.initialized=!0,S.backend}catch(P){return V||(S.error=`${P}`,S.aborted=!0),S.error}finally{delete S.initPromise}}},Ce=async R=>{const S=R.executionProviders||[],V=S.map(D=>typeof D=="string"?D:D.name),P=V.length===0?me:V;let re;const ne=[],_e=new Set;for(const D of P){const q=await Te(D);typeof q=="string"?ne.push({name:D,err:q}):(re||(re=q),re===q&&_e.add(D))}if(!re)throw new Error(`no available backend found. ERR: ${ne.map(D=>`[${D.name}] ${D.err}`).join(", ")}`);for(const{name:D,err:q}of ne)V.includes(D)&&console.warn(`removing requested execution provider "${D}" from session options because it is not available: ${q}`);const ce=S.filter(D=>_e.has(typeof D=="string"?D:D.name));return[re,new Proxy(R,{get:(D,q)=>q==="executionProviders"?ce:Reflect.get(D,q)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{registerBackend:()=>z.registerBackend});var z=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{env:()=>we});var z=N("./node_modules/onnxruntime-common/dist/esm/version.js");let me="warning";const we={wasm:{},webgl:{},webgpu:{},versions:{common:z.version},set logLevel(Te){if(Te!==void 0){if(typeof Te!="string"||["verbose","info","warning","error","fatal"].indexOf(Te)===-1)throw new Error(`Unsupported logging level: ${Te}`);me=Te}},get logLevel(){return me}};Object.defineProperty(we,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{env:()=>me});var z=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const me=z.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{InferenceSession:()=>we.InferenceSession,TRACE:()=>Ce.TRACE,TRACE_FUNC_BEGIN:()=>Ce.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Ce.TRACE_FUNC_END,Tensor:()=>Te.Tensor,TrainingSession:()=>R.TrainingSession,env:()=>me.env,registerBackend:()=>z.registerBackend});var z=N("./node_modules/onnxruntime-common/dist/esm/backend.js"),me=N("./node_modules/onnxruntime-common/dist/esm/env.js"),we=N("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Te=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),N("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Ce=N("./node_modules/onnxruntime-common/dist/esm/trace.js");N("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),N("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var R=N("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{InferenceSession:()=>Te});var z=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),me=N("./node_modules/onnxruntime-common/dist/esm/tensor.js"),we=N("./node_modules/onnxruntime-common/dist/esm/trace.js");class Te{constructor(R){this.handler=R}async run(R,S,V){(0,we.TRACE_FUNC_BEGIN)();const P={};let re={};if(typeof R!="object"||R===null||R instanceof me.Tensor||Array.isArray(R))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ne=!0;if(typeof S=="object"){if(S===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(S instanceof me.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(S)){if(S.length===0)throw new TypeError("'fetches' cannot be an empty array.");ne=!1;for(const D of S){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);P[D]=null}if(typeof V=="object"&&V!==null)re=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const q=Object.getOwnPropertyNames(S);for(const te of this.outputNames)if(q.indexOf(te)!==-1){const ie=S[te];(ie===null||ie instanceof me.Tensor)&&(D=!0,ne=!1,P[te]=ie)}if(D){if(typeof V=="object"&&V!==null)re=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else re=S}}else if(typeof S<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of this.inputNames)if(typeof R[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ne)for(const D of this.outputNames)P[D]=null;const _e=await this.handler.run(R,P,re),ce={};for(const D in _e)if(Object.hasOwnProperty.call(_e,D)){const q=_e[D];q instanceof me.Tensor?ce[D]=q:ce[D]=new me.Tensor(q.type,q.data,q.dims)}return(0,we.TRACE_FUNC_END)(),ce}async release(){return this.handler.dispose()}static async create(R,S,V,P){(0,we.TRACE_FUNC_BEGIN)();let re,ne={};if(typeof R=="string"){if(re=R,typeof S=="object"&&S!==null)ne=S;else if(typeof S<"u")throw new TypeError("'options' must be an object.")}else if(R instanceof Uint8Array){if(re=R,typeof S=="object"&&S!==null)ne=S;else if(typeof S<"u")throw new TypeError("'options' must be an object.")}else if(R instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&R instanceof SharedArrayBuffer){const q=R;let te=0,ie=R.byteLength;if(typeof S=="object"&&S!==null)ne=S;else if(typeof S=="number"){if(te=S,!Number.isSafeInteger(te))throw new RangeError("'byteOffset' must be an integer.");if(te<0||te>=q.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${q.byteLength}).`);if(ie=R.byteLength-te,typeof V=="number"){if(ie=V,!Number.isSafeInteger(ie))throw new RangeError("'byteLength' must be an integer.");if(ie<=0||te+ie>q.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${q.byteLength-te}].`);if(typeof P=="object"&&P!==null)ne=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof V<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof S<"u")throw new TypeError("'options' must be an object.");re=new Uint8Array(q,te,ie)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[_e,ce]=await(0,z.resolveBackendAndExecutionProviders)(ne),D=await _e.createInferenceSessionHandler(re,ce);return(0,we.TRACE_FUNC_END)(),new Te(D)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{InferenceSession:()=>me});var z=N("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const me=z.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Ft,Ee,N)=>{N.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Ft,Ee,N)=>{N.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{tensorToDataURL:()=>z,tensorToImageData:()=>me});const z=(we,Te)=>{const Ce=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Ce.width=we.dims[3],Ce.height=we.dims[2];const R=Ce.getContext("2d");if(R!=null){let S,V;(Te==null?void 0:Te.tensorLayout)!==void 0&&Te.tensorLayout==="NHWC"?(S=we.dims[2],V=we.dims[3]):(S=we.dims[3],V=we.dims[2]);const P=(Te==null?void 0:Te.format)!==void 0?Te.format:"RGB",re=Te==null?void 0:Te.norm;let ne,_e;re===void 0||re.mean===void 0?ne=[255,255,255,255]:typeof re.mean=="number"?ne=[re.mean,re.mean,re.mean,re.mean]:(ne=[re.mean[0],re.mean[1],re.mean[2],0],re.mean[3]!==void 0&&(ne[3]=re.mean[3])),re===void 0||re.bias===void 0?_e=[0,0,0,0]:typeof re.bias=="number"?_e=[re.bias,re.bias,re.bias,re.bias]:(_e=[re.bias[0],re.bias[1],re.bias[2],0],re.bias[3]!==void 0&&(_e[3]=re.bias[3]));const ce=V*S;let D=0,q=ce,te=ce*2,ie=-1;P==="RGBA"?(D=0,q=ce,te=ce*2,ie=ce*3):P==="RGB"?(D=0,q=ce,te=ce*2):P==="RBG"&&(D=0,te=ce,q=ce*2);for(let X=0;X{const Ce=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let R;if(Ce!=null){let S,V,P;(Te==null?void 0:Te.tensorLayout)!==void 0&&Te.tensorLayout==="NHWC"?(S=we.dims[2],V=we.dims[1],P=we.dims[3]):(S=we.dims[3],V=we.dims[2],P=we.dims[1]);const re=Te!==void 0&&Te.format!==void 0?Te.format:"RGB",ne=Te==null?void 0:Te.norm;let _e,ce;ne===void 0||ne.mean===void 0?_e=[255,255,255,255]:typeof ne.mean=="number"?_e=[ne.mean,ne.mean,ne.mean,ne.mean]:(_e=[ne.mean[0],ne.mean[1],ne.mean[2],255],ne.mean[3]!==void 0&&(_e[3]=ne.mean[3])),ne===void 0||ne.bias===void 0?ce=[0,0,0,0]:typeof ne.bias=="number"?ce=[ne.bias,ne.bias,ne.bias,ne.bias]:(ce=[ne.bias[0],ne.bias[1],ne.bias[2],0],ne.bias[3]!==void 0&&(ce[3]=ne.bias[3]));const D=V*S;if(Te!==void 0&&(Te.format!==void 0&&P===4&&Te.format!=="RGBA"||P===3&&Te.format!=="RGB"&&Te.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const q=4;let te=0,ie=1,X=2,j=3,I=0,L=D,k=D*2,de=-1;re==="RGBA"?(I=0,L=D,k=D*2,de=D*3):re==="RGB"?(I=0,L=D,k=D*2):re==="RBG"&&(I=0,k=D,L=D*2),R=Ce.createImageData(S,V);for(let ve=0;ve{N.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{bufferToTensor:()=>me,tensorFromGpuBuffer:()=>Ce,tensorFromImage:()=>we,tensorFromPinnedBuffer:()=>R,tensorFromTexture:()=>Te});var z=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const me=(S,V)=>{if(S===void 0)throw new Error("Image buffer must be defined");if(V.height===void 0||V.width===void 0)throw new Error("Image height and width must be defined");if(V.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:P,width:re}=V,ne=V.norm??{mean:255,bias:0};let _e,ce;typeof ne.mean=="number"?_e=[ne.mean,ne.mean,ne.mean,ne.mean]:_e=[ne.mean[0],ne.mean[1],ne.mean[2],ne.mean[3]??255],typeof ne.bias=="number"?ce=[ne.bias,ne.bias,ne.bias,ne.bias]:ce=[ne.bias[0],ne.bias[1],ne.bias[2],ne.bias[3]??0];const D=V.format!==void 0?V.format:"RGBA",q=V.tensorFormat!==void 0&&V.tensorFormat!==void 0?V.tensorFormat:"RGB",te=P*re,ie=q==="RGBA"?new Float32Array(te*4):new Float32Array(te*3);let X=4,j=0,I=1,L=2,k=3,de=0,ve=te,ke=te*2,ze=-1;D==="RGB"&&(X=3,j=0,I=1,L=2,k=-1),q==="RGBA"?ze=te*3:q==="RBG"?(de=0,ke=te,ve=te*2):q==="BGR"&&(ke=0,ve=te,de=te*2);for(let Ze=0;Ze{const P=typeof HTMLImageElement<"u"&&S instanceof HTMLImageElement,re=typeof ImageData<"u"&&S instanceof ImageData,ne=typeof ImageBitmap<"u"&&S instanceof ImageBitmap,_e=typeof S=="string";let ce,D=V??{};const q=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},te=ie=>ie instanceof HTMLCanvasElement||ie instanceof OffscreenCanvas?ie.getContext("2d"):null;if(P){const ie=q();ie.width=S.width,ie.height=S.height;const X=te(ie);if(X!=null){let j=S.height,I=S.width;if(V!==void 0&&V.resizedHeight!==void 0&&V.resizedWidth!==void 0&&(j=V.resizedHeight,I=V.resizedWidth),V!==void 0){if(D=V,V.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");D.tensorFormat="RGBA",D.height=j,D.width=I}else D.tensorFormat="RGBA",D.height=j,D.width=I;X.drawImage(S,0,0),ce=X.getImageData(0,0,I,j).data}else throw new Error("Can not access image data")}else if(re){let ie,X;if(V!==void 0&&V.resizedWidth!==void 0&&V.resizedHeight!==void 0?(ie=V.resizedHeight,X=V.resizedWidth):(ie=S.height,X=S.width),V!==void 0&&(D=V),D.format="RGBA",D.height=ie,D.width=X,V!==void 0){const j=q();j.width=X,j.height=ie;const I=te(j);if(I!=null)I.putImageData(S,0,0),ce=I.getImageData(0,0,X,ie).data;else throw new Error("Can not access image data")}else ce=S.data}else if(ne){if(V===void 0)throw new Error("Please provide image config with format for Imagebitmap");const ie=q();ie.width=S.width,ie.height=S.height;const X=te(ie);if(X!=null){const j=S.height,I=S.width;return X.drawImage(S,0,0,I,j),ce=X.getImageData(0,0,I,j).data,D.height=j,D.width=I,me(ce,D)}else throw new Error("Can not access image data")}else{if(_e)return new Promise((ie,X)=>{const j=q(),I=te(j);if(!S||!I)return X();const L=new Image;L.crossOrigin="Anonymous",L.src=S,L.onload=()=>{j.width=L.width,j.height=L.height,I.drawImage(L,0,0,j.width,j.height);const k=I.getImageData(0,0,j.width,j.height);D.height=j.height,D.width=j.width,ie(me(k.data,D))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ce!==void 0)return me(ce,D);throw new Error("Input data provided is not supported - aborted tensor creation")},Te=(S,V)=>{const{width:P,height:re,download:ne,dispose:_e}=V,ce=[1,re,P,4];return new z.Tensor({location:"texture",type:"float32",texture:S,dims:ce,download:ne,dispose:_e})},Ce=(S,V)=>{const{dataType:P,dims:re,download:ne,dispose:_e}=V;return new z.Tensor({location:"gpu-buffer",type:P??"float32",gpuBuffer:S,dims:re,download:ne,dispose:_e})},R=(S,V,P)=>new z.Tensor({location:"cpu-pinned",type:S,data:V,dims:P??[V.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Ft,Ee,N)=>{N.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>me,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>z,checkTypedArray:()=>Te});const z=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),me=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let we=!1;const Te=()=>{if(!we){we=!0;const Ce=typeof BigInt64Array<"u"&&BigInt64Array.from,R=typeof BigUint64Array<"u"&&BigUint64Array.from,S=typeof Float16Array<"u"&&Float16Array.from;Ce&&(z.set("int64",BigInt64Array),me.set(BigInt64Array,"int64")),R&&(z.set("uint64",BigUint64Array),me.set(BigUint64Array,"uint64")),S?(z.set("float16",Float16Array),me.set(Float16Array,"float16")):z.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{Tensor:()=>Ce});var z=N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),me=N("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),we=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Te=N("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Ce{constructor(S,V,P){(0,we.checkTypedArray)();let re,ne;if(typeof S=="object"&&"location"in S)switch(this.dataLocation=S.location,re=S.type,ne=S.dims,S.location){case"cpu-pinned":{const ce=we.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(re);if(!ce)throw new TypeError(`unsupported type "${re}" to create tensor from pinned buffer`);if(!(S.data instanceof ce))throw new TypeError(`buffer should be of type ${ce.name}`);this.cpuData=S.data;break}case"texture":{if(re!=="float32")throw new TypeError(`unsupported type "${re}" to create tensor from texture`);this.gpuTextureData=S.texture,this.downloader=S.download,this.disposer=S.dispose;break}case"gpu-buffer":{if(re!=="float32"&&re!=="float16"&&re!=="int32"&&re!=="int64"&&re!=="uint32"&&re!=="uint8"&&re!=="bool")throw new TypeError(`unsupported type "${re}" to create tensor from gpu buffer`);this.gpuBufferData=S.gpuBuffer,this.downloader=S.download,this.disposer=S.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ce,D;if(typeof S=="string")if(re=S,D=P,S==="string"){if(!Array.isArray(V))throw new TypeError("A string tensor's data must be a string array.");ce=V}else{const q=we.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(S);if(q===void 0)throw new TypeError(`Unsupported tensor type: ${S}.`);if(Array.isArray(V)){if(S==="float16"&&q===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");S==="uint64"||S==="int64"?ce=q.from(V,BigInt):ce=q.from(V)}else if(V instanceof q)ce=V;else throw new TypeError(`A ${re} tensor's data must be type of ${q}`)}else if(D=V,Array.isArray(S)){if(S.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const q=typeof S[0];if(q==="string")re="string",ce=S;else if(q==="boolean")re="bool",ce=Uint8Array.from(S);else throw new TypeError(`Invalid element type of data array: ${q}.`)}else{const q=we.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(S.constructor);if(q===void 0)throw new TypeError(`Unsupported type for tensor data: ${S.constructor}.`);re=q,ce=S}if(D===void 0)D=[ce.length];else if(!Array.isArray(D))throw new TypeError("A tensor's dims must be a number array");ne=D,this.cpuData=ce,this.dataLocation="cpu"}const _e=(0,Te.calculateSize)(ne);if(this.cpuData&&_e!==this.cpuData.length)throw new Error(`Tensor's size(${_e}) does not match data length(${this.cpuData.length}).`);this.type=re,this.dims=ne,this.size=_e}static async fromImage(S,V){return(0,me.tensorFromImage)(S,V)}static fromTexture(S,V){return(0,me.tensorFromTexture)(S,V)}static fromGpuBuffer(S,V){return(0,me.tensorFromGpuBuffer)(S,V)}static fromPinnedBuffer(S,V,P){return(0,me.tensorFromPinnedBuffer)(S,V,P)}toDataURL(S){return(0,z.tensorToDataURL)(this,S)}toImageData(S){return(0,z.tensorToImageData)(this,S)}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(S){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const V=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=V,S&&this.disposer&&(this.disposer(),this.disposer=void 0),V}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(S){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Te.tensorReshape)(this,S)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{calculateSize:()=>me,tensorReshape:()=>we});var z=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const me=Te=>{let Ce=1;for(let R=0;R{switch(Te.location){case"cpu":return new z.Tensor(Te.type,Te.data,Ce);case"cpu-pinned":return new z.Tensor({location:"cpu-pinned",data:Te.data,type:Te.type,dims:Ce});case"texture":return new z.Tensor({location:"texture",texture:Te.texture,type:Te.type,dims:Ce});case"gpu-buffer":return new z.Tensor({location:"gpu-buffer",gpuBuffer:Te.gpuBuffer,type:Te.type,dims:Ce});default:throw new Error(`tensorReshape: tensor location ${Te.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{Tensor:()=>me});var z=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const me=z.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{TRACE:()=>me,TRACE_FUNC_BEGIN:()=>Te,TRACE_FUNC_END:()=>Ce});var z=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const me=(R,S)=>{(typeof z.env.trace>"u"?!z.env.wasm.trace:!z.env.trace)||console.timeStamp(`${R}::ORT::${S}`)},we=(R,S)=>{var re;const V=((re=new Error().stack)==null?void 0:re.split(/\r\n|\r|\n/g))||[];let P=!1;for(let ne=0;ne{(typeof z.env.trace>"u"?!z.env.wasm.trace:!z.env.trace)||we("BEGIN",R)},Ce=R=>{(typeof z.env.trace>"u"?!z.env.wasm.trace:!z.env.trace)||we("END",R)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{TrainingSession:()=>Te});var z=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),me=N("./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 Te{constructor(R,S,V){this.handler=R,this.hasOptimizerModel=S,this.hasEvalModel=V}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(R,S){const V=R.evalModel||"",P=R.optimizerModel||"",re=S||{},[ne,_e]=await(0,z.resolveBackendAndExecutionProviders)(re);if(ne.createTrainingSessionHandler){const ce=await ne.createTrainingSessionHandler(R.checkpointState,R.trainModel,V,P,_e);return new Te(ce,!!R.optimizerModel,!!R.evalModel)}else throw new Error(we)}typeNarrowingForRunStep(R,S,V,P,re){const ne={};let _e={};if(typeof V!="object"||V===null||V instanceof me.Tensor||Array.isArray(V))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ce=!0;if(typeof P=="object"){if(P===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(P instanceof me.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(P)){if(P.length===0)throw new TypeError("'fetches' cannot be an empty array.");ce=!1;for(const D of P){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(S.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);ne[D]=null}if(typeof re=="object"&&re!==null)_e=re;else if(typeof re<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const q=Object.getOwnPropertyNames(P);for(const te of S)if(q.indexOf(te)!==-1){const ie=P[te];(ie===null||ie instanceof me.Tensor)&&(D=!0,ce=!1,ne[te]=ie)}if(D){if(typeof re=="object"&&re!==null)_e=re;else if(typeof re<"u")throw new TypeError("'options' must be an object.")}else _e=P}}else if(typeof P<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of R)if(typeof V[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ce)for(const D of S)ne[D]=null;return[ne,_e]}convertHandlerReturnTypeToMapOfTensors(R){const S={};for(const V in R)if(Object.hasOwnProperty.call(R,V)){const P=R[V];P instanceof me.Tensor?S[V]=P:S[V]=new me.Tensor(P.type,P.data,P.dims)}return S}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(R,S,V){const[P,re]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,R,S,V),ne=await this.handler.runTrainStep(R,P,re);return this.convertHandlerReturnTypeToMapOfTensors(ne)}async runOptimizerStep(R){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(R||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(R,S,V){if(this.hasEvalModel){const[P,re]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,R,S,V),ne=await this.handler.runEvalStep(R,P,re);return this.convertHandlerReturnTypeToMapOfTensors(ne)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(R=!0){return this.handler.getParametersSize(R)}async loadParametersBuffer(R,S=!0){const V=await this.getParametersSize(S);if(R.length!==4*V)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(R,S)}async getContiguousParameters(R=!0){return this.handler.getContiguousParameters(R)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{TrainingSession:()=>me});var z=N("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const me=z.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{version:()=>z});const z="1.19.2"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{InferenceSession:()=>Et,TRACE:()=>Ne,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>je,Tensor:()=>ee,TrainingSession:()=>ct,default:()=>Qf,env:()=>k,registerBackend:()=>_e});/*! + * ONNX Runtime Web v1.20.0-dev.20240928-1bda91fc57 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var z=Object.defineProperty,me=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyNames,Te=Object.prototype.hasOwnProperty,Ce=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),R=(e,t)=>()=>(e&&(t=e(e=0)),t),S=(e,t)=>{for(var r in t)z(e,r,{get:t[r],enumerable:!0})},V=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of we(t))!Te.call(e,s)&&s!==r&&z(e,s,{get:()=>t[s],enumerable:!(n=me(t,s))||n.enumerable});return e},P=e=>V(z({},"__esModule",{value:!0}),e),re,ne,_e,ce,D,q=R(()=>{re=new Map,ne=[],_e=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=re.get(e);if(n===void 0)re.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=ne.indexOf(e);s!==-1&&ne.splice(s,1);for(let a=0;a{let t=re.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},D=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?ne:r,s,a=[],i=new Set;for(let d of n){let p=await ce(d);typeof p=="string"?a.push({name:d,err:p}):(s||(s=p),s===p&&i.add(d))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:p}of a)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${p}`);let u=t.filter(d=>i.has(typeof d=="string"?d:d.name));return[s,new Proxy(e,{get:(d,p)=>p==="executionProviders"?u:Reflect.get(d,p)})]}}),te=R(()=>{q()}),ie,X=R(()=>{ie="1.20.0-dev.20240928-1bda91fc57"}),j,I,L=R(()=>{X(),j="warning",I={wasm:{},webgl:{},webgpu:{},versions:{common:ie},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(I,"logLevel",{enumerable:!0})}),k,de=R(()=>{L(),k=I}),ve,ke,ze=R(()=>{ve=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,d,p;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?p=[0,0,0,0]:typeof u.bias=="number"?p=[u.bias,u.bias,u.bias,u.bias]:(p=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(p[3]=u.bias[3]));let g=a*s,w=0,l=g,M=g*2,C=-1;i==="RGBA"?(w=0,l=g,M=g*2,C=g*3):i==="RGB"?(w=0,l=g,M=g*2):i==="RBG"&&(w=0,M=g,l=g*2);for(let E=0;E{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,p,g;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean=="number"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?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 w=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,M=0,C=1,E=2,B=3,G=0,O=w,ae=w*2,Z=-1;u==="RGBA"?(G=0,O=w,ae=w*2,Z=w*3):u==="RGB"?(G=0,O=w,ae=w*2):u==="RBG"&&(G=0,ae=w,O=w*2),n=r.createImageData(s,a);for(let le=0;le{qe(),Ie=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*n,g=d==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),w=4,l=0,M=1,C=2,E=3,B=0,G=p,O=p*2,ae=-1;u==="RGB"&&(w=3,l=0,M=1,C=2,E=-1),d==="RGBA"?ae=p*3:d==="RBG"?(B=0,O=p,G=p*2):d==="BGR"&&(O=0,G=p,B=p*2);for(let Z=0;Z{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,u=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=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 w=p(g);if(w!=null){let l=e.height,M=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,M=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=l,u.width=M}else u.tensorFormat="RGBA",u.height=l,u.width=M;w.drawImage(e,0,0),i=w.getImageData(0,0,M,l).data}else throw new Error("Can not access image data")}else if(n){let g,w;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,w=t.resizedWidth):(g=e.height,w=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=g,u.width=w,t!==void 0){let l=d();l.width=w,l.height=g;let M=p(l);if(M!=null)M.putImageData(e,0,0),i=M.getImageData(0,0,w,g).data;else throw new Error("Can not access image data")}else i=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=d();g.width=e.width,g.height=e.height;let w=p(g);if(w!=null){let l=e.height,M=e.width;return w.drawImage(e,0,0,M,l),i=w.getImageData(0,0,M,l).data,u.height=l,u.width=M,Ie(i,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((g,w)=>{let l=d(),M=p(l);if(!e||!M)return w();let C=new Image;C.crossOrigin="Anonymous",C.src=e,C.onload=()=>{l.width=C.width,l.height=C.height,M.drawImage(C,0,0,l.width,l.height);let E=M.getImageData(0,0,l.width,l.height);u.height=l.height,u.width=l.width,g(Ie(E.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ie(i,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Ke=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new bt({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},ut=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new bt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},ye=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new bt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},W=(e,t,r)=>new bt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),$e,Y,He,dt,nt=R(()=>{$e=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Y=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),He=!1,dt=()=>{if(!He){He=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&($e.set("int64",BigInt64Array),Y.set(BigInt64Array,"int64")),t&&($e.set("uint64",BigUint64Array),Y.set(BigUint64Array,"uint64")),r?($e.set("float16",Float16Array),Y.set(Float16Array,"float16")):$e.set("float16",Uint16Array)}}}),ot,Re,ht=R(()=>{qe(),ot=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new bt(e.type,e.data,t);case"cpu-pinned":return new bt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new bt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new bt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new bt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),bt,qe=R(()=>{ze(),fe(),nt(),ht(),bt=class{constructor(e,t,r){dt();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let i=$e.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let d=$e.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&d===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${d.name} as data.`);e==="uint64"||e==="int64"?i=d.from(t,BigInt):i=d.from(t)}else if(t instanceof d)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${d}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")n="string",i=e;else if(d==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let d=Y.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=d,i=e}if(u===void 0)u=[i.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");s=u,this.cpuData=i,this.dataLocation="cpu"}let a=ot(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return Ze(e,t)}static fromTexture(e,t){return Ke(e,t)}static fromGpuBuffer(e,t){return ut(e,t)}static fromMLTensor(e,t){return ye(e,t)}static fromPinnedBuffer(e,t,r){return W(e,t,r)}toDataURL(e){return ve(this,e)}toImageData(e){return ke(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)}}}),ee,Pe=R(()=>{qe(),ee=bt}),Ne,Qe,Ue,je,lt=R(()=>{L(),Ne=(e,t)=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||console.timeStamp(`${e}::ORT::${t}`)},Qe=(e,t)=>{var s;let r=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||Qe("BEGIN",e)},je=e=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||Qe("END",e)}}),yt,vt=R(()=>{q(),Pe(),lt(),yt=class Ef{constructor(t){this.handler=t}async run(t,r,n){Ue();let s={},a={};if(typeof t!="object"||t===null||t instanceof ee||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ee)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let p of r){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);s[p]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,g=Object.getOwnPropertyNames(r);for(let w of this.outputNames)if(g.indexOf(w)!==-1){let l=r[w];(l===null||l instanceof ee)&&(p=!0,i=!1,s[w]=l)}if(p){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(i)for(let p of this.outputNames)s[p]=null;let u=await this.handler.run(t,s,a),d={};for(let p in u)if(Object.hasOwnProperty.call(u,p)){let g=u[p];g instanceof ee?d[p]=g:d[p]=new ee(g.type,g.data,g.dims)}return je(),d}async release(){return this.handler.dispose()}static async create(t,r,n,s){Ue();let a,i={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let g=t,w=0,l=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(w=r,!Number.isSafeInteger(w))throw new RangeError("'byteOffset' must be an integer.");if(w<0||w>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(l=t.byteLength-w,typeof n=="number"){if(l=n,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||w+l>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-w}].`);if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(g,w,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await D(i),p=await u.createInferenceSessionHandler(a,d);return je(),new Ef(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Et,x=R(()=>{vt(),Et=yt}),H=R(()=>{}),$=R(()=>{}),Q=R(()=>{}),he=R(()=>{}),Ye,Je,Bt=R(()=>{q(),Pe(),Ye="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Je=class $f{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let n=t.evalModel||"",s=t.optimizerModel||"",a=r||{},[i,u]=await D(a);if(i.createTrainingSessionHandler){let d=await i.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,s,u);return new $f(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Ye)}typeNarrowingForRunStep(t,r,n,s,a){let i={},u={};if(typeof n!="object"||n===null||n instanceof ee||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof ee)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let p of s){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);i[p]=null}if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,g=Object.getOwnPropertyNames(s);for(let w of r)if(g.indexOf(w)!==-1){let l=s[w];(l===null||l instanceof ee)&&(p=!0,d=!1,i[w]=l)}if(p){if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else u=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of t)if(typeof n[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(d)for(let p of r)i[p]=null;return[i,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let s=t[n];s instanceof ee?r[n]=s:r[n]=new ee(s.type,s.data,s.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[s,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),i=await this.handler.runTrainStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[s,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),i=await this.handler.runEvalStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),ct,Tt=R(()=>{Bt(),ct=Je}),At={};S(At,{InferenceSession:()=>Et,TRACE:()=>Ne,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>je,Tensor:()=>ee,TrainingSession:()=>ct,env:()=>k,registerBackend:()=>_e});var Pt=R(()=>{te(),de(),x(),Pe(),H(),$(),lt(),Q(),he(),Tt()}),cr=R(()=>{}),Er={};S(Er,{default:()=>Ur});var Qr,Or,Ur,at=R(()=>{var e;Hp(),Wr(),Gt(),Qr="ort-wasm-proxy-worker",Or=((e=globalThis.self)==null?void 0:e.name)===Qr,Or&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Kr(n.wasm).then(()=>{Tc(n).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:a}=n;Cc(a,s).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})});break}case"copy-from":{let{buffer:s}=n,a=Qd(s);postMessage({type:r,out:a});break}case"create":{let{model:s,options:a}=n;Ec(s,a).then(i=>{postMessage({type:r,out:i})},i=>{postMessage({type:r,err:i})});break}case"release":$c(n),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:a,inputs:i,outputIndices:u,options:d}=n;kc(s,a,i,u,new Array(u.length).fill(null),d).then(p=>{p.some(g=>g[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:p},Ac([...i,...p]))},p=>{postMessage({type:r,err:p})});break}case"end-profiling":Pc(n),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),Ur=Or?null:t=>new Worker(t??Xe,{type:"module",name:Qr})}),U={};S(U,{default:()=>et});var ge,Ae,et,xe=R(()=>{var e;Ae=(ge=self.location.href,async function(t={}){function r(){return br.buffer!=dr.buffer&&mn(),dr}function n(){return br.buffer!=dr.buffer&&mn(),Pr}function s(){return br.buffer!=dr.buffer&&mn(),Ve}function a(){return br.buffer!=dr.buffer&&mn(),kt}function i(){return br.buffer!=dr.buffer&&mn(),tr}function u(){return br.buffer!=dr.buffer&&mn(),zr}function d(){return br.buffer!=dr.buffer&&mn(),nn}function p(){return br.buffer!=dr.buffer&&mn(),Zd}var g,w,l=Object.assign({},t),M=new Promise((o,h)=>{g=o,w=h}),C=typeof window=="object",E=typeof importScripts=="function",B=E&&self.name=="em-pthread";l.mountExternalData=(o,h)=>{o.startsWith("./")&&(o=o.substring(2)),(l.Fb||(l.Fb=new Map)).set(o,h)},l.unmountExternalData=()=>{delete l.Fb};var G=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let O=()=>{let o=(y,v,F)=>(...oe)=>{let We=ds,it=v==null?void 0:v();oe=y(...oe);let It=v==null?void 0:v();return it!==It&&(y=It,F(it),v=F=null),ds!=We?new Promise((Lt,Qt)=>{Yc={resolve:Lt,reject:Qt}}):oe},h=y=>async(...v)=>{var F;try{if(l.Eb)throw Error("Session already started");let oe=l.Eb={fc:v[0],errors:[]},We=await y(...v);if(l.Eb!==oe)throw Error("Session mismatch");(F=l.Gb)==null||F.flush();let it=oe.errors;if(0Lt),0l._OrtCreateSession,y=>l._OrtCreateSession=y),l._OrtRun=h(o(l._OrtRun,()=>l._OrtRun,y=>l._OrtRun=y)),l._OrtRunWithBinding=h(o(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,y=>l._OrtRunWithBinding=y)),l._OrtBindInput=o(l._OrtBindInput,()=>l._OrtBindInput,y=>l._OrtBindInput=y),O=void 0};l.jsepInit=(o,h)=>{if(O==null||O(),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 y=l.Gb;l.jsepRegisterBuffer=(v,F,oe,We)=>y.registerBuffer(v,F,oe,We),l.jsepGetBuffer=v=>y.getBuffer(v),l.jsepCreateDownloader=(v,F,oe)=>y.createDownloader(v,F,oe),l.jsepOnReleaseSession=v=>{y.onReleaseSession(v)},l.jsepOnRunStart=v=>y.onRunStart(v),l.cc=(v,F)=>{y.upload(v,F)}}else if(o==="webnn"){[l.Gb,l.ac,l.Ob,l.jsepEnsureTensor,l.dc,l.jsepDownloadTensor]=h,l.jsepReleaseTensorId=l.Ob;let y=l.Gb;l.jsepOnRunStart=v=>y.onRunStart(v),l.jsepRegisterMLContext=(v,F)=>{y.registerMLContext(v,F)},l.jsepOnReleaseSession=v=>{y.onReleaseSession(v)},l.jsepCreateMLTensorDownloader=(v,F)=>y.createMLTensorDownloader(v,F),l.jsepRegisterMLTensor=(v,F,oe)=>y.registerMLTensor(v,F,oe)}};var ae,Z,le=Object.assign({},l),Ge="./this.program",Le=(o,h)=>{throw h},pt="";(C||E)&&(E?pt=self.location.href:typeof document<"u"&&document.currentScript&&(pt=document.currentScript.src),ge&&(pt=ge),pt=pt.startsWith("blob:")?"":pt.substr(0,pt.replace(/[?#].*/,"").lastIndexOf("/")+1),E&&(Z=o=>{var h=new XMLHttpRequest;return h.open("GET",o,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),ae=(o,h,y)=>{var v=new XMLHttpRequest;v.open("GET",o,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):y()},v.onerror=y,v.send(null)});var Dt,Vt=console.log.bind(console),lr=console.error.bind(console),fr=Vt,er=lr;if(Object.assign(l,le),le=null,B){let o=function(h){try{var y=h.data,v=y.cmd;if(v==="load"){let F=[];self.onmessage=oe=>F.push(oe),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let oe of F)o(oe);self.onmessage=o};for(let oe of y.handlers)l[oe]&&!l[oe].proxy||(l[oe]=(...We)=>{postMessage({Mb:"callHandler",oc:oe,args:We})},oe=="print"&&(fr=l[oe]),oe=="printErr"&&(er=l[oe]));br=y.wasmMemory,mn(),Nr(y.wasmModule)}else if(v==="run"){tp(y.pthread_ptr,0,0,1,0,0),Kc(y.pthread_ptr),Zf(),_h(),Hr||(ff(),Hr=!0);try{em(y.start_routine,y.arg)}catch(F){if(F!="unwind")throw F}}else v==="cancel"?no()&&cc(-1):y.target!=="setimmediate"&&(v==="checkMailbox"?Hr&&rc():v&&(er(`worker: received unknown command ${v}`),er(y)))}catch(F){throw mf(),F}};var Nr,Hr=!1;er=function(...h){h=h.join(" "),console.error(h)},self.alert=function(...h){postMessage({Mb:"alert",text:h.join(" "),qc:no()})},l.instantiateWasm=(h,y)=>new Promise(v=>{Nr=F=>{F=new WebAssembly.Instance(F,ch()),y(F),v()}}),self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=o}l.wasmBinary&&(Dt=l.wasmBinary);var br,jr,Jt,dr,Pr,Ve,kt,tr,zr,nn,un,Vs,Zd,En=!1;function mn(){var o=br.buffer;l.HEAP8=dr=new Int8Array(o),l.HEAP16=Ve=new Int16Array(o),l.HEAPU8=Pr=new Uint8Array(o),l.HEAPU16=kt=new Uint16Array(o),l.HEAP32=tr=new Int32Array(o),l.HEAPU32=zr=new Uint32Array(o),l.HEAPF32=nn=new Float32Array(o),l.HEAPF64=Zd=new Float64Array(o),l.HEAP64=un=new BigInt64Array(o),l.HEAPU64=Vs=new BigUint64Array(o)}if(!B){if(!((br=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof G))throw er("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");mn()}var yi=[],hn=[],vn=[],Vn=0,Us=null;function ec(){if(--Vn==0&&Us){var o=Us;Us=null,o()}}function eo(o){throw er(o="Aborted("+o+")"),En=!0,Jt=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),w(o),o}var Dc,oh=o=>o.startsWith("data:application/octet-stream;base64,"),lh=o=>o.startsWith("file://");function uh(o){if(o==Dc&&Dt)return new Uint8Array(Dt);if(Z)return Z(o);throw"both async and sync fetching of the wasm failed"}function dh(o,h,y){return function(v){if(!Dt&&(C||E)){if(typeof fetch=="function"&&!lh(v))return fetch(v,{credentials:"same-origin"}).then(F=>{if(!F.ok)throw`failed to load wasm binary file at '${v}'`;return F.arrayBuffer()}).catch(()=>uh(v));if(ae)return new Promise((F,oe)=>{ae(v,We=>F(new Uint8Array(We)),oe)})}return Promise.resolve().then(()=>uh(v))}(o).then(v=>WebAssembly.instantiate(v,h)).then(y,v=>{er(`failed to asynchronously prepare wasm: ${v}`),eo(v)})}function ch(){return{a:{O:Jf,Aa:Yf,b:rm,aa:bh,B:xh,qa:Th,Y:Eh,_:$h,ra:Sh,oa:kh,ha:Ph,na:Ah,L:Ih,Z:Fh,W:zh,pa:Oh,X:Dh,wa:nm,F:sm,Q:im,P:om,E:um,u:dm,q:cm,G:pm,A:ym,R:bm,ua:Mm,ka:vm,U:xm,ba:Tm,H:Cm,ja:Kc,ta:Em,t:$m,x:Pm,o:Am,l:Fm,c:qc,n:zm,j:Lm,w:Bm,p:Rm,g:Nm,s:jm,m:Vm,e:Um,k:Wm,i:Gm,h:qm,d:Hm,ea:Km,fa:Xm,ga:Qm,ca:Qh,da:Yh,T:Ym,f:Jm,D:Zm,I:e_,M:t_,y:r_,sa:n_,V:s_,v:Zh,z:i_,N:a_,S:o_,za:l_,ya:u_,la:rf,ma:nf,$:jc,C:sf,K:af,ia:of,J:lf,a:br,xa:Nc,va:cf,r:p_}}}var Lc={864100:(o,h,y,v,F)=>{if(l===void 0||!l.Fb)return 1;if((o=gn(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=l.Fb.get(o)))return 2;if(v>>>=0,(h>>>=0)+(y>>>=0)>o.byteLength)return 3;try{let oe=o.subarray(h,h+y);switch(F){case 0:n().set(oe,v>>>0);break;case 1:l.cc(v,oe);break;default:return 4}return 0}catch{return 4}},864783:(o,h,y)=>{l.dc(o,n().subarray(h>>>0,h+y>>>0))},864846:()=>l.ac(),864887:o=>{l.Ob(o)},864923:()=>{l.Vb()},864954:()=>{l.Wb()},864983:()=>{l.$b()},865008:o=>l.Ub(o),865041:o=>l.Yb(o),865073:(o,h,y)=>{l.Nb(o,h,y,!0)},865112:(o,h,y)=>{l.Nb(o,h,y)},865145:()=>typeof wasmOffsetConverter<"u",865202:o=>{l.jb("Abs",o,void 0)},865253:o=>{l.jb("Neg",o,void 0)},865304:o=>{l.jb("Floor",o,void 0)},865357:o=>{l.jb("Ceil",o,void 0)},865409:o=>{l.jb("Reciprocal",o,void 0)},865467:o=>{l.jb("Sqrt",o,void 0)},865519:o=>{l.jb("Exp",o,void 0)},865570:o=>{l.jb("Erf",o,void 0)},865621:o=>{l.jb("Sigmoid",o,void 0)},865676:(o,h,y)=>{l.jb("HardSigmoid",o,{alpha:h,beta:y})},865755:o=>{l.jb("Log",o,void 0)},865806:o=>{l.jb("Sin",o,void 0)},865857:o=>{l.jb("Cos",o,void 0)},865908:o=>{l.jb("Tan",o,void 0)},865959:o=>{l.jb("Asin",o,void 0)},866011:o=>{l.jb("Acos",o,void 0)},866063:o=>{l.jb("Atan",o,void 0)},866115:o=>{l.jb("Sinh",o,void 0)},866167:o=>{l.jb("Cosh",o,void 0)},866219:o=>{l.jb("Asinh",o,void 0)},866272:o=>{l.jb("Acosh",o,void 0)},866325:o=>{l.jb("Atanh",o,void 0)},866378:o=>{l.jb("Tanh",o,void 0)},866430:o=>{l.jb("Not",o,void 0)},866481:(o,h,y)=>{l.jb("Clip",o,{min:h,max:y})},866550:o=>{l.jb("Clip",o,void 0)},866602:(o,h)=>{l.jb("Elu",o,{alpha:h})},866660:o=>{l.jb("Gelu",o,void 0)},866712:o=>{l.jb("Relu",o,void 0)},866764:(o,h)=>{l.jb("LeakyRelu",o,{alpha:h})},866828:(o,h)=>{l.jb("ThresholdedRelu",o,{alpha:h})},866898:(o,h)=>{l.jb("Cast",o,{to:h})},866956:o=>{l.jb("Add",o,void 0)},867007:o=>{l.jb("Sub",o,void 0)},867058:o=>{l.jb("Mul",o,void 0)},867109:o=>{l.jb("Div",o,void 0)},867160:o=>{l.jb("Pow",o,void 0)},867211:o=>{l.jb("Equal",o,void 0)},867264:o=>{l.jb("Greater",o,void 0)},867319:o=>{l.jb("GreaterOrEqual",o,void 0)},867381:o=>{l.jb("Less",o,void 0)},867433:o=>{l.jb("LessOrEqual",o,void 0)},867492:(o,h,y,v,F)=>{l.jb("ReduceMean",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},867651:(o,h,y,v,F)=>{l.jb("ReduceMax",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},867809:(o,h,y,v,F)=>{l.jb("ReduceMin",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},867967:(o,h,y,v,F)=>{l.jb("ReduceProd",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868126:(o,h,y,v,F)=>{l.jb("ReduceSum",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868284:(o,h,y,v,F)=>{l.jb("ReduceL1",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868441:(o,h,y,v,F)=>{l.jb("ReduceL2",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868598:(o,h,y,v,F)=>{l.jb("ReduceLogSum",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868759:(o,h,y,v,F)=>{l.jb("ReduceSumSquare",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868923:(o,h,y,v,F)=>{l.jb("ReduceLogSumExp",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},869087:o=>{l.jb("Where",o,void 0)},869140:(o,h,y)=>{l.jb("Transpose",o,{perm:h?Array.from(i().subarray(h>>>0,y>>>0)):[]})},869248:(o,h,y,v)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:gn(y),format:v?"NHWC":"NCHW"})},869381:(o,h,y,v)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:gn(y),format:v?"NHWC":"NCHW"})},869514:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be,Mr)=>{l.jb("ConvTranspose",o,{format:It?"NHWC":"NCHW",autoPad:h,dilations:[y],group:v,kernelShape:[F],pads:[oe,We],strides:[it],wIsConst:()=>!!r()[Lt>>>0],outputPadding:Qt?Array.from(i().subarray(Qt>>>0,Cr>>>0)):[],outputShape:Lr?Array.from(i().subarray(Lr>>>0,Be>>>0)):[],activation:gn(Mr)})},869915:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:h,dilations:Array.from(i().subarray(y>>>0,2+(y>>>0)>>>0)),group:v,kernelShape:Array.from(i().subarray(F>>>0,2+(F>>>0)>>>0)),pads:Array.from(i().subarray(oe>>>0,4+(oe>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[It>>>0],outputPadding:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],outputShape:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[],activation:gn(Be)})},870480:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be,Mr)=>{l.jb("ConvTranspose",o,{format:It?"NHWC":"NCHW",autoPad:h,dilations:[y],group:v,kernelShape:[F],pads:[oe,We],strides:[it],wIsConst:()=>!!r()[Lt>>>0],outputPadding:Qt?Array.from(i().subarray(Qt>>>0,Cr>>>0)):[],outputShape:Lr?Array.from(i().subarray(Lr>>>0,Be>>>0)):[],activation:gn(Mr)})},870881:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:h,dilations:Array.from(i().subarray(y>>>0,2+(y>>>0)>>>0)),group:v,kernelShape:Array.from(i().subarray(F>>>0,2+(F>>>0)>>>0)),pads:Array.from(i().subarray(oe>>>0,4+(oe>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[It>>>0],outputPadding:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],outputShape:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[],activation:gn(Be)})},871446:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},871537:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:v,storage_order:F,dilations:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,It>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[]})},871952:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},872043:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:v,storage_order:F,dilations:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,It>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[]})},872458:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},872545:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:v,storage_order:F,dilations:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,It>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[]})},872956:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},873043:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:v,storage_order:F,dilations:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,It>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[]})},873454:(o,h,y,v,F)=>{l.jb("Gemm",o,{alpha:h,beta:y,transA:v,transB:F})},873558:o=>{l.jb("MatMul",o,void 0)},873612:(o,h,y,v)=>{l.jb("ArgMax",o,{keepDims:!!h,selectLastIndex:!!y,axis:v})},873720:(o,h,y,v)=>{l.jb("ArgMin",o,{keepDims:!!h,selectLastIndex:!!y,axis:v})},873828:(o,h)=>{l.jb("Softmax",o,{axis:h})},873891:(o,h)=>{l.jb("Concat",o,{axis:h})},873951:(o,h,y,v,F)=>{l.jb("Split",o,{axis:h,numOutputs:y,splitSizes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},874091:o=>{l.jb("Expand",o,void 0)},874145:(o,h)=>{l.jb("Gather",o,{axis:Number(h)})},874216:(o,h)=>{l.jb("GatherElements",o,{axis:Number(h)})},874295:(o,h,y,v,F,oe,We,it,It,Lt,Qt)=>{l.jb("Resize",o,{antialias:h,axes:y?Array.from(i().subarray(y>>>0,v>>>0)):[],coordinateTransformMode:gn(F),cubicCoeffA:oe,excludeOutside:We,extrapolationValue:it,keepAspectRatioPolicy:gn(It),mode:gn(Lt),nearestMode:gn(Qt)})},874641:(o,h,y,v,F,oe,We)=>{l.jb("Slice",o,{starts:h?Array.from(i().subarray(h>>>0,y>>>0)):[],ends:v?Array.from(i().subarray(v>>>0,F>>>0)):[],axes:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[]})},874857:o=>{l.jb("Tile",o,void 0)},874909:(o,h,y)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:y?"NHWC":"NCHW"})},875023:(o,h,y)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:y?"NHWC":"NCHW"})},875137:o=>{l.jb("Range",o,void 0)},875190:(o,h)=>{l.jb("Einsum",o,{equation:gn(h)})},875271:(o,h,y,v,F)=>{l.jb("Pad",o,{mode:h,value:y,pads:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},875398:(o,h,y,v,F,oe)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:y,spatial:!!F,trainingMode:!!v,format:oe?"NHWC":"NCHW"})},875567:(o,h,y,v,F,oe)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:y,spatial:!!F,trainingMode:!!v,format:oe?"NHWC":"NCHW"})},875736:(o,h,y)=>{l.jb("CumSum",o,{exclusive:Number(h),reverse:Number(y)})},875833:(o,h,y)=>{l.jb("DequantizeLinear",o,{axis:h,blockSize:y})},875923:(o,h,y,v,F,oe,We,it,It)=>{l.jb("Attention",o,{numHeads:h,isUnidirectional:y,maskFilterValue:v,scale:F,doRotary:oe,qkvHiddenSizes:We?Array.from(i().subarray(Number(it)>>>0,Number(it)+We>>>0)):[],pastPresentShareBuffer:!!It})},876195:o=>{l.jb("BiasAdd",o,void 0)},876250:o=>{l.jb("BiasSplitGelu",o,void 0)},876311:o=>{l.jb("FastGelu",o,void 0)},876367:(o,h,y,v,F,oe,We,it,It,Lt,Qt,Cr,Lr,Be,Mr,tn)=>{l.jb("Conv",o,{format:Cr?"NHWC":"NCHW",auto_pad:h,dilations:y?Array.from(i().subarray(y>>>0,v>>>0)):[],group:F,kernel_shape:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],pads:it?Array.from(i().subarray(it>>>0,It>>>0)):[],strides:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],w_is_const:()=>!!r()[Lr>>>0],activation:gn(Be),activation_params:Mr?Array.from(d().subarray(Mr>>>0,tn>>>0)):[]})},876863:o=>{l.jb("Gelu",o,void 0)},876915:(o,h,y,v)=>{l.jb("GroupQueryAttention",o,{numHeads:h,kvNumHeads:y,scale:v})},877028:(o,h,y,v)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:y,simplified:!!v})},877139:(o,h,y,v)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:y,simplified:!!v})},877250:(o,h,y,v,F,oe)=>{l.jb("MatMulNBits",o,{k:h,n:y,accuracyLevel:v,bits:F,blockSize:oe})},877377:(o,h,y,v,F,oe)=>{l.jb("MultiHeadAttention",o,{numHeads:h,isUnidirectional:y,maskFilterValue:v,scale:F,doRotary:oe})},877536:(o,h)=>{l.jb("QuickGelu",o,{alpha:h})},877600:(o,h,y,v,F)=>{l.jb("RotaryEmbedding",o,{interleaved:!!h,numHeads:y,rotaryEmbeddingDim:v,scale:F})},877739:(o,h,y)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!y})},877841:(o,h,y)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!y})},877943:(o,h,y,v)=>{l.jb("GatherBlockQuantized",o,{gatherAxis:h,quantizeAxis:y,blockSize:v})},878064:o=>{l.Zb(o)},878098:(o,h)=>l.bc(o,h,l.Eb.fc,l.Eb.errors)};function Yf(o,h,y){return Gh(async()=>{await l.Xb(o,h,y)})}function Jf(){return typeof wasmOffsetConverter<"u"}function Bc(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var Rc=o=>{o.terminate(),o.onmessage=()=>{}},ph=o=>{Ws.length==0&&(wh(),gh(Ws[0]));var h=Ws.pop();if(!h)return 6;Mi.push(h),ls[o.Ab]=h,h.Ab=o.Ab;var y={cmd:"run",start_routine:o.hc,arg:o.Qb,pthread_ptr:o.Ab};return h.postMessage(y,o.mc),0},bi=0,Yr=(o,h,...y)=>{for(var v=2*y.length,F=sp(),oe=np(8*v),We=oe>>>3,it=0;it>>0]=It)}return o=_f(o,0,v,oe,h),pc(F),o};function Nc(o){if(B)return Yr(0,1,o);if(Jt=o,!(0{if(Jt=o,B)throw hh(o),"unwind";Nc(o)},Ws=[],Mi=[],fh=[],ls={},mh=o=>{var h=o.Ab;delete ls[h],Ws.push(o),Mi.splice(Mi.indexOf(o),1),o.Ab=0,rp(h)};function _h(){fh.forEach(o=>o())}var gh=o=>new Promise(h=>{o.onmessage=F=>{var oe=(F=F.data).cmd;if(F.targetThread&&F.targetThread!=no()){var We=ls[F.targetThread];We?We.postMessage(F,F.transferList):er(`Internal error! Worker sent a message "${oe}" to target pthread ${F.targetThread}, but that thread no longer exists!`)}else oe==="checkMailbox"?rc():oe==="spawnThread"?ph(F):oe==="cleanupThread"?mh(ls[F.thread]):oe==="killThread"?(F=F.thread,oe=ls[F],delete ls[F],Rc(oe),rp(F),Mi.splice(Mi.indexOf(oe),1),oe.Ab=0):oe==="cancelThread"?ls[F.thread].postMessage({cmd:"cancel"}):oe==="loaded"?(o.loaded=!0,h(o)):oe==="alert"?alert(`Thread ${F.threadId}: ${F.text}`):F.target==="setimmediate"?o.postMessage(F):oe==="callHandler"?l[F.handler](...F.args):oe&&er(`worker sent an unknown command ${oe}`)},o.onerror=F=>{throw er(`worker sent an error! ${F.filename}:${F.lineno}: ${F.message}`),F};var y,v=[];for(y of[])l.hasOwnProperty(y)&&v.push(y);o.postMessage({cmd:"load",handlers:v,wasmMemory:br,wasmModule:jr})});function wh(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ws.push(o)}var tc=o=>{for(;0{var o=no(),h=u()[o+52>>>2>>>0];o=u()[o+56>>>2>>>0],wf(h,h-o),pc(h)},em=(o,h)=>{bi=0,o=yf(o,h),0>>=0);throw h>>>=0,y>>>=0,u()[v.Jb+16>>>2>>>0]=0,u()[v.Jb+4>>>2>>>0]=h,u()[v.Jb+8>>>2>>>0]=y,o}function yh(o,h,y,v){return B?Yr(2,1,o,h,y,v):bh(o,h,y,v)}function bh(o,h,y,v){if(o>>>=0,h>>>=0,y>>>=0,v>>>=0,G===void 0)return er("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var F=[];return B&&F.length===0?yh(o,h,y,v):(o={hc:y,Ab:o,Qb:v,mc:F},B?(o.Mb="spawnThread",postMessage(o,F),0):ph(o))}var Mh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,vh=(o,h,y)=>{var v=(h>>>=0)+y;for(y=h;o[y]&&!(y>=v);)++y;if(16(F=(240&F)==224?(15&F)<<12|oe<<6|We:(7&F)<<18|oe<<12|We<<6|63&o[h++])?v+=String.fromCharCode(F):(F-=65536,v+=String.fromCharCode(55296|F>>10,56320|1023&F))}}else v+=String.fromCharCode(F)}return v},gn=(o,h)=>(o>>>=0)?vh(n(),o,h):"";function xh(o,h,y){return B?Yr(3,1,o,h,y):0}function Th(o,h){if(B)return Yr(4,1,o,h)}var Vc=o=>{for(var h=0,y=0;y=v?h++:2047>=v?h+=2:55296<=v&&57343>=v?(h+=4,++y):h+=3}return h},Ch=(o,h,y,v)=>{if(!(0>>=0;v=y+v-1;for(var oe=0;oe=We&&(We=65536+((1023&We)<<10)|1023&o.charCodeAt(++oe)),127>=We){if(y>=v)break;h[y++>>>0]=We}else{if(2047>=We){if(y+1>=v)break;h[y++>>>0]=192|We>>6}else{if(65535>=We){if(y+2>=v)break;h[y++>>>0]=224|We>>12}else{if(y+3>=v)break;h[y++>>>0]=240|We>>18,h[y++>>>0]=128|We>>12&63}h[y++>>>0]=128|We>>6&63}h[y++>>>0]=128|63&We}}return h[y>>>0]=0,y-F},to=(o,h,y)=>Ch(o,n(),h,y);function Eh(o,h){if(B)return Yr(5,1,o,h)}function $h(o,h,y){if(B)return Yr(6,1,o,h,y)}function Sh(o,h,y){return B?Yr(7,1,o,h,y):0}function kh(o,h){if(B)return Yr(8,1,o,h)}function Ph(o,h,y){if(B)return Yr(9,1,o,h,y)}function Ah(o,h,y,v){if(B)return Yr(10,1,o,h,y,v)}function Ih(o,h,y,v){if(B)return Yr(11,1,o,h,y,v)}function Fh(o,h,y,v){if(B)return Yr(12,1,o,h,y,v)}function zh(o){if(B)return Yr(13,1,o)}function Oh(o,h){if(B)return Yr(14,1,o,h)}function Dh(o,h,y){if(B)return Yr(15,1,o,h,y)}var Lh,Gs,nm=()=>{eo("")},us=o=>{for(var h="";n()[o>>>0];)h+=Lh[n()[o++>>>0]];return h},Uc={},Wc={};function xs(o,h,y={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(v,F,oe={}){var We=F.name;if(!v)throw new Gs(`type "${We}" must have a positive integer typeid pointer`);if(Wc.hasOwnProperty(v)){if(oe.Sb)return;throw new Gs(`Cannot register type '${We}' twice`)}Wc[v]=F,Uc.hasOwnProperty(v)&&(F=Uc[v],delete Uc[v],F.forEach(it=>it()))}(o,h,y)}var Bh=(o,h,y)=>{switch(h){case 1:return y?v=>r()[v>>>0]:v=>n()[v>>>0];case 2:return y?v=>s()[v>>>1>>>0]:v=>a()[v>>>1>>>0];case 4:return y?v=>i()[v>>>2>>>0]:v=>u()[v>>>2>>>0];case 8:return y?v=>un[v>>>3]:v=>Vs[v>>>3];default:throw new TypeError(`invalid integer width (${h}): ${o}`)}};function sm(o,h,y){y>>>=0,xs(o>>>=0,{name:h=us(h>>>0),fromWireType:v=>v,toWireType:function(v,F){if(typeof F!="bigint"&&typeof F!="number")throw F=F===null?"null":(v=typeof F)=="object"||v==="array"||v==="function"?F.toString():""+F,new TypeError(`Cannot convert "${F}" to ${this.name}`);return typeof F=="number"&&(F=BigInt(F)),F},argPackAdvance:qs,readValueFromPointer:Bh(h,y,h.indexOf("u")==-1),Db:null})}var qs=8;function im(o,h,y,v){xs(o>>>=0,{name:h=us(h>>>0),fromWireType:function(F){return!!F},toWireType:function(F,oe){return oe?y:v},argPackAdvance:qs,readValueFromPointer:function(F){return this.fromWireType(n()[F>>>0])},Db:null})}var Gc=[],Ts=[];function qc(o){9<(o>>>=0)&&--Ts[o+1]==0&&(Ts[o]=void 0,Gc.push(o))}var Un=o=>{if(!o)throw new Gs("Cannot use deleted val. handle = "+o);return Ts[o]},Wn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=Gc.pop()||Ts.length;return Ts[h]=o,Ts[h+1]=1,h}};function Hc(o){return this.fromWireType(u()[o>>>2>>>0])}var am={name:"emscripten::val",fromWireType:o=>{var h=Un(o);return qc(o),h},toWireType:(o,h)=>Wn(h),argPackAdvance:qs,readValueFromPointer:Hc,Db:null};function om(o){return xs(o>>>0,am)}var lm=(o,h)=>{switch(h){case 4:return function(y){return this.fromWireType(d()[y>>>2>>>0])};case 8:return function(y){return this.fromWireType(p()[y>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${o}`)}};function um(o,h,y){y>>>=0,xs(o>>>=0,{name:h=us(h>>>0),fromWireType:v=>v,toWireType:(v,F)=>F,argPackAdvance:qs,readValueFromPointer:lm(h,y),Db:null})}function dm(o,h,y,v,F){if(o>>>=0,y>>>=0,h=us(h>>>0),F===-1&&(F=4294967295),F=it=>it,v===0){var oe=32-8*y;F=it=>it<>>oe}var We=h.includes("unsigned")?function(it,It){return It>>>0}:function(it,It){return It};xs(o,{name:h,fromWireType:F,toWireType:We,argPackAdvance:qs,readValueFromPointer:Bh(h,y,v!==0),Db:null})}function cm(o,h,y){function v(oe){var We=u()[oe>>>2>>>0];return oe=u()[oe+4>>>2>>>0],new F(r().buffer,oe,We)}var F=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];xs(o>>>=0,{name:y=us(y>>>0),fromWireType:v,argPackAdvance:qs,readValueFromPointer:v},{Sb:!0})}function pm(o,h){o>>>=0;var y=(h=us(h>>>0))==="std::string";xs(o,{name:h,fromWireType:function(v){var F=u()[v>>>2>>>0],oe=v+4;if(y)for(var We=oe,it=0;it<=F;++it){var It=oe+it;if(it==F||n()[It>>>0]==0){if(We=gn(We,It-We),Lt===void 0)var Lt=We;else Lt+="\0",Lt+=We;We=It+1}}else{for(Lt=Array(F),it=0;it>>0]);Lt=Lt.join("")}return cs(v),Lt},toWireType:function(v,F){F instanceof ArrayBuffer&&(F=new Uint8Array(F));var oe=typeof F=="string";if(!(oe||F instanceof Uint8Array||F instanceof Uint8ClampedArray||F instanceof Int8Array))throw new Gs("Cannot pass non-string to std::string");var We=y&&oe?Vc(F):F.length,it=dc(4+We+1),It=it+4;if(u()[it>>>2>>>0]=We,y&&oe)to(F,It,We+1);else if(oe)for(oe=0;oe>>0]=Lt}else for(oe=0;oe>>0]=F[oe];return v!==null&&v.push(cs,it),it},argPackAdvance:qs,readValueFromPointer:Hc,Db(v){cs(v)}})}var Rh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,hm=(o,h)=>{for(var y=o>>1,v=y+h/2;!(y>=v)&&a()[y>>>0];)++y;if(32<(y<<=1)-o&&Rh)return Rh.decode(n().slice(o,y));for(y="",v=0;!(v>=h/2);++v){var F=s()[o+2*v>>>1>>>0];if(F==0)break;y+=String.fromCharCode(F)}return y},fm=(o,h,y)=>{if(y??(y=2147483647),2>y)return 0;var v=h;y=(y-=2)<2*o.length?y/2:o.length;for(var F=0;F>>1>>>0]=oe,h+=2}return s()[h>>>1>>>0]=0,h-v},mm=o=>2*o.length,_m=(o,h)=>{for(var y=0,v="";!(y>=h/4);){var F=i()[o+4*y>>>2>>>0];if(F==0)break;++y,65536<=F?(F-=65536,v+=String.fromCharCode(55296|F>>10,56320|1023&F)):v+=String.fromCharCode(F)}return v},gm=(o,h,y)=>{if(h>>>=0,y??(y=2147483647),4>y)return 0;var v=h;y=v+y-4;for(var F=0;F=oe&&(oe=65536+((1023&oe)<<10)|1023&o.charCodeAt(++F)),i()[h>>>2>>>0]=oe,(h+=4)+4>y)break}return i()[h>>>2>>>0]=0,h-v},wm=o=>{for(var h=0,y=0;y=v&&++y,h+=4}return h};function ym(o,h,y){if(o>>>=0,h>>>=0,y=us(y>>>=0),h===2)var v=hm,F=fm,oe=mm,We=it=>a()[it>>>1>>>0];else h===4&&(v=_m,F=gm,oe=wm,We=it=>u()[it>>>2>>>0]);xs(o,{name:y,fromWireType:it=>{for(var It,Lt=u()[it>>>2>>>0],Qt=it+4,Cr=0;Cr<=Lt;++Cr){var Lr=it+4+Cr*h;Cr!=Lt&&We(Lr)!=0||(Qt=v(Qt,Lr-Qt),It===void 0?It=Qt:(It+="\0",It+=Qt),Qt=Lr+h)}return cs(it),It},toWireType:(it,It)=>{if(typeof It!="string")throw new Gs(`Cannot pass non-string to C++ string type ${y}`);var Lt=oe(It),Qt=dc(4+Lt+h);return u()[Qt>>>2>>>0]=Lt/h,F(It,Qt+4,Lt+h),it!==null&&it.push(cs,Qt),Qt},argPackAdvance:qs,readValueFromPointer:Hc,Db(it){cs(it)}})}function bm(o,h){xs(o>>>=0,{Tb:!0,name:h=us(h>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Mm=()=>1;function vm(o){tp(o>>>0,!E,1,!C,131072,!1),_h()}var Nh=o=>{if(!En)try{if(o(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(i(),o>>>2,o).value.then(rc),o+=128,Atomics.store(i(),o>>>2,1))}var rc=()=>{var o=no();o&&(Kc(o),Nh(gf))};function xm(o,h){(o>>>=0)==h>>>0?setTimeout(rc):B?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=ls[o])&&o.postMessage({cmd:"checkMailbox"})}var Xc=[];function Tm(o,h,y,v,F){for(h>>>=0,v/=2,Xc.length=v,y=F>>>0>>>3,F=0;F>>0];return(h?Lc[h]:h_[o])(...Xc)}function Cm(o){o>>>=0,B?postMessage({cmd:"cleanupThread",thread:o}):mh(ls[o])}function Em(o){}var Qc=(o,h)=>{var y=Wc[o];if(y===void 0)throw o=hf(o),y=us(o),cs(o),new Gs(`${h} has unknown type ${y}`);return y},jh=(o,h,y)=>{var v=[];return o=o.toWireType(v,y),v.length&&(u()[h>>>2>>>0]=Wn(v)),o};function $m(o,h,y){return h>>>=0,y>>>=0,o=Un(o>>>0),h=Qc(h,"emval::as"),jh(h,y,o)}var nc=o=>{try{o()}catch(h){eo(h)}},Hs=0,ds=null,Vh=0,sc=[],Uh={},Wh={},Sm=0,Yc=null,km=[];function Gh(o){return function(h){if(!En){if(Hs===0){var y=!1,v=!1;h((F=0)=>{if(!En&&(Vh=F,y=!0,v)){Hs=2,nc(()=>vf(ds)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),F=!1;try{var oe=function(){var It=i()[ds+8>>>2>>>0];return It=Kt[Wh[It]],--bi,It()}()}catch(It){oe=It,F=!0}var We=!1;if(!ds){var it=Yc;it&&(Yc=null,(F?it.reject:it.resolve)(oe),We=!0)}if(F&&!We)throw oe}}),v=!0,y||(Hs=1,ds=function(){var F=dc(65548),oe=F+12;u()[F>>>2>>>0]=oe,u()[F+4>>>2>>>0]=oe+65536,oe=sc[0];var We=Uh[oe];return We===void 0&&(We=Sm++,Uh[oe]=We,Wh[We]=oe),oe=We,i()[F+8>>>2>>>0]=oe,F}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),nc(()=>bf(ds)))}else Hs===2?(Hs=0,nc(xf),cs(ds),ds=null,km.forEach(Nh)):eo(`invalid state: ${Hs}`);return Vh}}(h=>{o().then(h)})}function Pm(o){return o>>>=0,Gh(()=>(o=Un(o)).then(Wn))}var ic=[];function Am(o,h,y,v){return y>>>=0,v>>>=0,(o=ic[o>>>0])(null,h=Un(h>>>0),y,v)}var Im={},ac=o=>{var h=Im[o];return h===void 0?us(o):h};function Fm(o,h,y,v,F){return y>>>=0,v>>>=0,F>>>=0,(o=ic[o>>>0])(h=Un(h>>>0),h[y=ac(y)],v,F)}var qh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function zm(o){return(o>>>=0)==0?Wn(qh()):(o=ac(o),Wn(qh()[o]))}var Om=o=>{var h=ic.length;return ic.push(o),h},Dm=(o,h)=>{for(var y=Array(o),v=0;v>>2>>>0],"parameter "+v);return y},Hh=(o,h)=>Object.defineProperty(h,"name",{value:o});function Lm(o,h,y){var v=(h=Dm(o,h>>>0)).shift();o--;var F=`return function (obj, func, destructorsRef, args) { +`,oe=0,We=[];y===0&&We.push("obj");for(var it=["retType"],It=[v],Lt=0;LtQt.name).join(", ")}) => ${v.name}>`,Om(Hh(y,o))}function Bm(o){return o=ac(o>>>0),Wn(l[o])}function Rm(o,h){return h>>>=0,o=Un(o>>>0),h=Un(h),Wn(o[h])}function Nm(o){9<(o>>>=0)&&(Ts[o+1]+=1)}function jm(){return Wn([])}function Vm(o){o=Un(o>>>0);for(var h=Array(o.length),y=0;y>>0))}function Wm(){return Wn({})}function Gm(o){for(var h=Un(o>>>=0);h.length;){var y=h.pop();h.pop()(y)}qc(o)}function qm(o,h,y){h>>>=0,y>>>=0,o=Un(o>>>0),h=Un(h),y=Un(y),o[h]=y}function Hm(o,h){return h>>>=0,o=(o=Qc(o>>>0,"_emval_take_value")).readValueFromPointer(h),Wn(o)}function Km(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[h>>>2>>>0]=o.getUTCSeconds(),i()[h+4>>>2>>>0]=o.getUTCMinutes(),i()[h+8>>>2>>>0]=o.getUTCHours(),i()[h+12>>>2>>>0]=o.getUTCDate(),i()[h+16>>>2>>>0]=o.getUTCMonth(),i()[h+20>>>2>>>0]=o.getUTCFullYear()-1900,i()[h+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[h+28>>>2>>>0]=o}var ro=o=>o%4==0&&(o%100!=0||o%400==0),Kh=[0,31,60,91,121,152,182,213,244,274,305,335],Xh=[0,31,59,90,120,151,181,212,243,273,304,334];function Xm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[h>>>2>>>0]=o.getSeconds(),i()[h+4>>>2>>>0]=o.getMinutes(),i()[h+8>>>2>>>0]=o.getHours(),i()[h+12>>>2>>>0]=o.getDate(),i()[h+16>>>2>>>0]=o.getMonth(),i()[h+20>>>2>>>0]=o.getFullYear()-1900,i()[h+24>>>2>>>0]=o.getDay();var y=(ro(o.getFullYear())?Kh:Xh)[o.getMonth()]+o.getDate()-1|0;i()[h+28>>>2>>>0]=y,i()[h+36>>>2>>>0]=-60*o.getTimezoneOffset(),y=new Date(o.getFullYear(),6,1).getTimezoneOffset();var v=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(y!=v&&o.getTimezoneOffset()==Math.min(v,y)),i()[h+32>>>2>>>0]=o}function Qm(o){o>>>=0;var h=new Date(i()[o+20>>>2>>>0]+1900,i()[o+16>>>2>>>0],i()[o+12>>>2>>>0],i()[o+8>>>2>>>0],i()[o+4>>>2>>>0],i()[o>>>2>>>0],0),y=i()[o+32>>>2>>>0],v=h.getTimezoneOffset(),F=new Date(h.getFullYear(),6,1).getTimezoneOffset(),oe=new Date(h.getFullYear(),0,1).getTimezoneOffset(),We=Math.min(oe,F);return 0>y?i()[o+32>>>2>>>0]=+(F!=oe&&We==v):0>>2>>>0]=h.getDay(),y=(ro(h.getFullYear())?Kh:Xh)[h.getMonth()]+h.getDate()-1|0,i()[o+28>>>2>>>0]=y,i()[o>>>2>>>0]=h.getSeconds(),i()[o+4>>>2>>>0]=h.getMinutes(),i()[o+8>>>2>>>0]=h.getHours(),i()[o+12>>>2>>>0]=h.getDate(),i()[o+16>>>2>>>0]=h.getMonth(),i()[o+20>>>2>>>0]=h.getYear(),o=h.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Qh(o,h,y,v,F,oe,We){return B?Yr(16,1,o,h,y,v,F,oe,We):-52}function Yh(o,h,y,v,F,oe){if(B)return Yr(17,1,o,h,y,v,F,oe)}function Ym(o,h,y,v){o>>>=0,h>>>=0,y>>>=0,v>>>=0;var F=new Date().getFullYear(),oe=new Date(F,0,1),We=new Date(F,6,1);F=oe.getTimezoneOffset();var it=We.getTimezoneOffset(),It=Math.max(F,it);u()[o>>>2>>>0]=60*It,i()[h>>>2>>>0]=+(F!=it),oe=(o=Lt=>Lt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(oe),We=o(We),it{Jc.length=0;for(var y;y=n()[o++>>>0];){var v=y!=105;h+=(v&=y!=112)&&h%8?4:0,Jc.push(y==112?u()[h>>>2>>>0]:y==106?un[h>>>3]:y==105?i()[h>>>2>>>0]:p()[h>>>3>>>0]),h+=v?8:4}return Jc};function Jm(o,h,y){return o>>>=0,h=Jh(h>>>0,y>>>0),Lc[o](...h)}function Zm(o,h,y){return o>>>=0,h=Jh(h>>>0,y>>>0),Lc[o](...h)}var e_=()=>{},t_=()=>Date.now();function r_(o,h){return er(gn(o>>>0,h>>>0))}var Zh,n_=()=>{throw bi+=1,"unwind"};function s_(){return 4294901760}Zh=()=>performance.timeOrigin+performance.now();var i_=()=>navigator.hardwareConcurrency;function a_(){return eo("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function o_(o){o>>>=0;var h=n().length;if(o<=h||4294901760=y;y*=2){var v=h*(1+.2/y);v=Math.min(v,o+100663296);var F=Math;v=Math.max(o,v);e:{F=(F.min.call(F,4294901760,v+(65536-v%65536)%65536)-br.buffer.byteLength+65535)/65536;try{br.grow(F),mn();var oe=1;break e}catch{}oe=void 0}if(oe)return!0}return!1}var oc=()=>(eo("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),_d={},ef=o=>{o.forEach(h=>{oc()})};function l_(){var o=Error().stack.toString().split(` +`);return o[0]=="Error"&&o.shift(),ef(o),_d.Pb=oc(),_d.ec=o,_d.Pb}function u_(o,h,y){if(o>>>=0,h>>>=0,_d.Pb==o)var v=_d.ec;else(v=Error().stack.toString().split(` +`))[0]=="Error"&&v.shift(),ef(v);for(var F=3;v[F]&&oc()!=o;)++F;for(o=0;o>>2>>>0]=oc();return o}var Zc,ep={},tf=()=>{if(!Zc){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",_:Ge};for(o in ep)ep[o]===void 0?delete h[o]:h[o]=ep[o];var y=[];for(o in h)y.push(`${o}=${h[o]}`);Zc=y}return Zc};function rf(o,h){if(B)return Yr(18,1,o,h);o>>>=0,h>>>=0;var y=0;return tf().forEach((v,F)=>{var oe=h+y;for(F=u()[o+4*F>>>2>>>0]=oe,oe=0;oe>>0]=v.charCodeAt(oe);r()[F>>>0]=0,y+=v.length+1}),0}function nf(o,h){if(B)return Yr(19,1,o,h);o>>>=0,h>>>=0;var y=tf();u()[o>>>2>>>0]=y.length;var v=0;return y.forEach(F=>v+=F.length+1),u()[h>>>2>>>0]=v,0}function sf(o){return B?Yr(20,1,o):52}function af(o,h,y,v){return B?Yr(21,1,o,h,y,v):52}function of(o,h,y,v){return B?Yr(22,1,o,h,y,v):70}var d_=[null,[],[]];function lf(o,h,y,v){if(B)return Yr(23,1,o,h,y,v);h>>>=0,y>>>=0,v>>>=0;for(var F=0,oe=0;oe>>2>>>0],it=u()[h+4>>>2>>>0];h+=8;for(var It=0;It>>0],Qt=d_[o];Lt===0||Lt===10?((o===1?fr:er)(vh(Qt,0)),Qt.length=0):Qt.push(Lt)}F+=it}return u()[v>>>2>>>0]=F,0}var uf=[31,29,31,30,31,30,31,31,30,31,30,31],df=[31,28,31,30,31,30,31,31,30,31,30,31],c_=(o,h)=>{r().set(o,h>>>0)};function cf(o,h,y,v){function F(Be,Mr,tn){for(Be=typeof Be=="number"?Be.toString():Be||"";Be.lengthCf?-1:0vi-Be.getDate())){Be.setDate(Be.getDate()+Mr);break}Mr-=vi-Be.getDate()+1,Be.setDate(1),11>tn?Be.setMonth(tn+1):(Be.setMonth(0),Be.setFullYear(Be.getFullYear()+1))}return tn=new Date(Be.getFullYear()+1,0,4),Mr=it(new Date(Be.getFullYear(),0,4)),tn=it(tn),0>=We(Mr,Be)?0>=We(tn,Be)?Be.getFullYear()+1:Be.getFullYear():Be.getFullYear()-1}o>>>=0,h>>>=0,y>>>=0,v>>>=0;var Lt=u()[v+40>>>2>>>0];for(var Qt in v={kc:i()[v>>>2>>>0],jc:i()[v+4>>>2>>>0],Hb:i()[v+8>>>2>>>0],Lb:i()[v+12>>>2>>>0],Ib:i()[v+16>>>2>>>0],Cb:i()[v+20>>>2>>>0],ub:i()[v+24>>>2>>>0],Bb:i()[v+28>>>2>>>0],rc:i()[v+32>>>2>>>0],ic:i()[v+36>>>2>>>0],lc:Lt?gn(Lt):""},y=gn(y),Lt={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})y=y.replace(new RegExp(Qt,"g"),Lt[Qt]);var Cr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Lr="January February March April May June July August September October November December".split(" ");for(Qt in Lt={"%a":Be=>Cr[Be.ub].substring(0,3),"%A":Be=>Cr[Be.ub],"%b":Be=>Lr[Be.Ib].substring(0,3),"%B":Be=>Lr[Be.Ib],"%C":Be=>oe((Be.Cb+1900)/100|0,2),"%d":Be=>oe(Be.Lb,2),"%e":Be=>F(Be.Lb,2," "),"%g":Be=>It(Be).toString().substring(2),"%G":It,"%H":Be=>oe(Be.Hb,2),"%I":Be=>((Be=Be.Hb)==0?Be=12:12{for(var Mr=0,tn=0;tn<=Be.Ib-1;Mr+=(ro(Be.Cb+1900)?uf:df)[tn++]);return oe(Be.Lb+Mr,3)},"%m":Be=>oe(Be.Ib+1,2),"%M":Be=>oe(Be.jc,2),"%n":()=>` +`,"%p":Be=>0<=Be.Hb&&12>Be.Hb?"AM":"PM","%S":Be=>oe(Be.kc,2),"%t":()=>" ","%u":Be=>Be.ub||7,"%U":Be=>oe(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&&((tn=(Be.ub+371-Be.Bb)%7)==4||tn==3&&ro(Be.Cb)||(Mr=1));else{Mr=52;var tn=(Be.ub+7-Be.Bb-1)%7;(tn==4||tn==5&&ro(Be.Cb%400-1))&&Mr++}return oe(Mr,2)},"%w":Be=>Be.ub,"%W":Be=>oe(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,"%%":()=>"%"},y=y.replace(/%%/g,"\0\0"),Lt)y.includes(Qt)&&(y=y.replace(new RegExp(Qt,"g"),Lt[Qt](v)));return Qt=function(Be){var Mr=Array(Vc(Be)+1);return Ch(Be,Mr,0,Mr.length),Mr}(y=y.replace(/\0\0/g,"%")),Qt.length>h?0:(c_(Qt,o),Qt.length-1)}function p_(o,h,y,v){return cf(o>>>0,h>>>0,y>>>0,v>>>0)}B||function(){for(var o=l.numThreads-1;o--;)wh();yi.unshift(()=>{Vn++,function(h){B?h():Promise.all(Ws.map(gh)).then(h)}(()=>ec())})}();for(var pf=Array(256),lc=0;256>lc;++lc)pf[lc]=String.fromCharCode(lc);Lh=pf,Gs=l.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},l.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},Ts.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>Ts.length/2-5-Gc.length;var h_=[Nc,hh,yh,xh,Th,Eh,$h,Sh,kh,Ph,Ah,Ih,Fh,zh,Oh,Dh,Qh,Yh,rf,nf,sf,af,of,lf],Kt=function(){function o(y,v){return Kt=y.exports,Kt=function(){var F=Kt,oe={};for(let[We,it]of Object.entries(F))oe[We]=typeof it=="function"?(...It)=>{sc.push(We);try{return it(...It)}finally{En||(sc.pop(),ds&&Hs===1&&sc.length===0&&(Hs=0,bi+=1,nc(Mf),typeof Fibers<"u"&&Fibers.sc()))}}:it;return oe}(),Kt=function(){var F=Kt,oe=it=>It=>it(It)>>>0,We=it=>()=>it()>>>0;return(F=Object.assign({},F)).Ca=oe(F.Ca),F.fb=We(F.fb),F.gb=oe(F.gb),F.emscripten_main_runtime_thread_id=We(F.emscripten_main_runtime_thread_id),F.sb=oe(F.sb),F.tb=We(F.tb),F}(),fh.push(Kt.ib),hn.unshift(Kt.Ba),jr=v,ec(),Kt}var h=ch();if(Vn++,l.instantiateWasm)try{return l.instantiateWasm(h,o)}catch(y){er(`Module.instantiateWasm callback failed with error: ${y}`),w(y)}return Dc||(Dc=l.locateFile?oh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",pt):pt+"ort-wasm-simd-threaded.jsep.wasm":new URL(N("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),N.b).href),function(y,v){var F=Dc;return Dt||typeof WebAssembly.instantiateStreaming!="function"||oh(F)||lh(F)||typeof fetch!="function"?dh(F,y,v):fetch(F,{credentials:"same-origin"}).then(oe=>WebAssembly.instantiateStreaming(oe,y).then(v,function(We){return er(`wasm streaming compile failed: ${We}`),er("falling back to ArrayBuffer instantiation"),dh(F,y,v)}))}(h,function(y){o(y.instance,y.module)}).catch(w),{}}(),hf=o=>(hf=Kt.Ca)(o),ff=()=>(ff=Kt.Da)();l._OrtInit=(o,h)=>(l._OrtInit=Kt.Ea)(o,h),l._OrtGetLastError=(o,h)=>(l._OrtGetLastError=Kt.Fa)(o,h),l._OrtCreateSessionOptions=(o,h,y,v,F,oe,We,it,It,Lt)=>(l._OrtCreateSessionOptions=Kt.Ga)(o,h,y,v,F,oe,We,it,It,Lt),l._OrtAppendExecutionProvider=(o,h)=>(l._OrtAppendExecutionProvider=Kt.Ha)(o,h),l._OrtAddFreeDimensionOverride=(o,h,y)=>(l._OrtAddFreeDimensionOverride=Kt.Ia)(o,h,y),l._OrtAddSessionConfigEntry=(o,h,y)=>(l._OrtAddSessionConfigEntry=Kt.Ja)(o,h,y),l._OrtReleaseSessionOptions=o=>(l._OrtReleaseSessionOptions=Kt.Ka)(o),l._OrtCreateSession=(o,h,y)=>(l._OrtCreateSession=Kt.La)(o,h,y),l._OrtReleaseSession=o=>(l._OrtReleaseSession=Kt.Ma)(o),l._OrtGetInputOutputCount=(o,h,y)=>(l._OrtGetInputOutputCount=Kt.Na)(o,h,y),l._OrtGetInputName=(o,h)=>(l._OrtGetInputName=Kt.Oa)(o,h),l._OrtGetOutputName=(o,h)=>(l._OrtGetOutputName=Kt.Pa)(o,h),l._OrtFree=o=>(l._OrtFree=Kt.Qa)(o),l._OrtCreateTensor=(o,h,y,v,F,oe)=>(l._OrtCreateTensor=Kt.Ra)(o,h,y,v,F,oe),l._OrtGetTensorData=(o,h,y,v,F)=>(l._OrtGetTensorData=Kt.Sa)(o,h,y,v,F),l._OrtReleaseTensor=o=>(l._OrtReleaseTensor=Kt.Ta)(o),l._OrtCreateRunOptions=(o,h,y,v)=>(l._OrtCreateRunOptions=Kt.Ua)(o,h,y,v),l._OrtAddRunConfigEntry=(o,h,y)=>(l._OrtAddRunConfigEntry=Kt.Va)(o,h,y),l._OrtReleaseRunOptions=o=>(l._OrtReleaseRunOptions=Kt.Wa)(o),l._OrtCreateBinding=o=>(l._OrtCreateBinding=Kt.Xa)(o),l._OrtBindInput=(o,h,y)=>(l._OrtBindInput=Kt.Ya)(o,h,y),l._OrtBindOutput=(o,h,y,v)=>(l._OrtBindOutput=Kt.Za)(o,h,y,v),l._OrtClearBoundOutputs=o=>(l._OrtClearBoundOutputs=Kt._a)(o),l._OrtReleaseBinding=o=>(l._OrtReleaseBinding=Kt.$a)(o),l._OrtRunWithBinding=(o,h,y,v,F)=>(l._OrtRunWithBinding=Kt.ab)(o,h,y,v,F),l._OrtRun=(o,h,y,v,F,oe,We,it)=>(l._OrtRun=Kt.bb)(o,h,y,v,F,oe,We,it),l._OrtEndProfiling=o=>(l._OrtEndProfiling=Kt.cb)(o),l._JsepOutput=(o,h,y)=>(l._JsepOutput=Kt.db)(o,h,y),l._JsepGetNodeName=o=>(l._JsepGetNodeName=Kt.eb)(o);var uc,no=()=>(no=Kt.fb)(),dc=l._malloc=o=>(dc=l._malloc=Kt.gb)(o),cs=l._free=o=>(cs=l._free=Kt.hb)(o),tp=(o,h,y,v,F,oe)=>(tp=Kt.kb)(o,h,y,v,F,oe),mf=()=>(mf=Kt.lb)(),_f=(o,h,y,v,F)=>(_f=Kt.mb)(o,h,y,v,F),rp=o=>(rp=Kt.nb)(o),cc=o=>(cc=Kt.ob)(o),gf=()=>(gf=Kt.pb)(),wf=(o,h)=>(wf=Kt.qb)(o,h),pc=o=>(pc=Kt.rb)(o),np=o=>(np=Kt.sb)(o),sp=()=>(sp=Kt.tb)(),yf=l.dynCall_ii=(o,h)=>(yf=l.dynCall_ii=Kt.vb)(o,h),bf=o=>(bf=Kt.wb)(o),Mf=()=>(Mf=Kt.xb)(),vf=o=>(vf=Kt.yb)(o),xf=()=>(xf=Kt.zb)();function Tf(){0sp(),l.stackRestore=o=>pc(o),l.stackAlloc=o=>np(o),l.UTF8ToString=gn,l.stringToUTF8=to,l.lengthBytesUTF8=Vc,Us=function o(){uc||Tf(),uc||(Us=o)},Tf(),M}),et=Ae,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&Ae()}),Xe,gt,mt,$t,ft,zt,Nt,Rt,Gt=R(()=>{var e,t;cr(),Xe=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),gt=typeof location>"u"?void 0:location.origin,mt=(r,n)=>{try{let s=n??Xe;return(s?new URL(r,s):new URL(r)).origin===gt}catch{return!1}},$t=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},ft=(at(),P(Er)).default,zt=async()=>{if(!Xe)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(mt(Xe))return[void 0,ft()];let r=await $t(Xe);return[r,ft(r)]},Nt=(xe(),P(U)).default,Rt=async(r,n,s)=>[void 0,Nt]}),be,tt,st,qt,wr,Br,Kr,rr,Wr=R(()=>{Gt(),tt=!1,st=!1,qt=!1,wr=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},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}},Kr=async e=>{if(tt)return Promise.resolve();if(st)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(qt)throw new Error("previous call to 'initializeWebAssembly()' failed.");st=!0;let t=e.initTimeout,r=e.numThreads;if(!Br())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=wr();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,i=s==null?void 0:s.mjs,u=(i==null?void 0:i.href)??i,d=s==null?void 0:s.wasm,p=(d==null?void 0:d.href)??d,g=e.wasmBinary,[w,l]=await Rt(u,a,r>1),M=!1,C=[];if(t>0&&C.push(new Promise(E=>{setTimeout(()=>{M=!0,E()},t)})),C.push(new Promise((E,B)=>{let G={numThreads:r};g?G.wasmBinary=g:(p||a)&&(G.locateFile=(O,ae)=>p??(a??ae)+O),l(G).then(O=>{st=!1,tt=!0,be=O,E(),w&&URL.revokeObjectURL(w)},O=>{st=!1,qt=!0,B(O)})})),await Promise.race(C),M)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},rr=()=>{if(tt&&be)return be;throw new Error("WebAssembly is not initialized yet.")}}),Vr,Ln,Rr,Bn=R(()=>{Wr(),Vr=(e,t)=>{let r=rr(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Ln=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let i=t?t+s:s;if(typeof a=="object")Ln(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Rr=e=>{let t=rr(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let s=t.HEAP32[n/4],a=t.HEAPU32[n/4+1],i=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),Cs,Xs=R(()=>{Wr(),Bn(),Cs=e=>{let t=rr(),r=0,n=[],s=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)s.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(s.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Vr(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Rr("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Ln(e.extra,"",new WeakSet,(i,u)=>{let d=Vr(i,n),p=Vr(u,n);t._OrtAddRunConfigEntry(r,d,p)!==0&&Rr(`Can't set a run config entry: ${i} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),Es,$s,Ss,Gn,ks,Qs=R(()=>{Wr(),Bn(),Es=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},$s=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ss=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Gn=(e,t,r)=>{for(let n of t){let s=typeof n=="string"?n:n.name;switch(s){case"webnn":if(s="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let u=Vr("deviceType",r),d=Vr(i,r);rr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Rr(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(s="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let u=Vr("preferredLayout",r),d=Vr(i.preferredLayout,r);rr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Rr(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Vr(s,r);rr()._OrtAppendExecutionProvider(e,a)!==0&&Rr(`Can't append execution provider: ${s}.`)}},ks=e=>{let t=rr(),r=0,n=[],s=e||{};Ss(s);try{let a=Es(s.graphOptimizationLevel??"all"),i=$s(s.executionMode??"sequential"),u=typeof s.logId=="string"?Vr(s.logId,n):0,d=s.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let p=s.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let g=typeof s.optimizedModelFilePath=="string"?Vr(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,u,d,p,g),r===0&&Rr("Can't create session options."),s.executionProviders&&Gn(r,s.executionProviders,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);let w=Vr("enableGraphCapture",n),l=Vr(s.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,w,l)!==0&&Rr(`Can't set a session config entry: 'enableGraphCapture' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[w,l]of Object.entries(s.freeDimensionOverrides)){if(typeof w!="string")throw new Error(`free dimension override name must be a string: ${w}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let M=Vr(w,n);t._OrtAddFreeDimensionOverride(r,M,l)!==0&&Rr(`Can't set a free dimension override: ${w} - ${l}.`)}return s.extra!==void 0&&Ln(s.extra,"",new WeakSet,(w,l)=>{let M=Vr(w,n),C=Vr(l,n);t._OrtAddSessionConfigEntry(r,M,C)!==0&&Rr(`Can't set a session config entry: ${w} - ${l}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(i=>t._free(i)),a}}}),qn,Sn,Cn,ps,ts,hs,fs,rs,Xt=R(()=>{qn=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}`)}},Sn=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}`)}},Cn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},ps=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},ts=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},hs=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",fs=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool",rs=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}`)}}}),ms,_s=R(()=>{cr(),ms=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let d=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let i=0;for(;;){let{done:u,value:d}=await s.read();if(u)break;let p=d.byteLength;new Uint8Array(a,i,p).set(d),i+=p}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Ps,As,gs,Is,ws,ns,ue,m=R(()=>{Xt(),Ps=["V","I","W","E","F"],As=(e,t)=>{console.log(`[${Ps[e]},${new Date().toISOString()}]${t}`)},ws=(e,t)=>{gs=e,Is=t},ns=(e,t)=>{let r=ts(e),n=ts(gs);r>=n&&As(r,typeof t=="function"?t():t)},ue=(...e)=>{Is&&ns(...e)}}),A,K=R(()=>{Xt(),A=(e,t)=>new(ps(t))(e)}),se=R(()=>{}),pe,De,wt,xt,Mt,Ot,Yt,$r,ar,Dr=R(()=>{m(),se(),pe=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]]),De=[],wt=e=>Math.ceil(e/16)*16,xt=e=>{for(let t=0;tMt++,Yt=async(e,t,r,n)=>{let s=wt(r),a=e.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,s),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(u,0,r)),d}else return new Uint8Array(u.slice(0,r))}finally{a.destroy()}},$r=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 pe)De.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,s=t.byteLength,a=wt(s),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${s}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(r,n,s)),u.unmap();let p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(u,0,i.gpuData.buffer,0,a),ue("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(u)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=wt(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(e,t,r){let n;if(r){if(n=r[0],e===r[1])return ue("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else n=Ot();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),ue("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),ue("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=xt(e),n,s=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||a){let u=(s?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let i={id:Ot(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:e}),ue("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return ue("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 Yt(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=pe.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e))}},ar=(...e)=>new $r(...e)}),Jr,ur,Sr=R(()=>{Jr=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}},ur=e=>new Jr(e)}),_n,wn,Se,Zr,xn,kn,Nn,Ht=R(()=>{_n=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},wn=class{static calcShape(e,t,r=!1){let n=e.length,s=t.length;if(n===0)return t;if(s===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(r){if(n<2||s<2)return;let u=_n.calcMatMulShape([e[n-2],e[n-1]],[t[s-2],t[s-1]]);if(u===void 0)return;[i[a-2],i[a-1]]=u}for(let u=r?3:1;u<=a;u++){let d=n-u<0?1:e[n-u],p=s-u<0?1:t[s-u];if(d!==p&&d>1&&p>1)return;let g=Math.max(d,p);if(d&&p)i[a-u]=Math.max(d,p);else{if(g>1)return;i[a-u]=0}}return i}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let s=1;s<=r;s++)if(e[r-s]!==1&&e[r-s]!==t[n-s])return!1;return!0}},Se=class hc{static size(t){return hc.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let s=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){s[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");s[a]=1,r/=t[a],a--}for(a--;a>=0;a--)s[a]=t[a];return s}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return hc.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 hc.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let s=1;for(let a=r;a=0;--s)n[s]=n[s+1]*t[s+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((s,a)=>s+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,s)=>n===r[s])}},Zr=class gd{static adjustPoolAttributes(t,r,n,s,a,i){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||i[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,s,a,i,u){if(u){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{Xt(),Ht(),en=64,Xr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},yr=(e,t=1)=>{let r=Xr(e,t);return typeof r=="string"?r:r[0]},Ar=(e,t=1)=>{let r=Xr(e,t);return typeof r=="string"?r:r[1]},Ct=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:Se.computeStrides(r)})}),t},mr=e=>e%4===0?4:e%2===0?2:1,Hn=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Kn=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Xn=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,jt=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Ys=(e,t,r,n,s)=>{let a=typeof r=="number",i=a?r:r.length,u=[...new Array(i).keys()],d=i<2?"u32":i<=4?`vec${i}`:`array`,p=Xr(t,s),g=typeof p=="string"?p:p[1],w=typeof p=="string"?p:p[0],l={indices:d,value:g,storage:w,tensor:t},M=Ve=>typeof Ve=="string"?Ve:`${Ve}u`,C={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},E=a?"uniforms.":"",B=`${E}${e}_shape`,G=`${E}${e}_strides`,O="";for(let Ve=0;Ve ${l.indices} { + var indices: ${l.indices}; + var current = offset; + ${O} + return indices; + }`,Z=Ve=>(C.offsetToIndices=!0,i<2?Ve:`o2i_${e}(${Ve})`),le=[];if(i>=2)for(let Ve=i-1;Ve>=0;Ve--)le.push(`${jt(G,Ve,i)} * (indices[${Ve}])`);let Ge=i<2?"":` + fn i2o_${e}(indices: ${l.indices}) -> u32 { + return ${le.join("+")}; + }`,Le=Ve=>(C.indicesToOffset=!0,i<2?Ve:`i2o_${e}(${Ve})`),pt=(...Ve)=>i===0?"0u":`${l.indices}(${Ve.map(M).join(",")})`,Dt=(Ve,kt)=>i<2?`${Ve}`:`${jt(Ve,kt,i)}`,Vt=(Ve,kt,tr)=>i<2?`${Ve}=${tr};`:`${jt(Ve,kt,i)}=${tr};`,lr={},fr=(Ve,kt)=>{C.broadcastedIndicesToOffset=!0;let tr=`${kt.name}broadcastedIndicesTo${e}Offset`;if(tr in lr)return`${tr}(${Ve})`;let zr=[];for(let nn=i-1;nn>=0;nn--){let un=kt.indicesGet("outputIndices",nn+kt.rank-i);zr.push(`${Dt(G,nn)} * (${un} % ${Dt(B,nn)})`)}return lr[tr]=`fn ${tr}(outputIndices: ${kt.type.indices}) -> u32 { + return ${zr.length>0?zr.join("+"):"0u"}; + }`,`${tr}(${Ve})`},er=(Ve,kt)=>(()=>{if(l.storage===l.value)return`${e}[${Ve}]=${kt};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${Ve}]=vec2(u32(${kt}), select(0u, 0xFFFFFFFFu, ${kt} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${Ve}]=vec2(u32(${kt}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${Ve}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${kt}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Nr=Ve=>(()=>{if(l.storage===l.value)return`${e}[${Ve}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${Ve}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${Ve}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${Ve}] & 0xFFu), bool(${e}[${Ve}] & 0xFF00u), bool(${e}[${Ve}] & 0xFF0000u), bool(${e}[${Ve}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Hr=i<2?"":` + fn get_${e}ByIndices(indices: ${l.indices}) -> ${g} { + return ${Nr(`i2o_${e}(indices)`)}; + }`,br=i<2?"":(()=>{let Ve=u.map(tr=>`d${tr}: u32`).join(", "),kt=u.map(tr=>`d${tr}`).join(", ");return` + fn get_${e}(${Ve}) -> ${g} { + return get_${e}ByIndices(${pt(kt)}); + }`})(),jr=(...Ve)=>{if(Ve.length!==i)throw new Error(`indices length must be ${i}`);let kt=Ve.map(M).join(",");return i===0?Nr("0u"):i===1?Nr(kt[0]):(C.get=!0,C.getByIndices=!0,C.indicesToOffset=!0,`get_${e}(${kt})`)},Jt=Ve=>i<2?Nr(Ve):(C.getByIndices=!0,C.indicesToOffset=!0,`get_${e}ByIndices(${Ve})`),dr=i<2?"":` + fn set_${e}ByIndices(indices: ${l.indices}, value: ${g}) { + ${er(`i2o_${e}(indices)`,"value")} + }`,Pr=i<2?"":(()=>{let Ve=u.map(tr=>`d${tr}: u32`).join(", "),kt=u.map(tr=>`d${tr}`).join(", ");return` + fn set_${e}(${Ve}, value: ${g}) { + set_${e}ByIndices(${pt(kt)}, value); + }`})();return{impl:()=>{let Ve=[],kt=!1;return C.offsetToIndices&&(Ve.push(ae),kt=!0),C.indicesToOffset&&(Ve.push(Ge),kt=!0),C.broadcastedIndicesToOffset&&(Object.values(lr).forEach(tr=>Ve.push(tr)),kt=!0),C.set&&(Ve.push(Pr),kt=!0),C.setByIndices&&(Ve.push(dr),kt=!0),C.get&&(Ve.push(br),kt=!0),C.getByIndices&&(Ve.push(Hr),kt=!0),!a&&kt&&Ve.unshift(`const ${B} = ${l.indices}(${r.join(",")});`,`const ${G} = ${l.indices}(${Se.computeStrides(r).join(",")});`),Ve.join(` +`)},type:l,offsetToIndices:Z,indicesToOffset:Le,broadcastedIndicesToOffset:fr,indices:pt,indicesGet:Dt,indicesSet:Vt,set:(...Ve)=>{if(Ve.length!==i+1)throw new Error(`indices length must be ${i}`);let kt=Ve[i];if(typeof kt!="string")throw new Error("value must be string");let tr=Ve.slice(0,i).map(M).join(",");return i===0?er("0u",kt):i===1?er(tr[0],kt):(C.set=!0,C.setByIndices=!0,C.indicesToOffset=!0,`set_${e}(${tr}, ${kt})`)},setByOffset:er,setByIndices:(Ve,kt)=>i<2?er(Ve,kt):(C.setByIndices=!0,C.indicesToOffset=!0,`set_${e}ByIndices(${Ve}, ${kt});`),get:jr,getByOffset:Nr,getByIndices:Jt,usage:n,name:e,strides:G,shape:B,rank:i}},rt=(e,t,r,n=1)=>Ys(e,t,r,"input",n),Ut=(e,t,r,n=1)=>Ys(e,t,r,"output",n),Ti=(e,t,r,n=1)=>Ys(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=en){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=s?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=s?`let global_idx = global_id.x; + let local_idx = local_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) + fn main(${a}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",n=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${s}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},io=(e,t)=>new Ci(e,t),Fs=(e,t)=>{let r=e.length,n=[];for(let s=0;s1&&i===1&&n.unshift(a)}return n}}),ss,Ei,yd,ao,bd,Pn,$i,oo,is=R(()=>{Xt(),Ht(),Sr(),or(),ss=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Ei=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,yd=(e,t)=>Se.sortBasedOnPerm(e,Ei(e.length,t)),ao=(e,t,r,n)=>{let s=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`;for(let a=0;a{let r=[],n=[];for(let s=0;s{let r=e.dataType,n=e.dims.length,s=Ei(n,t),a=yd(e.dims,s),{newShape:i,newPerm:u}=bd(e.dims,s),d=Se.areEqual(u,[2,3,1]),p=Se.areEqual(u,[3,1,2]),g=i.length===2&&u[0]>u[1]||d||p,w=g?i:e.dims,l=a;g&&(w=d?[i[0],i[1]*i[2]]:p?[i[0]*i[1],i[2]]:i,l=[w[1],w[0]]);let M=rt("a",r,w.length),C=Ut("output",r,l.length),E=16,B;return g?B=G=>` + ${G.registerUniform("output_size","u32").declareVariables(M,C)} + var tile : array, ${E}>; + ${G.mainStart([E,E,1])} + let stride = (uniforms.output_shape[1] - 1) / ${E} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${E}u + local_id.x; + let input_row = workgroup_id_x * ${E}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${M.getByIndices(`${M.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${E}u + local_id.x; + let output_row = workgroup_id_y * ${E}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${C.setByIndices(`${C.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`:B=G=>` + ${G.registerUniform("output_size","u32").declareVariables(M,C)} + + ${ao(s,n,M,C)} + + ${G.mainStart()} + ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${C.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${C.setByOffset("global_idx",M.getByIndices("aIndices"))} + }`,{name:g?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let G=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:g?{x:Math.ceil(l[1]/E),y:Math.ceil(l[0]/E)}:{x:Math.ceil(G/64)},programUniforms:[{type:12,data:G},...Ct(w,l)]}},getShaderSource:B}},$i=(e,t)=>{ss(e.inputs),e.compute(Pn(e.inputs[0],t.perm))},oo=e=>ur({perm:e.perm})}),lo,uo,co,Si,po,ho,ki,fo,mo,Pi,An,_o,Ai,go,wo,Ii,yo,bo,Fi,Mo,vo,xo=R(()=>{Xt(),Ht(),or(),Js(),is(),lo={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"},uo={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"},co={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Si={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},po=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,s]},ki=(e,t)=>{let r=e.length+t.length,n=[],s=0;for(let a=0;a{for(let r=0;r{let r=[];if(!fo(e,t)){for(let n=0;nr.push(n))}return r},Pi=(e,t,r,n,s,a,i)=>{let u=r[0].dims,d=Se.size(a),p=Se.size(i),g=rt("_A",r[0].dataType,u),w=Ut("output",s,a),l=32,M=` + var aBestValues : array; + `;return{name:e,shaderCache:t,getShaderSource:C=>` + ${C.registerUniform("reduceSize","u32").declareVariables(g,w)} + ${M} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${C.mainStart(l)} + + let outputIndex = global_idx / ${l}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${co[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${l}) { + let candidate = f32(${g.getByOffset("offset + k")}); + bestValue = ${lo[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 = ${uo[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${w.setByOffset("outputIndex",`${n==="mean"?`${w.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${w.type.storage}(${Si[n]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:d},programUniforms:[{type:12,data:p}]})}},An=(e,t,r,n)=>{let s=e.inputs.length===1?r:zi(e.inputs,r),a=s.axes;a.length===0&&!s.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((M,C)=>C));let i=Se.normalizeAxes(a,e.inputs[0].dims.length),u=i,d=e.inputs[0],p=mo(u,e.inputs[0].dims.length);p.length>0&&(d=e.compute(Pn(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],u=po(u.length,d.dims.length));let[g,w]=ho(d.dims,u),l=g;s.keepDims&&(l=ki(g,i)),e.compute(Pi(t,{hint:s.cacheKey,inputDependencies:["type"]},[d],n,e.inputs[0].dataType,l,w),{inputs:[d]})},_o=(e,t)=>{An(e,"ReduceMeanShared",t,"mean")},Ai=(e,t)=>{An(e,"ReduceL1Shared",t,"l1")},go=(e,t)=>{An(e,"ReduceL2Shared",t,"l2")},wo=(e,t)=>{An(e,"ReduceLogSumExpShared",t,"logSumExp")},Ii=(e,t)=>{An(e,"ReduceMaxShared",t,"max")},yo=(e,t)=>{An(e,"ReduceMinShared",t,"min")},bo=(e,t)=>{An(e,"ReduceProdShared",t,"prod")},Fi=(e,t)=>{An(e,"ReduceSumShared",t,"sum")},Mo=(e,t)=>{An(e,"ReduceSumSquareShared",t,"sumSquare")},vo=(e,t)=>{An(e,"ReduceLogSumShared",t,"logSum")}}),In,To,zs,zi,Fn,Oi,Co,Eo,Di,$o,So,Li,ko,Po,Bi,zn,Ao,Ri,Io,Fo,Ni,zo,Oo,ji,Do,Lo,Js=R(()=>{Xt(),Ht(),Sr(),or(),xo(),In=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.")},To=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],zs=(e,t,r,n,s,a,i=!1,u=!1)=>{let d=[],p=r[0].dims,g=p.length,w=Se.normalizeAxes(s,g),l=!u&&w.length===0;p.forEach((E,B)=>{l||w.indexOf(B)>=0?i&&d.push(1):d.push(E)});let M=d.length,C=Se.size(d);return{name:e,shaderCache:t,getShaderSource:E=>{let B=[],G=rt("_A",r[0].dataType,g),O=Ut("output",a,M),ae=n(G,O,w),Z=ae[2];for(let le=0,Ge=0;le=0?(i&&Ge++,Z=`for(var j${le}: u32 = 0; j${le} < ${p[le]}; j${le}++) { + ${ae[2].includes("last_index")?`let last_index = j${le};`:""} + ${G.indicesSet("input_indices",le,`j${le}`)} + ${Z} + }`):(B.push(`${G.indicesSet("input_indices",le,O.indicesGet("output_indices",Ge))};`),Ge++);return` + + ${E.registerUniform("output_size","u32").declareVariables(G,O)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${G.type.indices}; + let output_indices = ${O.offsetToIndices("global_idx")}; + + ${B.join(` +`)} + ${ae[0]} // init ops for reduce max/min + ${ae[1]} + ${Z} + ${ae[3]} + ${ae.length===4?O.setByOffset("global_idx","value"):ae.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:d,dataType:a}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...Ct(p,d)]})}},zi=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),ur({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Fn=(e,t,r,n)=>{let s=e.inputs,a=s.length===1?r:zi(s,r);e.compute(zs(t,{hint:a.cacheKey,inputDependencies:["rank"]},[s[0]],a.noopWithEmptyAxes&&a.axes.length===0?To:n,a.axes,s[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Oi=(e,t)=>{In(e.inputs),Fn(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Co=(e,t)=>{In(e.inputs),Fn(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Eo=(e,t)=>{In(e.inputs),Fn(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);"])},Di=(e,t)=>{In(e.inputs),Fn(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},$o=(e,t)=>{In(e.inputs),Fn(e,"ReduceMax",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(r.indicesSet("input_indices",i,0));return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},So=(e,t)=>{In(e.inputs),Fn(e,"ReduceMean",t,(r,n,s)=>{let a=1;for(let i=0;i=0||s.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Li=(e,t)=>{In(e.inputs),Fn(e,"ReduceMin",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},ko=(e,t)=>{In(e.inputs),Fn(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Po=(e,t)=>{In(e.inputs),Fn(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Bi=(e,t)=>{In(e.inputs),Fn(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,s=1;for(let a=0;a1024},Ao=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?So(e,t):_o(e,t)},Ri=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Co(e,t):Ai(e,t)},Io=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Eo(e,t):go(e,t)},Fo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Di(e,t):wo(e,t)},Ni=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$o(e,t):Ii(e,t)},zo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Li(e,t):yo(e,t)},Oo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ko(e,t):bo(e,t)},ji=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Po(e,t):Fi(e,t)},Do=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bi(e,t):Mo(e,t)},Lo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Oi(e,t):vo(e,t)}}),Vi,Bo,Ui,Wi,Md=R(()=>{Xt(),Sr(),Js(),Vi=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Bo=(e,t)=>{Vi(e.inputs);let r=(n,s,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",s.setByOffset("global_idx","best_index")]};e.compute(zs("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Ui=(e,t)=>{Vi(e.inputs);let r=(n,s,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",s.setByOffset("global_idx","best_index")]};e.compute(zs("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Wi=e=>ur(e)}),Gi,Ro,No,qi,Os,jo,Hi,Ki=R(()=>{Xt(),Ht(),se(),or(),Gi=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4],u=e[5];if(i&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],p=r.dims[1],g=r.dims[2];if(s.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==g)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(s.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let w=s.dims[0]/3,l=w,M=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ae of t.qkvHiddenSizes)if(ae%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");w=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],M=t.qkvHiddenSizes[2]}let C=p;if(w!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==w+l+M)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let E=0;if(i){if(l!==M)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(E=i.dims[3])}let B=C+E,G=-1,O=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==t.numHeads||u.dims[2]!==p||u.dims[3]!==B)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:p,pastSequenceLength:E,kvSequenceLength:C,totalSequenceLength:B,maxSequenceLength:G,inputHiddenSize:g,hiddenSize:w,vHiddenSize:M,headSize:Math.floor(w/t.numHeads),vHeadSize:Math.floor(M/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:O,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ro=(e,t,r)=>{let n=mr(r),s=64,a=r/n;a{let M=Ut("x",e.dataType,e.dims,n),C=Ar(e.dataType),E=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${l.registerUniforms(E).declareVariables(M)} + ${l.mainStart([s,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${s}) * uniforms.d_comp + local_offset; + + var thread_max_vector = ${p}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${p}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(n){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${n}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${s}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${p}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${p}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(n){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${n}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${s}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + x[offset + i] = ${M.type.value}(${C}(uniforms.d_inv)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${p}(x[offset + i]); + x[offset + i] = ${M.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${d};${n}`,inputDependencies:g},getShaderSource:w,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:u})}},No=(e,t,r,n,s,a,i,u)=>{let d=u+a.kvSequenceLength,p=[a.batchSize,a.numHeads,a.sequenceLength,d],g=a.kvNumHeads===void 0&&e>1&&n,w=g?[a.batchSize,a.numHeads,d,a.headSize]:void 0,l=i.scale===0?1/Math.sqrt(a.headSize):i.scale,M=mr(a.headSize),C=a.headSize/M,E=12,B={x:Math.ceil(d/E),y:Math.ceil(a.sequenceLength/E),z:a.batchSize*a.numHeads},G=[{type:12,data:a.sequenceLength},{type:12,data:C},{type:12,data:d},{type:12,data:a.numHeads},{type:1,data:l},{type:12,data:u},{type:12,data:a.kvSequenceLength}],O=g&&n&&Se.size(n.dims)>0,ae=["type","type"];O&&ae.push("type"),s&&ae.push("type");let Z=[{dims:p,dataType:t.dataType,gpuDataType:0}];g&&Z.push({dims:w,dataType:t.dataType,gpuDataType:0});let le=Ge=>{let Le=rt("q",t.dataType,t.dims,M),pt=rt("key",r.dataType,r.dims,M),Dt=[Le,pt];if(O){let Nr=rt("past_key",n.dataType,n.dims,M);Dt.push(Nr)}s&&Dt.push(rt("attention_bias",s.dataType,s.dims));let Vt=Ut("output",t.dataType,p),lr=[Vt];g&&lr.push(Ut("present_key",t.dataType,w,M));let fr=Ar(1,M),er=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${E}u; + + var tileQ: array<${Le.type.storage}, ${E*E}>; + var tileK: array<${Le.type.storage}, ${E*E}>; + ${Ge.registerUniforms(er).declareVariables(...Dt,...lr)} + ${Ge.mainStart([E,E,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + ${O&&g?` + let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; + let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` + let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} + ${g?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${fr}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${O&&g?` + if (n + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else { + tileK[idx] = + key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; + }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} + ${g?"present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];":""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${fr}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + let headOffset = headIdx * uniforms.M * uniforms.N; + if (global_id.y < uniforms.M && global_id.x < uniforms.N) { + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(M){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${M}`)}})()}; + output[outputIdx] = ${Vt.type.value} (sum * uniforms.alpha) + ${s?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${s!==void 0};${n!==void 0};${e}`,inputDependencies:ae},getRunData:()=>({outputs:Z,dispatchGroup:B,programUniforms:G}),getShaderSource:le}},qi=(e,t,r,n,s,a)=>{let i=a+s.kvSequenceLength,u=s.nReps?s.nReps:1,d=s.vHiddenSize*u,p=s.kvNumHeads==null&&e>1&&n,g=p?[s.batchSize,s.numHeads,i,s.headSize]:void 0,w=[s.batchSize,s.sequenceLength,d],l=12,M={x:Math.ceil(s.vHeadSize/l),y:Math.ceil(s.sequenceLength/l),z:s.batchSize*s.numHeads},C=[{type:12,data:s.sequenceLength},{type:12,data:i},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:d},{type:12,data:a},{type:12,data:s.kvSequenceLength}],E=p&&n&&Se.size(n.dims)>0,B=["type","type"];E&&B.push("type");let G=[{dims:w,dataType:t.dataType,gpuDataType:0}];p&&G.push({dims:g,dataType:t.dataType,gpuDataType:0});let O=ae=>{let Z=rt("probs",t.dataType,t.dims),le=rt("v",r.dataType,r.dims),Ge=[Z,le];E&&Ge.push(rt("past_value",n.dataType,n.dims));let Le=[Ut("output",t.dataType,w)];p&&Le.push(Ut("present_value",t.dataType,g));let pt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${l}u; + var tileQ: array<${Z.type.value}, ${l*l}>; + var tileK: array<${Z.type.value}, ${l*l}>; + ${ae.registerUniforms(pt).declareVariables(...Ge,...Le)} + ${ae.mainStart([l,l,1])} + let headIdx = workgroup_id.z; + let m = global_id.y; + let n = global_id.x; + + let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; + ${E&&p?` + let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; + let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; + `:` + let offsetB = headIdx * uniforms.N * uniforms.K + n; + `} + ${p?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${Z.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${E&&p?` + if (w + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else { + tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; + } + `:` + tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; + `} + ${p?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + let batchIdx = workgroup_id.z / uniforms.num_heads; + let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + currentBatchHeadNumber * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:B},getRunData:()=>({outputs:G,dispatchGroup:M,programUniforms:C}),getShaderSource:O}},Os=(e,t,r,n,s,a,i,u,d,p,g)=>{let w=Math.min(e.outputCount,1+(i?1:0)+(u?1:0)),l=p.kvNumHeads!==void 0||w>1?p.pastSequenceLength:0,M=l+p.kvSequenceLength,C=d&&Se.size(d.dims)>0?d:void 0,E=[t,r];p.kvNumHeads===void 0&&w>1&&i&&Se.size(i.dims)>0&&E.push(i),C&&E.push(C);let B=e.compute(No(w,t,r,i,C,p,g,l),{inputs:E,outputs:p.kvNumHeads===void 0&&w>1?[-1,1]:[-1]})[0];e.compute(Ro(B,p.batchSize*p.numHeads*p.sequenceLength,M),{inputs:[B],outputs:[]});let G=[B,n];p.kvNumHeads===void 0&&w>1&&u&&Se.size(u.dims)>0&&G.push(u),e.compute(qi(w,B,n,u,p,l),{inputs:G,outputs:p.kvNumHeads===void 0&&w>1?[0,2]:[0]})},jo=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,s=t.inputHiddenSize,a=t.headSize,i=12,u={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:s},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],g=w=>{let l=Ut("output_q",d[0].dataType,r),M=Ut("output_k",d[0].dataType,r),C=Ut("output_v",d[0].dataType,r),E=rt("input",d[0].dataType,d[0].dims),B=rt("weight",d[1].dataType,d[1].dims),G=rt("bias",d[2].dataType,d[2].dims),O=E.type.storage,ae=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${i}u; + var tileInput: array<${O}, ${i*i}>; + var tileWeightQ: array<${O}, ${i*i}>; + var tileWeightK: array<${O}, ${i*i}>; + var tileWeightV: array<${O}, ${i*i}>; + ${w.registerUniforms(ae).declareVariables(E,B,G,l,M,C)} + ${w.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${O}(0); + var valueK = ${O}(0); + var valueV = ${O}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:p}),getShaderSource:g},{inputs:d,outputs:[-1,-1,-1]})},Hi=(e,t)=>{let r=Gi(e.inputs,t),[n,s,a]=jo(e,r);return Os(e,n,s,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),Vo,Xi,Uo,Wo,vd=R(()=>{Pt(),Xt(),Ht(),Sr(),or(),Vo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,s,a)=>{let i=s.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);s.forEach((u,d)=>{if(u!==n[d])throw new Error(`${a}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Xi=(e,t)=>{let{epsilon:r,spatial:n,format:s}=t,a=e[0].dims,i=n?mr(a[a.length-1]):1,u=s==="NHWC"&&a.length>1?i:1,d=Se.size(a)/i,p=n,g=p?a.length:a,w=rt("x",e[0].dataType,e[0].dims,i),l=rt("scale",e[1].dataType,e[1].dims,u),M=rt("bias",e[2].dataType,e[2].dims,u),C=rt("inputMean",e[3].dataType,e[3].dims,u),E=rt("inputVar",e[4].dataType,e[4].dims,u),B=Ut("y",e[0].dataType,g,i),G=()=>{let ae="";if(n)ae=`let cOffset = ${a.length===1?"0u":s==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(s==="NCHW")ae=` + ${B.indicesSet("outputIndices","0","0")} + let cOffset = ${B.indicesToOffset("outputIndices")};`;else{ae=`var cIndices = ${l.type.indices}(0); + cIndices[0] = outputIndices[${a.length-1}];`;for(let Z=1;Z` + const epsilon = ${r}; + ${ae.registerUniform("outputSize","u32").declareVariables(w,l,M,C,E,B)} + ${ae.mainStart()} + ${ae.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${B.offsetToIndices(`global_idx * ${i}`)}; + ${G()} + let scale = ${l.getByOffset("cOffset")}; + let bias = ${M.getByOffset("cOffset")}; + let inputMean = ${C.getByOffset("cOffset")}; + let inputVar = ${E.getByOffset("cOffset")}; + let x = ${w.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${B.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:O,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p?[{type:12,data:d},...Ct(a)]:[{type:12,data:d}]})}},Uo=e=>ur(e),Wo=(e,t)=>{let{inputs:r,outputCount:n}=e,s=Uo({...t,outputCount:n});if(k.webgpu.validateInputContent&&Vo(r,s),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Xi(r,s))}}),Go,Qi,qo,xd=R(()=>{Ht(),or(),Go=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")},Qi=e=>{let t=e[0].dims,r=e[0].dims[2],n=Se.size(t)/4,s=e[0].dataType,a=rt("input",s,t,4),i=rt("bias",s,[r],4),u=rt("residual",s,t,4),d=Ut("output",s,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:p=>` + const channels = ${r}u / 4; + ${p.declareVariables(a,i,u,d)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${a.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${d.setByOffset("global_idx","value")} + }`}},qo=e=>{Go(e.inputs),e.compute(Qi(e.inputs))}}),Ho,vr,Yi,Ko,Xo,Qo,Yo,Ji,Jo,Zo,Zi,el,tl,ea,rl,nl,ys,sl,Zs,ta,il,al,ei,ol,ll,ra,na,ul,sa,dl,cl,pl,ia,hl,fl,aa,oa,la,ua,da,ml,_l,ca,gl,wl,ti=R(()=>{Xt(),Ht(),Sr(),or(),Ho=(e,t,r,n,s,a,i)=>{let u=Math.ceil(t/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let p=rt("inputData",r,[u],4),g=Ut("outputData",n,[u],4),w=[{name:"vec_size",type:"u32"}];return i&&w.push(...i),` + ${e.registerUniforms(w).declareVariables(p,g)} + + ${a??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${p.getByOffset("global_idx")}; + ${g.setByOffset("global_idx",d)} + }`},vr=(e,t,r,n,s,a=e.dataType,i,u)=>{let d=[{type:12,data:Math.ceil(Se.size(e.dims)/4)}];return i&&d.push(...i),{name:t,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:p=>Ho(p,Se.size(e.dims),e.dataType,a,r,n,u),getRunData:p=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Se.size(p[0].dims)/64/4)},programUniforms:d})}},Yi=e=>{e.compute(vr(e.inputs[0],"Abs","abs"))},Ko=e=>{e.compute(vr(e.inputs[0],"Acos","acos"))},Xo=e=>{e.compute(vr(e.inputs[0],"Acosh","acosh"))},Qo=e=>{e.compute(vr(e.inputs[0],"Asin","asin"))},Yo=e=>{e.compute(vr(e.inputs[0],"Asinh","asinh"))},Ji=e=>{e.compute(vr(e.inputs[0],"Atan","atan"))},Jo=e=>{e.compute(vr(e.inputs[0],"Atanh","atanh"))},Zo=e=>ur(e),Zi=(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))},el=e=>{let t,r,n=e.length>=2&&e[1].data!==0,s=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=s?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=s?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return ur({min:t,max:r})},tl=(e,t)=>{let r=t||el(e.inputs),n=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Clip",s=>`clamp(${s}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},ea=e=>{e.compute(vr(e.inputs[0],"Ceil","ceil"))},rl=e=>{e.compute(vr(e.inputs[0],"Cos","cos"))},nl=e=>{e.compute(vr(e.inputs[0],"Cosh","cosh"))},ys=e=>ur(e),sl=(e,t)=>{let r=Ar(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))},Zs=(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)); +}`,ta=e=>{let t=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Zs(t)))},il=e=>{e.compute(vr(e.inputs[0],"Exp","exp"))},al=e=>{e.compute(vr(e.inputs[0],"Floor","floor"))},ei=e=>{let t=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Zs(t)))},ol=(e,t)=>{let r=Ar(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))},ll=e=>{e.compute(vr(e.inputs[0],"Not",t=>`!${t}`))},ra=e=>{e.compute(vr(e.inputs[0],"Neg",t=>`-${t}`))},na=e=>{e.compute(vr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},ul=e=>{let t=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},sa=e=>{e.compute(vr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},dl=e=>ur(e),cl=(e,t)=>{let r=Ar(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))},pl=e=>{e.compute(vr(e.inputs[0],"Sin","sin"))},ia=e=>{e.compute(vr(e.inputs[0],"Sinh","sinh"))},hl=e=>{e.compute(vr(e.inputs[0],"Sqrt","sqrt"))},fl=e=>{e.compute(vr(e.inputs[0],"Tan","tan"))},aa=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,oa=e=>{e.compute(vr(e.inputs[0],"Tanh",aa))},la=(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 ${aa("v")}; +} +`,ua=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,da=e=>{let t=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"FastGelu",ua,la(t),void 0,e.inputs[0].dataType))},ml=(e,t)=>{let r=Ar(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"))},ca=(e,t)=>` +const alpha = vec4<${e}>(${t}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,gl=e=>`quick_gelu_impl(${e})`,wl=(e,t)=>{let r=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"QuickGelu",gl,ca(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),yl,bl,pa,Td=R(()=>{Ht(),or(),ti(),yl=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")},bl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=rt("input",e[0].dataType,e[0].dims,4),n=rt("bias",e[0].dataType,[e[0].dims[2]],4),s=Ut("output",e[0].dataType,t,4),a=Se.size(t)/4,i=yr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${u.declareVariables(r,n,s)} + + ${Zs(i)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${s.setByOffset("global_idx","valueLeft * geluRight")} + }`}},pa=e=>{yl(e.inputs),e.compute(bl(e.inputs))}}),Ml,ha,On,vl,xl,Tl,ri,Cl,El,$l,fa,Sl,kl,Pl=R(()=>{Xt(),Ht(),or(),Ml=(e,t,r,n,s,a,i,u,d,p,g,w)=>{let l,M;typeof u=="string"?l=M=(O,ae)=>`${u}((${O}),(${ae}))`:typeof u=="function"?l=M=u:(l=u.scalar,M=u.vector);let C=Ut("outputData",g,n.length,4),E=rt("aData",d,t.length,4),B=rt("bData",p,r.length,4),G;if(s)if(a){let O=Se.size(t)===1,ae=Se.size(r)===1,Z=t.length>0&&t[t.length-1]%4===0,le=r.length>0&&r[r.length-1]%4===0;O||ae?G=C.setByOffset("global_idx",M(O?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),ae?`${B.type.value}(${B.getByOffset("0")}.x)`:B.getByOffset("global_idx"))):G=` + let outputIndices = ${C.offsetToIndices("global_idx * 4u")}; + let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",C)}; + let offsetB = ${B.broadcastedIndicesToOffset("outputIndices",C)}; + ${C.setByOffset("global_idx",M(i||Z?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||le?B.getByOffset("offsetB / 4u"):`${B.type.value}(${B.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else G=C.setByOffset("global_idx",M(E.getByOffset("global_idx"),B.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let O=(ae,Z,le="")=>{let Ge=`aData[indexA${Z}][componentA${Z}]`,Le=`bData[indexB${Z}][componentB${Z}]`;return` + let outputIndices${Z} = ${C.offsetToIndices(`global_idx * 4u + ${Z}u`)}; + let offsetA${Z} = ${E.broadcastedIndicesToOffset(`outputIndices${Z}`,C)}; + let offsetB${Z} = ${B.broadcastedIndicesToOffset(`outputIndices${Z}`,C)}; + let indexA${Z} = offsetA${Z} / 4u; + let indexB${Z} = offsetB${Z} / 4u; + let componentA${Z} = offsetA${Z} % 4u; + let componentB${Z} = offsetB${Z} % 4u; + ${ae}[${Z}] = ${le}(${l(Ge,Le)}); + `};g===9?G=` + var data = vec4(0); + ${O("data",0,"u32")} + ${O("data",1,"u32")} + ${O("data",2,"u32")} + ${O("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:G=` + ${O("outputData[global_idx]",0)} + ${O("outputData[global_idx]",1)} + ${O("outputData[global_idx]",2)} + ${O("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(E,B,C)} + + ${w??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${G} + }`},ha=(e,t,r,n,s,a,i=r.dataType)=>{let u=!Se.areEqual(r.dims,n.dims),d=r.dims,p=Se.size(r.dims),g=!1,w=!1,l=[u];if(u){let M=wn.calcShape(r.dims,n.dims,!1);if(!M)throw new Error("Can't perform binary op on the given tensors");d=M,p=Se.size(d);let C=Se.size(r.dims)===1,E=Se.size(n.dims)===1,B=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,G=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;l.push(C),l.push(E),l.push(B),l.push(G);let O=1;for(let ae=1;aeM.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:M=>Ml(M,r.dims,n.dims,d,g,u,w,s,r.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:[{type:12,data:Math.ceil(Se.size(d)/4)},...Ct(r.dims,n.dims,d)]})}},On=(e,t,r,n,s,a)=>{e.compute(ha(t,s??"",e.inputs[0],e.inputs[1],r,n,a))},vl=e=>{On(e,"Add",(t,r)=>`${t}+${r}`)},xl=e=>{On(e,"Div",(t,r)=>`${t}/${r}`)},Tl=e=>{On(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},ri=e=>{On(e,"Mul",(t,r)=>`${t}*${r}`)},Cl=e=>{let t=rt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;On(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)); + } + `)},El=e=>{On(e,"Sub",(t,r)=>`${t}-${r}`)},$l=e=>{On(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},fa=e=>{On(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Sl=e=>{On(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},kl=e=>{On(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),Al,Il,Fl,zl,ma,Ol,Cd=R(()=>{Xt(),Ht(),Sr(),or(),Al=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],s=n.dataType,a=n.dims.length;e.forEach((i,u)=>{if(u!==r){if(i.dataType!==s)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((d,p)=>{if(p!==t&&d!==n.dims[p])throw new Error("non concat dimensions must match")})}})},Il=(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; + }`,Fl=(e,t)=>{let r=e.length,n=[];for(let s=0;s{let s=Se.size(r),a=new Array(e.length),i=new Array(e.length),u=0,d=[],p=[],g=[{type:12,data:s}];for(let E=0;E`uniforms.sizeInConcatAxis${E}`).join(","),C=E=>` + + ${(()=>{E.registerUniform("outputSize","u32");for(let B=0;B(${M}); + ${l} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Fl(i,w)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:g}),getShaderSource:C}},ma=(e,t)=>{let r=e.inputs,n=r[0].dims,s=Se.normalizeAxis(t.axis,n.length);Al(r,s);let a=n.slice();a[s]=r.reduce((u,d)=>u+(d.dims.length>s?d.dims[s]:0),0);let i=r.filter(u=>Se.size(u.dims)>0);e.compute(zl(i,s,a,r[0].dataType),{inputs:i})},Ol=e=>ur({axis:e.axis})}),jn,Qn,Yn,ni,Jn=R(()=>{Xt(),Ht(),jn=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Qn=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},Yn=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},ni=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)||[kn,Nn];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),fn,si,ii=R(()=>{fn=(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.`)}},si=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),_a,Dl=R(()=>{_a=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)); +} +`}),Ll,Bl,ai,oi,Rl,li,ga,wa,ui=R(()=>{Xt(),Ht(),or(),Jn(),ii(),Ll=(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":""}); + `,Bl=(e,t)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,ai=(e,t,r="f32",n,s=!1,a=32,i=!1,u=32)=>{let d=t[1]*e[1],p=t[0]*e[0],g=s?d:a,w=s?a:d,l=g/t[0],M=a/t[1];if(!((s&&l===4&&e[1]===4||!s&&(l===3||l===4))&&g%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${l} must be 3 or 4. + tileAWidth ${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}>, ${w}>; +var mm_Bsub: array, ${p/e[0]}>, ${a}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${l}; +const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${d}; + + let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${M}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${Ll(s,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${M}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${l===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${Bl(s,l)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},oi=(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":""}); + `,Rl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",li=(e,t,r="f32",n,s=!1,a=32,i=!1,u=32,d=!1)=>{let p=e[1]*t[1],g=e[0]*t[0],w=s?p:a,l=s?a:p;if(!(l%t[1]===0&&w%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${w} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let M=l/t[1],C=w/t[0],E=a/t[1],B=d?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${p}; + 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 < ${w}; inputCol = inputCol + ${t[0]}) { + ${oi(s,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${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 = ${s?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${p}; + +let tileRowA = i32(localId.y) * ${M}; +let tileColA = i32(localId.x) * ${C}; +let tileRowB = i32(localId.y) * ${E}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${M}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${C}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${oi(s,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${E}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${Rl(s)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${l}>; + var mm_Bsub : array, ${a}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; + + var acc : array, rowPerThread>; + ${B} + } +`},ga=(e,t,r,n,s,a=!1)=>{let[i,u,d]=s,[p,g,w,l]=n,M=Fs(i,d),C=Fs(u,d),E=yr(n[0].type.tensor),B=()=>{let O=g.rank,ae=p.rank,Z=`var aIndices: ${g.type.indices};`;for(let le=O-2-1,Ge=ae-1;le>=0;le--,Ge--)Z+=` +aIndices[${le}] = ${ae>1?`batchIndices[${Ge}]`:"batchIndices"};`;return M.forEach(le=>{Z+=` +aIndices[${le}] = 0;`}),Z+=` +aIndices[${O-2}] = u32(row); + aIndices[${O-1}] = u32(colIn);`,Z},G=()=>{let O=w.rank,ae=p.rank,Z=`var bIndices: ${w.type.indices};`;for(let le=O-2-1,Ge=ae-1;le>=0;le--,Ge--)Z+=` +bIndices[${le}] = ${ae>1?`batchIndices[${Ge}]`:"batchIndices"};`;return C.forEach(le=>{Z+=` +bIndices[${le}] = 0;`}),Z+=` +bIndices[${O-2}] = u32(row); + bIndices[${O-1}] = u32(colIn);`,Z};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${fn(e,E)} { + var value = ${fn(e,E)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${B()} + value = ${g.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${fn(e,E)} { + var value = ${fn(e,E)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${G()} + value = ${w.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${fn(e,E)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${a?"bias[colIn]":`${fn(e,E)}(bias[row])`};`:""} + ${r} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},wa=(e,t,r,n,s=!1,a)=>{let i=e[0].dims,u=e[1].dims,d=i.slice(0,-2),p=u.slice(0,-2),g=n?n.slice(0,-2):r.slice(0,-2),w=Se.size(g),l=i[i.length-2],M=i[i.length-1],C=u[u.length-1],E=M%4===0&&C%4===0,B=l<=8?[4,1,1]:[4,4,1],G=[8,8,1],O=[Math.ceil(C/G[0]/B[0]),Math.ceil(l/G[1]/B[1]),Math.ceil(w/G[2]/B[2])],ae=E?4:1,Z=[...d,l,M/ae],le=Z.length,Ge=[...p,M,C/ae],Le=Ge.length,pt=[w,l,C/ae],Dt=[{type:6,data:l},{type:6,data:C},{type:6,data:M}];Qn(t,Dt),Dt.push(...Ct(g,Z,Ge));let Vt=["rank","rank"],lr=e.length>2;lr&&(Dt.push(...Ct(e[2].dims)),Vt.push("rank")),Dt.push(...Ct(pt));let fr=er=>{let Nr=g.length,Hr=Ti("batchDims",e[0].dataType,Nr,1),br=yr(e[0].dataType),jr=rt("a",e[0].dataType,le,ae),Jt=rt("b",e[1].dataType,Le,ae),dr=Ut("result",e[0].dataType,pt.length,ae),Pr=[jr,Jt];if(lr){let nn=s?ae:1;Pr.push(rt("bias",e[2].dataType,e[2].dims.length,nn))}let Ve=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Yn(t,Ve);let kt=yr(dr.type.tensor),tr=jn(t,dr.type.value,kt),zr=ga(ae,lr,tr,[Hr,jr,Jt,dr],[d,p,g],s);return` + ${er.registerUniforms(Ve).registerInternalVariables(Hr).declareVariables(...Pr,dr)} + ${zr} + ${E?ai(B,G,br,Hr):li(B,G,br,Hr)} + `};return{name:"MatMul",shaderCache:{hint:`${B};${t.activation};${E};${s}`,inputDependencies:Vt},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:O[0],y:O[1],z:O[2]},programUniforms:Dt}),getShaderSource:fr}}}),Zn,Nl,Ed=R(()=>{Xt(),m(),or(),Jn(),ii(),Dl(),ui(),Zn=(e,t,r,n,s=!1,a,i=4,u=4,d=4,p="f32")=>{let g=Dt=>{switch(Dt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},w=Dt=>{switch(Dt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},l=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,M=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,C=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",E=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",B=e?"row":"col",G=e?"col":"row",O=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${B} / outWidth; + let outCol = ${B} % outWidth; + + let WRow = ${G} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${G} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${G} % inChannels; + var resData = ${fn(i,p)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${C} && xCol >= 0 && xCol < ${E}) { + ${l} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${g(i)} + } + return resData;`,ae=e?t&&n?` + let col = colIn * ${i}; + ${O}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${O} + } + return ${fn(i,p)}(0.0);`:n&&r?` + let col = colIn * ${i}; + ${O}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${O} + } + return ${fn(i,p)}(0.0);`,Z=`${w(u)}`,le=fn(d,p),Ge=fn(e?i:u,p),Le=fn(e?u:i,p),pt=jn(a,le,p);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ge} { + ${e?ae:Z} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Le} { + ${e?Z:ae} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${le}) { + let col = colIn * ${d}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${M} + ${si(s)} + ${pt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Nl=(e,t,r,n,s,a,i,u,d)=>{let p=t.format==="NHWC",g=p?e[0].dims[3]:e[0].dims[1],w=r[0],l=p?r[2]:r[3],M=p?r[1]:r[2],C=p?r[3]:r[1],E=p&&(g%4===0||g%3===0)&&C%4===0,B=p?C:l*M,G=p?l*M:C,O=[8,8,1],ae=n<=8?[4,1,1]:[4,4,1],Z=[Math.ceil(B/O[0]/ae[0]),Math.ceil(G/O[1]/ae[1]),Math.ceil(w/O[2]/ae[2])];ue("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${Z}`);let le=E?p&&g%4!==0?3:4:1,Ge=O[1]*ae[1],Le=O[0]*ae[0],pt=Math.max(O[0]*le,O[1]),Dt=n%Ge===0,Vt=s%Le===0,lr=a%pt===0,fr=E?[le,4,4]:[1,1,1],er=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Qn(t,er),er.push(...Ct(e[0].dims,e[1].dims));let Nr=["rank","rank"];i&&(er.push(...Ct(e[2].dims)),Nr.push("rank")),er.push(...Ct(r));let Hr=br=>{let jr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Yn(t,jr);let Jt=E?4:1,dr=yr(e[0].dataType),Pr=` + fn setOutputAtIndex(flatIndex : i32, value : ${E?`vec4<${dr}>`:dr}) { + result[flatIndex] = ${E?`vec4<${dr}>`:dr}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${E?`vec4<${dr}>`:dr}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${E?"/ 4":""}, value); + }`,Ve=rt("x",e[0].dataType,e[0].dims.length,le===3?1:le),kt=rt("w",e[1].dataType,e[1].dims.length,Jt),tr=[Ve,kt],zr=Ut("result",e[0].dataType,r.length,Jt);if(i){let nn=rt("bias",e[2].dataType,e[2].dims.length,Jt);tr.push(nn),Pr+=` + fn getBiasByOutputCoords(coords : vec4) -> ${E?`vec4<${dr}>`:dr} { + return bias[coords.${p?"w":"y"}${E?"/ 4":""}]; + }`}return` + ${_a("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 }; + ${br.registerUniforms(jr).declareVariables(...tr,zr)} + ${Pr} + ${Zn(p,Dt,Vt,lr,i,t,fr[0],fr[1],fr[2],dr)} + ${E?ai(ae,O,dr,void 0,!p,pt):li(ae,O,dr,void 0,!p,pt,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${le};${E};${Dt};${Vt};${lr};${Ge};${Le};${pt}`,inputDependencies:Nr},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Z[0],y:Z[1],z:Z[2]},programUniforms:er}),getShaderSource:Hr}}}),jl,ya,bs,Vl,ba,Ul,Wl,di,$d=R(()=>{Xt(),m(),Ht(),or(),Jn(),ii(),jl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,bs=(e,t)=>t<=1?e:e+(e-1)*(t-1),Vl=(e,t,r,n=1)=>{let s=bs(t,n);return Math.floor((e[0]*(r-1)-r+s)/2)},ba=(e,t,r,n,s)=>{s==null&&(s=Vl(e,t[0],n[0]));let a=[0,0,0,r];for(let i=0;i<3;i++)e[i]+2*s>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*s)/n[i]+1));return a},Ul=(e,t,r,n,s,a,i,u,d,p)=>{let g,w,l,M;if(e==="VALID"&&(e=0),typeof e=="number"){g={top:e,bottom:e,left:e,right:e,front:e,back:e};let C=ba([t,r,n,1],[u,d,p],1,[s,a,i],e);w=C[0],l=C[1],M=C[2]}else if(Array.isArray(e)){if(!e.every((E,B,G)=>E===G[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 C=ba([t,r,n,1],[u,d,p],1,[s,a,i],e[0]);w=C[0],l=C[1],M=C[2]}else if(e==="SAME_UPPER"){w=Math.ceil(t/s),l=Math.ceil(r/a),M=Math.ceil(n/i);let C=(w-1)*s+u-t,E=(l-1)*a+d-r,B=(M-1)*i+p-n,G=Math.floor(C/2),O=C-G,ae=Math.floor(E/2),Z=E-ae,le=Math.floor(B/2),Ge=B-le;g={top:ae,bottom:Z,left:le,right:Ge,front:G,back:O}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:g,outDepth:w,outHeight:l,outWidth:M}},Wl=(e,t,r,n,s,a=!1,i="channelsLast")=>{let u,d,p,g,w;if(i==="channelsLast")[u,d,p,g,w]=e;else if(i==="channelsFirst")[u,w,d,p,g]=e;else throw new Error(`Unknown dataFormat ${i}`);let[l,,M,C,E]=t,[B,G,O]=ya(r),[ae,Z,le]=ya(n),Ge=bs(M,ae),Le=bs(C,Z),pt=bs(E,le),{padInfo:Dt,outDepth:Vt,outHeight:lr,outWidth:fr}=Ul(s,d,p,g,B,G,O,Ge,Le,pt),er=a?l*w:l,Nr=[0,0,0,0,0];return i==="channelsFirst"?Nr=[u,er,Vt,lr,fr]:i==="channelsLast"&&(Nr=[u,Vt,lr,fr,er]),{batchSize:u,dataFormat:i,inDepth:d,inHeight:p,inWidth:g,inChannels:w,outDepth:Vt,outHeight:lr,outWidth:fr,outChannels:er,padInfo:Dt,strideDepth:B,strideHeight:G,strideWidth:O,filterDepth:M,filterHeight:C,filterWidth:E,effectiveFilterDepth:Ge,effectiveFilterHeight:Le,effectiveFilterWidth:pt,dilationDepth:ae,dilationHeight:Z,dilationWidth:le,inShape:e,outShape:Nr,filterShape:t}},di=(e,t,r,n,s,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],d={x:r.map((B,G)=>G)},p=[Math.ceil(jl(d.x.map(B=>r[B]))/u[0]),1,1];ue("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);let g=1,w=Se.size(r),l=[{type:12,data:w},{type:12,data:n},{type:12,data:s},{type:12,data:t.strides},{type:12,data:t.dilations}];Qn(t,l),l.push(...Ct(e[0].dims,e[1].dims));let M=["rank","rank"],C=e.length===3;C&&(l.push(...Ct(e[2].dims)),M.push("rank")),l.push(...Ct(r));let E=B=>{let G=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:s.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Yn(t,G);let O=1,ae=yr(e[0].dataType),Z=rt("x",e[0].dataType,e[0].dims.length,g),le=rt("W",e[1].dataType,e[1].dims.length,O),Ge=[Z,le],Le=Ut("result",e[0].dataType,r.length,O),pt="";if(C){let lr=rt("bias",e[2].dataType,e[2].dims.length,O);Ge.push(lr),pt+=` + fn getBiasByOutputCoords(coords : array) -> ${ae} { + return bias[${i?jt("coords",4,5):jt("coords",1,5)}]; + }`}let Dt=fn(g,ae),Vt=jn(t,Dt,ae);return` + ${pt} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Z.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${le.getByIndices("aIndices")}; + } + ${B.registerUniforms(G).declareVariables(...Ge,Le)} + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Le.offsetToIndices("global_idx")}; + let batch = ${jt("coords",0,Z.rank)}; + let d2 = ${i?jt("coords",Z.rank-1,Z.rank):jt("coords",1,Z.rank)}; + let xFRCCorner = vec3(${i?jt("coords",1,Z.rank):jt("coords",2,Z.rank)}, + ${i?jt("coords",2,Z.rank):jt("coords",3,Z.rank)}, + ${i?jt("coords",3,Z.rank):jt("coords",4,Z.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?jt("uniforms.x_shape",1,Z.rank):jt("uniforms.x_shape",2,Z.rank)}; + let xShapeZ = ${i?jt("uniforms.x_shape",2,Z.rank):jt("uniforms.x_shape",3,Z.rank)}; + let xShapeW = ${i?jt("uniforms.x_shape",3,Z.rank):jt("uniforms.x_shape",4,Z.rank)}; + let xShapeU = ${i?jt("uniforms.x_shape",4,Z.rank):jt("uniforms.x_shape",1,Z.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${C?"value = value + getBiasByOutputCoords(coords)":""}; + ${Vt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${g};${C}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:l}),getShaderSource:E}}}),Gl,ql,ci=R(()=>{Xt(),Ht(),or(),Jn(),Gl=(e,t,r,n)=>{let s=e.length>2,a=s?"value += b[output_channel];":"",i=e[0].dims,u=e[1].dims,d=t.format==="NHWC",p=d?r[3]:r[1],g=p/t.group,w=d&&g>=4?mr(p):1,l=Se.size(r)/w,M=[{type:12,data:l},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:g}];Qn(t,M),M.push(...Ct(i,[u[0],u[1],u[2],u[3]/w]));let C=s?["rank","rank","rank"]:["rank","rank"];M.push(...Ct([r[0],r[1],r[2],r[3]/w]));let E=B=>{let G=Ut("output",e[0].dataType,r.length,w),O=yr(G.type.tensor),ae=jn(t,G.type.value,O),Z=rt("x",e[0].dataType,i.length),le=rt("w",e[1].dataType,u.length,w),Ge=[Z,le];s&&Ge.push(rt("b",e[2].dataType,e[2].dims,w));let Le=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Yn(t,Le);let pt=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 = ${Z.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${le.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 = ${Z.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${le.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${B.registerUniforms(Le).declareVariables(...Ge,G)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${G.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${d?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${w} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; + + var value: ${G.type.value} = ${G.type.value}(0); + ${pt} + ${a} + ${ae} + ${G.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${w}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:M}),getShaderSource:E}},ql=(e,t,r,n)=>{let s=e.length>2,a=mr(r[3]),i=mr(r[2]),u=Se.size(r)/a/i,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],g=[r[0],r[1],r[2],r[3]/a],w=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Qn(t,w),w.push(...Ct(d,p,g));let l=(i-1)*t.strides[1]+p[1],M=C=>{let E=Ut("output",e[0].dataType,g.length,a),B=yr(E.type.tensor),G=jn(t,E.type.value,B),O=rt("x",e[0].dataType,d.length,a),ae=rt("w",e[1].dataType,p.length,a),Z=[O,ae];s&&Z.push(rt("b",e[2].dataType,e[2].dims,a));let le=s?"value += b[output_channel];":"",Ge=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Yn(t,Ge),` + ${C.registerUniforms(Ge).declareVariables(...Z,E)} + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${O.type.value}, ${l}>; + var values: array<${E.type.value}, ${i}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${l}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${O.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${O.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) { + let w_val = ${ae.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${le} + ${G} + ${E.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${l};${p[0]};${p[1]}`,inputDependencies:s?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:w}),getShaderSource:M}}}),Ma,Hl,Kl,Xl=R(()=>{Xt(),Ht(),ui(),or(),Jn(),Ma=(e,t,r,n,s=!1,a)=>{let i=e[0].dims,u=e[1].dims,d=i[i.length-2],p=u[u.length-1],g=i[i.length-1],w=mr(p),l=mr(g),M=mr(d),C=Se.size(r)/w/M,E=e.length>2,B=n?n.slice(0,-2):r.slice(0,-2),G=[Se.size(B),d,p],O=[{type:12,data:C},{type:12,data:d},{type:12,data:p},{type:12,data:g}];Qn(t,O),O.push(...Ct(B,i,u)),E&&O.push(...Ct(e[2].dims)),O.push(...Ct(G));let ae=Z=>{let le=Ti("batch_dims",e[0].dataType,B.length),Ge=rt("a",e[0].dataType,i.length,l),Le=rt("b",e[1].dataType,u.length,w),pt=Ut("output",e[0].dataType,G.length,w),Dt=yr(pt.type.tensor),Vt=jn(t,pt.type.value,Dt),lr=[Ge,Le],fr="";if(E){let Pr=s?w:1;lr.push(rt("bias",e[2].dataType,e[2].dims.length,Pr)),fr=`${s?`value += bias[col / ${Pr}];`:`value += ${pt.type.value}(bias[row + i]);`}`}let er=i.slice(0,-2),Nr=u.slice(0,-2),Hr=Fs(er,B),br=Fs(Nr,B),jr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Yn(t,jr);let Jt=(Pr,Ve)=>{let kt=Pr.rank,tr=Pr.name;if(kt===2)return`var ${tr}_indices = ${Pr.type.indices}(0u, 0u);`;let zr=le.rank,nn=`var ${tr}_indices: ${Pr.type.indices};`;for(let un=kt-2-1,Vs=zr-1;un>=0;un--,Vs--)nn+=` +${tr}_indices[${un}] = ${zr>1?`batch_indices[${Vs}]`:"batch_indices"};`;return Ve.forEach(un=>{nn+=` +${tr}_indices[${un}] = 0;`}),nn+=`${tr}_indices[${kt-2}] = 0u; + ${tr}_indices[${kt-1}] = 0u;`,nn},dr=()=>{let Pr=`var a_data: ${Ge.type.value};`;for(let Ve=0;Ve; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { + ${dr()} + } + for (var i = 0u; i < ${M}u; i++) { + var value = values[i]; + ${fr} + ${Vt} + let cur_indices = ${pt.type.indices}(batch, row + i, col); + let offset = ${pt.indicesToOffset("cur_indices")}; + ${pt.setByOffset(`offset / ${w}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${w};${l};${M};${s}`,inputDependencies:E?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:O}),getShaderSource:ae}},Hl=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.")},Kl=e=>{Hl(e.inputs);let t=wn.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(wa(e.inputs,{activation:""},t))}}),pi,hi,Ql,fi,Yl,va,Jl,Zl,as,Sd=R(()=>{Ht(),Ed(),$d(),ui(),ci(),Jn(),Xl(),is(),pi=(e,t,r,n,s,a)=>{let i=e[0],u=e.slice(a?1:2,a?3:4),d=u.length,p=t[0],g=t.slice(2).map((l,M)=>l+(l-1)*(r[M]-1)),w=u.map((l,M)=>l+n[M]+n[M+d]).map((l,M)=>Math.floor((l-g[M]+s[M])/s[M]));return w.splice(0,0,i),w.splice(a?3:1,0,p),w},hi=[2,3,1,0],Ql=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},fi=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=ni(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],s=e.dilations,a=e.group,i=e.kernel_shape,u=e.pads,d=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,pads:u,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},va=(e,t,r,n)=>{let s=r.format==="NHWC",a=pi(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,s);if(r.group!==1){let Ge=[t[0]];if(s){let Le=e.kernelCustomData.wT??e.compute(Pn(t[1],hi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Le),Ge.push(Le)}else Ge.push(t[1]);t.length===3&&Ge.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&s&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(ql(Ge,r,a,n),{inputs:Ge}):e.compute(Gl(Ge,r,a,n),{inputs:Ge});return}let i=t.length===3,u=t[0].dims[s?1:2],d=t[0].dims[s?2:3],p=t[0].dims[s?3:1],g=t[1].dims[2],w=t[1].dims[3],l=a[s?1:2],M=a[s?2:3],C=a[s?3:1],E=s&&g===u&&w===d&&r.pads[0]===0&&r.pads[1]===0;if(E||g===1&&w===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 Ge=a[0],Le,pt,Dt,Vt=[];if(s){let er=e.kernelCustomData.wT??e.compute(Pn(t[1],hi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=er),E){let Nr=u*d*p;Le=t[0].reshape([1,Ge,Nr]),pt=er.reshape([1,Nr,C]),Dt=[1,Ge,C]}else Le=t[0].reshape([Ge,u*d,p]),pt=er.reshape([1,p,C]),Dt=[Ge,l*M,C];Vt.push(Le),Vt.push(pt)}else Le=t[0].reshape([Ge,p,u*d]),pt=t[1].reshape([1,C,p]),Dt=[Ge,C,l*M],Vt.push(pt),Vt.push(Le);i&&Vt.push(t[2]);let lr=Dt[2],fr=Vt[0].dims[Vt[0].dims.length-1];lr<8&&fr<8?e.compute(Ma(Vt,r,a,Dt,s,n),{inputs:Vt}):e.compute(wa(Vt,r,a,Dt,s,n),{inputs:Vt});return}let B=!0,G=e.kernelCustomData.wT??e.compute(Pn(t[1],hi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=G);let O=[t[0],G];i&&O.push(t[2]);let ae=s?l*M:C,Z=s?C:l*M,le=g*w*p;e.compute(Nl(O,r,a,ae,Z,le,i,B,n),{inputs:O})},Jl=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=fi({...t,pads:s,strides:a,dilations:i,kernelShape:u},n);va(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Zl=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",s=fi(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,i=Wl(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(di(t,s,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},as=(e,t)=>{if(Ql(e.inputs,t),e.inputs[0].dims.length===3)Jl(e,t);else if(e.inputs[0].dims.length===5)Zl(e,e.inputs,t);else{let r=fi(t,e.inputs);va(e,e.inputs,r)}}}),eu,tu,kd=R(()=>{Xt(),m(),or(),Jn(),ii(),Dl(),ui(),eu=(e,t=!1,r,n,s=4)=>{let a=B=>{switch(B){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 ${B} is not supported.`)}},i=e?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,u=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,d=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",p=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",g=e?"row":"col",w=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 = ${w} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${w} / inChannels % uniforms.filter_dims[1]; + let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) { + return ${n}(0.0); + } + if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) { + return ${n}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${w} % inChannels; + ${i} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,M=e?` + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${l} + } + return ${n}(0.0);`:` + let col = colIn * ${s}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${l} + } + return ${n}(0.0);`,C=` + let col = colIn * ${s}; + let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); + let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; + if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { + let rowInner = row % inChannels; + let coord = vec4(coordX, coordY, col, rowInner); + ${a(s)} + } + return ${n}(0.0); + `,E=jn(r,n);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { + ${e?M:C} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { + ${e?C:M} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${u} + ${si(t)} + ${E} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; + } + }`},tu=(e,t,r,n,s,a,i,u)=>{let d=t.format==="NHWC",p=d?e[0].dims[3]:e[0].dims[1],g=r[0],w=d?r[2]:r[3],l=d?r[1]:r[2],M=d?r[3]:r[1],C=d&&p%4===0&&p%3&&M%4===0,E=d?M:w*l,B=d?w*l:M,G=[8,8,1],O=n<=8?[4,1,1]:[4,4,1],ae=[Math.ceil(E/G[0]/O[0]),Math.ceil(B/G[1]/O[1]),Math.ceil(g/G[2]/O[2])];ue("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ae}`);let Z=C?4:1,le=Math.max(G[0]*Z,G[1]),Ge=C?4:1,Le=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],pt=[Le[0]+(t.dilations[0]<=1?0:(Le[0]-1)*(t.dilations[0]-1)),Le[1]+(t.dilations[1]<=1?0:(Le[1]-1)*(t.dilations[1]-1))],Dt=[pt[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),pt[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Vt=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Le},{type:6,data:Dt}];Qn(t,Vt),Vt.push(...Ct(e[0].dims,e[1].dims));let lr=["rank","rank"];i&&(Vt.push(...Ct(e[2].dims)),lr.push("rank")),Vt.push(...Ct(r));let fr=er=>{let Nr=rt("x",e[0].dataType,e[0].dims.length,Ge),Hr=rt("w",e[1].dataType,e[1].dims.length,1),br=Ut("result",e[0].dataType,r.length,Ge),jr=[Nr,Hr],Jt="";if(i){let Ve=rt("bias",e[2].dataType,e[2].dims.length,Ge);jr.push(Ve),Jt+=` + fn getBiasByOutputCoords(coords : vec4) -> ${Ve.type.value} { + return bias[coords.${d?"w":"y"}${C?"/ 4":""}]; + }`}let dr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:Le.length},{name:"pads",type:"i32",length:Dt.length}];Yn(t,dr);let Pr=yr(e[0].dataType,1);if(Pr!=="f16"&&Pr!=="f32")throw new Error(`elemType ${Pr} is not supported.`);return` + ${_a("uniforms.result_strides")} + ${er.registerUniforms(dr).declareVariables(...jr,br)}; + ${Jt} + ${eu(d,i,t,Nr.type.value,Z)} + ${C?ai(O,G,Pr,void 0,!d,le):li(O,G,Pr,void 0,!d,le,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${O};${G};${C}`,inputDependencies:lr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ae[0],y:ae[1],z:ae[2]},programUniforms:Vt}),getShaderSource:fr}}}),ru,Ds,gc=R(()=>{Xt(),m(),Ht(),or(),ru=(e,t,r,n,s,a=!1,i,u,d=!1)=>{let p=d?1:2,g=d?2:3,w=d?3:1,l=a?2:1,M=` + fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${i}>`:i}) { + result[flatIndex] = ${a?`vec4<${i}>`:i}(value); + }`;n&&(M+=` + fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${i}>`:i} { + return bias[coords.${d?"w":"y"}${a?"/ 4":""}]; + }`);let C=a?4:1,E=rt("W",t[1].dataType,t[1].dims.length,C),B=rt("Dy",t[0].dataType,t[0].dims.length,C),G=[B,E];n&&G.push(rt("bias",t[2].dataType,[r[w]].length,C));let O=Ut("result",t[0].dataType,r.length,C),ae=`{ + let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${s?"global_id.y":"workgroup_id.y"} * ${l}; + let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4; + + let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array, ${l}>; + for (var i = 0; i < ${l}; i++) { + dotProd[i] = vec4<${i}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${i}(dyCorner.x) + ${i}(wR)) / ${i}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[1]) || + fract(dyR) > 0.0 || wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { + let dyC = (${i}(dyCorner.y) + ${i}(wC)) / ${i}(uniforms.strides.y); + let dyC2 = (${i}(dyCorner.y) + 1.0 + ${i}(wC)) / ${i}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims[1] - 1 - wC; + if (wCPerm < 0) { + continue; + } + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${i}(uniforms.Dy_shape[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC: u32 = u32(dyC); + let idyC2: u32 = u32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${B.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${B.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${w}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${B.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${B.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${l}; i = i + 1) { + let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${i}>(0.0)`}; + ${O.set("batch","r","c + i","d1","value")}; + } + }`,Z=` + let outputIndices = ${O.offsetToIndices("global_idx")}; + let batch = ${O.indicesGet("outputIndices",0)}; + let d1 = ${O.indicesGet("outputIndices",w)}; + let r = ${O.indicesGet("outputIndices",p)}; + let c = ${O.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 = ${i}(0.0); + for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[${p}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[${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?B.get("batch","idyR","idyC","inputChannel"):B.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${E.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${n?"bias[d1]":`${i}(0.0)`}; + ${O.setByOffset("global_idx","value")}; + `;return` + ${e.registerUniforms(u).declareVariables(...G,O)} + ${M} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${a?ae:Z}}`},Ds=(e,t,r)=>{let n=e.length>2,s=t.outputShape,a=Se.size(s),i=[Math.ceil(a/64),1,1];ue("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let u=t.format==="NHWC",d=["rank","rank"],p=[t.strides[0],t.strides[1]],g=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],w=[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))],M=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],C=!1,E=t.group,B=e[1].dims,G=B[0]/E,O=B[1],ae=[{type:12,data:a},{type:12,data:p},{type:12,data:g},{type:12,data:w},{type:12,data:l},{type:6,data:M},{type:12,data:G},{type:12,data:O},...Ct(e[0].dims,e[1].dims)];n&&(ae.push(...Ct(e[2].dims)),d.push("rank")),ae.push(...Ct(s));let Z=i[1]===1&&i[2]===1,le=Ge=>{let Le=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:p.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:M.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],pt=yr(e[0].dataType);return`${ru(Ge,e,s,n,Z,C,pt,Le,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:r?r(s):s,dataType:e[0].dataType}],programUniforms:ae}),getShaderSource:le}}}),nu,su,iu,xa,au,Ta,ou,lu,Ca,uu,Pd=R(()=>{kd(),gc(),Jn(),is(),nu=(e,t,r,n,s,a)=>(e-1)*t+r+(n-1)*s+1-a,su=(e,t,r,n,s)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[s]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[s]=a)},iu=(e,t,r,n,s,a,i,u,d,p)=>{let g=e.length-2,w=p.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((w,l)=>w*l,1)===0){r.length=0;for(let w=2;ww+l,0)===0){let w=t[0].dims.length-2;d=new Array(w).fill(1)}let p=e.strides.slice();if(p.reduce((w,l)=>w+l,0)===0){let w=t[0].dims.length-2;p=new Array(w).fill(1)}iu(u,r,d,e.autoPad,e.group,s,p,n,i,a);let g=Object.assign({},e);return Object.assign(g,{kernelShape:r,pads:s,outputPadding:i,outputShape:a,dilations:d,strides:p}),g},au=e=>{let t=ni(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],s=e.dilations,a=e.group,i=e.kernelShape,u=e.pads,d=e.strides,p=e.wIsConst(),g=e.outputPadding,w=e.outputShape;return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,outputPadding:g,outputShape:w,pads:u,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Ta=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==s))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,u)=>i+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,u)=>i+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,u)=>i+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,u)=>i+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},ou=[2,3,1,0],lu=(e,t,r)=>{let n=xa(r,t),s=r.format==="NHWC",a=n.outputShape,i=a[s?3:1],u=t[0].dims[s?3:1];if(n.group!==1||i===1&&u===1){e.compute(Ds(t,n));return}let d=a[s?1:2],p=a[s?2:3],g=t[1].dims[2],w=t[1].dims[3],l=s?d*p:i,M=s?i:d*p,C=g*w*u,E=!0,B=e.kernelCustomData.wT??e.compute(Pn(t[1],ou),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=B);let G=[t[0],B],O=t.length===3;O&&(!s&&t[2].dims.length===1?G.push(t[2].reshape([t[2].dims[0],1,1])):G.push(t[2])),e.compute(tu(G,n,a,l,M,C,O,E),{inputs:G})},Ca=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=t.kernelShape;(s.length===0||s[0]===0)&&(s=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],i=[1].concat(i),a=[1].concat(a),s=[1].concat(s);let d=xa({...t,pads:u,strides:i,dilations:a,kernelShape:s},n);e.compute(Ds(n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},uu=(e,t)=>{Ta(e.inputs,t),e.inputs[0].dims.length===3?Ca(e,t):lu(e,e.inputs,t)}}),Ea,du,cu,$a=R(()=>{Xt(),Ht(),Sr(),or(),Ea=(e,t,r,n)=>{let s=Se.size(t),a=t.length,i=rt("input",e,a),u=Ut("output",e,a),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=Se.normalizeAxis(d,a),g=w=>{let l=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,M=jt("uniforms.input_shape","uniforms.axis",a),C=n.reverse?l+(n.exclusive?" + 1":""):"0",E=n.reverse?M:l+(n.exclusive?"":" + 1");return` + ${w.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,u)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${C}; + let last : i32 = ${E}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},{type:12,data:p},...Ct(t,t)]}),getShaderSource:g}},du=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,s=e.inputs[1];e.compute(Ea(n,r,s,t),{inputs:[0]})},cu=e=>{let t=e.exclusive===1,r=e.reverse===1;return ur({exclusive:t,reverse:r})}}),pu,hu,fu,mu,Sa,ka=R(()=>{Xt(),Ht(),Sr(),or(),pu=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.")},hu=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let a=0;a{let r,n,s,a,i,u,d=t.format==="NHWC",p=t.blocksize,g=t.mode==="DCR";d?([r,n,s,a]=e.dims,i=g?[r,n,s,p,p,a/p**2]:[r,n,s,a/p**2,p,p],u=g?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,s,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=g?[r,p,p,a/p**2,n,s]:[r,a/p**2,p,p,n,s],u=g?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let w=e.reshape(i),l=w.dims.length,M=e.dataType,C=rt("a",M,l),E=Ut("output",M,l),B=G=>` + ${G.registerUniform("output_size","u32").declareVariables(C,E)} + + ${hu(u,l,C,E)} + + ${G.mainStart()} + ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${E.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${E.setByOffset("global_idx",C.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:G=>{let O=d?[r,n*p,s*p,a/p**2]:[r,a/p**2,n*p,s*p],ae=Se.size(O),Z=w.dims,le=Se.sortBasedOnPerm(Z,u);return{outputs:[{dims:O,dataType:G[0].dataType}],dispatchGroup:{x:Math.ceil(ae/64)},programUniforms:[{type:12,data:ae},...Ct(Z,le)]}},getShaderSource:B}},mu=(e,t)=>{pu(e.inputs),e.compute(fu(e.inputs[0],t))},Sa=e=>ur({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Pa,Ls,Aa,Ia,_u,gu,Fa,za,wu,Oa,Ad,wc=R(()=>{Xt(),Ht(),Sr(),or(),Pa="[a-zA-Z]|\\.\\.\\.",Ls="("+Pa+")+",Aa="^"+Ls+"$",Ia="("+Ls+",)*"+Ls,_u="^"+Ia+"$",gu=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)}},Fa=class{constructor(e,t){var s;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(_u)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let u=e[i].dims.slice();if(!a.match(RegExp(Aa)))throw new Error("Invalid LHS term");let d=this.processTerm(a,!0,u,i);this.lhs.push(d)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Ls)))throw new Error("Invalid RHS");(s=n.match(RegExp(Pa,"g")))==null||s.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let s=r.length,a=!1,i=[],u=0;if(!e.match(RegExp(Aa))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(Pa,"g")),p=new gu(n);return d==null||d.forEach((g,w)=>{if(g==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let l=s-d.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(u,u+l),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let M=0;Me+"_max",wu=(e,t,r,n)=>{let s=e.map(p=>p.length).map((p,g)=>rt(`input${g}`,t,p)),a=Se.size(n),i=Ut("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(p=>!r.rhs.symbolToIndices.has(p)),d=p=>{let g=[],w="var prod = 1.0;",l="var sum = 0.0;",M="sum += prod;",C=[],E=[],B=[],G=[],O=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((Z,le)=>{var Ge;if(r.rhs.symbolToIndices.has(le)){let Le=(Ge=r.rhs.symbolToIndices.get(le))==null?void 0:Ge[0];Le!==void 0&&r.lhs.forEach((pt,Dt)=>{if(Z.inputIndices.includes(Dt)){let Vt=pt.symbolToIndices.get(le);if(Vt===void 0)throw new Error("Invalid symbol error");Vt.forEach(lr=>{g.push(`${s[Dt].indicesSet(`input${Dt}Indices`,lr,i.indicesGet("outputIndices",Le))}`)})}})}else r.lhs.forEach((Le,pt)=>{if(Z.inputIndices.includes(pt)){let Dt=Le.symbolToIndices.get(le);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(Vt=>{C.push(`${s[pt].indicesSet(`input${pt}Indices`,Vt,`${le}`)}`)}),G.push(`prod *= ${s[pt].getByIndices(`input${pt}Indices`)};`)}}),E.push(`for(var ${le}: u32 = 0; ${le} < uniforms.${za(le)}; ${le}++) {`),B.push("}")});let ae=O?[...g,`let sum = ${s.map((Z,le)=>Z.getByIndices(`input${le}Indices`)).join(" * ")};`]:[...g,l,...E,...C,w,...G,M,...B];return` + ${p.registerUniforms(u.map(Z=>({name:`${za(Z)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,i)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${s.map((Z,le)=>`var input${le}Indices: ${s[le].type.indices};`).join(` +`)} + ${ae.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=u.filter(w=>r.symbolToInfo.has(w)).map(w=>{var l;return{type:12,data:((l=r.symbolToInfo.get(w))==null?void 0:l.dimValue)||0}});p.push({type:12,data:a});let g=e.map((w,l)=>[...Ct(w)]).reduce((w,l)=>w.concat(l),p);return g.push(...Ct(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:g}},getShaderSource:d}},Oa=(e,t)=>{let r=new Fa(e.inputs,t.equation),n=r.outputDims,s=e.inputs.map((a,i)=>a.dims);e.compute(wu(s,e.inputs[0].dataType,r,n))},Ad=e=>{let t=e.equation.replace(/\s+/g,"");return ur({equation:t})}}),Da,mi,yu,bu,La,Id=R(()=>{Xt(),Ht(),or(),Da=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let s=0;se.length>t.length?mi(e,t):mi(t,e),bu=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=yu(t,r),s=e[0].dataType,a=s===9?4:1,i=Math.ceil(Se.size(n)/a),u=p=>{let g=rt("input",s,t.length,a),w=Ut("output",s,n.length,a),l;if(s===9){let M=(C,E,B="")=>` + let outputIndices${E} = ${w.offsetToIndices(`outputOffset + ${E}u`)}; + let offset${E} = ${g.broadcastedIndicesToOffset(`outputIndices${E}`,w)}; + let index${E} = offset${E} / 4u; + let component${E} = offset${E} % 4u; + ${C}[${E}] = ${B}(${g.getByOffset(`index${E}`)}[component${E}]); + `;l=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${M("data",0,"u32")} + ${M("data",1,"u32")} + ${M("data",2,"u32")} + ${M("data",3,"u32")} + ${w.setByOffset("global_idx","data")} + }`}else l=` + let outputIndices = ${w.offsetToIndices("global_idx")}; + let inputOffset = ${g.broadcastedIndicesToOffset("outputIndices",w)}; + ${w.setByOffset("global_idx",g.getByOffset("inputOffset"))} + }`;return` + ${p.registerUniform("vec_size","u32").declareVariables(g,w)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${l}`},d=[{type:12,data:i},...Ct(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d})}},La=e=>{Da(e.inputs),e.compute(bu(e.inputs),{inputs:[0]})}}),Mu,Ba,Fd=R(()=>{Xt(),Ht(),or(),ti(),Mu=e=>{let t=e[0].dataType,r=Se.size(e[0].dims),n=Se.size(e[1].dims),s=n%4===0,a=i=>{let u=rt("x",t,[1],4),d=rt("bias",t,[1],4),p=Ut("y",t,[1],4),g=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],w=M=>` + let bias${M}_offset: u32 = (global_idx * 4 + ${M}) % uniforms.bias_size; + let bias${M} = ${d.getByOffset(`bias${M}_offset / 4`)}[bias${M}_offset % 4];`,l=s?` + let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${w(0)}${w(1)}${w(2)}${w(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(g).declareVariables(u,d,p)} + + ${la(Ar(t))} + + ${i.mainStart(en)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${l} + let x_in = x + bias; + ${p.setByOffset("global_idx",ua("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/en/4)}})}},Ba=e=>{e.inputs.length<2||Se.size(e.inputs[1].dims)===0?da(e):e.compute(Mu(e.inputs))}}),vu,Ra,xu,Tu,zd=R(()=>{Xt(),Ht(),Sr(),or(),vu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ra=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Se.normalizeAxis(t.axis,s),i=r.slice(0);i.splice(a,1,...n);let u=r[a],d=e[0].dataType===9?4:1,p=Math.ceil(Se.size(i)/d),g=[{type:12,data:p},{type:6,data:u},{type:12,data:a},...Ct(e[0].dims,e[1].dims,i)],w=l=>{let M=rt("data",e[0].dataType,e[0].dims.length,d),C=rt("inputIndices",e[1].dataType,e[1].dims.length),E=Ut("output",e[0].dataType,i.length,d),B=O=>{let ae=n.length,Z=`var indicesIndices${O} = ${C.type.indices}(0);`;for(let le=0;le1?`indicesIndices${O}[${le}]`:`indicesIndices${O}`} = ${i.length>1?`outputIndices${O}[uniforms.axis + ${le}]`:`outputIndices${O}`};`;Z+=` + var idx${O} = ${C.getByIndices(`indicesIndices${O}`)}; + if (idx${O} < 0) { + idx${O} = idx${O} + uniforms.axisDimLimit; + } + var dataIndices${O} : ${M.type.indices}; + `;for(let le=0,Ge=0;le1?`dataIndices${O}[${le}]`:`dataIndices${O}`} = u32(idx${O});`,Ge+=ae):(Z+=`${s>1?`dataIndices${O}[${le}]`:`dataIndices${O}`} = ${i.length>1?`outputIndices${O}[${Ge}]`:`outputIndices${O}`};`,Ge++);return Z},G;if(e[0].dataType===9){let O=(ae,Z,le="")=>` + let outputIndices${Z} = ${E.offsetToIndices(`outputOffset + ${Z}u`)}; + ${B(Z)}; + let offset${Z} = ${M.indicesToOffset(`dataIndices${Z}`)}; + let index${Z} = offset${Z} / 4u; + let component${Z} = offset${Z} % 4u; + ${ae}[${Z}] = ${le}(${M.getByOffset(`index${Z}`)}[component${Z}]); + `;G=` + let outputOffset = global_idx * ${d}; + var value = vec4(0); + ${O("value",0,"u32")} + ${O("value",1,"u32")} + ${O("value",2,"u32")} + ${O("value",3,"u32")} + ${E.setByOffset("global_idx","value")} + `}else G=` + let outputIndices = ${E.offsetToIndices("global_idx")}; + ${B("")}; + let value = ${M.getByIndices("dataIndices")}; + ${E.setByOffset("global_idx","value")}; + `;return` + ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(M,C,E)} + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${G} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:g}),getShaderSource:w}},xu=e=>ur({axis:e.axis}),Tu=(e,t)=>{let r=e.inputs;vu(r),e.compute(Ra(e.inputs,t))}}),Cu,Ir,Od,Dd,yc=R(()=>{Xt(),Ht(),Sr(),or(),Cu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=Se.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,s=e[0],a=e[2],i=e.length===4?e[3]:void 0;if(a.dims.length!==s.dims.length||!s.dims.map((u,d)=>d===r?Math.ceil(u/n)===a.dims[d]:u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==s.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==a.dims.length||!i.dims.map((u,d)=>u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Ir=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Se.normalizeAxis(t.gatherAxis,s),i=Se.normalizeAxis(t.quantizeAxis,s),u=r.slice(0);u.splice(a,1,...n);let d=Se.size(u),p=e[2].dataType,g=e[0].dataType===22,w=[{type:12,data:d},{type:12,data:i},{type:12,data:a},{type:12,data:t.blockSize},...Ct(...e.map((M,C)=>M.dims),u)],l=M=>{let C=rt("data",e[0].dataType,e[0].dims.length),E=rt("inputIndices",e[1].dataType,e[1].dims.length),B=rt("scales",e[2].dataType,e[2].dims.length),G=e.length>3?rt("zeroPoint",e[3].dataType,e[3].dims.length):void 0,O=Ut("output",p,u.length),ae=[C,E,B];G&&ae.push(G);let Z=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${M.registerUniforms(Z).declareVariables(...ae,O)} + ${M.mainStart()} + let output_indices = ${O.offsetToIndices("global_idx")}; + var indices_indices = ${E.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${O.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${E.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${O.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${C.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${O.indicesGet("output_indices","i")}; + ${C.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${E.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${r[a]}; + } + ${C.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { + let index = ${O.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${C.indicesSet("data_indices","i","index")}; + } + let data_offset = ${C.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${C.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 = ${B.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${B.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${B.getByIndices("scale_indices")}; + ${G?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${G.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${G.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${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 = ${Ar(p)}(quantized_data - zero_point) * scale; + ${O.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((M,C)=>C!==1).map(M=>M.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(M,C)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:p}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:w}),getShaderSource:l}},Od=(e,t)=>{let r=e.inputs;Cu(r,t),e.compute(Ir(e.inputs,t))},Dd=e=>ur({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Na,Eu,$u,Su,Ld=R(()=>{Xt(),Ht(),Sr(),or(),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.`)},Eu=(e,t)=>{let r=e[0].dims,n=e[0].dataType,s=r.length,a=e[1].dims,i=e[1].dataType,u=Se.normalizeAxis(t.axis,s),d=r[u],p=a.slice(0),g=Se.size(p),w=rt("input",n,s),l=rt("indicesInput",i,a.length),M=Ut("output",n,p.length),C=[{type:12,data:g},{type:6,data:d},{type:12,data:u}];return C.push(...Ct(r,a,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:C}),getShaderSource:E=>` + ${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(w,l,M)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${M.offsetToIndices("global_idx")}; + + var idx = ${l.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${w.type.indices}(outputIndices); + ${w.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${w.getByIndices("inputIndices")}; + + ${M.setByOffset("global_idx","value")}; + }`}},$u=e=>ur({axis:e.axis}),Su=(e,t)=>{let r=e.inputs;Na(r),e.compute(Eu(e.inputs,t))}}),ja,Va,ku,Pu,Au=R(()=>{Xt(),Ht(),or(),ja=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")},Va=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[s,a,i]=xn.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[s,a];if(!u)throw new Error("Can't use gemm on the given tensors");let d=Se.size(u),p=[{type:12,data:d},{type:12,data:s},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],g=["type","type"];e.length===3&&(p.push(...Ct(e[2].dims)),g.push("rank")),p.push(...Ct(u));let w=l=>{let M="";t.transA&&t.transB?M="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?M="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?M="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(M="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let C=t.alpha===1?"":"value *= uniforms.alpha;",E=rt("a",e[0].dataType,e[0].dims),B=rt("b",e[1].dataType,e[1].dims),G=E.type.value,O=null,ae=[E,B];e.length===3&&(O=rt("c",e[2].dataType,e[2].dims.length),ae.push(O));let Z=Ut("output",e[0].dataType,u.length);ae.push(Z);let le=[{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(le).declareVariables(...ae)} + + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${G}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${M} + } + + ${C} + ${O!=null?`let cOffset = ${O.broadcastedIndicesToOffset("vec2(m, n)",Z)}; value += ${G}(uniforms.beta) * ${O.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:p}),getShaderSource:w}},ku=e=>{let t=e.transA,r=e.transB,n=e.alpha,s=e.beta;return{transA:t,transB:r,alpha:n,beta:s,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Pu=(e,t)=>{ja(e.inputs),e.compute(Va(e.inputs,t))}}),yn,Bd,Iu,Ua,Fu,Bs,zu,Ou=R(()=>{Xt(),Ht(),Sr(),se(),Ki(),or(),is(),yn=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Bd=(e,t)=>{let r=e[0],n=yn(e,1),s=yn(e,2),a=yn(e,3),i=yn(e,4),u=yn(e,5),d=yn(e,6),p=yn(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],w=r.dims[1],l=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],M=w,C=0,E=0,B=Math.floor(l/t.numHeads);if(d&&p&&Se.size(d.dims)&&Se.size(p.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]!==B)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==g||p.dims[1]!==t.numHeads||p.dims[3]!==B)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');C=d.dims[2],E=d.dims[2]}else if(d&&Se.size(d.dims)||p&&Se.size(p.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let G;if(n&&Se.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');G=2,M=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==B)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');G=5,M=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==B)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');G=0,M=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');G=3}if(a&&Se.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 O=C+M,ae=0;if(i&&Se.size(i.dims)>0){ae=8;let Le=i.dims;throw Le.length===1?Le[0]===g?ae=1:Le[0]===3*g+2&&(ae=3):Le.length===2&&Le[0]===g&&Le[1]===O&&(ae=5),ae===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let Z=!1,le=l;if(s&&Se.size(s.dims)>0){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(M!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');le=s.dims[2]}else{if(M!==s.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');le=s.dims[1]*s.dims[3],Z=!0}}let Ge=!1;if(i&&Se.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(u&&Se.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]!==w||u.dims[3]!==O)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:g,sequenceLength:w,pastSequenceLength:C,kvSequenceLength:M,totalSequenceLength:O,maxSequenceLength:E,inputHiddenSize:0,hiddenSize:l,vHiddenSize:le,headSize:B,vHeadSize:Math.floor(le/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ae,scale:t.scale,broadcastResPosBias:Ge,passPastInKv:Z,qkvFormat:G}},Iu=e=>ur({...e}),Ua=ur({perm:[0,2,1,3]}),Fu=(e,t,r,n,s,a,i)=>{let u=[n,s,a],d=Se.size(u),p=[{type:12,data:d},{type:12,data:i},{type:12,data:a}],g=w=>{let l=Ut("qkv_with_bias",t.dataType,u),M=rt("qkv",t.dataType,u),C=rt("bias",r.dataType,u),E=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${w.registerUniforms(E).declareVariables(M,C,l)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:g},{inputs:[t,r],outputs:[-1]})[0]},Bs=(e,t,r,n,s,a,i,u)=>{let d=a;if(i&&Se.size(i.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Fu(e,a,i,t,n,r*s,u),d=d.reshape([t,n,r,s]),e.compute(Pn(d,Ua.perm),{inputs:[d],outputs:[-1]})[0]}else return a.dims.length===3&&(d=a.reshape([t,n,r,s])),e.compute(Pn(d,Ua.perm),{inputs:[d],outputs:[-1]})[0]},zu=(e,t)=>{let r=Bd(e.inputs,t),n=e.inputs[0],s=yn(e.inputs,1),a=yn(e.inputs,2),i=yn(e.inputs,3),u=yn(e.inputs,4),d=yn(e.inputs,5),p=yn(e.inputs,6),g=yn(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((s==null?void 0:s.dims.length)===5)throw new Error("Packed KV is not implemented");let w=s&&a&&s.dims.length===4&&a.dims.length===4,l=Bs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(w)return Os(e,l,s,a,u,void 0,p,g,d,r,t);if(!s||!a)throw new Error("key and value must be provided");let M=Bs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,s,i,r.hiddenSize),C=Bs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,i,2*r.hiddenSize);Os(e,l,M,C,u,void 0,p,g,d,r,t)}}),Wa,Du,Lu,Ga,Bu,Ru=R(()=>{Xt(),Ht(),or(),Wa=e=>Array.from(e.getBigInt64Array(),Number),Du=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(Wa(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")},Lu=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Wa(e[1]),s=Lu(r,n),a=Se.size(s),i=e[0].dataType,u=rt("input",i,r.length),d=Ut("output",i,s.length),p=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:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...Ct(e[0].dims,s)]}),getShaderSource:p}},Bu=e=>{Du(e.inputs),e.compute(Ga(e.inputs),{inputs:[0]})}}),Nu,qa,ju,Vu,Ha,Rd,Uu=R(()=>{Xt(),Ht(),Sr(),Ki(),or(),Ou(),Ru(),is(),Nu=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,d=r.dims[0],p=r.dims[1],g=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],w=p,l=0,M=0,C=Math.floor(g/t.numHeads),E=a&&a.dims.length!==0,B=i&&i.dims.length!==0,G=!0;if(E&&B){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=a.dims[1],M=a.dims[1]}else if(E||B)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let O;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');O=2,w=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==C)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');O=5,w=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==C)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');O=0,w=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');O=3}let ae=0,Z=!1,le=g;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(w!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');le=s.dims[2]}else{if(w!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');le=s.dims[1]*s.dims[3],Z=!0}}let Ge=l+w;return{batchSize:d,sequenceLength:p,pastSequenceLength:l,kvSequenceLength:w,totalSequenceLength:Ge,maxSequenceLength:M,inputHiddenSize:0,hiddenSize:g,vHiddenSize:le,headSize:C,vHeadSize:Math.floor(le/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:ae,scale:t.scale,broadcastResPosBias:!1,passPastInKv:Z,qkvFormat:O,isPastkvBSNH:G}},qa=(e,t,r,n)=>{let s=[n.batchSize,n.totalSequenceLength,n.kvNumHeads,n.headSize],a=4,i=Se.size(s)/a,u=n.totalSequenceLength,d=Ut("present_kv",r,s.length,a),p=rt("new_kv",e.dataType,e.dims.length,a),g=t?rt("past_kv",t.dataType,t.dims.length,a):void 0,w=Math.ceil(n.headSize/a),l={x:u,y:e.dims[0],z:1},M=t?["rank","rank"]:["rank"],C=[{type:12,data:i},{type:12,data:n.pastSequenceLength},{type:12,data:n.kvSequenceLength},{type:12,data:n.totalSequenceLength}],E=[p];g?(C.push(...Ct(e.dims),...Ct(t.dims),...Ct(s)),E.push(g)):C.push(...Ct(e.dims),...Ct(s));let B=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],G=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; + var past_head_stride = uniforms.past_seqlen * H; + if (is_bsnh) { + past_head_stride = H; + } + let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; + present_kv[out_offset] = past_kv[in_offset];`,O=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; + let new_row_stride = num_heads * H; + let new_head_stride = H; + let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; + present_kv[out_offset] = new_kv[in_offset];`,ae=t?`if (s < past_seqlen) { + ${G} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${O} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${O} + }`,Z=le=>` + + ${le.registerUniforms(B).declareVariables(...E,d)} + ${le.mainStart([w,n.kvNumHeads,1])} + ${le.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${d.offsetToIndices("global_idx")}; + let h = local_id.x; + let n = local_id.y; + let s = workgroup_id.x; + let b = workgroup_id.y; + let num_heads = ${n.kvNumHeads}u; + let H = ${w}u; + + let present_seqlen = uniforms.present_seqlen; + let present_batch_stride = present_seqlen * num_heads * H; + var row_stride = H; + let is_bsnh = ${n.isPastkvBSNH}; + + if (is_bsnh) { + row_stride = num_heads * H; + } + var present_head_stride = present_seqlen * H; + if (is_bsnh) { + present_head_stride = H; + } + + let past_seqlen = uniforms.past_seqlen; + + let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; + ${ae} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${n.kvNumHeads}${w}${!!t}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:l,programUniforms:C}),getShaderSource:Z}},ju=e=>ur({...e}),Vu=ur({perm:[0,2,1,3]}),Ha=(e,t,r,n,s)=>{let a=t,i=n.kvNumHeads,u=n.nReps;return t.dims.length===3&&n.kvSequenceLength!==0&&(a=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize])),r?a=e.compute(qa(a,r,a.dataType,n),{inputs:[a,r],outputs:[n.isPastkvBSNH?s:-1]})[0]:a=e.compute(qa(a,void 0,a.dataType,n),{inputs:[a],outputs:[n.isPastkvBSNH?s:-1]})[0],u!==1&&(a=e.compute(Ga([a],[1,1,1,u]),{inputs:[a],outputs:[-1]})[0],a=a.reshape([n.batchSize,n.totalSequenceLength,i*u,n.headSize])),e.compute(Pn(a,Vu.perm),{inputs:[a],outputs:[-1]})[0]},Rd=(e,t)=>{var d;let r=Nu(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=Bs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],void 0,0),s=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,i=Ha(e,e.inputs[1],s,r,1),u=Ha(e,e.inputs[2],a,r,2);Os(e,n,i,u,void 0,void 0,void 0,void 0,void 0,r,t)}}),Ka,Wu,Gu,qu,Nd=R(()=>{Xt(),Ht(),is(),or(),Ka=(e,t,r,n,s,a,i,u)=>{let d=mr(a),p=d===1?"f32":`vec${d}f`,g=d===1?"vec2f":`mat2x${d}f`,w=s*i,l=[s,i,a/d],M=[s,i,2],C=["rank","type","type"],E=[];E.push(...Ct(l,M));let B=G=>{let O=rt("x",t.dataType,3,d),ae=rt("scale",r.dataType,r.dims),Z=rt("bias",n.dataType,n.dims),le=Ut("output",1,3,2),Ge=[O,ae,Z,le],Le=64;return` + var workgroup_shared : array<${g}, ${Le}>; + const workgroup_size = ${Le}u; + ${G.declareVariables(...Ge)} + ${G.mainStart(Le)} + 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 = ${p}(0); + var squared_sum = ${p}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${p}(${O.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 = ${Xn("workgroup_shared[0][0]",d)} / f32(hight * ${d}); + let squared_sum_final = ${Xn("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:C},getRunData:()=>({outputs:[{dims:M,dataType:1}],dispatchGroup:{x:w},programUniforms:E}),getShaderSource:B},{inputs:[t,r,n],outputs:[-1]})[0]},Wu=(e,t,r)=>{let n=t[0].dims,s=n,a=2,i=n[0],u=n[1],d=Se.sizeFromDimension(n,a),p=mr(d),g=Se.size(s)/p,w=Ka(e,t[0],t[1],t[2],i,d,u,r.epsilon),l=[i,u,d/p],M=[i,u],C=["type","none"],E=B=>{let G=rt("x",t[0].dataType,l.length,p),O=rt("scale_shift",1,M.length,2),ae=Ut("output",t[0].dataType,l.length,p),Z=[G,O,ae];return` + ${B.registerUniform("output_size","u32").declareVariables(...Z)} + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${ae.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${O.getByIndices("vec2(batch, channel)")}; + let value = ${G.getByOffset("global_idx")} * ${ae.type.value}(scale_shift.x) + ${ae.type.value}(scale_shift.y); + ${ae.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${p}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...Ct(l,M,l)]}),getShaderSource:E},{inputs:[t[0],w]})},Gu=(e,t,r)=>{let n=t[0].dims,s=n,a=n[0],i=n[n.length-1],u=Se.sizeFromDimension(n,1)/i,d=mr(i),p=Se.size(s)/d,g=[{type:12,data:u},{type:12,data:Math.floor(i/d)}],w=["type","type"],l=[0,n.length-1];for(let B=0;B{let G=yr(t[0].dataType),O=d===1?"vec2f":`mat${d}x2f`,ae=Ge=>{let Le=Ge===0?"x":"y",pt=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${G}(${pt}(scale.${Le}))`;case 2:return`vec2<${G}>(${pt}(scale[0].${Le}, scale[1].${Le}))`;case 4:return`vec4<${G}>(${pt}(scale[0].${Le}, scale[1].${Le}, scale[2].${Le}, scale[3].${Le}))`;default:throw new Error(`Not supported compoents ${d}`)}},Z=rt("input",t[0].dataType,t[0].dims,d),le=Ut("output",t[0].dataType,s,d);return` + @group(0) @binding(0) var input : array<${Z.type.storage}>; + @group(0) @binding(1) var scale_input : array<${O}>; + @group(0) @binding(2) var output : array<${le.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${B.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], ${ae(0)}, ${ae(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:g}),getShaderSource:E},{inputs:[t[0],C]})},qu=(e,t)=>{t.format==="NHWC"?Gu(e,e.inputs,t):Wu(e,e.inputs,t)}}),Hu,Ku,Xu,jd=R(()=>{Xt(),Ht(),or(),Hu=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Ku=(e,t,r)=>{let n=t.simplified,s=e[0].dims,a=e[1],i=!n&&e[2],u=s,d=Se.normalizeAxis(t.axis,s.length),p=Se.sizeToDimension(s,d),g=Se.sizeFromDimension(s,d),w=Se.size(a.dims),l=i?Se.size(i.dims):0;if(w!==g||i&&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 ${w} and bias size of ${l}`);let M=[];for(let le=0;le1,O=r>2,ae=le=>{let Ge=yr(e[0].dataType),Le=[rt("x",e[0].dataType,e[0].dims,C),rt("scale",a.dataType,a.dims,C)];i&&Le.push(rt("bias",i.dataType,i.dims,C)),Le.push(Ut("output",e[0].dataType,u,C)),G&&Le.push(Ut("mean_data_output",1,M)),O&&Le.push(Ut("inv_std_output",1,M));let pt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${le.registerUniforms(pt).declareVariables(...Le)} + ${le.mainStart()} + ${le.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Hn("f32",C)}; + var mean_square_vector = ${Hn("f32",C)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Kn(Ge,C,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Xn("mean_vector",C)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Xn("mean_square_vector",C)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Kn(Ge,C,"x[j + offset]")}; + let f32scale = ${Kn(Ge,C,"scale[j]")}; + output[j + offset] = ${Le[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Kn(Ge,C,"bias[j]")}`:""} + ); + } + + ${G?"mean_data_output[global_idx] = mean":""}; + ${O?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},Z=[{dims:u,dataType:e[0].dataType}];return G&&Z.push({dims:M,dataType:1}),O&&Z.push({dims:M,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${C};${r};${n}`,inputDependencies:E},getRunData:()=>({outputs:Z,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:B}),getShaderSource:ae}},Xu=(e,t)=>{Hu(e.inputs),e.compute(Ku(e.inputs,t,e.outputCount))}}),Qu,Yu,Ju,Zu,Vd=R(()=>{Xt(),Ht(),Sr(),or(),Qu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let s=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!Se.areEqual(i.dims,[t.n,s,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(Se.size(u)!==t.n*s)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,p=t.bits>4?t.n*s:t.n*Math.floor((s+1)/2);if(Se.size(d)!==p)throw new Error("zeroPoints input size error.")}},Yu=(e,t)=>{let r=e[0].dims,n=r.length,s=r[n-2],a=t.k,i=t.n,u=r.slice(0,n-2),d=Se.size(u),p=e[1].dims[2]/4,g=e[0].dataType,w=mr(t.k),l=mr(p),M=mr(i),C=u.concat([s,i]),E=s>1&&i/M%2===0?2:1,B=Se.size(C)/M/E,G=64,O=[],ae=[d,s,a/w],Z=Se.convertShape(e[1].dims).slice();Z.splice(-1,1,p/l),O.push(...Ct(ae)),O.push(...Ct(Z)),O.push(...Ct(e[2].dims)),e.length===4&&O.push(...Ct(Se.convertShape(e[3].dims)));let le=[d,s,i/M];O.push(...Ct(le));let Ge=Le=>{let pt=ae.length,Dt=rt("a",e[0].dataType,pt,w),Vt=rt("b",12,Z.length,l),lr=rt("scales",e[2].dataType,e[2].dims.length),fr=[Dt,Vt,lr],er=e.length===4?rt("zero_points",12,e[3].dims.length):void 0;er&&fr.push(er);let Nr=le.length,Hr=Ut("output",e[0].dataType,Nr,M),br=yr(e[0].dataType),jr=(()=>{switch(w){case 1:return`array<${br}, 8>`;case 2:return`mat4x2<${br}>`;case 4:return`mat2x4<${br}>`;default:throw new Error(`${w}-component is not supported.`)}})(),Jt=()=>{let Ve=` + // reuse a data + var input_offset = ${Dt.indicesToOffset(`${Dt.type.indices}(batch, row, word_offset)`)}; + var a_data: ${jr}; + for (var j: u32 = 0; j < ${8/w}; j++) { + a_data[j] = ${Dt.getByOffset("input_offset")}; + input_offset++; + } + `;for(let kt=0;kt> 4) & b_mask); + b_quantized_values = ${jr}(${Array.from({length:4},(tr,zr)=>`${br}(b_value_lower[${zr}]), ${br}(b_value_upper[${zr}])`).join(", ")}); + b_dequantized_values = ${w===1?`${jr}(${Array.from({length:8},(tr,zr)=>`(b_quantized_values[${zr}] - ${er?`zero_point${kt}`:"zero_point"}) * scale${kt}`).join(", ")});`:`(b_quantized_values - ${jr}(${Array(8).fill(`${er?`zero_point${kt}`:"zero_point"}`).join(",")})) * scale${kt};`}; + workgroup_shared[local_id.x * ${E} + ${Math.floor(kt/M)}]${M>1?`[${kt%M}]`:""} += ${Array.from({length:8/w},(tr,zr)=>`${w===1?`a_data[${zr}] * b_dequantized_values[${zr}]`:`dot(a_data[${zr}], b_dequantized_values[${zr}])`}`).join(" + ")}; + `;return Ve},dr=()=>{let Ve=` + var col_index = col * ${M}; + ${er?` + 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 = ${br}(8);`} + `;for(let kt=0;kt> 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 = ${er.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${kt} = ${br}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return Ve},Pr=()=>{let Ve=`col_index = col * ${M};`;for(let kt=0;kt; + var b_value_upper: vec4; + var b_quantized_values: ${jr}; + var b_dequantized_values: ${jr};`,Ve};return` + var workgroup_shared: array<${Hr.type.value}, ${E*G}>; + ${Le.declareVariables(...fr,Hr)} + ${Le.mainStart([G,1,1])} + let output_indices = ${Hr.offsetToIndices(`(global_idx / ${G}) * ${E}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${G}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/w}; + ${dr()} + for (var word: u32 = 0; word < ${p}; word += ${l}) { + ${Pr()} + for (var i: u32 = 0; i < ${l}; i++) { + ${Jt()} + word_offset += ${8/w}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${E}) { + var output_value: ${Hr.type.value} = ${Hr.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${G}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${E}; + } + ${Hr.setByIndices(`${Hr.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${w};${l};${M};${E};${G}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:C,dataType:g}],dispatchGroup:{x:B},programUniforms:O}),getShaderSource:Ge}},Ju=(e,t)=>{Qu(e.inputs,t),e.compute(Yu(e.inputs,t))},Zu=e=>ur(e)}),ed,td,rd,nd,sd,id,ad,od,ld,Ud=R(()=>{Xt(),Ht(),or(),ed=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},td=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; + if (k < 0) { + break; + } + if (k >= i32(${jt("uniforms.x_shape",s,t)})) { + break; + } + offset += k * i32(${jt("uniforms.x_strides",s,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},rd=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${jt("uniforms.x_shape",s,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${jt("uniforms.x_shape",s,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${jt("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},nd=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${jt("uniforms.x_shape",s,t)})) { + k = i32(${jt("uniforms.x_shape",s,t)}) - 1; + } + offset += k * i32(${jt("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},sd=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; + if (k < 0) { + k += i32(${jt("uniforms.x_shape",s,t)}]); + } + if (k >= i32(${jt("uniforms.x_shape",s,t)})) { + k -= i32(${jt("uniforms.x_shape",s,t)}); + } + offset += k * i32(${jt("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},id=(e,t,r)=>{switch(r.mode){case 0:return td(e,t,r.pads.length);case 1:return rd(e,t,r.pads.length);case 2:return nd(e,t,r.pads.length);case 3:return sd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},ad=(e,t)=>{let r=Se.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,s=Se.size(r),a=[{type:12,data:s},{type:6,data:t.pads}],i=e.length>=3&&e[2].data;t.mode===0&&a.push({type:i?e[2].dataType:1,data:t.value}),a.push(...Ct(e[0].dims,r));let u=["rank"],d=p=>{let g=Ut("output",e[0].dataType,r.length),w=rt("x",e[0].dataType,n.length),l=w.type.value,M=id(g,n.length,t),C=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&C.push({name:"constant_value",type:i?l:"f32"}),` + ${p.registerUniforms(C).declareVariables(w,g)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${g.offsetToIndices("global_idx")}; + + var value = ${l}(0); + ${M} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${i}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(r)/64)},programUniforms:a}),getShaderSource:d}},od=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,s=e[0].dims.length,a=new Int32Array(2*s).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;da[Number(d)]=Number(u));let i=[];return a.forEach(u=>i.push(u)),{mode:t.mode,value:n,pads:i}}else return t},ld=(e,t)=>{ed(e.inputs);let r=od(e.inputs,t);e.compute(ad(e.inputs,r),{inputs:[0]})}}),Rs,Xa,Qa,ud,ir,dd,sn,an,cn,os,Wd,Ya,cd,f,_,T,J,Fe,Oe,_t=R(()=>{Pt(),Xt(),Ht(),or(),Rs=e=>{if(k.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Xa=(e,t,r)=>{let n=t.format==="NHWC",s=e.dims.slice();n&&s.splice(1,0,s.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),u=t.strides.slice(),d=a?t.dilations.slice():[],p=t.pads.slice();Zr.adjustPoolAttributes(r,s,i,u,d,p);let g=Zr.computePoolOutputShape(r,s,u,d,i,p,t.autoPad),w=Object.assign({},t);a?Object.assign(w,{kernelShape:i,strides:u,pads:p,dilations:d,cacheKey:t.cacheKey}):Object.assign(w,{kernelShape:i,strides:u,pads:p,cacheKey:t.cacheKey});let l=g.slice();return l.push(l.splice(1,1)[0]),[w,n?l:g]},Qa=(e,t)=>{let r=t.format==="NHWC",n=Se.size(e),s=Se.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:s}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],g=t.pads[t.pads.length-1],w=!!(p+g);a.push({type:12,data:u},{type:12,data:d},{type:12,data:p},{type:12,data:g}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(t.kernelShape.length===2){let M=t.kernelShape[t.kernelShape.length-2],C=t.strides[t.strides.length-2],E=t.pads[t.pads.length/2-2],B=t.pads[t.pads.length-2];l=!!(E+B),a.push({type:12,data:M},{type:12,data:C},{type:12,data:E},{type:12,data:B}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,w,l]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=Se.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((p,g)=>p+g);return[a,i,!!d,!1,!1]}},ud=(e,t,r,n,s,a,i,u,d,p,g,w)=>{let l=s.format==="NHWC",M=t.type.value,C=Ut("output",t.type.tensor,n);if(s.kernelShape.length<=2){let E="",B="",G="",O=r-(l?2:1);if(g?E=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${O}] = indices[${O}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${O}] < 0 || xIndices[${O}] + >= uniforms.x_shape[${O}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:E=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${O}] = indices[${O}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`,s.kernelShape.length===2){let ae=r-(l?3:2);w?B=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ae}] = indices[${ae}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${ae}] < 0 || xIndices[${ae}] >= uniforms.x_shape[${ae}]) { + pad += i32(uniforms.kw); + continue; + } + `:B=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ae}] = indices[${ae}] * uniforms.sh - uniforms.phStart + j; + `,G=` + } + `}return` + ${e.registerUniforms(d).declareVariables(t,C)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${C.offsetToIndices("global_idx")}; + var xIndices = ${C.offsetToIndices("global_idx")}; + + var value = ${M}(${u}); + var pad = 0; + ${B} + ${E} + ${G} + ${i} + + output[global_idx] = value; + }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let E=s.kernelShape.length,B=s.pads.length,G="";return p?G=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:G=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + `,` + ${e.registerUniforms(d).declareVariables(t,C)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${C.offsetToIndices("global_idx")}; + var xIndices = ${C.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${M}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${E-1}u; j++) { + offsets[j] = offset / ${jt("uniforms.kernelStrides","j",E)}; + offset -= offsets[j] * ${jt("uniforms.kernelStrides","j",E)}; + } + offsets[${E-1}] = offset; + + isPad = false; + for (var j = ${r-E}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${jt("uniforms.strides",`j - ${r-E}u`,E)} + + offsets[j - ${r-E}u] - ${jt("uniforms.pads","j - 2u",B)}; + ${G} + } + ${i} + + output[global_idx] = value; + }`}},ir=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,dd=e=>`${ir(e)};${e.countIncludePad}`,sn=e=>`${ir(e)};${e.storageOrder};${e.dilations}`,an=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}),cn=(e,t,r,n)=>{let[s,a]=Xa(t,n,r),i=rt("x",t.dataType,t.dims.length),u=i.type.value,d="value += x_val;",p="";s.countIncludePad?p+=`value /= ${u}(uniforms.kernelSize);`:p+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[g,w,l,M,C]=Qa(a,s);g.push(...Ct(t.dims,a));let E=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${l};${M};${C}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:g}),getShaderSource:B=>ud(B,i,t.dims.length,a.length,s,d,p,0,w,l,M,C)}},os=e=>{let t=e.count_include_pad!==0,r=an(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:dd(n)}},Wd=(e,t)=>{Rs(e.inputs),e.compute(cn("AveragePool",e.inputs[0],!1,t))},Ya={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},cd=e=>{let t=e.format;return{format:t,...Ya,cacheKey:t}},f=(e,t)=>{Rs(e.inputs),e.compute(cn("GlobalAveragePool",e.inputs[0],!0,t))},_=(e,t,r,n)=>{let[s,a]=Xa(t,n,r),i=` + value = max(x_val, value); + `,u="",d=rt("x",t.dataType,t.dims.length),p=["rank"],[g,w,l,M,C]=Qa(a,s);return g.push(...Ct(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${l};${M};${C}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:g}),getShaderSource:E=>ud(E,d,t.dims.length,a.length,s,i,u,t.dataType===10?-65504:-1e5,w,l,M,C)}},T=(e,t)=>{Rs(e.inputs),e.compute(_("MaxPool",e.inputs[0],!1,t))},J=e=>{let t=e.storage_order,r=e.dilations,n=an(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let s={storageOrder:t,dilations:r,...n,cacheKey:""};return{...s,cacheKey:sn(s)}},Fe=e=>{let t=e.format;return{format:t,...Ya,cacheKey:t}},Oe=(e,t)=>{Rs(e.inputs),e.compute(_("GlobalMaxPool",e.inputs[0],!0,t))}}),St,Wt,nr,kr,pr=R(()=>{Xt(),Ht(),Sr(),or(),St=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((s,a)=>a===t.axis||s===e[0].dims[a]).reduce((s,a)=>s&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Wt=(e,t)=>{let r=Se.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,s=n===3,a=e[0].dims,i=e[1].dataType,u=Se.size(a),d=n===3||n===2,p=d?[Math.ceil(Se.size(e[0].dims)/4)]:e[0].dims,g=e[1].dims,w=e.length>2?e[2]:void 0,l=w?d?[Math.ceil(Se.size(w.dims)/4)]:w.dims:void 0,M=g.length===0||g.length===1&&g[0]===1,C=M===!1&&g.length===1,E=mr(u),B=M&&(!d||E===4),G=B?E:1,O=B&&!d?E:1,ae=rt("input",d?12:n,p.length,O),Z=rt("scale",i,g.length),le=w?rt("zero_point",d?12:n,l.length):void 0,Ge=Ut("output",i,a.length,G),Le=[ae,Z];le&&Le.push(le);let pt=[p,g];w&&pt.push(l);let Dt=[{type:12,data:u/G},{type:12,data:r},{type:12,data:t.blockSize},...Ct(...pt,a)],Vt=lr=>{let fr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${lr.registerUniforms(fr).declareVariables(...Le,Ge)} + ${lr.mainStart()} + ${lr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Ge.offsetToIndices("global_idx")}; + + // Set input x + ${d?` + let input = ${ae.getByOffset("global_idx / 4")}; + let x_vec = ${s?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${G===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ae.getByOffset("global_idx")};`}; + + // Set scale input + ${M?`let scale_value= ${Z.getByOffset("0")}`:C?` + let scale_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${Z.getByOffset("scale_index")};`:` + var scale_indices: ${Z.type.indices} = output_indices; + let index = ${Z.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${Z.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${Z.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${le?M?d?` + let zero_point_input = ${le.getByOffset("0")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${le.getByOffset("0")}`:C?d?` + let zero_point_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${le.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${le.getByOffset("zero_point_index")};`:d?` + let zero_point_offset = ${Z.indicesToOffset("scale_indices")}; + let zero_point_input = ${le.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${le.getByIndices("scale_indices")};`:`let zero_point_value = ${d?s?"i32":"u32":ae.type.value}(0);`}; + // Compute and write output + ${Ge.setByOffset("global_idx",`${Ge.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:le?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Vt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(u/G/64),y:1,z:1},programUniforms:Dt})}},nr=(e,t)=>{St(e.inputs,t),e.compute(Wt(e.inputs,t))},kr=e=>ur({axis:e.axis,blockSize:e.blockSize})}),hr,_r,xr,Fr=R(()=>{Pt(),Xt(),or(),hr=(e,t,r)=>{let n=e===t,s=et&&r>0;if(n||s||a)throw new Error("Range these inputs' contents are invalid.")},_r=(e,t,r,n)=>{let s=Math.abs(Math.ceil((t-e)/r)),a=[s],i=s,u=[{type:12,data:i},{type:n,data:e},{type:n,data:r},...Ct(a)],d=p=>{let g=Ut("output",n,a.length),w=g.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:w},{name:"delta",type:w}];return` + ${p.registerUniforms(l).declareVariables(g)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${w}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:u})}},xr=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),k.webgpu.validateInputContent&&hr(t,r,n),e.compute(_r(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),Tr,gr,rn,on,bn,pn,ln,Mn,Ms,_i,Ja,Gd,Rn,vs,qd,Hd,Kd,pd,ip,zf=R(()=>{Xt(),Ht(),Sr(),or(),Tr=(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")}},gr=(e,t,r)=>{t.every(s=>s>=0&&s{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((s,a)=>n[s]=e[a]),n},rn=(e,t,r,n,s,a)=>{let[i,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(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>0){if(e[u].getFloat32Array().forEach(g=>n.push(g)),n.length!==0&&n.length!==p&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Tr(n,t),t.axes.length>0&&gr(n,t.axes,p).forEach((g,w)=>n[w]=g)}if(d>0&&e.length>d&&(e[d].getBigInt64Array().forEach(g=>s.push(Number(g))),s.length!==p||r>=18&&s.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(s.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof s<"u"&&n.length>0&&s.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},on=(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`)}})()+"}",bn=(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`)}})()+"}",pn=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),s=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=s[i],n[i+r]=s[t.length+i]}),n):s},ln=(e,t,r,n)=>{let s=[];if(r.length>0)if(n.length>0){if(e.forEach(a=>s.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>s[a]=r[i])}else r.forEach(a=>s.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");s=e.map((a,i)=>Math.round(a*t[i]))}return s},Mn=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let s=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.axes.forEach(a=>s[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),s.forEach((a,i)=>s[i]=Math.round(a*t[i]))),s},Ms=(e,t,r,n,s)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { + var original_indices: array<${e.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${jt("uniforms.scales","i",n)}; + var roi_low = ${jt("uniforms.roi","i",s)}; + var roi_hi = ${jt("uniforms.roi",`i + ${t.length}`,s)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${jt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${jt("uniforms.output_shape","i",r.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,_i=(e,t,r,n,s,a,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${jt("uniforms.scales","i",s)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${jt("uniforms.roi","i",a)}; + var roi_hi = ${jt("uniforms.roi",`i + ${r.length}`,a)}; + var input_shape_i = ${jt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${jt("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,Ja=(e,t)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${t.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${jt("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,Gd=(e,t,r,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",r,"batch")}; +`:"",Rn=(e,t,r,n,s)=>{let[a,i,u,d]=r.length===2?[-1,0,1,-1]:[0,2,3,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${r[i]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; + ${Gd(e,d,a,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${p} = originalIndices[${i}]; + var col:${p} = originalIndices[${u}]; + ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[u]} - 1)) { + return ${s}; + }`:""}; + row = max(0, min(row, ${r[i]} - 1)); + col = max(0, min(col, ${r[u]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${r.length>2?`u32(originalIndices[${d}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; + var x11: ${p} = getInputValue(batch, channel, row1, col1); + var x12: ${p} = getInputValue(batch, channel, row1, col2); + var x21: ${p} = getInputValue(batch, channel, row2, col1); + var x22: ${p} = getInputValue(batch, channel, row2, col2); + var dx1: ${p} = abs(row - ${p}(row1)); + var dx2: ${p} = abs(${p}(row2) - row); + var dy1: ${p} = abs(col - ${p}(col1)); + var dy2: ${p} = abs(${p}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},vs=(e,t,r,n,s,a,i,u,d,p)=>{let g=r.length===2,[w,l]=g?[0,1]:[2,3],M=e.type.value,C=E=>{let B=E===w?"row":"col";return` + fn ${B}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${M} { + var output_index = ${t.indicesGet("output_indices",E)}; + var originalIdx: ${M} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[E]}, + ${n[E]}, ${r[E]}, ${a[E]}, ${a[E]} + ${r.length}); + var fractOriginalIdx: ${M} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${r[E]} - 1))) { + return ${d}; + } + var data: array<${M}, 4> = array<${M}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${B}: ${M} = originalIdx + ${M}(i); + if (${B} < 0 || ${B} >= ${r[E]}) { + ${p?`coefs[i + 1] = 0.0; + continue;`:u?`return ${d};`:`${B} = max(0, min(${B}, ${r[E]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",E,`u32(${B})`)}; + data[i + 1] = ${E===w?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${C(w)}; + ${C(l)}; + fn getCubicInterpolationCoefs(s: ${M}) -> array<${M}, 4> { + var absS = abs(s); + var coeffs: array<${M}, 4> = array<${M}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${M} = 1.0 - absS; + var twoMinusAbsS: ${M} = 2.0 - absS; + var onePlusAbsS: ${M} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${M}, 4>, coefs: array<${M}, 4>) -> ${M} { + var coefsSum: ${M} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${M} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},qd=(e,t,r,n,s)=>{let[a,i,u,d,p]=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",i,`max(0, min(depth, ${r[i]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; + ${e.indicesSet("input_indices",d,`max(0, min(width, ${r[d]} - 1))`)}; + ${Gd(e,p,a,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${g} = originalIndices[${i}]; + var height:${g} = originalIndices[${u}]; + var width:${g} = originalIndices[${d}]; + ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { + return ${s}; + }`:""}; + + depth = max(0, min(depth, ${r[i]} - 1)); + height = max(0, min(height, ${r[u]} - 1)); + width = max(0, min(width, ${r[d]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${r.length>3?`u32(originalIndices[${p}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; + + var x111: ${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); + }`},Hd=(e,t,r,n,s,a)=>{let i=e.dims,u=pn(a,t.axes,i.length),d=ln(i,n,s,t.axes),p=n.slice();n.length===0&&(p=i.map((O,ae)=>O===0?1:d[ae]/O),t.keepAspectRatioPolicy!=="stretch"&&(d=Mn(i,p,t)));let g=Ut("output",e.dataType,d.length),w=rt("input",e.dataType,i.length),l=Se.size(d),M=i.length===d.length&&i.every((O,ae)=>O===d[ae]),C=t.coordinateTransformMode==="tf_crop_and_resize",E=t.extrapolationValue,B=w.type.value,G=O=>` + ${M?"":` + ${on(t.coordinateTransformMode,B)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${Ja(w,i)}; + ${bn(t.nearestMode,r,B)}; + ${_i(w,g,i,d,p.length,u.length,C)}; + `;case"linear":return` + ${Ms(g,i,d,p.length,u.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${Rn(w,g,i,C,E)}`;if(i.length===3||i.length===5)return`${qd(w,g,i,C,E)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${vs(w,g,i,d,p,u,t.cubicCoeffA,C,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")}})()}; + `} + ${O.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",u.length).declareVariables(w,g)} + ${O.mainStart()} + ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${M?"output[global_idx] = input[global_idx];":` + let output_indices = ${g.offsetToIndices("global_idx")}; + var input_indices: ${w.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${w.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${s.length>0?s:""}|${u.length>0?u:""}|${M}|${i}`,inputDependencies:["rank"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:p},{type:1,data:u},...Ct(i,d)]})}},Kd=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},pd=(e,t)=>{let r=[],n=[],s=[],a=Kd(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");rn(e.inputs,t,a,r,n,s),e.compute(Hd(e.inputs[0],t,a,r,n,s),{inputs:[0]})},ip=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,s=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return ur({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:s,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:u,mode:d,nearestMode:p})}}),ap,op,lp,Of=R(()=>{Xt(),Ht(),Sr(),or(),ap=(e,t)=>{let[r,n,s,a]=e,{numHeads:i,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!Se.areEqual(n.dims,[])&&!Se.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(s.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Se.areEqual(s.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],p=r.dims[r.dims.length-2],g=s.dims[0],w=Se.sizeFromDimension(r.dims,1)/p,l=u===0?s.dims[1]*2:w/i;if(u>l)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(p!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(l/2!==s.dims[1]&&u/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(p>g)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},op=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:s,scale:a}=t,i=e[0].dims[0],u=Se.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],p=u/d,g=e[2].dims[1],w=s===0?g*2:p/n,l=new Array(i,d,p/w,w-g),M=Se.computeStrides(l),C=[{type:1,data:a},{type:12,data:l},{type:12,data:M},...e[0].dims.length===3?new Array({type:12,data:[u,p,w,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,w,d*w,1]}):[],...Ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],E=B=>{let G=rt("input",e[0].dataType,e[0].dims.length),O=rt("position_ids",e[1].dataType,e[1].dims.length),ae=rt("cos_cache",e[2].dataType,e[2].dims.length),Z=rt("sin_cache",e[3].dataType,e[3].dims.length),le=Ut("output",e[0].dataType,e[0].dims.length);return B.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:M.length},{name:"input_output_strides",type:"u32",length:M.length}]),` + ${B.declareVariables(G,O,ae,Z,le)} + + ${B.mainStart(en)} + let half_rotary_emb_dim = uniforms.${ae.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${B.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${O.broadcastedIndicesToOffset("bsnh.xy",Ut("",O.type.tensor,2))}; + let position_id = + u32(${O.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); + let j = i + select(half_rotary_emb_dim, 1, ${r}); + let re = ${G.getByOffset("i")} * ${ae.get("position_id","bsnh[3]")} - + ${G.getByOffset("j")} * ${Z.get("position_id","bsnh[3]")}; + ${le.setByOffset("i","re")} + let im = ${G.getByOffset("i")} * ${Z.get("position_id","bsnh[3]")} + + ${G.getByOffset("j")} * ${ae.get("position_id","bsnh[3]")}; + ${le.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${le.setByOffset("k",G.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:ur({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(l)/en)},programUniforms:C})}},lp=(e,t)=>{ap(e.inputs,t),e.compute(op(e.inputs,t))}}),up,dp,cp,Df=R(()=>{Xt(),Ht(),or(),up=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let s=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==s)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==s)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},dp=(e,t,r,n)=>{let s=t.simplified,a=e[0].dims,i=Se.size(a),u=a,d=i,p=a.slice(-1)[0],g=n?a.slice(0,-1).concat(1):[],w=!s&&e.length>3,l=e.length>4,M=n&&r>1,C=n&&r>2,E=r>3,B=64,G=mr(p),O=[{type:12,data:d},{type:12,data:G},{type:12,data:p},{type:1,data:t.epsilon}],ae=le=>{let Ge=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Le=[rt("x",e[0].dataType,e[0].dims,G),rt("skip",e[1].dataType,e[1].dims,G),rt("gamma",e[2].dataType,e[2].dims,G)];w&&Le.push(rt("beta",e[3].dataType,e[3].dims,G)),l&&Le.push(rt("bias",e[4].dataType,e[4].dims,G)),Le.push(Ut("output",e[0].dataType,u,G)),M&&Le.push(Ut("mean_output",1,g)),C&&Le.push(Ut("inv_std_output",1,g)),E&&Le.push(Ut("input_skip_bias_sum",e[0].dataType,u,G));let pt=yr(e[0].dataType),Dt=yr(1,G);return` + + ${le.registerUniforms(Ge).declareVariables(...Le)} + var sum_shared : array<${Dt}, ${B}>; + var sum_squared_shared : array<${Dt}, ${B}>; + + ${le.mainStart([B,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${B}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${B}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${B-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]":pt+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${E?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Kn(pt,G,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${B}; + 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 = ${Xn("sum",G)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Xn("square_sum",G)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); + ${M?"mean_output[global_idx] = mean;":""} + ${C?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${s?"":`- ${pt}(mean)`}) * + ${pt}(inv_std_dev) * gamma[offset1d + i] + ${w?"+ beta[offset1d + i]":""}; + } + }`},Z=[{dims:u,dataType:e[0].dataType}];return r>1&&Z.push({dims:g,dataType:1}),r>2&&Z.push({dims:g,dataType:1}),r>3&&Z.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${G};${M};${C};${E}`,inputDependencies:e.map((le,Ge)=>"type")},getShaderSource:ae,getRunData:()=>({outputs:Z,dispatchGroup:{x:Math.ceil(d/p)},programUniforms:O})}},cp=(e,t)=>{up(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(dp(e.inputs,t,e.outputCount,!1),{outputs:r})}}),pp,hd,hp,bc,fp,mp,_p,gp,Lf=R(()=>{Xt(),Ht(),Sr(),or(),pp=(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`)})},hd=(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},hp=(e,t)=>{if(e.length>1){let r=hd(e,1),n=hd(e,2),s=hd(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),ur({starts:r,ends:n,axes:s})}else return t},bc=(e,t,r,n,s)=>{let a=e;return e<0&&(a+=r[n[t]]),s[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},fp=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${r.length}; i >= 0; i--) { + let input_shape_i = ${jt("uniforms.input_shape","i",r.length)}; + let steps_i = ${jt("uniforms.steps","i",r.length)}; + let signs_i = ${jt("uniforms.signs","i",r.length)}; + let starts_i = ${jt("uniforms.starts","i",r.length)}; + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,mp=(e,t)=>{let r=e[0].dims,n=Se.size(r),s=t.axes.length>0?Se.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=hd(e,4);a.forEach(G=>G!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(s.length).fill(1));let i=t.starts.map((G,O)=>bc(G,O,r,s,a)),u=t.ends.map((G,O)=>bc(G,O,r,s,a));if(s.length!==i.length||s.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==r.length)for(let G=0;GMath.sign(G));a.forEach((G,O,ae)=>{if(G<0){let Z=(u[O]-i[O])/G,le=i[O],Ge=le+Z*a[O];i[O]=Ge,u[O]=le,ae[O]=-G}});let p=r.slice(0);s.forEach((G,O)=>{p[G]=Math.ceil((u[G]-i[G])/a[G])});let g={dims:p,dataType:e[0].dataType},w=Ut("output",e[0].dataType,p.length),l=rt("input",e[0].dataType,e[0].dims.length),M=Se.size(p),C=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:a.length}],E=[{type:12,data:M},{type:12,data:i},{type:6,data:d},{type:12,data:a},...Ct(e[0].dims,p)],B=G=>` + ${G.registerUniforms(C).declareVariables(l,w)} + ${fp(l,w,r)} + ${G.mainStart()} + ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${w.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${w.setByOffset("global_idx",l.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:B,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:E})}},_p=(e,t)=>{pp(e.inputs,t);let r=hp(e.inputs,t);e.compute(mp(e.inputs,r),{inputs:[0]})},gp=e=>{let t=e.starts,r=e.ends,n=e.axes;return ur({starts:t,ends:r,axes:n})}}),wp,yp,bp,Mp,Bf=R(()=>{Xt(),Ht(),Sr(),or(),wp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},yp=(e,t)=>{let r=e.dims,n=Se.size(r),s=64,a=t.axis;if(a<0&&(a=r.length+a),aG===4?`max(max(${B}.x, ${B}.y), max(${B}.z, ${B}.w))`:G===2?`max(${B}.x, ${B}.y)`:G===3?`max(max(${B}.x, ${B}.y), ${B}.z)`:B,w=rt("x",e.dataType,e.dims,d),l=Ut("result",e.dataType,e.dims,d),M=w.type.value,C=yr(e.dataType)==="f32"?`var threadMax = ${M}(-3.402823e+38f);`:`var threadMax = ${M}(-65504.0h);`,E=B=>` + var rowMaxShared : ${M}; + var rowSumShared : ${M}; + var threadShared : array<${M}, ${s}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${M} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${M}) { + let index = row * row_stride + col; + result[index] = value; + } + ${B.registerUniform("packedCols","i32").declareVariables(w,l)} + ${B.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${s}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${C} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${M}(${g("threadShared[0]",d)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${M}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${M}(${Xn("threadShared[0]",d)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`;return{name:"Softmax",shaderCache:{hint:`${d}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:p}]}),getShaderSource:E}},bp=(e,t)=>{wp(e.inputs),e.compute(yp(e.inputs[0],t))},Mp=e=>ur({axis:e.axis})}),vp,xp,Tp,Cp,Ep,$p,Sp,Rf=R(()=>{Xt(),Ht(),Sr(),or(),vp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},xp=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),n=r.length),ur({numOutputs:n,axis:t.axis,splitSizes:r})},Tp=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${jt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Cp=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=Se.size(r),s=e[0].dataType,a=Se.normalizeAxis(t.axis,r.length),i=new Array(t.numOutputs),u=rt("input",s,r.length),d=new Array(t.numOutputs),p=[],g=[],w=0,l=[{type:12,data:n}];for(let C=0;C` + ${C.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...i)} + ${Tp(d.length)} + ${Cp(i)} + + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",a)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${jt("uniforms.size_in_split_axis","output_number - 1u",d.length)}; + ${u.indicesSet("indices",a,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:l})}},$p=(e,t)=>{vp(e.inputs);let r=e.inputs.length===1?t:xp(e.inputs,t);e.compute(Ep(e.inputs,r),{inputs:[0]})},Sp=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 ur({axis:t,numOutputs:n,splitSizes:r})}}),kp,Pp,Ap,Nf=R(()=>{Xt(),Ht(),or(),kp=(e,t,r,n,s)=>{let a=Ut("output_data",s,r.length,4),i=rt("a_data",t[1].dataType,t[1].dims.length,4),u=rt("b_data",t[2].dataType,t[2].dims.length,4),d=rt("c_data",t[0].dataType,t[0].dims.length,4),p,g=(w,l,M)=>`select(${l}, ${w}, ${M})`;if(!n)p=a.setByOffset("global_idx",g(i.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let w=(l,M,C="")=>{let E=`a_data[index_a${M}][component_a${M}]`,B=`b_data[index_b${M}][component_b${M}]`,G=`bool(c_data[index_c${M}] & (0xffu << (component_c${M} * 8)))`;return` + let output_indices${M} = ${a.offsetToIndices(`global_idx * 4u + ${M}u`)}; + let offset_a${M} = ${i.broadcastedIndicesToOffset(`output_indices${M}`,a)}; + let offset_b${M} = ${u.broadcastedIndicesToOffset(`output_indices${M}`,a)}; + let offset_c${M} = ${d.broadcastedIndicesToOffset(`output_indices${M}`,a)}; + let index_a${M} = offset_a${M} / 4u; + let index_b${M} = offset_b${M} / 4u; + let index_c${M} = offset_c${M} / 4u; + let component_a${M} = offset_a${M} % 4u; + let component_b${M} = offset_b${M} % 4u; + let component_c${M} = offset_c${M} % 4u; + ${l}[${M}] = ${C}(${g(E,B,G)}); + `};s===9?p=` + var data = vec4(0); + ${w("data",0,"u32")} + ${w("data",1,"u32")} + ${w("data",2,"u32")} + ${w("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=` + ${w("output_data[global_idx]",0)} + ${w("output_data[global_idx]",1)} + ${w("output_data[global_idx]",2)} + ${w("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(d,i,u,a)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${p} + }`},Pp=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,s=e[1].dataType,a=!(Se.areEqual(t,r)&&Se.areEqual(r,n)),i=t,u=Se.size(t);if(a){let p=wn.calcShape(wn.calcShape(t,r,!1),n,!1);if(!p)throw new Error("Can't perform where op on the given tensors");i=p,u=Se.size(i)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>kp(p,e,i,a,s),getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...Ct(n,t,r,i)]})}},Ap=e=>{e.compute(Pp(e.inputs))}}),Ip,jf=R(()=>{Md(),Ki(),vd(),xd(),Td(),Pl(),Cd(),Sd(),Pd(),$a(),ka(),wc(),Id(),Fd(),zd(),yc(),Ld(),Au(),Uu(),Nd(),jd(),Xl(),Vd(),Ou(),Ud(),_t(),pr(),Fr(),Js(),zf(),Of(),Df(),Lf(),Bf(),Rf(),Ru(),is(),ti(),Nf(),Ip=new Map([["Abs",[Yi]],["Acos",[Ko]],["Acosh",[Xo]],["Add",[vl]],["ArgMax",[Ui,Wi]],["ArgMin",[Bo,Wi]],["Asin",[Qo]],["Asinh",[Yo]],["Atan",[Ji]],["Atanh",[Jo]],["Attention",[Hi]],["AveragePool",[Wd,os]],["BatchNormalization",[Wo]],["BiasAdd",[qo]],["BiasSplitGelu",[pa]],["Cast",[Zi,Zo]],["Ceil",[ea]],["Clip",[tl]],["Concat",[ma,Ol]],["Conv",[as,Yl]],["ConvTranspose",[uu,au]],["Cos",[rl]],["Cosh",[nl]],["CumSum",[du,cu]],["DepthToSpace",[mu,Sa]],["DequantizeLinear",[nr,kr]],["Div",[xl]],["Einsum",[Oa,Ad]],["Elu",[sl,ys]],["Equal",[Tl]],["Erf",[ta]],["Exp",[il]],["Expand",[La]],["FastGelu",[Ba]],["Floor",[al]],["FusedConv",[as,Yl]],["Gather",[Tu,xu]],["GatherElements",[Su,$u]],["GatherBlockQuantized",[Od,Dd]],["Gelu",[ei]],["Gemm",[Pu,ku]],["GlobalAveragePool",[f,cd]],["GlobalMaxPool",[Oe,Fe]],["Greater",[$l]],["GreaterOrEqual",[Sl]],["GroupQueryAttention",[Rd,ju]],["HardSigmoid",[cl,dl]],["InstanceNormalization",[qu]],["LayerNormalization",[Xu]],["LeakyRelu",[ol,ys]],["Less",[fa]],["LessOrEqual",[kl]],["Log",[_l]],["MatMul",[Kl]],["MatMulNBits",[Ju,Zu]],["MaxPool",[T,J]],["Mul",[ri]],["MultiHeadAttention",[zu,Iu]],["Neg",[ra]],["Not",[ll]],["Pad",[ld]],["Pow",[Cl]],["QuickGelu",[wl,ys]],["Range",[xr]],["Reciprocal",[na]],["ReduceMin",[zo]],["ReduceMean",[Ao]],["ReduceMax",[Ni]],["ReduceSum",[ji]],["ReduceProd",[Oo]],["ReduceL1",[Ri]],["ReduceL2",[Io]],["ReduceLogSum",[Lo]],["ReduceLogSumExp",[Fo]],["ReduceSumSquare",[Do]],["Relu",[ul]],["Resize",[pd,ip]],["RotaryEmbedding",[lp]],["Sigmoid",[sa]],["Sin",[pl]],["Sinh",[ia]],["Slice",[_p,gp]],["SkipLayerNormalization",[cp]],["Split",[$p,Sp]],["Sqrt",[hl]],["Softmax",[bp,Mp]],["Sub",[El]],["Tan",[fl]],["Tanh",[oa]],["ThresholdedRelu",[ml,ys]],["Tile",[Bu]],["Transpose",[$i,oo]],["Where",[Ap]]])}),Fp,Vf=R(()=>{Pt(),m(),or(),Fp=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,s){Ue(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let p of t)u.push({binding:u.length,resource:{buffer:p.buffer}});for(let p of r)u.push({binding:u.length,resource:{buffer:p.buffer}});s&&u.push({binding:u.length,resource:s});let d=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:d,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}i.setPipeline(e.computePipeline),i.setBindGroup(0,d),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),je(e.programInfo.name)}dispose(){}build(e,t){Ue(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let s=io(t,this.backend.device.limits),a=e.getShaderSource(s),i=`${n.join(` +`)} +${s.additionalImplementations} +${a}`,u=r.createShaderModule({code:i,label:e.name});ue("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let d=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return je(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:s.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=s&&r<=s&&n<=s)return[t,r,n];let a=t*r*n,i=Math.ceil(Math.sqrt(a));if(i>s){if(i=Math.ceil(Math.cbrt(a)),i>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),zp,Op,Dp,Lp,Uf=R(()=>{Pt(),Xt(),m(),K(),Dr(),jf(),Vf(),zp=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{var s,a;let n=e.name;return(s=e.shaderCache)!=null&&s.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${zp(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Dp=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Lp=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 Dp(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ar(this),this.programManager=new Fp(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ws(e.logLevel,!!e.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ue(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=M);let E=Number(M-this.queryTimeBase),B=Number(C-this.queryTimeBase);if(!Number.isSafeInteger(E)||!Number.isSafeInteger(B))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:w.map(G=>({dims:G.dims,dataType:Sn(G.dataType)})),outputsMetadata:l.map(G=>({dims:G.dims,dataType:Sn(G.dataType)})),kernelId:i,kernelType:d,kernelName:p,programName:g,startTime:E,endTime:B});else{let G="";w.forEach((ae,Z)=>{G+=`input[${Z}]: [${ae.dims}] | ${Sn(ae.dataType)}, `});let O="";l.forEach((ae,Z)=>{O+=`output[${Z}]: [${ae.dims}] | ${Sn(ae.dataType)}, `}),console.log(`[profiling] kernel "${i}|${d}|${p}|${g}" ${G}${O}execution time: ${B-E} ns`)}Ne("GPU",`${g}::${M}::${C}`)}e.unmap(),this.pendingQueries.delete(e)}),je()}run(e,t,r,n,s,a){Ue(e.name);let i=[];for(let O=0;Oae):r;if(g.length!==u.length)throw new Error(`Output size ${g.length} must be equal to ${u.length}.`);let w=[],l=[];for(let O=0;O=a)throw new Error(`Invalid output index: ${g[O]}`);if(g[O]===-3)continue;let ae=g[O]===-1,Z=g[O]===-2,le=ae||Z?s(u[O].dataType,u[O].dims):n(g[O],u[O].dataType,u[O].dims);if(w.push(le),le.data===0)continue;let Ge=this.gpuDataManager.get(le.data);if(!Ge)throw new Error(`no GPU data for output: ${le.data}`);if(ae&&this.temporaryData.push(Ge),Z){let Le=this.kernelPersistentData.get(this.currentKernelId);Le||(Le=[],this.kernelPersistentData.set(this.currentKernelId,Le)),Le.push(Ge)}l.push(Ge)}if(i.length!==t.length||l.length!==w.length){if(l.length===0)return je(e.name),w;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let M;if(p){let O=0,ae=[];p.forEach(Le=>{let pt=typeof Le.data=="number"?[Le.data]:Le.data;if(pt.length===0)return;let Dt=Le.type===10?2:4,Vt,lr;Le.type===10?(lr=pt.length>4?16:pt.length>2?8:pt.length*Dt,Vt=pt.length>4?16:Dt*pt.length):(lr=pt.length<=2?pt.length*Dt:16,Vt=16),O=Math.ceil(O/lr)*lr,ae.push(O);let fr=Le.type===10?8:4;O+=pt.length>4?Math.ceil(pt.length/fr)*Vt:pt.length*Dt});let Z=16;O=Math.ceil(O/Z)*Z;let le=new ArrayBuffer(O);p.forEach((Le,pt)=>{let Dt=ae[pt],Vt=typeof Le.data=="number"?[Le.data]:Le.data;if(Le.type===6)new Int32Array(le,Dt,Vt.length).set(Vt);else if(Le.type===12)new Uint32Array(le,Dt,Vt.length).set(Vt);else if(Le.type===10)new Uint16Array(le,Dt,Vt.length).set(Vt);else if(Le.type===1)new Float32Array(le,Dt,Vt.length).set(Vt);else throw new Error(`Unsupported uniform type: ${Sn(Le.type)}`)});let Ge=this.gpuDataManager.create(O,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ge.buffer,0,le,0,O),this.gpuDataManager.release(Ge.id),M={offset:0,size:O,buffer:Ge.buffer}}let C=this.programManager.normalizeDispatchGroupSize(d),E=C[1]===1&&C[2]===1,B=Op(e,t,E),G=this.programManager.getArtifact(B);if(G||(G=this.programManager.build(e,C),this.programManager.setArtifact(B,G),ue("info",()=>`[artifact] key: ${B}, programName: ${e.name}`)),p&&G.uniformVariablesInfo){if(p.length!==G.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${G.uniformVariablesInfo.length}, got ${p.length} in program "${G.programInfo.name}".`);for(let O=0;O`[ProgramManager] run "${e.name}" (key=${B}) with ${C[0]}x${C[1]}x${C[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let O={kernelId:this.currentKernelId,programName:G.programInfo.name,inputTensorViews:t,outputTensorViews:w};this.pendingKernels.push(O),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(O)}return this.programManager.run(G,i,l,C,M),je(e.name),w}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,n){let s=Ip.get(e);if(!s)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:s[0],attributes:[s[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let s=n.kernelType,a=n.kernelName,i=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),ue("info",()=>`[WebGPU] Start to run kernel "[${s}] ${a}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),i(t,u[1]),0}catch(p){return r.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${a}" failed. ${p}`)),1}finally{d&&r.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${s}] ${a}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let s=this.sessionExternalDataMapping.get(e);s||(s=new Map,this.sessionExternalDataMapping.set(e,s));let a=s.get(t),i=this.gpuDataManager.registerExternalBuffer(r,n,a);return s.set(t,[i,r]),i}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 Yt(this,e,t);return A(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(){ue("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(){ue("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ue("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Bp,Mc,vc,Rp,Np,Wf=R(()=>{m(),Bp=1,Mc=()=>Bp++,vc=class{constructor(e,t){this.mlContext=e,this.tensorEntry=t,this.tensorCache=t?[t]:[]}get tensor(){var e;return(e=this.tensorEntry)==null?void 0:e[0]}get context(){if(!this.mlContext)throw new Error("MLContext has not been set.");return this.mlContext}set context(e){if(this.mlContext&&this.mlContext!==e)throw new Error("MLTensor in use in a different MLContext.");this.mlContext=e}destroy(){for(let[e]of this.tensorCache)e.destroy();this.tensorCache=[],this.tensorEntry=void 0}trySelectTensor(e,t){for(let[r,n,s]of this.tensorCache)if(t===r){if(this.context!==e)throw new Error("MLTensor cannot be registered with a different MLContext.");return this.tensorEntry=[r,n,s],!0}return!1}async ensureTensor(e,t,r){var a;if(this.tensorEntry){let[i,u,d]=this.tensorEntry;if(u===e&&d.every((p,g)=>p===t[g]))return i}for(let[i,u,d]of this.tensorCache)if(u===e&&d.every((p,g)=>p===t[g])){if(r&&this.tensorEntry){ue("verbose",()=>`[WebNN] Slowdown may occur, having to copy existing tensor {dataType: ${e}, shape: ${t}}`);let p=await this.context.readTensor(this.tensorEntry[0]);this.context.writeTensor(i,p)}return this.tensorEntry=[i,u,d],i}ue("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let n=MLTensorUsage.READ|MLTensorUsage.WRITE,s=await this.context.createTensor({dataType:e,shape:t,dimensions:t,usage:n});return this.tensorEntry=[s,e,t],this.tensorCache.push(this.tensorEntry),this.activeUpload&&((a=this.mlContext)==null||a.writeTensor(s,this.activeUpload),this.activeUpload=void 0),s}upload(e){var t;if(!this.tensorEntry){this.activeUpload=new Uint8Array(e);return}(t=this.mlContext)==null||t.writeTensor(this.tensorEntry[0],e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.tensorEntry)throw new Error("Tensor has not been created.");return e?this.context.readTensor(this.tensorEntry[0],e):this.context.readTensor(this.tensorEntry[0])}},Rp=class{constructor(e){this.backend=e,this.tensorsById=new Map,this.tensorIdsByContext=new Map}reserveTensorId(){let e=Mc();return this.tensorsById.set(e,new vc),e}releaseTensorId(e){let t=this.tensorsById.get(e);if(t){t.destroy(),this.tensorsById.delete(e);for(let[r,n]of this.tensorIdsByContext)if(n.has(e)){n.delete(e),n.size===0&&this.tensorIdsByContext.delete(r);break}}}async ensureTensor(e,t,r,n){var a;ue("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${n}}`);let s=this.tensorsById.get(e);if(!s)throw new Error("Tensor not found.");return s.context=this.backend.currentContext,this.tensorIdsByContext.has(this.backend.currentContext)||this.tensorIdsByContext.set(this.backend.currentContext,new Set),(a=this.tensorIdsByContext.get(this.backend.currentContext))==null||a.add(e),s.ensureTensor(t,r,n)}upload(e,t){this.tensorsById.get(e).upload(t)}async download(e,t){return ue("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`),this.tensorsById.get(e).download(t)}releaseTensorsForContext(e){let t=this.tensorIdsByContext.get(e);if(t){for(let r of t)this.tensorsById.get(r).destroy(),this.tensorsById.delete(r);this.tensorIdsByContext.delete(e)}}registerTensor(e,t,r,n){for(let[i,u]of this.tensorsById)if(u.trySelectTensor(e,t))return i;let s=Mc();this.tensorsById.set(s,new vc(e,[t,r,n]));let a=this.tensorIdsByContext.get(e);return a||(a=new Set,this.tensorIdsByContext.set(e,a)),a.add(s),s}},Np=(...e)=>new Rp(...e)}),xc,jp,Gf=R(()=>{Xt(),Wr(),K(),Wf(),m(),xc=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),jp=class{constructor(e){this.tensorManager=Np(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,ws(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);r.delete(e),r.size===0&&(this.sessionIdsByMLContext.delete(t),this.tensorManager.releaseTensorsForContext(t))}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ue("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n){let s=xc.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,s,r,n)}uploadTensor(e,t){if(!rr().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ue("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 A(r,t)}}registerMLTensor(e,t,r){let n=xc.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let s=this.tensorManager.registerTensor(this.currentContext,e,n,r);return ue("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${r}} -> {tensorId: ${s}}`),s}flush(){}}}),Vp={};S(Vp,{init:()=>Wp});var Xd,Up,Wp,qf=R(()=>{Xt(),Uf(),m(),Ht(),Gf(),Xd=class Sf{constructor(t,r,n,s){this.module=t,this.dataType=r,this.data=n,this.dims=s}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Se.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=Se.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=Se.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=Se.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Se.size(t)!==Se.size(this.dims))throw new Error("Invalid new shape");return new Sf(this.module,this.dataType,this.data,t)}},Up=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.HEAPU32,s=r>>>2;this.opKernelContext=n[s++];let a=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let i=[];for(let u=0;utypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],s=(u,d,p)=>new Xd(this.module,d,this.output(u,p),p),a=(u,d)=>{let p=Cn(u,d);if(!p)throw new Error(`Unsupported data type: ${u}`);let g=p>0?this.backend.gpuDataManager.create(p).id:0;return new Xd(this.module,u,g,d)};return this.backend.run(e,r,n,s,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),s=n>>2;this.module.HEAPU32[s++]=t.length;for(let a=0;a{let s=t.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Lp;await a.initialize(r,n),s("webgpu",[a,i=>a.alloc(i),i=>a.free(i),(i,u,d,p=!1)=>{if(p)ue("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${u}, size=${d}`),a.memcpy(i,u);else{ue("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${u}, size=${d}`);let g=t.HEAPU8.subarray(i>>>0,(i>>>0)+d);a.upload(u,g)}},async(i,u,d)=>{ue("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${u}, size=${d}`),await a.download(i,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+d))},(i,u,d)=>a.createKernel(i,u,d,t.UTF8ToString(t._JsepGetNodeName(u))),i=>a.releaseKernel(i),(i,u,d,p)=>{ue("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${i}, contextDataOffset=${u}`);let g=new Up(t,a,u);return a.computeKernel(i,g,p)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new jp(r);s("webnn",[a,()=>a.reserveTensorId(),i=>a.releaseTensorId(i),async(i,u,d,p)=>a.ensureTensor(i,u,d,p),(i,u)=>{a.uploadTensor(i,u)},async(i,u)=>a.downloadTensor(i,u)])}}}),Gp,Tc,Cc,Ns,qp,Qd,Ec,$c,Sc,kc,Pc,Ac,Hp=R(()=>{Xs(),Qs(),Xt(),Wr(),Bn(),_s(),Gp=(e,t)=>{rr()._OrtInit(e,t)!==0&&Rr("Can't initialize onnxruntime.")},Tc=async e=>{Gp(e.wasm.numThreads,ts(e.logLevel))},Cc=async(e,t)=>{{let r=(qf(),P(Vp)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",rr(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",rr(),e)}}},Ns=new Map,qp=e=>{let t=rr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Rr("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},Qd=e=>{let t=rr(),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]},Ec=async(e,t)=>{var w,l;let r,n,s=rr();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Qd(e);let a=0,i=0,u=0,d=[],p=[],g=[];try{if([i,d]=ks(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let Z=[];for(let le of t.externalData){let Ge=typeof le=="string"?le:le.path;Z.push(ms(typeof le=="string"?le:le.data).then(Le=>{s.mountExternalData(Ge,Le)}))}await Promise.all(Z)}for(let Z of(t==null?void 0:t.executionProviders)??[])if((typeof Z=="string"?Z:Z.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof Z!="string"){let le=Z,Ge=le==null?void 0:le.context,Le=le==null?void 0:le.gpuDevice,pt=le==null?void 0:le.deviceType,Dt=le==null?void 0:le.numThreads,Vt=le==null?void 0:le.powerPreference;Ge?s.currentContext=Ge:Le?s.currentContext=await navigator.ml.createContext(Le):s.currentContext=await navigator.ml.createContext({deviceType:pt,numThreads:Dt,powerPreference:Vt})}else s.currentContext=await navigator.ml.createContext();break}a=await s._OrtCreateSession(r,n,i),a===0&&Rr("Can't create a session."),s.currentContext&&(s.jsepRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[M,C]=qp(a),E=!!(t!=null&&t.enableGraphCapture),B=[],G=[],O=[];for(let Z=0;ZZ==="gpu-buffer"||Z==="ml-tensor")&&(u=s._OrtCreateBinding(a),u===0&&Rr("Can't create IO binding."),ae={handle:u,outputPreferredLocations:O,outputPreferredLocationsEncoded:O.map(Z=>rs(Z))}),Ns.set(a,[a,p,g,ae,E,!1]),[a,B,G]}catch(M){throw p.forEach(C=>s._OrtFree(C)),g.forEach(C=>s._OrtFree(C)),u!==0&&s._OrtReleaseBinding(u),a!==0&&s._OrtReleaseSession(a),M}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i),d.forEach(M=>s._free(M)),(l=s.unmountExternalData)==null||l.call(s)}},$c=e=>{var d;let t=rr(),r=Ns.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,i,u]=r;i&&(u&&t._OrtClearBoundOutputs(i.handle),t._OrtReleaseBinding(i.handle)),(d=t.jsepOnReleaseSession)==null||d.call(t,e),s.forEach(p=>t._OrtFree(p)),a.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n),Ns.delete(e)},Sc=(e,t,r,n,s,a=!1)=>{if(!e){t.push(0);return}let i=rr(),u=e[0],d=e[1],p=e[3],g,w;if(u==="string"&&(p==="gpu-buffer"||p==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let C=e[2].gpuBuffer;w=Cn(qn(u),d);let E=i.jsepRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=E(n,s,C,w)}else if(p==="ml-tensor"){let C=e[2].mlTensor;w=Cn(qn(u),d);let E=i.jsepRegisterMLTensor;if(!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=E(C,qn(u),d)}else{let C=e[2];if(Array.isArray(C)){w=4*C.length,g=i._malloc(w),r.push(g);let E=g/4;for(let B=0;Bi.HEAP32[C++]=B);let E=i._OrtCreateTensor(qn(u),g,w,M,d.length,rs(p));E===0&&Rr(`Can't create tensor for input/output. session=${n}, index=${s}.`),t.push(E)}finally{i.stackRestore(l)}},kc=async(e,t,r,n,s,a)=>{var Vt,lr;let i=rr(),u=Ns.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=u[0],p=u[1],g=u[2],w=u[3],l=u[4],M=u[5],C=t.length,E=n.length,B=0,G=[],O=[],ae=[],Z=[],le=i.stackSave(),Ge=i.stackAlloc(C*4),Le=i.stackAlloc(C*4),pt=i.stackAlloc(E*4),Dt=i.stackAlloc(E*4);try{(Vt=i.jsepOnRunStart)==null||Vt.call(i,d),[B,G]=Cs(a);for(let Jt=0;Jthn*vn,1);tr=Sn(un);let yi=w==null?void 0:w.outputPreferredLocations[n[Jt]];if(tr==="string"){if(yi==="gpu-buffer"||yi==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let hn=[],vn=zr/4;for(let Vn=0;Vn0){let hn=i.jsepGetBuffer;if(!hn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let vn=hn(zr),Vn=Cn(un,mn);if(Vn===void 0||!hs(tr))throw new Error(`Unsupported data type: ${tr}`);kt=!0,jr.push([tr,En,{gpuBuffer:vn,download:i.jsepCreateDownloader(vn,Vn,tr),dispose:()=>{i._OrtReleaseTensor(dr)}},"gpu-buffer"])}else if(yi==="ml-tensor"&&mn>0){let hn=i.jsepEnsureTensor;if(!hn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Cn(un,mn)===void 0||!fs(tr))throw new Error(`Unsupported data type: ${tr}`);let vn=await hn(zr,un,En,!1);kt=!0,jr.push([tr,En,{mlTensor:vn,download:i.jsepCreateMLTensorDownloader(zr,tr),dispose:()=>{i.jsepReleaseTensorId(zr),i._OrtReleaseTensor(dr)}},"ml-tensor"])}else{let hn=ps(tr),vn=new hn(mn);new Uint8Array(vn.buffer,vn.byteOffset,vn.byteLength).set(i.HEAPU8.subarray(zr,zr+vn.byteLength)),jr.push([tr,En,vn,"cpu"])}}finally{i.stackRestore(Pr),tr==="string"&&zr&&i._free(zr),kt||i._OrtReleaseTensor(dr)}}return w&&!l&&(i._OrtClearBoundOutputs(w.handle),Ns.set(e,[d,p,g,w,l,!1])),jr}finally{i.stackRestore(le),O.forEach(fr=>i._OrtReleaseTensor(fr)),ae.forEach(fr=>i._OrtReleaseTensor(fr)),Z.forEach(fr=>i._free(fr)),B!==0&&i._OrtReleaseRunOptions(B),G.forEach(fr=>i._free(fr))}},Pc=e=>{let t=rr(),r=Ns.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Rr("Can't get an profile file name."),t._OrtFree(s)},Ac=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),js,Dn,Za,fd,md,Yd,Ic,Jd,gi,wi,Kp,Xp,Qp,Yp,Jp,Zp,eh,th,rh=R(()=>{Pt(),Hp(),Wr(),Gt(),js=()=>!!k.wasm.proxy&&typeof document<"u",Za=!1,fd=!1,md=!1,Jd=new Map,gi=(e,t)=>{let r=Jd.get(e);r?r.push(t):Jd.set(e,[t])},wi=()=>{if(Za||!fd||md||!Dn)throw new Error("worker not ready")},Kp=e=>{switch(e.data.type){case"init-wasm":Za=!1,e.data.err?(md=!0,Ic[1](e.data.err)):(fd=!0,Ic[0]()),Yd&&(URL.revokeObjectURL(Yd),Yd=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Jd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Xp=async()=>{if(!fd){if(Za)throw new Error("multiple calls to 'initWasm()' detected.");if(md)throw new Error("previous call to 'initWasm()' failed.");if(Za=!0,js())return new Promise((e,t)=>{Dn==null||Dn.terminate(),zt().then(([r,n])=>{try{Dn=n,Dn.onerror=a=>t(a),Dn.onmessage=Kp,Ic=[e,t];let s={type:"init-wasm",in:k};Dn.postMessage(s),Yd=r}catch(s){t(s)}},t)});try{await Kr(k.wasm),await Tc(k),fd=!0}catch(e){throw md=!0,e}finally{Za=!1}}},Qp=async e=>{if(js())return wi(),new Promise((t,r)=>{gi("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:k}};Dn.postMessage(n)});await Cc(k,e)},Yp=async e=>js()?(wi(),new Promise((t,r)=>{gi("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Dn.postMessage(n,[e.buffer])})):Qd(e),Jp=async(e,t)=>{if(js()){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 s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Dn.postMessage(s,a)})}else return Ec(e,t)},Zp=async e=>{if(js())return wi(),new Promise((t,r)=>{gi("release",[t,r]);let n={type:"release",in:e};Dn.postMessage(n)});$c(e)},eh=async(e,t,r,n,s,a)=>{if(js()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return wi(),new Promise((i,u)=>{gi("run",[i,u]);let d=r,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:a}};Dn.postMessage(p,Ac(d))})}else return kc(e,t,r,n,s,a)},th=async e=>{if(js())return wi(),new Promise((t,r)=>{gi("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Dn.postMessage(n)});Pc(e)}}),Fc,nh,sh,Hf=R(()=>{Pt(),rh(),Xt(),cr(),_s(),Fc=(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()}`)}},nh=e=>{switch(e[3]){case"cpu":return new ee(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!hs(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return ee.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!fs(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return ee.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},sh=class{async fetchModelAndCopyToWasmMemory(e){return Yp(await ms(e))}async loadModel(e,t){Ue();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await Jp(r,t),je()}async dispose(){return Zp(this.sessionId)}async run(e,t,r){Ue();let n=[],s=[];Object.entries(e).forEach(w=>{let l=w[0],M=w[1],C=this.inputNames.indexOf(l);if(C===-1)throw new Error(`invalid input '${l}'`);n.push(M),s.push(C)});let a=[],i=[];Object.entries(t).forEach(w=>{let l=w[0],M=w[1],C=this.outputNames.indexOf(l);if(C===-1)throw new Error(`invalid output '${l}'`);a.push(M),i.push(C)});let u=n.map((w,l)=>Fc(w,()=>`input "${this.inputNames[s[l]]}"`)),d=a.map((w,l)=>w?Fc(w,()=>`output "${this.outputNames[i[l]]}"`):null),p=await eh(this.sessionId,s,u,i,d,r),g={};for(let w=0;wOc,initializeFlags:()=>zc,wasmBackend:()=>ah});var zc,Oc,ah,Kf=R(()=>{Pt(),rh(),Hf(),Gt(),zc=()=>{if((typeof k.wasm.initTimeout!="number"||k.wasm.initTimeout<0)&&(k.wasm.initTimeout=0),k.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof k.wasm.proxy!="boolean"&&(k.wasm.proxy=!1),typeof k.wasm.trace!="boolean"&&(k.wasm.trace=!1),typeof k.wasm.numThreads!="number"||!Number.isInteger(k.wasm.numThreads)||k.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)k.wasm.numThreads=1;else{let e=typeof navigator>"u"?Ce("node:os").cpus().length:navigator.hardwareConcurrency;k.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Oc=class{async init(e){zc(),await Xp(),await Qp(e)}async createInferenceSessionHandler(e,t){let r=new sh;return await r.loadModel(e,t),Promise.resolve(r)}},ah=new Oc});Pt(),Pt(),Pt();var Xf="1.20.0-dev.20240928-1bda91fc57",Qf=At;{let e=(Kf(),P(ih)).wasmBackend;_e("webgpu",e,5),_e("webnn",e,5),_e("cpu",e,10),_e("wasm",e,10)}Object.defineProperty(k.versions,"web",{value:Xf,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":(Ft,Ee,N)=>{var z;N.r(Ee),N.d(Ee,{Tensor:()=>Ce.Tensor,createInferenceSession:()=>ce,deviceToExecutionProviders:()=>ne,isONNXProxy:()=>te,isONNXTensor:()=>D});var me=N("./src/env.js"),we=N("?2ce3"),Te=N("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Ce=N("./node_modules/onnxruntime-common/dist/esm/index.js");const R=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"}}),S=[];let V,P;if(me.apis.IS_NODE_ENV){switch(P=we??(z||(z=N.t(we,2))),process.platform){case"win32":S.push("dml");break;case"linux":process.arch==="x64"&&S.push("cuda");break}S.push("cpu"),V=["cpu"]}else P=Te,me.apis.IS_WEBNN_AVAILABLE&&S.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),me.apis.IS_WEBGPU_AVAILABLE&&S.push("webgpu"),S.push("wasm"),V=["wasm"];const re=P.InferenceSession;function ne(ie=null){if(!ie)return V;switch(ie){case"auto":return S;case"gpu":return S.filter(X=>["webgpu","cuda","dml","webnn-gpu"].includes(X))}if(S.includes(ie))return[R[ie]??ie];throw new Error(`Unsupported device: "${ie}". Should be one of: ${S.join(", ")}.`)}let _e=null;async function ce(ie,X){_e&&await _e;const j=re.create(ie,X);return _e??(_e=j),await j}function D(ie){return ie instanceof P.Tensor}const q=P==null?void 0:P.env;q!=null&&q.wasm&&(q.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${me.env.version}/dist/`,q.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(q.wasm.numThreads=1)),q!=null&&q.webgpu&&(q.webgpu.powerPreference="high-performance");function te(){var ie;return(ie=q==null?void 0:q.wasm)==null?void 0:ie.proxy}me.env.backends.onnx=q},"./src/configs.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{AutoConfig:()=>S,PretrainedConfig:()=>R,getKeyValueShapes:()=>Ce});var z=N("./src/utils/core.js"),me=N("./src/utils/hub.js");async function we(V,P){return await(0,me.getModelJSON)(V,"config.json",!0,P)}function Te(V){const P={};let re={};switch(V.model_type){case"llava":case"paligemma":case"florence2":re=Te(V.text_config);break;case"moondream1":re=Te(V.phi_config);break;case"musicgen":re=Te(V.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":P.num_heads="num_attention_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size",P.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.dim_kv="head_dim";break;case"openelm":P.num_heads="num_kv_heads",P.num_layers="num_transformer_layers",P.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":P.num_heads="num_heads",P.num_layers="num_layers",P.hidden_size="hidden_size";break;case"bloom":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="hidden_size";break;case"mpt":P.num_heads="n_heads",P.num_layers="n_layers",P.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":P.num_decoder_layers="num_decoder_layers",P.num_decoder_heads="num_heads",P.decoder_dim_kv="d_kv",P.num_encoder_layers="num_layers",P.num_encoder_heads="num_heads",P.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":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="d_model",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="d_model";break;case"speecht5":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="hidden_size",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="hidden_size";break;case"trocr":P.num_encoder_layers=P.num_decoder_layers="decoder_layers",P.num_encoder_heads=P.num_decoder_heads="decoder_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="d_model";break;case"musicgen_decoder":P.num_encoder_layers=P.num_decoder_layers="num_hidden_layers",P.num_encoder_heads=P.num_decoder_heads="num_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const _e=Te(V.decoder),ce="num_decoder_layers"in _e,D=(0,z.pick)(V,["model_type","is_encoder_decoder"]);return ce?(D.num_decoder_layers=_e.num_decoder_layers,D.num_decoder_heads=_e.num_decoder_heads,D.decoder_hidden_size=_e.decoder_hidden_size,D.num_encoder_layers=_e.num_encoder_layers,D.num_encoder_heads=_e.num_encoder_heads,D.encoder_hidden_size=_e.encoder_hidden_size):(D.num_layers=_e.num_layers,D.num_heads=_e.num_heads,D.hidden_size=_e.hidden_size),D}const ne={...re,...(0,z.pick)(V,["model_type","multi_query","is_encoder_decoder"])};for(const _e in P)ne[_e]=V[P[_e]];return ne}function Ce(V,{prefix:P="past_key_values"}={}){const re={},ne=V.normalized_config,_e=1;if(ne.is_encoder_decoder&&"num_encoder_heads"in ne&&"num_decoder_heads"in ne){const ce=ne.encoder_dim_kv??ne.encoder_hidden_size/ne.num_encoder_heads,D=ne.decoder_dim_kv??ne.decoder_hidden_size/ne.num_decoder_heads,q=[_e,ne.num_encoder_heads,0,ce],te=[_e,ne.num_decoder_heads,0,D];for(let ie=0;ie{var k;N.r(Ee),N.d(Ee,{apis:()=>D,env:()=>I});var z=N("?569f"),me=N("?3f59"),we=N("?154a");const Te="3.0.0-alpha.19",Ce=typeof self<"u",R=Ce&&self.constructor.name==="DedicatedWorkerGlobalScope",S=Ce&&"caches"in self,V=typeof navigator<"u"&&"gpu"in navigator,P=typeof navigator<"u"&&"ml"in navigator,re=typeof process<"u",ne=re&&((k=process==null?void 0:process.release)==null?void 0:k.name)==="node",_e=!L(z),ce=!L(me),D=Object.freeze({IS_BROWSER_ENV:Ce,IS_WEBWORKER_ENV:R,IS_WEB_CACHE_AVAILABLE:S,IS_WEBGPU_AVAILABLE:V,IS_WEBNN_AVAILABLE:P,IS_PROCESS_AVAILABLE:re,IS_NODE_ENV:ne,IS_FS_AVAILABLE:_e,IS_PATH_AVAILABLE:ce}),q=_e&&ce,te=q?me.dirname(me.dirname(we.fileURLToPath(self.location.href))):"./",ie=q?me.join(te,"/.cache/"):null,X="/models/",j=q?me.join(te,X):X,I={version:Te,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ce,localModelPath:j,useFS:_e,useBrowserCache:S,useFSCache:_e,cacheDir:ie,useCustomCache:!1,customCache:null};function L(de){return Object.keys(de).length===0}},"./src/generation/configuration_utils.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{GenerationConfig:()=>me});var z=N("./src/utils/core.js");class me{constructor(Te){Me(this,"max_length",20);Me(this,"max_new_tokens",null);Me(this,"min_length",0);Me(this,"min_new_tokens",null);Me(this,"early_stopping",!1);Me(this,"max_time",null);Me(this,"do_sample",!1);Me(this,"num_beams",1);Me(this,"num_beam_groups",1);Me(this,"penalty_alpha",null);Me(this,"use_cache",!0);Me(this,"temperature",1);Me(this,"top_k",50);Me(this,"top_p",1);Me(this,"typical_p",1);Me(this,"epsilon_cutoff",0);Me(this,"eta_cutoff",0);Me(this,"diversity_penalty",0);Me(this,"repetition_penalty",1);Me(this,"encoder_repetition_penalty",1);Me(this,"length_penalty",1);Me(this,"no_repeat_ngram_size",0);Me(this,"bad_words_ids",null);Me(this,"force_words_ids",null);Me(this,"renormalize_logits",!1);Me(this,"constraints",null);Me(this,"forced_bos_token_id",null);Me(this,"forced_eos_token_id",null);Me(this,"remove_invalid_values",!1);Me(this,"exponential_decay_length_penalty",null);Me(this,"suppress_tokens",null);Me(this,"begin_suppress_tokens",null);Me(this,"forced_decoder_ids",null);Me(this,"guidance_scale",null);Me(this,"num_return_sequences",1);Me(this,"output_attentions",!1);Me(this,"output_hidden_states",!1);Me(this,"output_scores",!1);Me(this,"return_dict_in_generate",!1);Me(this,"pad_token_id",null);Me(this,"bos_token_id",null);Me(this,"eos_token_id",null);Me(this,"encoder_no_repeat_ngram_size",0);Me(this,"decoder_start_token_id",null);Me(this,"generation_kwargs",{});Object.assign(this,(0,z.pick)(Te,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{ClassifierFreeGuidanceLogitsProcessor:()=>q,ForcedBOSTokenLogitsProcessor:()=>R,ForcedEOSTokenLogitsProcessor:()=>S,LogitsProcessor:()=>we,LogitsProcessorList:()=>Ce,LogitsWarper:()=>Te,MinLengthLogitsProcessor:()=>_e,MinNewTokensLengthLogitsProcessor:()=>ce,NoBadWordsLogitsProcessor:()=>D,NoRepeatNGramLogitsProcessor:()=>re,RepetitionPenaltyLogitsProcessor:()=>ne,SuppressTokensAtBeginLogitsProcessor:()=>V,TemperatureLogitsWarper:()=>te,TopKLogitsWarper:()=>X,TopPLogitsWarper:()=>ie,WhisperTimeStampLogitsProcessor:()=>P});var z=N("./src/utils/generic.js");N("./src/utils/tensor.js");var me=N("./src/utils/maths.js");class we extends z.Callable{_call(I,L){throw Error("`_call` should be implemented in a subclass")}}class Te extends z.Callable{_call(I,L){throw Error("`_call` should be implemented in a subclass")}}class Ce extends z.Callable{constructor(){super(),this.processors=[]}push(I){this.processors.push(I)}extend(I){this.processors.push(...I)}_call(I,L){let k=L;for(const de of this.processors)k=de(I,k);return k}[Symbol.iterator](){return this.processors.values()}}class R extends we{constructor(I){super(),this.bos_token_id=I}_call(I,L){for(let k=0;k=1&&ve[ve.length-1]>=this.timestamp_begin,ze=ve.length<2||ve[ve.length-2]>=this.timestamp_begin;if(ke&&(ze?de.subarray(this.timestamp_begin).fill(-1/0):de.subarray(0,this.eos_token_id).fill(-1/0)),I[k].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ut=this.timestamp_begin+this.max_initial_timestamp_index;de.subarray(ut+1).fill(-1/0)}const Ie=(0,me.log_softmax)(de),Ze=Math.log(Ie.subarray(this.timestamp_begin).map(Math.exp).reduce((ut,ye)=>ut+ye)),Ke=(0,me.max)(Ie.subarray(0,this.timestamp_begin))[0];Ze>Ke&&de.subarray(0,this.timestamp_begin).fill(-1/0)}return L}}class re extends we{constructor(I){super(),this.no_repeat_ngram_size=I}getNgrams(I){const L=I.length,k=[];for(let ve=0;ve1 to use the classifier free guidance processor, got guidance scale ${I}.`);this.guidance_scale=I}_call(I,L){if(L.dims[0]!==2*I.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${L.dims[0]} for the logits and ${I.length} for the input ids.`);const k=I.length,de=L.slice([0,k],null),ve=L.slice([k,L.dims[0]],null);for(let ke=0;ke1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${I}`);if(!Number.isInteger(k)||k<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${k}`);this.top_p=I,this.filter_value=L,this.min_tokens_to_keep=k}}class X extends Te{constructor(I,{filter_value:L=-1/0,min_tokens_to_keep:k=1}={}){if(super(),!Number.isInteger(I)||I<0)throw new Error(`\`top_k\` must be a positive integer, but is ${I}`);this.top_k=Math.max(I,k),this.filter_value=L}}},"./src/generation/logits_sampler.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{LogitsSampler:()=>Te});var z=N("./src/utils/generic.js"),me=N("./src/utils/tensor.js"),we=N("./src/utils/maths.js");N("./src/generation/configuration_utils.js");class Te extends z.Callable{constructor(P){super(),this.generation_config=P}async _call(P){return this.sample(P)}async sample(P){throw Error("sample should be implemented in subclasses.")}getLogits(P,re){let ne=P.dims.at(-1),_e=P.data;if(re===-1)_e=_e.slice(-ne);else{let ce=re*ne;_e=_e.slice(ce,ce+ne)}return _e}randomSelect(P){let re=0;for(let _e=0;_e1)return new S(P);if(P.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${P.num_return_sequences}.`);return new Ce(P)}}class Ce extends Te{async sample(P){const re=(0,we.max)(P.data)[1];return[[BigInt(re),0]]}}class R extends Te{async sample(P){let re=P.dims.at(-1);this.generation_config.top_k>0&&(re=Math.min(this.generation_config.top_k,re));const[ne,_e]=await(0,me.topk)(P,re),ce=(0,we.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},()=>{const D=this.randomSelect(ce);return[_e.data[D],Math.log(ce[D])]})}}class S extends Te{async sample(P){let re=P.dims.at(-1);this.generation_config.top_k>0&&(re=Math.min(this.generation_config.top_k,re));const[ne,_e]=await(0,me.topk)(P,re),ce=(0,we.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},(D,q)=>[_e.data[q],Math.log(ce[q])])}}},"./src/generation/stopping_criteria.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{EosTokenCriteria:()=>Ce,InterruptableStoppingCriteria:()=>R,MaxLengthCriteria:()=>Te,StoppingCriteria:()=>me,StoppingCriteriaList:()=>we});var z=N("./src/utils/generic.js");class me extends z.Callable{_call(V,P){throw Error("StoppingCriteria needs to be subclassed")}}class we extends z.Callable{constructor(){super(),this.criteria=[]}push(V){this.criteria.push(V)}extend(V){V instanceof we?V=V.criteria:V instanceof me&&(V=[V]),this.criteria.push(...V)}_call(V,P){const re=new Array(V.length).fill(!1);for(const ne of this.criteria){const _e=ne(V,P);for(let ce=0;ceP.length>=this.max_length)}}class Ce extends me{constructor(V){super(),Array.isArray(V)||(V=[V]),this.eos_token_id=V}_call(V,P){return V.map(re=>{const ne=re.at(-1);return this.eos_token_id.some(_e=>ne==_e)})}}class R extends me{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(V,P){return new Array(V.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{BaseStreamer:()=>Te,TextStreamer:()=>R,WhisperTextStreamer:()=>S});var z=N("./src/utils/core.js"),me=N("./src/tokenizers.js"),we=N("./src/env.js");class Te{put(P){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Ce=we.apis.IS_PROCESS_AVAILABLE?V=>process.stdout.write(V):V=>console.log(V);class R extends Te{constructor(P,{skip_prompt:re=!1,callback_function:ne=null,token_callback_function:_e=null,decode_kwargs:ce={},...D}={}){super(),this.tokenizer=P,this.skip_prompt=re,this.callback_function=ne??Ce,this.token_callback_function=_e,this.decode_kwargs={...ce,...D},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(P){var ce;if(P.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 re=P[0];(ce=this.token_callback_function)==null||ce.call(this,re),this.token_cache=(0,z.mergeArrays)(this.token_cache,re);const ne=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let _e;ne.endsWith(` +`)?(_e=ne.slice(this.print_len),this.token_cache=[],this.print_len=0):ne.length>0&&(0,me.is_chinese_char)(ne.charCodeAt(ne.length-1))?(_e=ne.slice(this.print_len),this.print_len+=_e.length):(_e=ne.slice(this.print_len,ne.lastIndexOf(" ")+1),this.print_len+=_e.length),this.on_finalized_text(_e,!1)}end(){let P;this.token_cache.length>0?(P=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):P="",this.next_tokens_are_prompt=!0,this.on_finalized_text(P,!0)}on_finalized_text(P,re){var ne,_e;P.length>0&&((ne=this.callback_function)==null||ne.call(this,P)),re&&this.callback_function===Ce&&we.apis.IS_PROCESS_AVAILABLE&&((_e=this.callback_function)==null||_e.call(this,` +`))}}class S extends R{constructor(P,{skip_prompt:re=!1,callback_function:ne=null,token_callback_function:_e=null,on_chunk_start:ce=null,on_chunk_end:D=null,on_finalize:q=null,time_precision:te=.02,skip_special_tokens:ie=!0,decode_kwargs:X={}}={}){super(P,{skip_prompt:re,callback_function:ne,token_callback_function:_e,decode_kwargs:{skip_special_tokens:ie,...X}}),this.timestamp_begin=P.timestamp_begin,this.on_chunk_start=ce,this.on_chunk_end=D,this.on_finalize=q,this.time_precision=te,this.waiting_for_timestamp=!1}put(P){var ne,_e;if(P.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const re=P[0];if(re.length===1){const ce=Number(re[0])-this.timestamp_begin;if(ce>=0){const D=ce*this.time_precision;this.waiting_for_timestamp?(ne=this.on_chunk_end)==null||ne.call(this,D):(_e=this.on_chunk_start)==null||_e.call(this,D),this.waiting_for_timestamp=!this.waiting_for_timestamp,P=[[]]}}return super.put(P)}end(){var P;super.end(),(P=this.on_finalize)==null||P.call(this)}}},"./src/models.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{ASTForAudioClassification:()=>Xn,ASTModel:()=>Kn,ASTPreTrainedModel:()=>Hn,AlbertForMaskedLM:()=>fs,AlbertForQuestionAnswering:()=>hs,AlbertForSequenceClassification:()=>ts,AlbertModel:()=>ps,AlbertPreTrainedModel:()=>Cn,AutoModel:()=>Uu,AutoModelForAudioClassification:()=>sd,AutoModelForAudioFrameClassification:()=>ad,AutoModelForCTC:()=>nd,AutoModelForCausalLM:()=>Ku,AutoModelForDepthEstimation:()=>Rs,AutoModelForDocumentQuestionAnswering:()=>od,AutoModelForImageClassification:()=>Yu,AutoModelForImageFeatureExtraction:()=>Qa,AutoModelForImageMatting:()=>ld,AutoModelForImageSegmentation:()=>Ju,AutoModelForImageToImage:()=>Ud,AutoModelForMaskGeneration:()=>rd,AutoModelForMaskedLM:()=>Xu,AutoModelForNormalEstimation:()=>Xa,AutoModelForObjectDetection:()=>ed,AutoModelForQuestionAnswering:()=>jd,AutoModelForSemanticSegmentation:()=>Zu,AutoModelForSeq2SeqLM:()=>Gu,AutoModelForSequenceClassification:()=>Ka,AutoModelForSpeechSeq2Seq:()=>qu,AutoModelForTextToSpectrogram:()=>Nd,AutoModelForTextToWaveform:()=>Hu,AutoModelForTokenClassification:()=>Wu,AutoModelForUniversalSegmentation:()=>Vd,AutoModelForVision2Seq:()=>Qu,AutoModelForXVector:()=>id,AutoModelForZeroShotObjectDetection:()=>td,BartForConditionalGeneration:()=>m,BartForSequenceClassification:()=>A,BartModel:()=>ue,BartPretrainedModel:()=>ns,BaseModelOutput:()=>dt,BeitForImageClassification:()=>al,BeitModel:()=>il,BeitPreTrainedModel:()=>ta,BertForMaskedLM:()=>Re,BertForQuestionAnswering:()=>qe,BertForSequenceClassification:()=>ht,BertForTokenClassification:()=>bt,BertModel:()=>ot,BertPreTrainedModel:()=>nt,BlenderbotForConditionalGeneration:()=>Ot,BlenderbotModel:()=>Mt,BlenderbotPreTrainedModel:()=>xt,BlenderbotSmallForConditionalGeneration:()=>ar,BlenderbotSmallModel:()=>$r,BlenderbotSmallPreTrainedModel:()=>Yt,BloomForCausalLM:()=>Md,BloomModel:()=>Wi,BloomPreTrainedModel:()=>Ui,CLIPModel:()=>Ei,CLIPPreTrainedModel:()=>ss,CLIPSegForImageSegmentation:()=>ho,CLIPSegModel:()=>po,CLIPSegPreTrainedModel:()=>Si,CLIPTextModel:()=>yd,CLIPTextModelWithProjection:()=>ao,CLIPVisionModel:()=>bd,CLIPVisionModelWithProjection:()=>Pn,CamembertForMaskedLM:()=>cr,CamembertForQuestionAnswering:()=>Or,CamembertForSequenceClassification:()=>Er,CamembertForTokenClassification:()=>Qr,CamembertModel:()=>Pt,CamembertPreTrainedModel:()=>At,CausalLMOutput:()=>os,CausalLMOutputWithPast:()=>Wd,ChineseCLIPModel:()=>co,ChineseCLIPPreTrainedModel:()=>uo,ClapAudioModelWithProjection:()=>fu,ClapModel:()=>pu,ClapPreTrainedModel:()=>$a,ClapTextModelWithProjection:()=>hu,CodeGenForCausalLM:()=>Fn,CodeGenModel:()=>zi,CodeGenPreTrainedModel:()=>zs,CohereForCausalLM:()=>So,CohereModel:()=>$o,CoherePreTrainedModel:()=>Di,ConvBertForMaskedLM:()=>x,ConvBertForQuestionAnswering:()=>Q,ConvBertForSequenceClassification:()=>H,ConvBertForTokenClassification:()=>$,ConvBertModel:()=>Et,ConvBertPreTrainedModel:()=>vt,ConvNextForImageClassification:()=>Cd,ConvNextModel:()=>Ol,ConvNextPreTrainedModel:()=>ma,ConvNextV2ForImageClassification:()=>Yn,ConvNextV2Model:()=>Qn,ConvNextV2PreTrainedModel:()=>jn,DPTForDepthEstimation:()=>vl,DPTModel:()=>On,DPTPreTrainedModel:()=>ha,DebertaForMaskedLM:()=>U,DebertaForQuestionAnswering:()=>et,DebertaForSequenceClassification:()=>ge,DebertaForTokenClassification:()=>Ae,DebertaModel:()=>at,DebertaPreTrainedModel:()=>Ur,DebertaV2ForMaskedLM:()=>gt,DebertaV2ForQuestionAnswering:()=>ft,DebertaV2ForSequenceClassification:()=>mt,DebertaV2ForTokenClassification:()=>$t,DebertaV2Model:()=>Xe,DebertaV2PreTrainedModel:()=>xe,DecisionTransformerModel:()=>Cu,DecisionTransformerPreTrainedModel:()=>zd,DeiTForImageClassification:()=>ua,DeiTModel:()=>la,DeiTPreTrainedModel:()=>oa,DepthAnythingForDepthEstimation:()=>Tl,DepthAnythingPreTrainedModel:()=>xl,DetrForObjectDetection:()=>ll,DetrForSegmentation:()=>ra,DetrModel:()=>ol,DetrObjectDetectionOutput:()=>na,DetrPreTrainedModel:()=>ei,DetrSegmentationOutput:()=>ul,Dinov2ForImageClassification:()=>fn,Dinov2Model:()=>Jn,Dinov2PreTrainedModel:()=>ni,DistilBertForMaskedLM:()=>tt,DistilBertForQuestionAnswering:()=>be,DistilBertForSequenceClassification:()=>Rt,DistilBertForTokenClassification:()=>Gt,DistilBertModel:()=>Nt,DistilBertPreTrainedModel:()=>zt,DonutSwinModel:()=>zl,DonutSwinPreTrainedModel:()=>Fl,EfficientNetForImageClassification:()=>wu,EfficientNetModel:()=>za,EfficientNetPreTrainedModel:()=>Fa,ElectraForMaskedLM:()=>Je,ElectraForQuestionAnswering:()=>Tt,ElectraForSequenceClassification:()=>Bt,ElectraForTokenClassification:()=>ct,ElectraModel:()=>Ye,ElectraPreTrainedModel:()=>he,EsmForMaskedLM:()=>wr,EsmForSequenceClassification:()=>Br,EsmForTokenClassification:()=>Kr,EsmModel:()=>qt,EsmPreTrainedModel:()=>st,FalconForCausalLM:()=>cu,FalconModel:()=>du,FalconPreTrainedModel:()=>Ea,FastViTForImageClassification:()=>Xo,FastViTModel:()=>Ko,FastViTPreTrainedModel:()=>Yi,Florence2ForConditionalGeneration:()=>or,Florence2PreTrainedModel:()=>Fs,GLPNForDepthEstimation:()=>Il,GLPNModel:()=>Al,GLPNPreTrainedModel:()=>Pl,GPT2LMHeadModel:()=>mo,GPT2Model:()=>fo,GPT2PreTrainedModel:()=>ki,GPTBigCodeForCausalLM:()=>To,GPTBigCodeModel:()=>In,GPTBigCodePreTrainedModel:()=>xo,GPTJForCausalLM:()=>vo,GPTJModel:()=>Mo,GPTJPreTrainedModel:()=>Fi,GPTNeoForCausalLM:()=>wo,GPTNeoModel:()=>go,GPTNeoPreTrainedModel:()=>Ai,GPTNeoXForCausalLM:()=>bo,GPTNeoXModel:()=>yo,GPTNeoXPreTrainedModel:()=>Ii,Gemma2ForCausalLM:()=>Ao,Gemma2Model:()=>zn,Gemma2PreTrainedModel:()=>Bi,GemmaForCausalLM:()=>Po,GemmaModel:()=>ko,GemmaPreTrainedModel:()=>Li,GroupViTModel:()=>vr,GroupViTPreTrainedModel:()=>Ho,HieraForImageClassification:()=>_l,HieraModel:()=>ml,HieraPreTrainedModel:()=>da,HubertForCTC:()=>Jl,HubertForSequenceClassification:()=>Zl,HubertModel:()=>va,HubertPreTrainedModel:()=>Yl,ImageMattingOutput:()=>Ya,JAISLMHeadModel:()=>_o,JAISModel:()=>An,JAISPreTrainedModel:()=>Pi,LlamaForCausalLM:()=>Eo,LlamaModel:()=>Co,LlamaPreTrainedModel:()=>Oi,LlavaForConditionalGeneration:()=>Ci,LlavaPreTrainedModel:()=>Ti,LongT5ForConditionalGeneration:()=>As,LongT5Model:()=>Ps,LongT5PreTrainedModel:()=>_s,M2M100ForConditionalGeneration:()=>ui,M2M100Model:()=>wa,M2M100PreTrainedModel:()=>ga,MBartForCausalLM:()=>wt,MBartForConditionalGeneration:()=>pe,MBartForSequenceClassification:()=>De,MBartModel:()=>se,MBartPreTrainedModel:()=>K,MPNetForMaskedLM:()=>Xs,MPNetForQuestionAnswering:()=>Ss,MPNetForSequenceClassification:()=>Es,MPNetForTokenClassification:()=>$s,MPNetModel:()=>Cs,MPNetPreTrainedModel:()=>Bn,MT5ForConditionalGeneration:()=>ws,MT5Model:()=>Is,MT5PreTrainedModel:()=>gs,MarianMTModel:()=>li,MarianModel:()=>Rl,MarianPreTrainedModel:()=>oi,MaskFormerForInstanceSegmentation:()=>kl,MaskFormerModel:()=>Sl,MaskFormerPreTrainedModel:()=>fa,MaskedLMOutput:()=>an,MistralForCausalLM:()=>lu,MistralModel:()=>ou,MistralPreTrainedModel:()=>Ta,MobileBertForMaskedLM:()=>Vr,MobileBertForQuestionAnswering:()=>Rr,MobileBertForSequenceClassification:()=>Ln,MobileBertModel:()=>Wr,MobileBertPreTrainedModel:()=>rr,MobileNetV1ForImageClassification:()=>bu,MobileNetV1Model:()=>yu,MobileNetV1PreTrainedModel:()=>mi,MobileNetV2ForImageClassification:()=>Mu,MobileNetV2Model:()=>Id,MobileNetV2PreTrainedModel:()=>La,MobileNetV3ForImageClassification:()=>vu,MobileNetV3Model:()=>Fd,MobileNetV3PreTrainedModel:()=>Ba,MobileNetV4ForImageClassification:()=>Tu,MobileNetV4Model:()=>xu,MobileNetV4PreTrainedModel:()=>Ra,MobileViTForImageClassification:()=>Zo,MobileViTModel:()=>Jo,MobileViTPreTrainedModel:()=>Ji,MobileViTV2ForImageClassification:()=>tl,MobileViTV2Model:()=>el,MobileViTV2PreTrainedModel:()=>Zi,ModelOutput:()=>He,Moondream1ForConditionalGeneration:()=>io,MptForCausalLM:()=>No,MptModel:()=>Ro,MptPreTrainedModel:()=>Gi,MusicgenForCausalLM:()=>wc,MusicgenForConditionalGeneration:()=>Da,MusicgenModel:()=>Ad,MusicgenPreTrainedModel:()=>Oa,NomicBertModel:()=>Pe,NomicBertPreTrainedModel:()=>ee,OPTForCausalLM:()=>jo,OPTModel:()=>Os,OPTPreTrainedModel:()=>qi,OpenELMForCausalLM:()=>Fo,OpenELMModel:()=>Io,OpenELMPreTrainedModel:()=>Ri,OwlViTForObjectDetection:()=>nl,OwlViTModel:()=>rl,OwlViTPreTrainedModel:()=>ea,Owlv2ForObjectDetection:()=>Zs,Owlv2Model:()=>sl,Owlv2PreTrainedModel:()=>ys,Phi3ForCausalLM:()=>Bo,Phi3Model:()=>Vi,Phi3PreTrainedModel:()=>Js,PhiForCausalLM:()=>Lo,PhiModel:()=>Do,PhiPreTrainedModel:()=>ji,PreTrainedModel:()=>Y,PretrainedMixin:()=>Ir,PvtForImageClassification:()=>Wo,PvtModel:()=>Uo,PvtPreTrainedModel:()=>Xi,PyAnnoteForAudioFrameClassification:()=>ba,PyAnnoteModel:()=>Vl,PyAnnotePreTrainedModel:()=>bs,QuestionAnsweringModelOutput:()=>cn,Qwen2ForCausalLM:()=>Oo,Qwen2Model:()=>zo,Qwen2PreTrainedModel:()=>Ni,RTDetrForObjectDetection:()=>cl,RTDetrModel:()=>dl,RTDetrObjectDetectionOutput:()=>pl,RTDetrPreTrainedModel:()=>sa,ResNetForImageClassification:()=>wl,ResNetModel:()=>gl,ResNetPreTrainedModel:()=>ca,RoFormerForMaskedLM:()=>Ue,RoFormerForQuestionAnswering:()=>yt,RoFormerForSequenceClassification:()=>je,RoFormerForTokenClassification:()=>lt,RoFormerModel:()=>Qe,RoFormerPreTrainedModel:()=>Ne,RobertaForMaskedLM:()=>ur,RobertaForQuestionAnswering:()=>wn,RobertaForSequenceClassification:()=>Sr,RobertaForTokenClassification:()=>_n,RobertaModel:()=>Jr,RobertaPreTrainedModel:()=>Dr,SamImageSegmentationOutput:()=>ai,SamModel:()=>Bl,SamPreTrainedModel:()=>Ll,SapiensForDepthEstimation:()=>El,SapiensForNormalEstimation:()=>$l,SapiensForSemanticSegmentation:()=>Cl,SapiensPreTrainedModel:()=>ri,SegformerForImageClassification:()=>Ls,SegformerForSemanticSegmentation:()=>Aa,SegformerModel:()=>Pa,SegformerPreTrainedModel:()=>ka,Seq2SeqLMOutput:()=>ud,SequenceClassifierOutput:()=>ir,SiglipModel:()=>oo,SiglipPreTrainedModel:()=>$i,SiglipTextModel:()=>is,SiglipVisionModel:()=>lo,SpeechT5ForSpeechToText:()=>nu,SpeechT5ForTextToSpeech:()=>su,SpeechT5HifiGan:()=>iu,SpeechT5Model:()=>gc,SpeechT5PreTrainedModel:()=>Ds,SqueezeBertForMaskedLM:()=>Qs,SqueezeBertForQuestionAnswering:()=>Sn,SqueezeBertForSequenceClassification:()=>qn,SqueezeBertModel:()=>ks,SqueezeBertPreTrainedModel:()=>Gn,StableLmForCausalLM:()=>gu,StableLmModel:()=>_u,StableLmPreTrainedModel:()=>Ia,Starcoder2ForCausalLM:()=>Pd,Starcoder2Model:()=>uu,Starcoder2PreTrainedModel:()=>Ca,Swin2SRForImageSuperResolution:()=>Ml,Swin2SRModel:()=>Td,Swin2SRPreTrainedModel:()=>pa,SwinForImageClassification:()=>bl,SwinModel:()=>yl,SwinPreTrainedModel:()=>ti,T5ForConditionalGeneration:()=>ms,T5Model:()=>Xt,T5PreTrainedModel:()=>rs,TableTransformerForObjectDetection:()=>fl,TableTransformerModel:()=>hl,TableTransformerObjectDetectionOutput:()=>aa,TableTransformerPreTrainedModel:()=>ia,TokenClassifierOutput:()=>sn,TrOCRForCausalLM:()=>au,TrOCRPreTrainedModel:()=>xa,UniSpeechForCTC:()=>Gl,UniSpeechForSequenceClassification:()=>ql,UniSpeechModel:()=>$d,UniSpeechPreTrainedModel:()=>di,UniSpeechSatForAudioFrameClassification:()=>Xl,UniSpeechSatForCTC:()=>Hl,UniSpeechSatForSequenceClassification:()=>Kl,UniSpeechSatModel:()=>Ma,UniSpeechSatPreTrainedModel:()=>ci,ViTForImageClassification:()=>Vo,ViTMAEModel:()=>Go,ViTMAEPreTrainedModel:()=>vd,ViTMSNForImageClassification:()=>xd,ViTMSNModel:()=>qo,ViTMSNPreTrainedModel:()=>Qi,ViTModel:()=>Ki,ViTPreTrainedModel:()=>Hi,VisionEncoderDecoderModel:()=>Ut,VitMatteForImageMatting:()=>Yo,VitMattePreTrainedModel:()=>Qo,VitsModel:()=>Sa,VitsModelOutput:()=>cd,VitsPreTrainedModel:()=>mu,Wav2Vec2BertForCTC:()=>Ql,Wav2Vec2BertForSequenceClassification:()=>fi,Wav2Vec2BertModel:()=>hi,Wav2Vec2BertPreTrainedModel:()=>pi,Wav2Vec2ForAudioFrameClassification:()=>ya,Wav2Vec2ForCTC:()=>Ed,Wav2Vec2ForSequenceClassification:()=>jl,Wav2Vec2Model:()=>Nl,Wav2Vec2PreTrainedModel:()=>Zn,WavLMForAudioFrameClassification:()=>ru,WavLMForCTC:()=>eu,WavLMForSequenceClassification:()=>tu,WavLMForXVector:()=>kd,WavLMModel:()=>Sd,WavLMPreTrainedModel:()=>as,WeSpeakerResNetModel:()=>Wl,WeSpeakerResNetPreTrainedModel:()=>Ul,WhisperForConditionalGeneration:()=>rt,WhisperModel:()=>Ys,WhisperPreTrainedModel:()=>jt,XLMForQuestionAnswering:()=>Ht,XLMForSequenceClassification:()=>kn,XLMForTokenClassification:()=>Nn,XLMModel:()=>Zr,XLMPreTrainedModel:()=>Se,XLMRobertaForMaskedLM:()=>yr,XLMRobertaForQuestionAnswering:()=>mr,XLMRobertaForSequenceClassification:()=>Ar,XLMRobertaForTokenClassification:()=>Ct,XLMRobertaModel:()=>Xr,XLMRobertaPreTrainedModel:()=>en,XLMWithLMHeadModel:()=>xn,XVectorOutput:()=>dd,YolosForObjectDetection:()=>_a,YolosModel:()=>ii,YolosObjectDetectionOutput:()=>Dl,YolosPreTrainedModel:()=>si});var z=N("./src/configs.js"),me=N("./src/backends/onnx.js"),we=N("./src/utils/dtypes.js"),Te=N("./src/utils/generic.js"),Ce=N("./src/utils/core.js"),R=N("./src/utils/hub.js"),S=N("./src/generation/logits_process.js"),V=N("./src/generation/configuration_utils.js"),P=N("./src/utils/tensor.js"),re=N("./src/utils/maths.js"),ne=N("./src/generation/stopping_criteria.js"),_e=N("./src/generation/logits_sampler.js"),ce=N("./src/env.js"),D=N("./src/models/whisper/generation_whisper.js"),q=N("./src/models/whisper/common_whisper.js");const te={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},ie=new Map,X=new Map,j=new Map;async function I(f,_,T){var Tr;const J=((Tr=T.config)==null?void 0:Tr["transformers.js_config"])??{};let Fe=T.device??J.device;Fe&&typeof Fe!="string"&&(Fe.hasOwnProperty(_)?Fe=Fe[_]:(console.warn(`device not specified for "${_}". Using the default device.`),Fe=null));const Oe=Fe??(ce.apis.IS_NODE_ENV?"cpu":"wasm"),_t=(0,me.deviceToExecutionProviders)(Oe);let St=T.dtype??J.dtype;typeof St!="string"&&(St&&St.hasOwnProperty(_)?St=St[_]:(St=we.DEFAULT_DEVICE_DTYPE_MAPPING[Oe]??we.DATA_TYPES.fp32,console.warn(`dtype not specified for "${_}". Using the default dtype (${St}) for this device (${Oe}).`)));const Wt=St;if(we.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Wt)){if(Wt===we.DATA_TYPES.fp16&&Oe==="webgpu"&&!await(0,we.isWebGpuFp16Supported)())throw new Error(`The device (${Oe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Wt}. Should be one of: ${Object.keys(we.DATA_TYPES).join(", ")}`);const nr=we.DEFAULT_DTYPE_SUFFIX_MAPPING[Wt],kr=`${T.subfolder??""}/${_}${nr}.onnx`,pr={...T.session_options};pr.executionProviders??(pr.executionProviders=_t);const hr=J.free_dimension_overrides;hr?pr.freeDimensionOverrides??(pr.freeDimensionOverrides=hr):Oe.startsWith("webnn")&&!pr.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,R.getModelFile)(f,kr,!0,T);let xr=[];if(T.use_external_data_format&&(T.use_external_data_format===!0||typeof T.use_external_data_format=="object"&&T.use_external_data_format.hasOwnProperty(_)&&T.use_external_data_format[_]===!0)){if(ce.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const gr=`${_}${nr}.onnx_data`,rn=`${T.subfolder??""}/${gr}`;xr.push(new Promise(async(on,bn)=>{const pn=await(0,R.getModelFile)(f,rn,!0,T);on({path:gr,data:pn})}))}else pr.externalData!==void 0&&(xr=pr.externalData.map(async gr=>{if(typeof gr.data=="string"){const rn=await(0,R.getModelFile)(f,gr.data,!0,T);return{...gr,data:rn}}return gr}));if(xr.length>0&&(pr.externalData=await Promise.all(xr)),Oe==="webgpu"){const gr=(0,z.getKeyValueShapes)(T.config,{prefix:"present"});if(Object.keys(gr).length>0&&!(0,me.isONNXProxy)()){const rn={};for(const on in gr)rn[on]="gpu-buffer";pr.preferredOutputLocation=rn}}return{buffer:await _r,session_options:pr}}async function L(f,_,T){return Object.fromEntries(await Promise.all(Object.keys(_).map(async J=>{const{buffer:Fe,session_options:Oe}=await I(f,_[J],T),_t=await(0,me.createInferenceSession)(Fe,Oe);return[J,_t]})))}function k(f,_){const T=Object.create(null),J=[];for(const _t of f.inputNames){const St=_[_t];if(!(St instanceof P.Tensor)){J.push(_t);continue}T[_t]=(0,me.isONNXProxy)()?St.clone():St}if(J.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${J.join(", ")}.`);const Fe=Object.keys(_).length,Oe=f.inputNames.length;if(Fe>Oe){let _t=Object.keys(_).filter(St=>!f.inputNames.includes(St));console.warn(`WARNING: Too many inputs were provided (${Fe} > ${Oe}). The following inputs will be ignored: "${_t.join(", ")}".`)}return T}async function de(f,_){const T=k(f,_);try{const J=Object.fromEntries(Object.entries(T).map(([Oe,_t])=>[Oe,_t.ort_tensor]));let Fe=await f.run(J);return Fe=ve(Fe),Fe}catch(J){throw console.error(`An error occurred during model execution: "${J}".`),console.error("Inputs given to model:",T),J}}function ve(f){for(let _ in f)(0,me.isONNXTensor)(f[_])?f[_]=new P.Tensor(f[_]):typeof f[_]=="object"&&ve(f[_]);return f}function ke(f){if(f instanceof P.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(_=>_.length!==f[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new P.Tensor("int64",BigInt64Array.from(f.flat().map(_=>BigInt(_))),[f.length,f[0].length])}else return new P.Tensor("int64",BigInt64Array.from(f.map(_=>BigInt(_))),[1,f.length])}function ze(f){return new P.Tensor("bool",[f],[1])}async function Ie(f,_){let{encoder_outputs:T,input_ids:J,decoder_input_ids:Fe,...Oe}=_;if(!T){const St=(0,Ce.pick)(_,f.sessions.model.inputNames);T=(await Ze(f,St)).last_hidden_state}return Oe.input_ids=Fe,Oe.encoder_hidden_states=T,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Oe.encoder_attention_mask=_.attention_mask),await Ke(f,Oe,!0)}async function Ze(f,_){const T=f.sessions.model,J=(0,Ce.pick)(_,T.inputNames);if(T.inputNames.includes("inputs_embeds")&&!J.inputs_embeds){if(!_.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");J.inputs_embeds=await f.encode_text({input_ids:_.input_ids})}return T.inputNames.includes("token_type_ids")&&!J.token_type_ids&&(J.token_type_ids=new P.Tensor("int64",new BigInt64Array(J.input_ids.data.length),J.input_ids.dims)),await de(T,J)}async function Ke(f,_,T=!1){const J=f.sessions[T?"decoder_model_merged":"model"],{past_key_values:Fe,...Oe}=_;J.inputNames.includes("use_cache_branch")&&(Oe.use_cache_branch=ze(!!Fe)),J.inputNames.includes("position_ids")&&Oe.attention_mask&&!Oe.position_ids&&(Oe.position_ids=ye(Oe,Fe)),f.addPastKeyValues(Oe,Fe);const _t=(0,Ce.pick)(Oe,J.inputNames);return await de(J,_t)}async function ut(f,{input_ids:_=null,attention_mask:T=null,pixel_values:J=null,position_ids:Fe=null,inputs_embeds:Oe=null,past_key_values:_t=null,generation_config:St=null,logits_processor:Wt=null,...nr}){if(!Oe){if(Oe=await f.encode_text({input_ids:_}),J&&_.dims[1]!==1){const pr=await f.encode_image({pixel_values:J});({inputs_embeds:Oe,attention_mask:T}=f._merge_input_ids_with_image_features({image_features:pr,inputs_embeds:Oe,input_ids:_,attention_mask:T}))}else if(_t&&J&&_.dims[1]===1){const pr=_.dims[1],hr=Object.values(_t)[0].dims.at(-2);T=(0,P.cat)([(0,P.ones)([_.dims[0],hr]),T.slice(null,[T.dims[1]-pr,T.dims[1]])],1)}}return await Ke(f,{inputs_embeds:Oe,past_key_values:_t,attention_mask:T,position_ids:Fe,generation_config:St,logits_processor:Wt},!0)}function ye(f,_=null){const{input_ids:T,inputs_embeds:J,attention_mask:Fe}=f,[Oe,_t]=Fe.dims,St=new BigInt64Array(Fe.data.length);for(let nr=0;nrOe.dims[1])){if(FeSt==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 Wt=Oe.dims[1]-(Fe-St);T.input_ids=Oe.slice(null,[-Wt,null]),T.attention_mask=(0,P.ones)([1,Fe+Wt])}}}return T}function fe(f,_,T,J){return T.past_key_values&&(_=_.map(Fe=>[Fe.at(-1)])),{...T,decoder_input_ids:ke(_)}}function $e(f,..._){return f.config.is_encoder_decoder?fe(f,..._):W(f,..._)}class Y extends Te.Callable{constructor(T,J){super();Me(this,"main_input_name","input_ids");Me(this,"forward_params",["input_ids","attention_mask"]);this.config=T,this.sessions=J;const Fe=j.get(this.constructor),Oe=ie.get(Fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Oe){case te.DecoderOnly:this.can_generate=!0,this._forward=Ke,this._prepare_inputs_for_generation=W;break;case te.Seq2Seq:case te.Vision2Seq:case te.Musicgen:this.can_generate=!0,this._forward=Ie,this._prepare_inputs_for_generation=fe;break;case te.EncoderDecoder:this._forward=Ie;break;case te.ImageTextToText:this.can_generate=!0,this._forward=ut,this._prepare_inputs_for_generation=$e;break;default:this._forward=Ze;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var J;const T=[];for(const Fe of Object.values(this.sessions))(J=Fe==null?void 0:Fe.handler)!=null&&J.dispose&&T.push(Fe.handler.dispose());return await Promise.all(T)}static async from_pretrained(T,{progress_callback:J=null,config:Fe=null,cache_dir:Oe=null,local_files_only:_t=!1,revision:St="main",model_file_name:Wt=null,subfolder:nr="onnx",device:kr=null,dtype:pr=null,use_external_data_format:hr=null,session_options:_r={}}={}){let xr={progress_callback:J,config:Fe,cache_dir:Oe,local_files_only:_t,revision:St,model_file_name:Wt,subfolder:nr,device:kr,dtype:pr,use_external_data_format:hr,session_options:_r};const Fr=j.get(this),Tr=ie.get(Fr);Fe=xr.config=await z.AutoConfig.from_pretrained(T,xr);let gr;if(Tr===te.DecoderOnly)gr=await Promise.all([L(T,{model:xr.model_file_name??"model"},xr),(0,R.getModelJSON)(T,"generation_config.json",!1,xr)]);else if(Tr===te.Seq2Seq||Tr===te.Vision2Seq)gr=await Promise.all([L(T,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},xr),(0,R.getModelJSON)(T,"generation_config.json",!1,xr)]);else if(Tr===te.MaskGeneration)gr=await Promise.all([L(T,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},xr)]);else if(Tr===te.EncoderDecoder)gr=await Promise.all([L(T,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},xr)]);else if(Tr===te.ImageTextToText){const rn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Fe.is_encoder_decoder&&(rn.model="encoder_model"),gr=await Promise.all([L(T,rn,xr),(0,R.getModelJSON)(T,"generation_config.json",!1,xr)])}else Tr===te.Musicgen?gr=await Promise.all([L(T,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},xr),(0,R.getModelJSON)(T,"generation_config.json",!1,xr)]):(Tr!==te.EncoderOnly&&console.warn(`Model type for '${Fr??(Fe==null?void 0:Fe.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),gr=await Promise.all([L(T,{model:xr.model_file_name??"model"},xr)]));return new this(Fe,...gr)}async _call(T){return await this.forward(T)}async forward(T){return await this._forward(this,T)}_get_logits_warper(T){const J=new S.LogitsProcessorList;return T.temperature!==null&&T.temperature!==1&&J.push(new S.TemperatureLogitsWarper(T.temperature)),T.top_k!==null&&T.top_k!==0&&J.push(new S.TopKLogitsWarper(T.top_k)),T.top_p!==null&&T.top_p<1&&J.push(new S.TopPLogitsWarper(T.top_p)),J}_get_logits_processor(T,J,Fe=null){const Oe=new S.LogitsProcessorList;if(T.repetition_penalty!==null&&T.repetition_penalty!==1&&Oe.push(new S.RepetitionPenaltyLogitsProcessor(T.repetition_penalty)),T.no_repeat_ngram_size!==null&&T.no_repeat_ngram_size>0&&Oe.push(new S.NoRepeatNGramLogitsProcessor(T.no_repeat_ngram_size)),T.bad_words_ids!==null&&Oe.push(new S.NoBadWordsLogitsProcessor(T.bad_words_ids,T.eos_token_id)),T.min_length!==null&&T.eos_token_id!==null&&T.min_length>0&&Oe.push(new S.MinLengthLogitsProcessor(T.min_length,T.eos_token_id)),T.min_new_tokens!==null&&T.eos_token_id!==null&&T.min_new_tokens>0&&Oe.push(new S.MinNewTokensLengthLogitsProcessor(J,T.min_new_tokens,T.eos_token_id)),T.forced_bos_token_id!==null&&Oe.push(new S.ForcedBOSTokenLogitsProcessor(T.forced_bos_token_id)),T.forced_eos_token_id!==null&&Oe.push(new S.ForcedEOSTokenLogitsProcessor(T.max_length,T.forced_eos_token_id)),T.begin_suppress_tokens!==null){const _t=J>1||T.forced_bos_token_id===null?J:J+1;Oe.push(new S.SuppressTokensAtBeginLogitsProcessor(T.begin_suppress_tokens,_t))}return T.guidance_scale!==null&&T.guidance_scale>1&&Oe.push(new S.ClassifierFreeGuidanceLogitsProcessor(T.guidance_scale)),Fe!==null&&Oe.extend(Fe),Oe}_prepare_generation_config(T,J,Fe=V.GenerationConfig){const Oe={...this.config};for(const St of["decoder","generator","text_config"])St in Oe&&Object.assign(Oe,Oe[St]);const _t=new Fe(Oe);return"generation_config"in this&&Object.assign(_t,this.generation_config),T&&Object.assign(_t,T),J&&Object.assign(_t,(0,Ce.pick)(J,Object.getOwnPropertyNames(_t))),_t}_get_stopping_criteria(T,J=null){const Fe=new ne.StoppingCriteriaList;return T.max_length!==null&&Fe.push(new ne.MaxLengthCriteria(T.max_length,this.config.max_position_embeddings??null)),T.eos_token_id!==null&&Fe.push(new ne.EosTokenCriteria(T.eos_token_id)),J&&Fe.extend(J),Fe}_validate_model_class(){if(!this.can_generate){const T=[Va,Au,ja,Na],J=j.get(this.constructor),Fe=new Set,Oe=this.config.model_type;for(const St of T){const Wt=St.get(Oe);Wt&&Fe.add(Wt[0])}let _t=`The current model class (${J}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Fe.size>0&&(_t+=` Please use the following class instead: ${[...Fe].join(", ")}`),Error(_t)}}prepare_inputs_for_generation(...T){return this._prepare_inputs_for_generation(this,...T)}_update_model_kwargs_for_generation({generated_input_ids:T,outputs:J,model_inputs:Fe,is_encoder_decoder:Oe}){return Fe.past_key_values=this.getPastKeyValues(J,Fe.past_key_values),Fe.input_ids=new P.Tensor("int64",T.flat(),[T.length,1]),Oe||(Fe.attention_mask=(0,P.cat)([Fe.attention_mask,(0,P.ones)([Fe.attention_mask.dims[0],1])],1)),Fe.position_ids=null,Fe}_prepare_model_inputs({inputs:T,bos_token_id:J,model_kwargs:Fe}){const Oe=(0,Ce.pick)(Fe,this.forward_params),_t=this.main_input_name;if(_t in Oe){if(T)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Oe[_t]=T;return{inputs_tensor:Oe[_t],model_inputs:Oe,model_input_name:_t}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:T,model_inputs:J,model_input_name:Fe,generation_config:Oe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!J.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:St,pixel_values:Wt,attention_mask:nr,...kr}=J,pr=await this._prepare_inputs_embeds(J);J={...kr,...(0,Ce.pick)(pr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_t}=await Ze(this,J);if(Oe.guidance_scale!==null&&Oe.guidance_scale>1)_t=(0,P.cat)([_t,(0,P.full_like)(_t,0)],0),"attention_mask"in J&&(J.attention_mask=(0,P.cat)([J.attention_mask,(0,P.zeros_like)(J.attention_mask)],0));else if(J.decoder_input_ids){const St=ke(J.decoder_input_ids).dims[0];if(St!==_t.dims[0]){if(_t.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_t.dims[0]}) than the decoder inputs (${St}).`);_t=(0,P.cat)(Array.from({length:St},()=>_t),0)}}return J.encoder_outputs=_t,J}_prepare_decoder_input_ids_for_generation({batch_size:T,model_input_name:J,model_kwargs:Fe,decoder_start_token_id:Oe,bos_token_id:_t,generation_config:St}){let{decoder_input_ids:Wt,...nr}=Fe;if(Wt)Array.isArray(Wt[0])||(Wt=Array.from({length:T},()=>Wt));else if(Oe??(Oe=_t),this.config.model_type==="musicgen")Wt=Array.from({length:T*this.config.decoder.num_codebooks},()=>[Oe]);else if(Array.isArray(Oe)){if(Oe.length!==T)throw new Error(`\`decoder_start_token_id\` expcted to have length ${T} but got ${Oe.length}`);Wt=Oe}else Wt=Array.from({length:T},()=>[Oe]);return Wt=ke(Wt),Fe.decoder_attention_mask=(0,P.ones_like)(Wt),{input_ids:Wt,model_inputs:nr}}async generate({inputs:T=null,generation_config:J=null,logits_processor:Fe=null,stopping_criteria:Oe=null,streamer:_t=null,...St}){this._validate_model_class(),J=this._prepare_generation_config(J,St);let{inputs_tensor:Wt,model_inputs:nr,model_input_name:kr}=this._prepare_model_inputs({inputs:T,model_kwargs:St});const pr=this.config.is_encoder_decoder;pr&&("encoder_outputs"in nr||(nr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Wt,model_inputs:nr,model_input_name:kr,generation_config:J})));let hr;pr?{input_ids:hr,model_inputs:nr}=this._prepare_decoder_input_ids_for_generation({batch_size:nr[kr].dims.at(0),model_input_name:kr,model_kwargs:nr,decoder_start_token_id:J.decoder_start_token_id,bos_token_id:J.bos_token_id,generation_config:J}):hr=nr[kr];let _r=hr.dims.at(-1);J.max_new_tokens!==null&&(J.max_length=_r+J.max_new_tokens);const xr=this._get_logits_processor(J,_r,Fe),Fr=this._get_stopping_criteria(J,Oe),Tr=nr[kr].dims.at(0),gr=_e.LogitsSampler.getSampler(J),rn=new Array(Tr).fill(0),on=hr.tolist();_t&&_t.put(on);let bn,pn={};for(;;){if(nr=this.prepare_inputs_for_generation(on,nr,J),bn=await this.forward(nr),J.output_attentions&&J.return_dict_in_generate){const Rn=this.getAttentions(bn);for(const vs in Rn)vs in pn||(pn[vs]=[]),pn[vs].push(Rn[vs])}const Ms=bn.logits.slice(null,-1,null),_i=xr(on,Ms),Ja=[];for(let Rn=0;Rn<_i.dims.at(0);++Rn){const vs=_i[Rn],qd=await gr(vs);for(const[Hd,Kd]of qd){const pd=BigInt(Hd);rn[Rn]+=Kd,on[Rn].push(pd),Ja.push([pd]);break}}if(_t&&_t.put(Ja),Fr(on).every(Rn=>Rn))break;nr=this._update_model_kwargs_for_generation({generated_input_ids:Ja,outputs:bn,model_inputs:nr,is_encoder_decoder:pr})}_t&&_t.end();const ln=this.getPastKeyValues(bn,nr.past_key_values,!0),Mn=new P.Tensor("int64",on.flat(),[on.length,on[0].length]);if(J.return_dict_in_generate)return{sequences:Mn,past_key_values:ln,...pn};for(const Ms of Object.values(bn))Ms.location==="gpu-buffer"&&Ms.dispose();return Mn}getPastKeyValues(T,J,Fe=!1){const Oe=Object.create(null);for(const _t in T)if(_t.startsWith("present")){const St=_t.replace("present","past_key_values"),Wt=_t.includes("encoder");if(Wt&&J?Oe[St]=J[St]:Oe[St]=T[_t],J&&(!Wt||Fe)){const nr=J[St];nr.location==="gpu-buffer"&&nr.dispose()}}return Oe}getAttentions(T){const J={};for(const Fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Oe in T)Oe.startsWith(Fe)&&(Fe in J||(J[Fe]=[]),J[Fe].push(T[Oe]));return J}addPastKeyValues(T,J){if(J)Object.assign(T,J);else{const Fe=this.custom_config.kv_cache_dtype??"float32",Oe=Fe==="float16"?new Uint16Array:[],_t=(0,z.getKeyValueShapes)(this.config);for(const St in _t)T[St]=new P.Tensor(Fe,Oe,_t[St])}}async encode_image({pixel_values:T}){const J=(await de(this.sessions.vision_encoder,{pixel_values:T})).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 (${J.dims[1]}).`),this.config.num_image_tokens=J.dims[1]),J}async encode_text({input_ids:T}){return(await de(this.sessions.embed_tokens,{input_ids:T})).inputs_embeds}}class He{}class dt extends He{constructor({last_hidden_state:_,hidden_states:T=null,attentions:J=null}){super(),this.last_hidden_state=_,this.hidden_states=T,this.attentions=J}}class nt extends Y{}class ot extends nt{}class Re extends nt{async _call(_){return new an(await super._call(_))}}class ht extends nt{async _call(_){return new ir(await super._call(_))}}class bt extends nt{async _call(_){return new sn(await super._call(_))}}class qe extends nt{async _call(_){return new cn(await super._call(_))}}class ee extends Y{}class Pe extends ee{}class Ne extends Y{}class Qe extends Ne{}class Ue extends Ne{async _call(_){return new an(await super._call(_))}}class je extends Ne{async _call(_){return new ir(await super._call(_))}}class lt extends Ne{async _call(_){return new sn(await super._call(_))}}class yt extends Ne{async _call(_){return new cn(await super._call(_))}}class vt extends Y{}class Et extends vt{}class x extends vt{async _call(_){return new an(await super._call(_))}}class H extends vt{async _call(_){return new ir(await super._call(_))}}class $ extends vt{async _call(_){return new sn(await super._call(_))}}class Q extends vt{async _call(_){return new cn(await super._call(_))}}class he extends Y{}class Ye extends he{}class Je extends he{async _call(_){return new an(await super._call(_))}}class Bt extends he{async _call(_){return new ir(await super._call(_))}}class ct extends he{async _call(_){return new sn(await super._call(_))}}class Tt extends he{async _call(_){return new cn(await super._call(_))}}class At extends Y{}class Pt extends At{}class cr extends At{async _call(_){return new an(await super._call(_))}}class Er extends At{async _call(_){return new ir(await super._call(_))}}class Qr extends At{async _call(_){return new sn(await super._call(_))}}class Or extends At{async _call(_){return new cn(await super._call(_))}}class Ur extends Y{}class at extends Ur{}class U extends Ur{async _call(_){return new an(await super._call(_))}}class ge extends Ur{async _call(_){return new ir(await super._call(_))}}class Ae extends Ur{async _call(_){return new sn(await super._call(_))}}class et extends Ur{async _call(_){return new cn(await super._call(_))}}class xe extends Y{}class Xe extends xe{}class gt extends xe{async _call(_){return new an(await super._call(_))}}class mt extends xe{async _call(_){return new ir(await super._call(_))}}class $t extends xe{async _call(_){return new sn(await super._call(_))}}class ft extends xe{async _call(_){return new cn(await super._call(_))}}class zt extends Y{}class Nt extends zt{}class Rt extends zt{async _call(_){return new ir(await super._call(_))}}class Gt extends zt{async _call(_){return new sn(await super._call(_))}}class be extends zt{async _call(_){return new cn(await super._call(_))}}class tt extends zt{async _call(_){return new an(await super._call(_))}}class st extends Y{}class qt extends st{}class wr extends st{async _call(_){return new an(await super._call(_))}}class Br extends st{async _call(_){return new ir(await super._call(_))}}class Kr extends st{async _call(_){return new sn(await super._call(_))}}class rr extends Y{}class Wr extends rr{}class Vr extends rr{async _call(_){return new an(await super._call(_))}}class Ln extends rr{async _call(_){return new ir(await super._call(_))}}class Rr extends rr{async _call(_){return new cn(await super._call(_))}}class Bn extends Y{}class Cs extends Bn{}class Xs extends Bn{async _call(_){return new an(await super._call(_))}}class Es extends Bn{async _call(_){return new ir(await super._call(_))}}class $s extends Bn{async _call(_){return new sn(await super._call(_))}}class Ss extends Bn{async _call(_){return new cn(await super._call(_))}}class Gn extends Y{}class ks extends Gn{}class Qs extends Gn{async _call(_){return new an(await super._call(_))}}class qn extends Gn{async _call(_){return new ir(await super._call(_))}}class Sn extends Gn{async _call(_){return new cn(await super._call(_))}}class Cn extends Y{}class ps extends Cn{}class ts extends Cn{async _call(_){return new ir(await super._call(_))}}class hs extends Cn{async _call(_){return new cn(await super._call(_))}}class fs extends Cn{async _call(_){return new an(await super._call(_))}}class rs extends Y{constructor(T,J,Fe){super(T,J);Me(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Xt extends rs{}class ms extends rs{}class _s extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class Ps extends _s{}class As extends _s{}class gs extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class Is extends gs{}class ws extends gs{}class ns extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class ue extends ns{}class m extends ns{}class A extends ns{async _call(_){return new ir(await super._call(_))}}class K extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class se extends K{}class pe extends K{}class De extends K{async _call(_){return new ir(await super._call(_))}}class wt extends K{}class xt extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class Mt extends xt{}class Ot extends xt{}class Yt extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class $r extends Yt{}class ar extends Yt{}class Dr extends Y{}class Jr extends Dr{}class ur extends Dr{async _call(_){return new an(await super._call(_))}}class Sr extends Dr{async _call(_){return new ir(await super._call(_))}}class _n extends Dr{async _call(_){return new sn(await super._call(_))}}class wn extends Dr{async _call(_){return new cn(await super._call(_))}}class Se extends Y{}class Zr extends Se{}class xn extends Se{async _call(_){return new an(await super._call(_))}}class kn extends Se{async _call(_){return new ir(await super._call(_))}}class Nn extends Se{async _call(_){return new sn(await super._call(_))}}class Ht extends Se{async _call(_){return new cn(await super._call(_))}}class en extends Y{}class Xr extends en{}class yr extends en{async _call(_){return new an(await super._call(_))}}class Ar extends en{async _call(_){return new ir(await super._call(_))}}class Ct extends en{async _call(_){return new sn(await super._call(_))}}class mr extends en{async _call(_){return new cn(await super._call(_))}}class Hn extends Y{}class Kn extends Hn{}class Xn extends Hn{}class jt extends Y{constructor(T,J,Fe){super(T,J);Me(this,"requires_attention_mask",!1);Me(this,"main_input_name","input_features");Me(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Ys extends jt{}class rt extends jt{_prepare_generation_config(_,T){return super._prepare_generation_config(_,T,D.WhisperGenerationConfig)}_retrieve_init_tokens(_){const T=[_.decoder_start_token_id];let J=_.language;const Fe=_.task;if(_.is_multilingual){J||(console.warn("No language specified - defaulting to English (en)."),J="en");const _t=`<|${(0,q.whisper_language_to_code)(J)}|>`;T.push(_.lang_to_id[_t]),T.push(_.task_to_id[Fe??"transcribe"])}else if(J||Fe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!_.return_timestamps&&_.no_timestamps_token_id&&T.at(-1)!==_.no_timestamps_token_id?T.push(_.no_timestamps_token_id):_.return_timestamps&&T.at(-1)===_.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),T.pop()),T.filter(Oe=>Oe!=null)}async generate({inputs:_=null,generation_config:T=null,logits_processor:J=null,stopping_criteria:Fe=null,...Oe}){T=this._prepare_generation_config(T,Oe);const _t=Oe.decoder_input_ids??this._retrieve_init_tokens(T);if(T.return_timestamps&&(J??(J=new S.LogitsProcessorList),J.push(new S.WhisperTimeStampLogitsProcessor(T,_t))),T.begin_suppress_tokens&&(J??(J=new S.LogitsProcessorList),J.push(new S.SuppressTokensAtBeginLogitsProcessor(T.begin_suppress_tokens,_t.length))),T.return_token_timestamps){if(!T.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.");T.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),T.output_attentions=!0,T.return_dict_in_generate=!0}const St=await super.generate({inputs:_,generation_config:T,logits_processor:J,decoder_input_ids:_t,...Oe});return T.return_token_timestamps&&(St.token_timestamps=this._extract_token_timestamps(St,T.alignment_heads,T.num_frames)),St}_extract_token_timestamps(_,T,J=null,Fe=.02){if(!_.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`.");J==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 Oe=this.config.median_filter_width;Oe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Oe=7);const _t=_.cross_attentions,St=Array.from({length:this.config.decoder_layers},(Fr,Tr)=>(0,P.cat)(_t.map(gr=>gr[Tr]),2)),Wt=(0,P.stack)(T.map(([Fr,Tr])=>{if(Fr>=St.length)throw new Error(`Layer index ${Fr} is out of bounds for cross attentions (length ${St.length}).`);return J?St[Fr].slice(null,Tr,null,[0,J]):St[Fr].slice(null,Tr)})).transpose(1,0,2,3),[nr,kr]=(0,P.std_mean)(Wt,-2,0,!0),pr=Wt.clone();for(let Fr=0;Frgr[Mn+1]-gr[Mn]),bn=(0,Ce.mergeArrays)([1],on).map(ln=>!!ln),pn=[];for(let ln=0;lnhr.findIndex(_r=>_r==Oe)),Wt=St.every(hr=>hr===-1),nr=St.every(hr=>hr!==-1);if(!Wt&&!nr)throw new Error("Every input should contain either 0 or 1 image token.");if(Wt)return{inputs_embeds:_,attention_mask:Fe};const kr=[],pr=[];for(let hr=0;hrOe*_t,1);_.input_labels=new P.Tensor("int64",new BigInt64Array(Fe).fill(1n),J)}const T={image_embeddings:_.image_embeddings,image_positional_embeddings:_.image_positional_embeddings};return _.input_points&&(T.input_points=_.input_points),_.input_labels&&(T.input_labels=_.input_labels),_.input_boxes&&(T.input_boxes=_.input_boxes),await de(this.sessions.prompt_encoder_mask_decoder,T)}async _call(_){return new ai(await super._call(_))}}class ai extends He{constructor({iou_scores:_,pred_masks:T}){super(),this.iou_scores=_,this.pred_masks=T}}class oi extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class Rl extends oi{}class li extends oi{}class ga extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class wa extends ga{}class ui extends ga{}class Zn extends Y{}class Nl extends Zn{}class Ed extends Zn{async _call(_){return new os(await super._call(_))}}class jl extends Zn{async _call(_){return new ir(await super._call(_))}}class ya extends Zn{async _call(_){return new sn(await super._call(_))}}class bs extends Y{}class Vl extends bs{}class ba extends bs{async _call(_){return new sn(await super._call(_))}}class Ul extends Y{}class Wl extends Ul{}class di extends Y{}class $d extends di{}class Gl extends di{async _call(_){return new os(await super._call(_))}}class ql extends di{async _call(_){return new ir(await super._call(_))}}class ci extends Y{}class Ma extends ci{}class Hl extends ci{async _call(_){return new os(await super._call(_))}}class Kl extends ci{async _call(_){return new ir(await super._call(_))}}class Xl extends ci{async _call(_){return new sn(await super._call(_))}}class pi extends Y{}class hi extends pi{}class Ql extends pi{async _call(_){return new os(await super._call(_))}}class fi extends pi{async _call(_){return new ir(await super._call(_))}}class Yl extends Y{}class va extends Zn{}class Jl extends Zn{async _call(_){return new os(await super._call(_))}}class Zl extends Zn{async _call(_){return new ir(await super._call(_))}}class as extends Y{}class Sd extends as{}class eu extends as{async _call(_){return new os(await super._call(_))}}class tu extends as{async _call(_){return new ir(await super._call(_))}}class kd extends as{async _call(_){return new dd(await super._call(_))}}class ru extends as{async _call(_){return new sn(await super._call(_))}}class Ds extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class gc extends Ds{}class nu extends Ds{}class su extends Ds{async generate_speech(_,T,{threshold:J=.5,minlenratio:Fe=0,maxlenratio:Oe=20,vocoder:_t=null}={}){const St={input_ids:_},{encoder_outputs:Wt,encoder_attention_mask:nr}=await Ze(this,St),kr=Wt.dims[1]/this.config.reduction_factor,pr=Math.floor(kr*Oe),hr=Math.floor(kr*Fe),_r=this.config.num_mel_bins;let xr=[],Fr=null,Tr=null,gr=0;for(;;){++gr;const bn=ze(!!Tr);let pn;Tr?pn=Tr.output_sequence_out:pn=new P.Tensor("float32",new Float32Array(_r),[1,1,_r]);let ln={use_cache_branch:bn,output_sequence:pn,encoder_attention_mask:nr,speaker_embeddings:T,encoder_hidden_states:Wt};this.addPastKeyValues(ln,Fr),Tr=await de(this.sessions.decoder_model_merged,ln),Fr=this.getPastKeyValues(Tr,Fr);const{prob:Mn,spectrum:Ms}=Tr;if(xr.push(Ms),gr>=hr&&(Array.from(Mn.data).filter(_i=>_i>=J).length>0||gr>=pr))break}const rn=(0,P.cat)(xr),{waveform:on}=await de(_t.sessions.model,{spectrogram:rn});return{spectrogram:rn,waveform:on}}}class iu extends Y{constructor(){super(...arguments);Me(this,"main_input_name","spectrogram")}}class xa extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class au extends xa{}class Ta extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class ou extends Ta{}class lu extends Ta{}class Ca extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class uu extends Ca{}class Pd extends Ca{}class Ea extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class du extends Ea{}class cu extends Ea{}class $a extends Y{}class pu extends $a{}class hu extends $a{static async from_pretrained(_,T={}){return T.model_file_name??(T.model_file_name="text_model"),super.from_pretrained(_,T)}}class fu extends $a{static async from_pretrained(_,T={}){return T.model_file_name??(T.model_file_name="audio_model"),super.from_pretrained(_,T)}}class mu extends Y{}class Sa extends mu{async _call(_){return new cd(await super._call(_))}}class ka extends Y{}class Pa extends ka{}class Ls extends ka{}class Aa extends ka{}class Ia extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class _u extends Ia{}class gu extends Ia{}class Fa extends Y{}class za extends Fa{}class wu extends Fa{async _call(_){return new ir(await super._call(_))}}class Oa extends Y{}class Ad extends Oa{}class wc extends Oa{}class Da extends Y{constructor(T,J,Fe){super(T,J);Me(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}_apply_and_filter_by_delay_pattern_mask(T){const[J,Fe]=T.dims,Oe=this.config.decoder.num_codebooks,_t=Fe-Oe;let St=0;for(let kr=0;kr0&&_r<=_t&&(T.data[St++]=T.data[kr])}const Wt=Math.floor(J/Oe),nr=St/(Wt*Oe);return new P.Tensor(T.type,T.data.slice(0,St),[Wt,Oe,nr])}prepare_inputs_for_generation(T,J,Fe){let Oe=structuredClone(T);for(let St=0;St=Wt&&(Oe[St][Wt]=BigInt(this.config.decoder.pad_token_id));return Fe.guidance_scale!==null&&Fe.guidance_scale>1&&(Oe=Oe.concat(Oe)),super.prepare_inputs_for_generation(Oe,J,Fe)}async generate(T){const J=await super.generate(T),Fe=this._apply_and_filter_by_delay_pattern_mask(J).unsqueeze_(0),{audio_values:Oe}=await de(this.sessions.encodec_decode,{audio_codes:Fe});return Oe}}class mi extends Y{}class yu extends mi{}class bu extends mi{async _call(_){return new ir(await super._call(_))}}class La extends Y{}class Id extends La{}class Mu extends La{async _call(_){return new ir(await super._call(_))}}class Ba extends Y{}class Fd extends Ba{}class vu extends Ba{async _call(_){return new ir(await super._call(_))}}class Ra extends Y{}class xu extends Ra{}class Tu extends Ra{async _call(_){return new ir(await super._call(_))}}class zd extends Y{}class Cu extends zd{}class Ir{static async from_pretrained(_,{progress_callback:T=null,config:J=null,cache_dir:Fe=null,local_files_only:Oe=!1,revision:_t="main",model_file_name:St=null,subfolder:Wt="onnx",device:nr=null,dtype:kr=null,use_external_data_format:pr=null,session_options:hr={}}={}){const _r={progress_callback:T,config:J,cache_dir:Fe,local_files_only:Oe,revision:_t,model_file_name:St,subfolder:Wt,device:nr,dtype:kr,use_external_data_format:pr,session_options:hr};if(_r.config=await z.AutoConfig.from_pretrained(_,_r),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const xr of this.MODEL_CLASS_MAPPINGS){const Fr=xr.get(_r.config.model_type);if(Fr)return await Fr[1].from_pretrained(_,_r)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${_r.config.model_type}", attempting to construct from base class.`),await Y.from_pretrained(_,_r);throw Error(`Unsupported model type: ${_r.config.model_type}`)}}Me(Ir,"MODEL_CLASS_MAPPINGS",null),Me(Ir,"BASE_IF_FAIL",!1);const Od=new Map([["bert",["BertModel",ot]],["nomic_bert",["NomicBertModel",Pe]],["roformer",["RoFormerModel",Qe]],["electra",["ElectraModel",Ye]],["esm",["EsmModel",qt]],["convbert",["ConvBertModel",Et]],["camembert",["CamembertModel",Pt]],["deberta",["DebertaModel",at]],["deberta-v2",["DebertaV2Model",Xe]],["mpnet",["MPNetModel",Cs]],["albert",["AlbertModel",ps]],["distilbert",["DistilBertModel",Nt]],["roberta",["RobertaModel",Jr]],["xlm",["XLMModel",Zr]],["xlm-roberta",["XLMRobertaModel",Xr]],["clap",["ClapModel",pu]],["clip",["CLIPModel",Ei]],["clipseg",["CLIPSegModel",po]],["chinese_clip",["ChineseCLIPModel",co]],["siglip",["SiglipModel",oo]],["mobilebert",["MobileBertModel",Wr]],["squeezebert",["SqueezeBertModel",ks]],["wav2vec2",["Wav2Vec2Model",Nl]],["wav2vec2-bert",["Wav2Vec2BertModel",hi]],["unispeech",["UniSpeechModel",$d]],["unispeech-sat",["UniSpeechSatModel",Ma]],["hubert",["HubertModel",va]],["wavlm",["WavLMModel",Sd]],["audio-spectrogram-transformer",["ASTModel",Kn]],["vits",["VitsModel",Sa]],["pyannote",["PyAnnoteModel",Vl]],["wespeaker-resnet",["WeSpeakerResNetModel",Wl]],["detr",["DetrModel",ol]],["rt_detr",["RTDetrModel",dl]],["table-transformer",["TableTransformerModel",hl]],["vit",["ViTModel",Ki]],["pvt",["PvtModel",Uo]],["vit_msn",["ViTMSNModel",qo]],["vit_mae",["ViTMAEModel",Go]],["groupvit",["GroupViTModel",vr]],["fastvit",["FastViTModel",Ko]],["mobilevit",["MobileViTModel",Jo]],["mobilevitv2",["MobileViTV2Model",el]],["owlvit",["OwlViTModel",rl]],["owlv2",["Owlv2Model",sl]],["beit",["BeitModel",il]],["deit",["DeiTModel",la]],["hiera",["HieraModel",ml]],["convnext",["ConvNextModel",Ol]],["convnextv2",["ConvNextV2Model",Qn]],["dinov2",["Dinov2Model",Jn]],["resnet",["ResNetModel",gl]],["swin",["SwinModel",yl]],["swin2sr",["Swin2SRModel",Td]],["donut-swin",["DonutSwinModel",zl]],["yolos",["YolosModel",ii]],["dpt",["DPTModel",On]],["glpn",["GLPNModel",Al]],["hifigan",["SpeechT5HifiGan",iu]],["efficientnet",["EfficientNetModel",za]],["decision_transformer",["DecisionTransformerModel",Cu]],["mobilenet_v1",["MobileNetV1Model",yu]],["mobilenet_v2",["MobileNetV2Model",Id]],["mobilenet_v3",["MobileNetV3Model",Fd]],["mobilenet_v4",["MobileNetV4Model",xu]],["maskformer",["MaskFormerModel",Sl]]]),Dd=new Map([["t5",["T5Model",Xt]],["longt5",["LongT5Model",Ps]],["mt5",["MT5Model",Is]],["bart",["BartModel",ue]],["mbart",["MBartModel",se]],["marian",["MarianModel",Rl]],["whisper",["WhisperModel",Ys]],["m2m_100",["M2M100Model",wa]],["blenderbot",["BlenderbotModel",Mt]],["blenderbot-small",["BlenderbotSmallModel",$r]]]),yc=new Map([["bloom",["BloomModel",Wi]],["jais",["JAISModel",An]],["gpt2",["GPT2Model",fo]],["gptj",["GPTJModel",Mo]],["gpt_bigcode",["GPTBigCodeModel",In]],["gpt_neo",["GPTNeoModel",go]],["gpt_neox",["GPTNeoXModel",yo]],["codegen",["CodeGenModel",zi]],["llama",["LlamaModel",Co]],["cohere",["CohereModel",$o]],["gemma",["GemmaModel",ko]],["gemma2",["Gemma2Model",zn]],["openelm",["OpenELMModel",Io]],["qwen2",["Qwen2Model",zo]],["phi",["PhiModel",Do]],["phi3",["Phi3Model",Vi]],["mpt",["MptModel",Ro]],["opt",["OPTModel",Os]],["mistral",["MistralModel",ou]],["starcoder2",["Starcoder2Model",uu]],["falcon",["FalconModel",du]],["stablelm",["StableLmModel",_u]]]),Na=new Map([["speecht5",["SpeechT5ForSpeechToText",nu]],["whisper",["WhisperForConditionalGeneration",rt]]]),Eu=new Map([["speecht5",["SpeechT5ForTextToSpeech",su]]]),$u=new Map([["vits",["VitsModel",Sa]],["musicgen",["MusicgenForConditionalGeneration",Da]]]),Su=new Map([["bert",["BertForSequenceClassification",ht]],["roformer",["RoFormerForSequenceClassification",je]],["electra",["ElectraForSequenceClassification",Bt]],["esm",["EsmForSequenceClassification",Br]],["convbert",["ConvBertForSequenceClassification",H]],["camembert",["CamembertForSequenceClassification",Er]],["deberta",["DebertaForSequenceClassification",ge]],["deberta-v2",["DebertaV2ForSequenceClassification",mt]],["mpnet",["MPNetForSequenceClassification",Es]],["albert",["AlbertForSequenceClassification",ts]],["distilbert",["DistilBertForSequenceClassification",Rt]],["roberta",["RobertaForSequenceClassification",Sr]],["xlm",["XLMForSequenceClassification",kn]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ar]],["bart",["BartForSequenceClassification",A]],["mbart",["MBartForSequenceClassification",De]],["mobilebert",["MobileBertForSequenceClassification",Ln]],["squeezebert",["SqueezeBertForSequenceClassification",qn]]]),Ld=new Map([["bert",["BertForTokenClassification",bt]],["roformer",["RoFormerForTokenClassification",lt]],["electra",["ElectraForTokenClassification",ct]],["esm",["EsmForTokenClassification",Kr]],["convbert",["ConvBertForTokenClassification",$]],["camembert",["CamembertForTokenClassification",Qr]],["deberta",["DebertaForTokenClassification",Ae]],["deberta-v2",["DebertaV2ForTokenClassification",$t]],["mpnet",["MPNetForTokenClassification",$s]],["distilbert",["DistilBertForTokenClassification",Gt]],["roberta",["RobertaForTokenClassification",_n]],["xlm",["XLMForTokenClassification",Nn]],["xlm-roberta",["XLMRobertaForTokenClassification",Ct]]]),ja=new Map([["t5",["T5ForConditionalGeneration",ms]],["longt5",["LongT5ForConditionalGeneration",As]],["mt5",["MT5ForConditionalGeneration",ws]],["bart",["BartForConditionalGeneration",m]],["mbart",["MBartForConditionalGeneration",pe]],["marian",["MarianMTModel",li]],["m2m_100",["M2M100ForConditionalGeneration",ui]],["blenderbot",["BlenderbotForConditionalGeneration",Ot]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ar]]]),Va=new Map([["bloom",["BloomForCausalLM",Md]],["gpt2",["GPT2LMHeadModel",mo]],["jais",["JAISLMHeadModel",_o]],["gptj",["GPTJForCausalLM",vo]],["gpt_bigcode",["GPTBigCodeForCausalLM",To]],["gpt_neo",["GPTNeoForCausalLM",wo]],["gpt_neox",["GPTNeoXForCausalLM",bo]],["codegen",["CodeGenForCausalLM",Fn]],["llama",["LlamaForCausalLM",Eo]],["cohere",["CohereForCausalLM",So]],["gemma",["GemmaForCausalLM",Po]],["gemma2",["Gemma2ForCausalLM",Ao]],["openelm",["OpenELMForCausalLM",Fo]],["qwen2",["Qwen2ForCausalLM",Oo]],["phi",["PhiForCausalLM",Lo]],["phi3",["Phi3ForCausalLM",Bo]],["mpt",["MptForCausalLM",No]],["opt",["OPTForCausalLM",jo]],["mbart",["MBartForCausalLM",wt]],["mistral",["MistralForCausalLM",lu]],["starcoder2",["Starcoder2ForCausalLM",Pd]],["falcon",["FalconForCausalLM",cu]],["trocr",["TrOCRForCausalLM",au]],["stablelm",["StableLmForCausalLM",gu]]]),ku=new Map([["bert",["BertForMaskedLM",Re]],["roformer",["RoFormerForMaskedLM",Ue]],["electra",["ElectraForMaskedLM",Je]],["esm",["EsmForMaskedLM",wr]],["convbert",["ConvBertForMaskedLM",x]],["camembert",["CamembertForMaskedLM",cr]],["deberta",["DebertaForMaskedLM",U]],["deberta-v2",["DebertaV2ForMaskedLM",gt]],["mpnet",["MPNetForMaskedLM",Xs]],["albert",["AlbertForMaskedLM",fs]],["distilbert",["DistilBertForMaskedLM",tt]],["roberta",["RobertaForMaskedLM",ur]],["xlm",["XLMWithLMHeadModel",xn]],["xlm-roberta",["XLMRobertaForMaskedLM",yr]],["mobilebert",["MobileBertForMaskedLM",Vr]],["squeezebert",["SqueezeBertForMaskedLM",Qs]]]),Pu=new Map([["bert",["BertForQuestionAnswering",qe]],["roformer",["RoFormerForQuestionAnswering",yt]],["electra",["ElectraForQuestionAnswering",Tt]],["convbert",["ConvBertForQuestionAnswering",Q]],["camembert",["CamembertForQuestionAnswering",Or]],["deberta",["DebertaForQuestionAnswering",et]],["deberta-v2",["DebertaV2ForQuestionAnswering",ft]],["mpnet",["MPNetForQuestionAnswering",Ss]],["albert",["AlbertForQuestionAnswering",hs]],["distilbert",["DistilBertForQuestionAnswering",be]],["roberta",["RobertaForQuestionAnswering",wn]],["xlm",["XLMForQuestionAnswering",Ht]],["xlm-roberta",["XLMRobertaForQuestionAnswering",mr]],["mobilebert",["MobileBertForQuestionAnswering",Rr]],["squeezebert",["SqueezeBertForQuestionAnswering",Sn]]]),Au=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ut]]]),yn=new Map([["llava",["LlavaForConditionalGeneration",Ci]],["moondream1",["Moondream1ForConditionalGeneration",io]],["florence2",["Florence2ForConditionalGeneration",or]]]),Bd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ut]]]),Iu=new Map([["vit",["ViTForImageClassification",Vo]],["pvt",["PvtForImageClassification",Wo]],["vit_msn",["ViTMSNForImageClassification",xd]],["fastvit",["FastViTForImageClassification",Xo]],["mobilevit",["MobileViTForImageClassification",Zo]],["mobilevitv2",["MobileViTV2ForImageClassification",tl]],["beit",["BeitForImageClassification",al]],["deit",["DeiTForImageClassification",ua]],["hiera",["HieraForImageClassification",_l]],["convnext",["ConvNextForImageClassification",Cd]],["convnextv2",["ConvNextV2ForImageClassification",Yn]],["dinov2",["Dinov2ForImageClassification",fn]],["resnet",["ResNetForImageClassification",wl]],["swin",["SwinForImageClassification",bl]],["segformer",["SegformerForImageClassification",Ls]],["efficientnet",["EfficientNetForImageClassification",wu]],["mobilenet_v1",["MobileNetV1ForImageClassification",bu]],["mobilenet_v2",["MobileNetV2ForImageClassification",Mu]],["mobilenet_v3",["MobileNetV3ForImageClassification",vu]],["mobilenet_v4",["MobileNetV4ForImageClassification",Tu]]]),Ua=new Map([["detr",["DetrForObjectDetection",ll]],["rt_detr",["RTDetrForObjectDetection",cl]],["table-transformer",["TableTransformerForObjectDetection",fl]],["yolos",["YolosForObjectDetection",_a]]]),Fu=new Map([["owlvit",["OwlViTForObjectDetection",nl]],["owlv2",["Owlv2ForObjectDetection",Zs]]]),Bs=new Map([["detr",["DetrForSegmentation",ra]],["clipseg",["CLIPSegForImageSegmentation",ho]]]),zu=new Map([["segformer",["SegformerForSemanticSegmentation",Aa]],["sapiens",["SapiensForSemanticSegmentation",Cl]]]),Ou=new Map([["detr",["DetrForSegmentation",ra]],["maskformer",["MaskFormerForInstanceSegmentation",kl]]]),Wa=new Map([["sam",["SamModel",Bl]]]),Du=new Map([["wav2vec2",["Wav2Vec2ForCTC",Ed]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ql]],["unispeech",["UniSpeechForCTC",Gl]],["unispeech-sat",["UniSpeechSatForCTC",Hl]],["wavlm",["WavLMForCTC",eu]],["hubert",["HubertForCTC",Jl]]]),Lu=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",jl]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",fi]],["unispeech",["UniSpeechForSequenceClassification",ql]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Kl]],["wavlm",["WavLMForSequenceClassification",tu]],["hubert",["HubertForSequenceClassification",Zl]],["audio-spectrogram-transformer",["ASTForAudioClassification",Xn]]]),Ga=new Map([["wavlm",["WavLMForXVector",kd]]]),Bu=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Xl]],["wavlm",["WavLMForAudioFrameClassification",ru]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ya]],["pyannote",["PyAnnoteForAudioFrameClassification",ba]]]),Ru=new Map([["vitmatte",["VitMatteForImageMatting",Yo]]]),Nu=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ml]]]),qa=new Map([["dpt",["DPTForDepthEstimation",vl]],["depth_anything",["DepthAnythingForDepthEstimation",Tl]],["glpn",["GLPNForDepthEstimation",Il]],["sapiens",["SapiensForDepthEstimation",El]]]),ju=new Map([["sapiens",["SapiensForNormalEstimation",$l]]]),Vu=new Map([["clip",["CLIPVisionModelWithProjection",Pn]],["siglip",["SiglipVisionModel",lo]]]),Ha=[[Od,te.EncoderOnly],[Dd,te.EncoderDecoder],[yc,te.DecoderOnly],[Su,te.EncoderOnly],[Ld,te.EncoderOnly],[ja,te.Seq2Seq],[Na,te.Seq2Seq],[Va,te.DecoderOnly],[ku,te.EncoderOnly],[Pu,te.EncoderOnly],[Au,te.Vision2Seq],[yn,te.ImageTextToText],[Iu,te.EncoderOnly],[Bs,te.EncoderOnly],[Ou,te.EncoderOnly],[zu,te.EncoderOnly],[Ru,te.EncoderOnly],[Nu,te.EncoderOnly],[qa,te.EncoderOnly],[ju,te.EncoderOnly],[Ua,te.EncoderOnly],[Fu,te.EncoderOnly],[Wa,te.MaskGeneration],[Du,te.EncoderOnly],[Lu,te.EncoderOnly],[Eu,te.Seq2Seq],[$u,te.EncoderOnly],[Ga,te.EncoderOnly],[Bu,te.EncoderOnly],[Vu,te.EncoderOnly]];for(const[f,_]of Ha)for(const[T,J]of f.values())ie.set(T,_),j.set(J,T),X.set(T,J);const Rd=[["MusicgenForConditionalGeneration",Da,te.Musicgen],["CLIPTextModelWithProjection",ao,te.EncoderOnly],["SiglipTextModel",is,te.EncoderOnly],["ClapTextModelWithProjection",hu,te.EncoderOnly],["ClapAudioModelWithProjection",fu,te.EncoderOnly]];for(const[f,_,T]of Rd)ie.set(f,T),j.set(_,f),X.set(f,_);class Uu extends Ir{}Me(Uu,"MODEL_CLASS_MAPPINGS",Ha.map(_=>_[0])),Me(Uu,"BASE_IF_FAIL",!0);class Ka extends Ir{}Me(Ka,"MODEL_CLASS_MAPPINGS",[Su]);class Wu extends Ir{}Me(Wu,"MODEL_CLASS_MAPPINGS",[Ld]);class Gu extends Ir{}Me(Gu,"MODEL_CLASS_MAPPINGS",[ja]);class qu extends Ir{}Me(qu,"MODEL_CLASS_MAPPINGS",[Na]);class Nd extends Ir{}Me(Nd,"MODEL_CLASS_MAPPINGS",[Eu]);class Hu extends Ir{}Me(Hu,"MODEL_CLASS_MAPPINGS",[$u]);class Ku extends Ir{}Me(Ku,"MODEL_CLASS_MAPPINGS",[Va]);class Xu extends Ir{}Me(Xu,"MODEL_CLASS_MAPPINGS",[ku]);class jd extends Ir{}Me(jd,"MODEL_CLASS_MAPPINGS",[Pu]);class Qu extends Ir{}Me(Qu,"MODEL_CLASS_MAPPINGS",[Au]);class Yu extends Ir{}Me(Yu,"MODEL_CLASS_MAPPINGS",[Iu]);class Ju extends Ir{}Me(Ju,"MODEL_CLASS_MAPPINGS",[Bs]);class Zu extends Ir{}Me(Zu,"MODEL_CLASS_MAPPINGS",[zu]);class Vd extends Ir{}Me(Vd,"MODEL_CLASS_MAPPINGS",[Ou]);class ed extends Ir{}Me(ed,"MODEL_CLASS_MAPPINGS",[Ua]);class td extends Ir{}Me(td,"MODEL_CLASS_MAPPINGS",[Fu]);class rd extends Ir{}Me(rd,"MODEL_CLASS_MAPPINGS",[Wa]);class nd extends Ir{}Me(nd,"MODEL_CLASS_MAPPINGS",[Du]);class sd extends Ir{}Me(sd,"MODEL_CLASS_MAPPINGS",[Lu]);class id extends Ir{}Me(id,"MODEL_CLASS_MAPPINGS",[Ga]);class ad extends Ir{}Me(ad,"MODEL_CLASS_MAPPINGS",[Bu]);class od extends Ir{}Me(od,"MODEL_CLASS_MAPPINGS",[Bd]);class ld extends Ir{}Me(ld,"MODEL_CLASS_MAPPINGS",[Ru]);class Ud extends Ir{}Me(Ud,"MODEL_CLASS_MAPPINGS",[Nu]);class Rs extends Ir{}Me(Rs,"MODEL_CLASS_MAPPINGS",[qa]);class Xa extends Ir{}Me(Xa,"MODEL_CLASS_MAPPINGS",[ju]);class Qa extends Ir{}Me(Qa,"MODEL_CLASS_MAPPINGS",[Vu]);class ud extends He{constructor({logits:_,past_key_values:T,encoder_outputs:J,decoder_attentions:Fe=null,cross_attentions:Oe=null}){super(),this.logits=_,this.past_key_values=T,this.encoder_outputs=J,this.decoder_attentions=Fe,this.cross_attentions=Oe}}class ir extends He{constructor({logits:_}){super(),this.logits=_}}class dd extends He{constructor({logits:_,embeddings:T}){super(),this.logits=_,this.embeddings=T}}class sn extends He{constructor({logits:_}){super(),this.logits=_}}class an extends He{constructor({logits:_}){super(),this.logits=_}}class cn extends He{constructor({start_logits:_,end_logits:T}){super(),this.start_logits=_,this.end_logits=T}}class os extends He{constructor({logits:_}){super(),this.logits=_}}class Wd extends He{constructor({logits:_,past_key_values:T}){super(),this.logits=_,this.past_key_values=T}}class Ya extends He{constructor({alphas:_}){super(),this.alphas=_}}class cd extends He{constructor({waveform:_,spectrogram:T}){super(),this.waveform=_,this.spectrogram=T}}},"./src/models/whisper/common_whisper.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{WHISPER_LANGUAGE_MAPPING:()=>me,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>we,whisper_language_to_code:()=>Te});const z=[["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"]],me=new Map(z),we=new Map([...z.map(([Ce,R])=>[R,Ce]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Te(Ce){Ce=Ce.toLowerCase();let R=we.get(Ce);if(R===void 0)if(me.has(Ce))R=Ce;else{const V=Ce.length===2?me.keys():me.values();throw new Error(`Language "${Ce}" is not supported. Must be one of: ${JSON.stringify(V)}`)}return R}},"./src/models/whisper/generation_whisper.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{WhisperGenerationConfig:()=>me});var z=N("./src/generation/configuration_utils.js");class me extends z.GenerationConfig{constructor(){super(...arguments);Me(this,"return_timestamps",null);Me(this,"return_token_timestamps",null);Me(this,"num_frames",null);Me(this,"alignment_heads",null);Me(this,"task",null);Me(this,"language",null);Me(this,"no_timestamps_token_id",null);Me(this,"prompt_ids",null);Me(this,"is_multilingual",null);Me(this,"lang_to_id",null);Me(this,"task_to_id",null);Me(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{TensorOpRegistry:()=>Te});var z=N("./src/backends/onnx.js"),me=N("./src/utils/tensor.js");const we=async(Ce,R,S)=>{const V=await(0,z.createInferenceSession)(new Uint8Array(Ce),R);return async P=>{const re=Object.fromEntries(Object.entries(P).map(([_e,ce])=>[_e,ce.ort_tensor])),ne=await V.run(re);return Array.isArray(S)?S.map(_e=>new me.Tensor(ne[_e])):new me.Tensor(ne[S])}};class Te{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}}Me(Te,"session_options",{})},"./src/pipelines.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{AudioClassificationPipeline:()=>ze,AutomaticSpeechRecognitionPipeline:()=>Ze,DepthEstimationPipeline:()=>nt,DocumentQuestionAnsweringPipeline:()=>Y,FeatureExtractionPipeline:()=>ve,FillMaskPipeline:()=>ie,ImageClassificationPipeline:()=>ut,ImageFeatureExtractionPipeline:()=>ke,ImageSegmentationPipeline:()=>ye,ImageToImagePipeline:()=>dt,ImageToTextPipeline:()=>Ke,ObjectDetectionPipeline:()=>fe,Pipeline:()=>ce,QuestionAnsweringPipeline:()=>te,SummarizationPipeline:()=>j,Text2TextGenerationPipeline:()=>X,TextClassificationPipeline:()=>D,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>He,TokenClassificationPipeline:()=>q,TranslationPipeline:()=>I,ZeroShotAudioClassificationPipeline:()=>Ie,ZeroShotClassificationPipeline:()=>de,ZeroShotImageClassificationPipeline:()=>W,ZeroShotObjectDetectionPipeline:()=>$e,pipeline:()=>ht});var z=N("./src/tokenizers.js"),me=N("./src/models.js"),we=N("./src/processors.js"),Te=N("./src/utils/generic.js"),Ce=N("./src/utils/core.js"),R=N("./src/utils/maths.js"),S=N("./src/utils/audio.js"),V=N("./src/utils/tensor.js"),P=N("./src/utils/image.js");async function re(qe){return Array.isArray(qe)||(qe=[qe]),await Promise.all(qe.map(ee=>P.RawImage.read(ee)))}async function ne(qe,ee){return Array.isArray(qe)||(qe=[qe]),await Promise.all(qe.map(Pe=>typeof Pe=="string"||Pe instanceof URL?(0,S.read_audio)(Pe,ee):Pe instanceof Float64Array?new Float32Array(Pe):Pe))}function _e(qe,ee){ee&&(qe=qe.map(je=>je|0));const[Pe,Ne,Qe,Ue]=qe;return{xmin:Pe,ymin:Ne,xmax:Qe,ymax:Ue}}class ce extends Te.Callable{constructor({task:ee,model:Pe,tokenizer:Ne=null,processor:Qe=null}){super(),this.task=ee,this.model=Pe,this.tokenizer=Ne,this.processor=Qe}async dispose(){await this.model.dispose()}}class D extends ce{constructor(ee){super(ee)}async _call(ee,{top_k:Pe=1}={}){const Ne=this.tokenizer(ee,{padding:!0,truncation:!0}),Qe=await this.model(Ne),Ue=this.model.config.problem_type==="multi_label_classification"?yt=>yt.sigmoid():yt=>new V.Tensor("float32",(0,R.softmax)(yt.data),yt.dims),je=this.model.config.id2label,lt=[];for(const yt of Qe.logits){const vt=Ue(yt),Et=await(0,V.topk)(vt,Pe),x=Et[0].tolist(),$=Et[1].tolist().map((Q,he)=>({label:je?je[Q]:`LABEL_${Q}`,score:x[he]}));Pe===1?lt.push(...$):lt.push($)}return Array.isArray(ee)||Pe===1?lt:lt[0]}}class q extends ce{constructor(ee){super(ee)}async _call(ee,{ignore_labels:Pe=["O"]}={}){const Ne=Array.isArray(ee),Qe=this.tokenizer(Ne?ee:[ee],{padding:!0,truncation:!0}),je=(await this.model(Qe)).logits,lt=this.model.config.id2label,yt=[];for(let vt=0;vtct==this.tokenizer.sep_token_id);yt[x].map((ct,Tt)=>ct==1&&(Tt===0||Tt>$&&vt.findIndex(At=>At==H[Tt])===-1));const Q=Ue[x].tolist(),he=je[x].tolist();for(let ct=1;ctTt==H[ct])!==-1)&&(Q[ct]=-1/0,he[ct]=-1/0);const Ye=(0,R.softmax)(Q).map((ct,Tt)=>[ct,Tt]),Je=(0,R.softmax)(he).map((ct,Tt)=>[ct,Tt]);Ye[0][0]=0,Je[0][0]=0;const Bt=(0,Ce.product)(Ye,Je).filter(ct=>ct[0][1]<=ct[1][1]).map(ct=>[ct[0][1],ct[1][1],ct[0][0]*ct[1][0]]).sort((ct,Tt)=>Tt[2]-ct[2]);for(let ct=0;ctQ==this.tokenizer.mask_token_id);if(vt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Et=Qe[lt][vt],x=await(0,V.topk)(new V.Tensor("float32",(0,R.softmax)(Et.data),Et.dims),Pe),H=x[0].tolist(),$=x[1].tolist();Ue.push($.map((Q,he)=>{const Ye=yt.slice();return Ye[vt]=Q,{score:H[he],token:Number(Q),token_str:this.tokenizer.model.vocab[Q],sequence:this.tokenizer.decode(Ye,{skip_special_tokens:!0})}}))}return Array.isArray(ee)?Ue:Ue[0]}}class X extends ce{constructor(Pe){super(Pe);Me(this,"_key","generated_text")}async _call(Pe,Ne={}){Array.isArray(Pe)||(Pe=[Pe]),this.model.config.prefix&&(Pe=Pe.map(vt=>this.model.config.prefix+vt));const Qe=this.model.config.task_specific_params;Qe&&Qe[this.task]&&Qe[this.task].prefix&&(Pe=Pe.map(vt=>Qe[this.task].prefix+vt));const Ue=this.tokenizer,je={padding:!0,truncation:!0};let lt;this instanceof I&&"_build_translation_inputs"in Ue?lt=Ue._build_translation_inputs(Pe,je,Ne):lt=Ue(Pe,je);const yt=await this.model.generate({...lt,...Ne});return Ue.batch_decode(yt,{skip_special_tokens:!0}).map(vt=>({[this._key]:vt}))}}class j extends X{constructor(Pe){super(Pe);Me(this,"_key","summary_text")}}class I extends X{constructor(Pe){super(Pe);Me(this,"_key","translation_text")}}function L(qe){return Array.isArray(qe)&&qe.every(ee=>"role"in ee&&"content"in ee)}class k extends ce{constructor(ee){super(ee)}async _call(ee,Pe={}){let Ne=!1,Qe=!1,Ue;if(typeof ee=="string")Ue=ee=[ee];else if(Array.isArray(ee)&&ee.every($=>typeof $=="string"))Ne=!0,Ue=ee;else{if(L(ee))ee=[ee];else if(Array.isArray(ee)&&ee.every(L))Ne=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Qe=!0,Ue=ee.map($=>this.tokenizer.apply_chat_template($,{tokenize:!1,add_generation_prompt:!0}))}const je=Pe.add_special_tokens??!1,lt=Qe?!1:Pe.return_full_text??!0;this.tokenizer.padding_side="left";const yt=this.tokenizer(Ue,{add_special_tokens:je,padding:!0,truncation:!0}),vt=await this.model.generate({...yt,...Pe}),Et=this.tokenizer.batch_decode(vt,{skip_special_tokens:!0});let x;!lt&&yt.input_ids.dims.at(-1)>0&&(x=this.tokenizer.batch_decode(yt.input_ids,{skip_special_tokens:!0}).map($=>$.length));const H=Array.from({length:ee.length},$=>[]);for(let $=0;$[Pe.toLowerCase(),Ne])),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(ee,Pe,{hypothesis_template:Ne="This example is {}.",multi_label:Qe=!1}={}){const Ue=Array.isArray(ee);Ue||(ee=[ee]),Array.isArray(Pe)||(Pe=[Pe]);const je=Pe.map(vt=>Ne.replace("{}",vt)),lt=Qe||Pe.length===1,yt=[];for(const vt of ee){const Et=[];for(const $ of je){const Q=this.tokenizer(vt,{text_pair:$,padding:!0,truncation:!0}),he=await this.model(Q);lt?Et.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):Et.push(he.logits.data[this.entailment_id])}const H=(lt?Et.map($=>(0,R.softmax)($)[1]):(0,R.softmax)(Et)).map(($,Q)=>[$,Q]).sort(($,Q)=>Q[0]-$[0]);yt.push({sequence:vt,labels:H.map($=>Pe[$[1]]),scores:H.map($=>$[0])})}return Ue?yt:yt[0]}}class ve extends ce{constructor(ee){super(ee)}async _call(ee,{pooling:Pe="none",normalize:Ne=!1,quantize:Qe=!1,precision:Ue="binary"}={}){const je=this.tokenizer(ee,{padding:!0,truncation:!0}),lt=await this.model(je);let yt=lt.last_hidden_state??lt.logits??lt.token_embeddings;if(Pe!=="none")if(Pe==="mean")yt=(0,V.mean_pooling)(yt,je.attention_mask);else if(Pe==="cls")yt=yt.slice(null,0);else throw Error(`Pooling method '${Pe}' not supported.`);return Ne&&(yt=yt.normalize(2,-1)),Qe&&(yt=(0,V.quantize_embeddings)(yt,Ue)),yt}}class ke extends ce{constructor(ee){super(ee)}async _call(ee,{pool:Pe=null}={}){const Ne=await re(ee),{pixel_values:Qe}=await this.processor(Ne),Ue=await this.model({pixel_values:Qe});let je;if(Pe){if(!("pooler_output"in Ue))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");je=Ue.pooler_output}else je=Ue.last_hidden_state??Ue.logits??Ue.image_embeds;return je}}class ze extends ce{constructor(ee){super(ee)}async _call(ee,{top_k:Pe=5}={}){const Ne=this.processor.feature_extractor.config.sampling_rate,Qe=await ne(ee,Ne),Ue=this.model.config.id2label,je=[];for(const lt of Qe){const yt=await this.processor(lt),Et=(await this.model(yt)).logits[0],x=await(0,V.topk)(new V.Tensor("float32",(0,R.softmax)(Et.data),Et.dims),Pe),H=x[0].tolist(),Q=x[1].tolist().map((he,Ye)=>({label:Ue?Ue[he]:`LABEL_${he}`,score:H[Ye]}));je.push(Q)}return Array.isArray(ee)?je:je[0]}}class Ie extends ce{constructor(ee){super(ee)}async _call(ee,Pe,{hypothesis_template:Ne="This is a sound of {}."}={}){const Qe=!Array.isArray(ee);Qe&&(ee=[ee]);const Ue=Pe.map(Et=>Ne.replace("{}",Et)),je=this.tokenizer(Ue,{padding:!0,truncation:!0}),lt=this.processor.feature_extractor.config.sampling_rate,yt=await ne(ee,lt),vt=[];for(const Et of yt){const x=await this.processor(Et),H=await this.model({...je,...x}),$=(0,R.softmax)(H.logits_per_audio.data);vt.push([...$].map((Q,he)=>({score:Q,label:Pe[he]})))}return Qe?vt[0]:vt}}class Ze extends ce{constructor(ee){super(ee)}async _call(ee,Pe={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ee,Pe);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ee,Pe);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ee,Pe){Pe.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Pe.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ne=!Array.isArray(ee);Ne&&(ee=[ee]);const Qe=this.processor.feature_extractor.config.sampling_rate,Ue=await ne(ee,Qe),je=[];for(const lt of Ue){const yt=await this.processor(lt),Et=(await this.model(yt)).logits[0],x=[];for(const $ of Et)x.push((0,R.max)($.data)[1]);const H=this.tokenizer.decode(x);je.push({text:H})}return Ne?je[0]:je}async _call_whisper(ee,Pe){const Ne=Pe.return_timestamps??!1,Qe=Pe.chunk_length_s??0,Ue=Pe.force_full_sequences??!1;let je=Pe.stride_length_s??null;const lt={...Pe};Ne==="word"&&(lt.return_token_timestamps=!0,lt.return_timestamps=!1);const yt=!Array.isArray(ee);yt&&(ee=[ee]);const vt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Et=this.processor.feature_extractor.config.hop_length,x=this.processor.feature_extractor.config.sampling_rate,H=await ne(ee,x),$=[];for(const Q of H){let he=[];if(Qe>0){if(je===null)je=Qe/6;else if(Qe<=je)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Bt=x*Qe,ct=x*je,Tt=Bt-2*ct;let At=0;for(;;){const Pt=At+Bt,cr=Q.subarray(At,Pt),Er=await this.processor(cr),Qr=At===0,Or=Pt>=Q.length;if(he.push({stride:[cr.length,Qr?0:ct,Or?0:ct],input_features:Er.input_features,is_last:Or}),Or)break;At+=Tt}}else he=[{stride:[Q.length,0,0],input_features:(await this.processor(Q)).input_features,is_last:!0}];for(const Bt of he){lt.num_frames=Math.floor(Bt.stride[0]/Et);const ct=await this.model.generate({inputs:Bt.input_features,...lt});Ne==="word"?(Bt.tokens=ct.sequences.tolist()[0],Bt.token_timestamps=ct.token_timestamps.tolist()[0].map(Tt=>(0,R.round)(Tt,2))):Bt.tokens=ct[0].tolist(),Bt.stride=Bt.stride.map(Tt=>Tt/x)}const[Ye,Je]=this.tokenizer._decode_asr(he,{time_precision:vt,return_timestamps:Ne,force_full_sequences:Ue});$.push({text:Ye,...Je})}return yt?$[0]:$}}class Ke extends ce{constructor(ee){super(ee)}async _call(ee,Pe={}){const Ne=Array.isArray(ee),Qe=await re(ee),{pixel_values:Ue}=await this.processor(Qe),je=[];for(const lt of Ue){lt.dims=[1,...lt.dims];const yt=await this.model.generate({inputs:lt,...Pe}),vt=this.tokenizer.batch_decode(yt,{skip_special_tokens:!0}).map(Et=>({generated_text:Et.trim()}));je.push(vt)}return Ne?je:je[0]}}class ut extends ce{constructor(ee){super(ee)}async _call(ee,{top_k:Pe=5}={}){const Ne=await re(ee),{pixel_values:Qe}=await this.processor(Ne),Ue=await this.model({pixel_values:Qe}),je=this.model.config.id2label,lt=[];for(const yt of Ue.logits){const vt=await(0,V.topk)(new V.Tensor("float32",(0,R.softmax)(yt.data),yt.dims),Pe),Et=vt[0].tolist(),H=vt[1].tolist().map(($,Q)=>({label:je?je[$]:`LABEL_${$}`,score:Et[Q]}));lt.push(H)}return Array.isArray(ee)?lt:lt[0]}}class ye extends ce{constructor(ee){super(ee),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ee,{threshold:Pe=.5,mask_threshold:Ne=.5,overlap_mask_area_threshold:Qe=.8,label_ids_to_fuse:Ue=null,target_sizes:je=null,subtask:lt=null}={}){if(Array.isArray(ee)&&ee.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const vt=await re(ee),Et=vt.map(Je=>[Je.height,Je.width]),{pixel_values:x,pixel_mask:H}=await this.processor(vt),$=await this.model({pixel_values:x,pixel_mask:H});let Q=null;if(lt!==null)Q=this.subtasks_mapping[lt];else for(let[Je,Bt]of Object.entries(this.subtasks_mapping))if(Bt in this.processor.feature_extractor){Q=this.processor.feature_extractor[Bt].bind(this.processor.feature_extractor),lt=Je;break}const he=this.model.config.id2label,Ye=[];if(lt==="panoptic"||lt==="instance"){const Je=Q($,Pe,Ne,Qe,Ue,je??Et)[0],Bt=Je.segmentation;for(const ct of Je.segments_info){const Tt=new Uint8ClampedArray(Bt.data.length);for(let Pt=0;PtNe.replace("{}",H)),lt=this.tokenizer(je,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:yt}=await this.processor(Ue),vt=await this.model({...lt,pixel_values:yt}),Et=this.model.config.model_type==="siglip"?H=>H.sigmoid().data:H=>(0,R.softmax)(H.data),x=[];for(const H of vt.logits_per_image){const Q=[...Et(H)].map((he,Ye)=>({score:he,label:Pe[Ye]}));Q.sort((he,Ye)=>Ye.score-he.score),x.push(Q)}return Qe?x:x[0]}}class fe extends ce{constructor(ee){super(ee)}async _call(ee,{threshold:Pe=.9,percentage:Ne=!1}={}){const Qe=Array.isArray(ee);if(Qe&&ee.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ue=await re(ee),je=Ne?null:Ue.map($=>[$.height,$.width]),{pixel_values:lt,pixel_mask:yt}=await this.processor(Ue),vt=await this.model({pixel_values:lt,pixel_mask:yt}),Et=this.processor.feature_extractor.post_process_object_detection(vt,Pe,je),x=this.model.config.id2label,H=Et.map($=>$.boxes.map((Q,he)=>({score:$.scores[he],label:x[$.classes[he]],box:_e(Q,!Ne)})));return Qe?H:H[0]}}class $e extends ce{constructor(ee){super(ee)}async _call(ee,Pe,{threshold:Ne=.1,top_k:Qe=null,percentage:Ue=!1}={}){const je=Array.isArray(ee),lt=await re(ee),yt=this.tokenizer(Pe,{padding:!0,truncation:!0}),vt=await this.processor(lt),Et=[];for(let x=0;x({score:Ye.scores[ct],label:Pe[Ye.classes[ct]],box:_e(Bt,!Ue)})).sort((Bt,ct)=>ct.score-Bt.score);Qe!==null&&(Je=Je.slice(0,Qe)),Et.push(Je)}return je?Et:Et[0]}}class Y extends ce{constructor(ee){super(ee)}async _call(ee,Pe,Ne={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class He extends ce{constructor(Pe){super(Pe);Me(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Pe.vocoder??null}async _call(Pe,{speaker_embeddings:Ne=null}={}){return this.processor?this._call_text_to_spectrogram(Pe,{speaker_embeddings:Ne}):this._call_text_to_waveform(Pe)}async _call_text_to_waveform(Pe){const Ne=this.tokenizer(Pe,{padding:!0,truncation:!0}),{waveform:Qe}=await this.model(Ne),Ue=this.model.config.sampling_rate;return{audio:Qe.data,sampling_rate:Ue}}async _call_text_to_spectrogram(Pe,{speaker_embeddings:Ne}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await me.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ne=="string"||Ne instanceof URL)&&(Ne=new Float32Array(await(await fetch(Ne)).arrayBuffer())),Ne instanceof Float32Array)Ne=new V.Tensor("float32",Ne,[1,Ne.length]);else if(!(Ne instanceof V.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Qe}=this.tokenizer(Pe,{padding:!0,truncation:!0}),{waveform:Ue}=await this.model.generate_speech(Qe,Ne,{vocoder:this.vocoder}),je=this.processor.feature_extractor.config.sampling_rate;return{audio:Ue.data,sampling_rate:je}}}class dt extends ce{constructor(ee){super(ee)}async _call(ee){const Pe=await re(ee),Ne=await this.processor(Pe),Qe=await this.model(Ne),Ue=[];for(const je of Qe.reconstruction){const lt=je.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ue.push(P.RawImage.fromTensor(lt))}return Ue.length>1?Ue:Ue[0]}}class nt extends ce{constructor(ee){super(ee)}async _call(ee){const Pe=await re(ee),Ne=await this.processor(Pe),{predicted_depth:Qe}=await this.model(Ne),Ue=[];for(let je=0;je1?Ue:Ue[0]}}const ot=Object.freeze({"text-classification":{tokenizer:z.AutoTokenizer,pipeline:D,model:me.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:z.AutoTokenizer,pipeline:q,model:me.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:z.AutoTokenizer,pipeline:te,model:me.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:z.AutoTokenizer,pipeline:ie,model:me.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:z.AutoTokenizer,pipeline:j,model:me.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:z.AutoTokenizer,pipeline:I,model:me.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:z.AutoTokenizer,pipeline:X,model:me.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:z.AutoTokenizer,pipeline:k,model:me.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:z.AutoTokenizer,pipeline:de,model:me.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ze,model:me.AutoModelForAudioClassification,processor:we.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:z.AutoTokenizer,pipeline:Ie,model:me.AutoModel,processor:we.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:z.AutoTokenizer,pipeline:Ze,model:[me.AutoModelForSpeechSeq2Seq,me.AutoModelForCTC],processor:we.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:z.AutoTokenizer,pipeline:He,model:[me.AutoModelForTextToWaveform,me.AutoModelForTextToSpectrogram],processor:[we.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:z.AutoTokenizer,pipeline:Ke,model:me.AutoModelForVision2Seq,processor:we.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ut,model:me.AutoModelForImageClassification,processor:we.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ye,model:[me.AutoModelForImageSegmentation,me.AutoModelForSemanticSegmentation,me.AutoModelForUniversalSegmentation],processor:we.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:z.AutoTokenizer,pipeline:W,model:me.AutoModel,processor:we.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:fe,model:me.AutoModelForObjectDetection,processor:we.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:z.AutoTokenizer,pipeline:$e,model:me.AutoModelForZeroShotObjectDetection,processor:we.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:z.AutoTokenizer,pipeline:Y,model:me.AutoModelForDocumentQuestionAnswering,processor:we.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:dt,model:me.AutoModelForImageToImage,processor:we.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:nt,model:me.AutoModelForDepthEstimation,processor:we.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:z.AutoTokenizer,pipeline:ve,model:me.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:we.AutoProcessor,pipeline:ke,model:[me.AutoModelForImageFeatureExtraction,me.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(qe,ee=null,{progress_callback:Pe=null,config:Ne=null,cache_dir:Qe=null,local_files_only:Ue=!1,revision:je="main",device:lt=null,dtype:yt=null,model_file_name:vt=null,session_options:Et={}}={}){qe=Re[qe]??qe;const x=ot[qe.split("_",1)[0]];if(!x)throw Error(`Unsupported pipeline: ${qe}. Must be one of [${Object.keys(ot)}]`);ee||(ee=x.default.model,console.log(`No model specified. Using default model: "${ee}".`));const H={progress_callback:Pe,config:Ne,cache_dir:Qe,local_files_only:Ue,revision:je,device:lt,dtype:yt,model_file_name:vt,session_options:Et},$=new Map([["tokenizer",x.tokenizer],["model",x.model],["processor",x.processor]]),Q=await bt($,ee,H);Q.task=qe,(0,Ce.dispatchCallback)(Pe,{status:"ready",task:qe,model:ee});const he=x.pipeline;return new he(Q)}async function bt(qe,ee,Pe){const Ne=Object.create(null),Qe=[];for(const[Ue,je]of qe.entries()){if(!je)continue;let lt;Array.isArray(je)?lt=new Promise(async(yt,vt)=>{var x,H;let Et;for(const $ of je){if($===null){yt(null);return}try{yt(await $.from_pretrained(ee,Pe));return}catch(Q){if((x=Q.message)!=null&&x.includes("Unsupported model type"))Et=Q;else if((H=Q.message)!=null&&H.includes("Could not locate file"))Et=Q;else{vt(Q);return}}}vt(Et)}):lt=je.from_pretrained(ee,Pe),Ne[Ue]=lt,Qe.push(lt)}await Promise.all(Qe);for(const[Ue,je]of Object.entries(Ne))Ne[Ue]=await je;return Ne}},"./src/processors.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{ASTFeatureExtractor:()=>Q,AutoProcessor:()=>Ur,BeitFeatureExtractor:()=>Pe,BitImageProcessor:()=>ve,CLIPFeatureExtractor:()=>ze,CLIPImageProcessor:()=>Ie,ChineseCLIPFeatureExtractor:()=>Ze,ClapFeatureExtractor:()=>he,ConvNextFeatureExtractor:()=>ut,ConvNextImageProcessor:()=>ye,DPTFeatureExtractor:()=>k,DPTImageProcessor:()=>de,DeiTFeatureExtractor:()=>ee,DetrFeatureExtractor:()=>Ue,DonutFeatureExtractor:()=>Ne,EfficientNetImageProcessor:()=>$e,FeatureExtractor:()=>ie,Florence2Processor:()=>Or,GLPNFeatureExtractor:()=>ke,ImageFeatureExtractor:()=>X,MaskFormerFeatureExtractor:()=>je,MobileNetV1FeatureExtractor:()=>Y,MobileNetV2FeatureExtractor:()=>He,MobileNetV3FeatureExtractor:()=>dt,MobileNetV4FeatureExtractor:()=>nt,MobileViTFeatureExtractor:()=>ot,MobileViTImageProcessor:()=>Re,NougatImageProcessor:()=>Qe,OwlViTFeatureExtractor:()=>ht,OwlViTProcessor:()=>Qr,Owlv2ImageProcessor:()=>bt,Processor:()=>ct,PvtImageProcessor:()=>L,PyAnnoteFeatureExtractor:()=>Ye,PyAnnoteProcessor:()=>cr,RTDetrImageProcessor:()=>qe,SamImageProcessor:()=>yt,SamProcessor:()=>Tt,SapiensFeatureExtractor:()=>j,SeamlessM4TFeatureExtractor:()=>$,SegformerFeatureExtractor:()=>I,SiglipImageProcessor:()=>Ke,SpeechT5FeatureExtractor:()=>Bt,SpeechT5Processor:()=>Er,Swin2SRImageProcessor:()=>vt,ViTFeatureExtractor:()=>W,ViTImageProcessor:()=>fe,VitMatteImageProcessor:()=>Et,Wav2Vec2FeatureExtractor:()=>H,Wav2Vec2ProcessorWithLM:()=>Pt,WeSpeakerFeatureExtractor:()=>Je,WhisperFeatureExtractor:()=>x,WhisperProcessor:()=>At,YolosFeatureExtractor:()=>lt});var z=N("./src/utils/generic.js"),me=N("./src/utils/core.js"),we=N("./src/utils/hub.js"),Te=N("./src/utils/maths.js"),Ce=N("./src/utils/tensor.js");N("./src/utils/image.js");var R=N("./src/utils/audio.js");function S([at,U,ge,Ae]){return[at-ge/2,U-Ae/2,at+ge/2,U+Ae/2]}function V(at,U=.5,ge=null,Ae=!1){const et=at.logits,xe=at.pred_boxes,[Xe,gt,mt]=et.dims;if(ge!==null&&ge.length!==Xe)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;ftU&&st.push(wr)}else{let wr=(0,Te.max)(tt.data)[1];if(wr===mt-1||(qt=(0,Te.softmax)(tt.data),qt[wr]Kr*zt[(rr+1)%2])),Nt.boxes.push(Br),Nt.classes.push(wr),Nt.scores.push(qt[wr])}}$t.push(Nt)}return $t}function P(at,U=null){const ge=at.logits,Ae=ge.dims[0];if(U!==null&&U.length!==Ae)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const et=[];for(let xe=0;xezt[st]&&(zt[st]=tt[st],Nt[st]=be)}const Rt=new Array(gt.dims[0]);for(let be=0;bebe!==void 0);et.push({segmentation:ft,labels:Gt})}return et}function re(at,U,ge,Ae){const et=[],xe=[],Xe=[];for(let gt=0;gtge&&(et.push($t),xe.push(Nt),Xe.push(ft))}return[et,xe,Xe]}function ne(at,U,ge,Ae=.5,et=.8){const xe=[];let Xe=0,gt=0;const mt=U[ge].data;for(let ft=0;ft=Ae&&++gt;let $t=Xe>0&>>0;return $t&&($t=Xe/gt>et),[$t,xe]}function _e(at,U,ge,Ae,et,xe=null,Xe=null){const[gt,mt]=Xe??at[0].dims,$t=new Ce.Tensor("int32",new Int32Array(gt*mt),[gt,mt]),ft=[];if(Xe!==null)for(let be=0;beNt[qt]&&(zt[qt]=be,Nt[qt]=st[qt])}let Rt=0;const Gt=$t.data;for(let be=0;beAe&&(xe=Math.floor(et)*U),xexe?$t=Math.floor(xe*mt/et):xe>et&&(mt=Math.floor(et*$t/xe)),await U.resize($t,mt,{resample:Ae}))}async crop_margin(U,ge=200){const Ae=U.clone().grayscale(),et=(0,Te.min)(Ae.data)[0],Xe=(0,Te.max)(Ae.data)[0]-et;if(Xe===0)return U;const gt=ge/255;let mt=Ae.width,$t=Ae.height,ft=0,zt=0;const Nt=Ae.data;for(let Rt=0;Rtthis.preprocess(xe)));return{pixel_values:(0,Ce.stack)(Ae.map(xe=>xe.pixel_values),0),original_sizes:Ae.map(xe=>xe.original_size),reshaped_input_sizes:Ae.map(xe=>xe.reshaped_input_size)}}}class j extends X{post_process_semantic_segmentation(...U){return P(...U)}}class I extends X{post_process_semantic_segmentation(...U){return P(...U)}}class L extends X{}class k extends X{}class de extends k{}class ve extends X{}class ke extends X{}class ze extends X{}class Ie extends ze{}class Ze extends X{}class Ke extends X{}class ut extends X{constructor(U){super(U),this.crop_pct=this.config.crop_pct??.875}async resize(U){var Ae;const ge=(Ae=this.size)==null?void 0:Ae.shortest_edge;if(ge===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(ge<384){const et=Math.floor(ge/this.crop_pct),[xe,Xe]=this.get_resize_output_image_size(U,{shortest_edge:et});U=await U.resize(xe,Xe,{resample:this.resample}),U=await U.center_crop(ge,ge)}else U=await U.resize(ge,ge,{resample:this.resample});return U}}class ye extends ut{}class W extends X{}class fe extends X{}class $e extends X{constructor(U){super(U),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(ge=>ge*ge))}}class Y extends X{}class He extends X{}class dt extends X{}class nt extends X{}class ot extends X{}class Re extends ot{}class ht extends X{post_process_object_detection(...U){return V(...U)}}class bt extends ht{}class qe extends X{post_process_object_detection(...U){return V(...U)}}class ee extends X{}class Pe extends X{}class Ne extends X{pad_image(U,ge,Ae,et={}){const[xe,Xe,gt]=ge;let mt=this.image_mean;Array.isArray(this.image_mean)||(mt=new Array(gt).fill(mt));let $t=this.image_std;Array.isArray($t)||($t=new Array(gt).fill(mt));const ft=mt.map((zt,Nt)=>-zt/$t[Nt]);return super.pad_image(U,ge,Ae,{center:!0,constant_values:ft,...et})}}class Qe extends Ne{}class Ue extends X{async _call(U){const ge=await super._call(U),Ae=[ge.pixel_values.dims[0],64,64],et=(0,Ce.full)(Ae,1n);return{...ge,pixel_mask:et}}post_process_object_detection(...U){return V(...U)}post_process_panoptic_segmentation(...U){return ce(...U)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class je extends X{post_process_panoptic_segmentation(...U){return ce(...U)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class lt extends X{post_process_object_detection(...U){return V(...U)}}class yt extends X{reshape_input_points(U,ge,Ae,et=!1){U=structuredClone(U);let xe=(0,me.calculateDimensions)(U);if(xe.length===3)et||(xe=[1,...xe]),U=[U];else if(xe.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 Xe=0;Xeet!==ge.dims[xe]))throw Error(`The first ${Ae.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Ce.Tensor("int64",U.flat(1/0).map(BigInt),Ae)}async _call(U,{input_points:ge=null,input_labels:Ae=null,input_boxes:et=null}={}){const xe=await super._call(U);if(ge&&(xe.input_points=this.reshape_input_points(ge,xe.original_sizes,xe.reshaped_input_sizes)),Ae){if(!xe.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");xe.input_labels=this.add_input_labels(Ae,xe.input_points)}return et&&(xe.input_boxes=this.reshape_input_points(et,xe.original_sizes,xe.reshaped_input_sizes,!0)),xe}async post_process_masks(U,ge,Ae,{mask_threshold:et=0,binarize:xe=!0,pad_size:Xe=null}={}){const gt=[];Xe=Xe??this.pad_size;const mt=[Xe.height,Xe.width];for(let $t=0;$tet&&(Gt[be]=1);Nt=new Ce.Tensor("bool",Gt,Nt.dims)}gt.push(Nt)}return gt}generate_crop_boxes(U,ge,{crop_n_layers:Ae=0,overlap_ratio:et=.3413333333333333,points_per_crop:xe=32,crop_n_points_downscale_factor:Xe=1}={}){}}class vt extends X{pad_image(U,ge,Ae,et={}){const[xe,Xe,gt]=ge;return super.pad_image(U,ge,{width:Xe+(Ae-Xe%Ae)%Ae,height:xe+(Ae-xe%Ae)%Ae},{mode:"symmetric",center:!1,constant_values:-1,...et})}}class Et extends X{async _call(U,ge){Array.isArray(U)||(U=[U]),Array.isArray(ge)||(ge=[ge]);const Ae=await Promise.all(U.map(Xe=>this.preprocess(Xe))),et=await Promise.all(ge.map(Xe=>this.preprocess(Xe,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,Ce.stack)(Ae.map((Xe,gt)=>(0,Ce.cat)([Xe.pixel_values,et[gt].pixel_values],0)),0),original_sizes:Ae.map(Xe=>Xe.original_size),reshaped_input_sizes:Ae.map(Xe=>Xe.reshaped_input_size)}}}class x extends ie{constructor(U){var ge;super(U),(ge=this.config).mel_filters??(ge.mel_filters=(0,R.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,R.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(U){const ge=await(0,R.spectrogram)(U,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),Ae=ge.data,et=(0,Te.max)(Ae)[0];for(let xe=0;xethis.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=U.slice(0,this.config.n_samples)):(ge=new Float32Array(this.config.n_samples),ge.set(U)),{input_features:(await this._extract_fbank_features(ge)).unsqueeze_(0)}}}class H extends ie{_zero_mean_unit_var_norm(U){const Ae=U.reduce((xe,Xe)=>xe+Xe,0)/U.length,et=U.reduce((xe,Xe)=>xe+(Xe-Ae)**2,0)/U.length;return U.map(xe=>(xe-Ae)/Math.sqrt(et+1e-7))}async _call(U){D(U,"Wav2Vec2FeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));let ge=U;this.config.do_normalize&&(ge=this._zero_mean_unit_var_norm(ge));const Ae=[1,ge.length];return{input_values:new Ce.Tensor("float32",ge,Ae),attention_mask:new Ce.Tensor("int64",new BigInt64Array(ge.length).fill(1n),Ae)}}}class $ extends ie{constructor(U){super(U);const ge=this.config.sampling_rate,Ae=(0,R.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ge/2),ge,null,"kaldi",!0);for(let et=0;etAe*32768),(0,R.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:ge,transpose:!0})}async _call(U,{padding:ge=!0,pad_to_multiple_of:Ae=2,do_normalize_per_mel_bins:et=!0,return_attention_mask:xe=!0}={}){D(U,"SeamlessM4TFeatureExtractor");let Xe=await this._extract_fbank_features(U,this.config.max_length);if(et){const[Gt,be]=Xe.dims,tt=Xe.data;for(let st=0;st0){const qt=new Float32Array(be*(Gt+st));qt.set(tt),qt.fill(this.config.padding_value,tt.length);const wr=Gt+st;Xe=new Ce.Tensor(Xe.type,qt,[wr,be]),xe&&(gt=new Ce.Tensor("int64",new BigInt64Array(wr),[1,wr]),gt.data.fill(1n,0,Gt))}}const[mt,$t]=Xe.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 Nt=Xe.view(1,Math.floor(mt/ft),$t*ft),Rt={input_features:Nt};if(xe){const Gt=Nt.dims[1],be=new BigInt64Array(Gt);if(gt){const tt=gt.data;for(let st=1,qt=0;st0)if(Ae==="rand_trunc"){const gt=Math.floor(Math.random()*(Xe+1));U=U.subarray(gt,gt+ge),xe=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Ae}" not implemented`);else{if(Xe<0){let gt=new Float64Array(ge);if(gt.set(U),et==="repeat")for(let mt=U.length;mt({id:mt,start:$t*Ae,end:ft*Ae,confidence:zt/(ft-$t)})))}return et}}class Je extends ie{constructor(U){super(U);const ge=this.config.sampling_rate,Ae=(0,R.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ge/2),ge,null,"kaldi",!0);for(let et=0;etge*32768),(0,R.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(U){D(U,"WeSpeakerFeatureExtractor");const ge=(await this._extract_fbank_features(U)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Ae=ge.mean(1).data,et=ge.data,[xe,Xe,gt]=ge.dims;for(let mt=0;mt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(U){typeof U=="string"&&(U=[U]);const ge=[];for(const Ae of U)if(this.task_prompts_without_inputs.has(Ae))ge.push(this.task_prompts_without_inputs.get(Ae));else{for(const[et,xe]of this.task_prompts_with_input)if(Ae.includes(et)){ge.push(xe.replaceAll("{input}",Ae).replaceAll(et,""));break}ge.length!==U.length&&ge.push(Ae)}return ge}post_process_generation(U,ge,Ae){const et=this.tasks_answer_post_processing_type.get(ge)??"pure_text";U=U.replaceAll("","").replaceAll("","");let xe;switch(et){case"pure_text":xe=U;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Xe=et==="ocr"?"quad_boxes":"bboxes",gt=U.matchAll(this.regexes[Xe]),mt=[],$t=[];for(const[ft,zt,...Nt]of gt)mt.push(zt?zt.trim():mt.at(-1)??""),$t.push(Nt.map((Rt,Gt)=>(Number(Rt)+.5)/this.size_per_bin*Ae[Gt%2]));xe={labels:mt,[Xe]:$t};break;default:throw new Error(`Task "${ge}" (of type "${et}") not yet implemented.`)}return{[ge]:xe}}}class Ur{static async from_pretrained(U,{progress_callback:ge=null,config:Ae=null,cache_dir:et=null,local_files_only:xe=!1,revision:Xe="main"}={}){let gt=Ae??await(0,we.getModelJSON)(U,"preprocessor_config.json",!0,{progress_callback:ge,config:Ae,cache_dir:et,local_files_only:xe,revision:Xe}),mt=gt.feature_extractor_type??gt.image_processor_type,$t=this.FEATURE_EXTRACTOR_CLASS_MAPPING[mt];if(!$t)if(gt.size!==void 0)console.warn(`Feature extractor type "${mt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),$t=X;else throw new Error(`Unknown Feature Extractor type: ${mt}`);let ft=this.PROCESSOR_CLASS_MAPPING[gt.processor_class]??ct,zt=new $t(gt);return new ft(zt)}}Me(Ur,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:X,WhisperFeatureExtractor:x,ViTFeatureExtractor:W,MobileViTFeatureExtractor:ot,MobileViTImageProcessor:Re,MobileNetV1FeatureExtractor:Y,MobileNetV2FeatureExtractor:He,MobileNetV3FeatureExtractor:dt,MobileNetV4FeatureExtractor:nt,OwlViTFeatureExtractor:ht,Owlv2ImageProcessor:bt,CLIPFeatureExtractor:ze,CLIPImageProcessor:Ie,Florence2Processor:Or,ChineseCLIPFeatureExtractor:Ze,SiglipImageProcessor:Ke,ConvNextFeatureExtractor:ut,ConvNextImageProcessor:ye,SegformerFeatureExtractor:I,SapiensFeatureExtractor:j,BitImageProcessor:ve,DPTImageProcessor:de,DPTFeatureExtractor:k,PvtImageProcessor:L,GLPNFeatureExtractor:ke,BeitFeatureExtractor:Pe,DeiTFeatureExtractor:ee,DetrFeatureExtractor:Ue,RTDetrImageProcessor:qe,MaskFormerFeatureExtractor:je,YolosFeatureExtractor:lt,DonutFeatureExtractor:Ne,NougatImageProcessor:Qe,EfficientNetImageProcessor:$e,ViTImageProcessor:fe,VitMatteImageProcessor:Et,SamImageProcessor:yt,Swin2SRImageProcessor:vt,Wav2Vec2FeatureExtractor:H,SeamlessM4TFeatureExtractor:$,SpeechT5FeatureExtractor:Bt,ASTFeatureExtractor:Q,ClapFeatureExtractor:he,PyAnnoteFeatureExtractor:Ye,WeSpeakerFeatureExtractor:Je}),Me(Ur,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:At,Wav2Vec2ProcessorWithLM:Pt,PyAnnoteProcessor:cr,SamProcessor:Tt,SpeechT5Processor:Er,OwlViTProcessor:Qr,Florence2Processor:Or})},"./src/tokenizers.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{AlbertTokenizer:()=>gt,AutoTokenizer:()=>ns,BartTokenizer:()=>Kr,BertTokenizer:()=>Xe,BlenderbotSmallTokenizer:()=>Ps,BlenderbotTokenizer:()=>_s,BloomTokenizer:()=>Ln,CLIPTokenizer:()=>fs,CamembertTokenizer:()=>tt,CodeGenTokenizer:()=>hs,CodeLlamaTokenizer:()=>Cs,CohereTokenizer:()=>ws,ConvBertTokenizer:()=>Rt,DebertaTokenizer:()=>ft,DebertaV2Tokenizer:()=>zt,DistilBertTokenizer:()=>be,ElectraTokenizer:()=>qt,EsmTokenizer:()=>Gn,FalconTokenizer:()=>$s,GPT2Tokenizer:()=>Br,GPTNeoXTokenizer:()=>Ss,GemmaTokenizer:()=>Qs,Grok1Tokenizer:()=>qn,HerbertTokenizer:()=>Nt,LlamaTokenizer:()=>Bn,M2M100Tokenizer:()=>ps,MBart50Tokenizer:()=>Wr,MBartTokenizer:()=>rr,MPNetTokenizer:()=>Es,MarianTokenizer:()=>Xt,MobileBertTokenizer:()=>mt,NllbTokenizer:()=>Cn,NougatTokenizer:()=>gs,PreTrainedTokenizer:()=>xe,Qwen2Tokenizer:()=>ks,RoFormerTokenizer:()=>Gt,RobertaTokenizer:()=>Vr,SiglipTokenizer:()=>rs,SpeechT5Tokenizer:()=>As,SqueezeBertTokenizer:()=>$t,T5Tokenizer:()=>wr,TokenizerModel:()=>ke,VitsTokenizer:()=>Is,Wav2Vec2CTCTokenizer:()=>ms,WhisperTokenizer:()=>ts,XLMRobertaTokenizer:()=>Xs,XLMTokenizer:()=>st,is_chinese_char:()=>X});var z=N("./src/utils/generic.js"),me=N("./src/utils/core.js"),we=N("./src/utils/hub.js"),Te=N("./src/utils/maths.js"),Ce=N("./src/utils/tensor.js"),R=N("./src/utils/data-structures.js"),S=N("./node_modules/@huggingface/jinja/dist/index.js"),V=N("./src/models/whisper/common_whisper.js"),P=N("./src/utils/constants.js");async function re(ue,m){const A=await Promise.all([(0,we.getModelJSON)(ue,"tokenizer.json",!0,m),(0,we.getModelJSON)(ue,"tokenizer_config.json",!0,m)]);return m.legacy!==null&&(A[1].legacy=m.legacy),A}function ne(ue,m){const A=[];let K=0;for(const se of ue.matchAll(m)){const pe=se[0];K0&&A.push(pe),K=se.index+pe.length}return K=19968&&ue<=40959||ue>=13312&&ue<=19903||ue>=131072&&ue<=173791||ue>=173824&&ue<=177983||ue>=177984&&ue<=178207||ue>=178208&&ue<=183983||ue>=63744&&ue<=64255||ue>=194560&&ue<=195103}function j(ue,m,A){const K=[];let se=0;for(;sethis.tokens_to_ids.get(A)??this.unk_token_id)}convert_ids_to_tokens(m){return m.map(A=>this.vocab[A]??this.unk_token)}}class ze extends ke{constructor(m){super(m),this.tokens_to_ids=ce(m.vocab),this.unk_token_id=this.tokens_to_ids.get(m.unk_token),this.unk_token=m.unk_token,this.max_input_chars_per_word=m.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[A,K]of this.tokens_to_ids)this.vocab[K]=A}encode(m){const A=[];for(const K of m){const se=[...K];if(se.length>this.max_input_chars_per_word){A.push(this.unk_token);continue}let pe=!1,De=0;const wt=[];for(;De0&&(Ot=this.config.continuing_subword_prefix+Ot),this.tokens_to_ids.has(Ot)){Mt=Ot;break}--xt}if(Mt===null){pe=!0;break}wt.push(Mt),De=xt}pe?A.push(this.unk_token):A.push(...wt)}return A}}class Ie extends ke{constructor(m,A){super(m);const K=m.vocab.length;this.vocab=new Array(K),this.scores=new Array(K);for(let se=0;se[se,pe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=A.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,Te.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new R.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(m){const A=m.chars,K=1;let se=0;for(;se{const ue=[...Array.from({length:94},(se,pe)=>pe+33),...Array.from({length:12},(se,pe)=>pe+161),...Array.from({length:82},(se,pe)=>pe+174)],m=ue.slice();let A=0;for(let se=0;se<256;++se)ue.includes(se)||(ue.push(se),m.push(256+A),A+=1);const K=m.map(se=>String.fromCharCode(se));return Object.fromEntries(ue.map((se,pe)=>[se,K[pe]]))})(),Ke=(0,me.reverseDictionary)(Ze);class ut extends ke{constructor(m){super(m),this.tokens_to_ids=ce(m.vocab),this.unk_token_id=this.tokens_to_ids.get(m.unk_token),this.unk_token=m.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[K,se]of this.tokens_to_ids)this.vocab[se]=K;const A=Array.isArray(m.merges[0]);this.merges=A?m.merges:m.merges.map(K=>K.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((K,se)=>[JSON.stringify(K),se])),this.end_of_word_suffix=m.end_of_word_suffix,this.continuing_subword_suffix=m.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(m){if(m.length===0)return[];const A=this.cache.get(m);if(A!==void 0)return A;const K=Array.from(m);this.end_of_word_suffix&&(K[K.length-1]+=this.end_of_word_suffix);let se=[];if(K.length>1){const pe=new R.PriorityQueue((xt,Mt)=>xt.score`<0x${wt.toString(16).toUpperCase().padStart(2,"0")}>`);De.every(wt=>this.tokens_to_ids.has(wt))?A.push(...De):A.push(this.unk_token)}else A.push(this.unk_token)}return A}}class ye extends ke{constructor(m,A){super(m),this.tokens_to_ids=ce(A.target_lang?m.vocab[A.target_lang]:m.vocab),this.bos_token=A.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=A.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=A.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=A.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[K,se]of this.tokens_to_ids)this.vocab[se]=K}encode(m){return m}}class W extends z.Callable{constructor(m){super(),this.config=m}static fromConfig(m){if(m===null)return null;switch(m.type){case"BertNormalizer":return new bt(m);case"Precompiled":return new Qr(m);case"Sequence":return new ht(m);case"Replace":return new fe(m);case"NFC":return new $e(m);case"NFKC":return new Y(m);case"NFKD":return new He(m);case"Strip":return new dt(m);case"StripAccents":return new nt(m);case"Lowercase":return new ot(m);case"Prepend":return new Re(m);default:throw new Error(`Unknown Normalizer type: ${m.type}`)}}normalize(m){throw Error("normalize should be implemented in subclass.")}_call(m){return this.normalize(m)}}class fe extends W{normalize(m){const A=_e(this.config.pattern);return A===null?m:m.replaceAll(A,this.config.content)}}class $e extends W{normalize(m){return m=m.normalize("NFC"),m}}class Y extends W{normalize(m){return m=m.normalize("NFKC"),m}}class He extends W{normalize(m){return m=m.normalize("NFKD"),m}}class dt extends W{normalize(m){return this.config.strip_left&&this.config.strip_right?m=m.trim():(this.config.strip_left&&(m=m.trimStart()),this.config.strip_right&&(m=m.trimEnd())),m}}class nt extends W{normalize(m){return m=te(m),m}}class ot extends W{normalize(m){return m=m.toLowerCase(),m}}class Re extends W{normalize(m){return m=this.config.prepend+m,m}}class ht extends W{constructor(m){super(m),this.normalizers=m.normalizers.map(A=>W.fromConfig(A))}normalize(m){return this.normalizers.reduce((A,K)=>K.normalize(A),m)}}class bt extends W{_tokenize_chinese_chars(m){const A=[];for(let K=0;Kthis.pre_tokenize_text(K,A)):this.pre_tokenize_text(m,A)).flat()}_call(m,A){return this.pre_tokenize(m,A)}}class ee extends qe{constructor(m){super(),this.pattern=new RegExp(`[^\\s${L}]+|[${L}]`,"gu")}pre_tokenize_text(m,A){return m.trim().match(this.pattern)||[]}}class Pe extends qe{constructor(m){super(),this.config=m,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Ze,this.text_encoder=new TextEncoder}pre_tokenize_text(m,A){return this.add_prefix_space&&!m.startsWith(" ")&&(m=" "+m),(this.use_regex?m.match(this.pattern)||[]:[m]).map(se=>Array.from(this.text_encoder.encode(se),pe=>this.byte_encoder[pe]).join(""))}}class Ne extends qe{constructor(m){super(),this.config=m,this.pattern=_e(this.config.pattern,this.config.invert)}pre_tokenize_text(m,A){return this.pattern===null?[]:this.config.invert?m.match(this.pattern)||[]:ne(m,this.pattern)}}class Qe extends qe{constructor(m){super(),this.config=m,this.pattern=new RegExp(`[^${L}]+|[${L}]+`,"gu")}pre_tokenize_text(m,A){return m.match(this.pattern)||[]}}class Ue extends qe{constructor(m){super(),this.config=m;const A=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(A,"gu")}pre_tokenize_text(m,A){return m.match(this.pattern)||[]}}class je extends z.Callable{constructor(m){super(),this.config=m}static fromConfig(m){if(m===null)return null;switch(m.type){case"TemplateProcessing":return new vt(m);case"ByteLevel":return new Et(m);case"RobertaProcessing":return new yt(m);case"BertProcessing":return new lt(m);case"Sequence":return new x(m);default:throw new Error(`Unknown PostProcessor type: ${m.type}`)}}post_process(m,...A){throw Error("post_process should be implemented in subclass.")}_call(m,...A){return this.post_process(m,...A)}}class lt extends je{constructor(m){super(m),this.cls=m.cls[0],this.sep=m.sep[0]}post_process(m,A=null,{add_special_tokens:K=!0}={}){K&&(m=(0,me.mergeArrays)([this.cls],m,[this.sep]));let se=new Array(m.length).fill(0);if(A!==null){const pe=K&&this instanceof yt?[this.sep]:[],De=K?[this.sep]:[];m=(0,me.mergeArrays)(m,pe,A,De),se=(0,me.mergeArrays)(se,new Array(A.length+pe.length+De.length).fill(1))}return{tokens:m,token_type_ids:se}}}class yt extends lt{}class vt extends je{constructor(m){super(m),this.single=m.single,this.pair=m.pair}post_process(m,A=null,{add_special_tokens:K=!0}={}){const se=A===null?this.single:this.pair;let pe=[],De=[];for(const wt of se)"SpecialToken"in wt?K&&(pe.push(wt.SpecialToken.id),De.push(wt.SpecialToken.type_id)):"Sequence"in wt&&(wt.Sequence.id==="A"?(pe=(0,me.mergeArrays)(pe,m),De=(0,me.mergeArrays)(De,new Array(m.length).fill(wt.Sequence.type_id))):wt.Sequence.id==="B"&&(pe=(0,me.mergeArrays)(pe,A),De=(0,me.mergeArrays)(De,new Array(A.length).fill(wt.Sequence.type_id))));return{tokens:pe,token_type_ids:De}}}class Et extends je{post_process(m,A=null){return A&&(m=(0,me.mergeArrays)(m,A)),{tokens:m}}}class x extends je{constructor(m){super(m),this.processors=m.processors.map(A=>je.fromConfig(A))}post_process(m,A=null,K={}){let se;for(const pe of this.processors)if(pe instanceof Et)m=pe.post_process(m).tokens,A&&(A=pe.post_process(A).tokens);else{const De=pe.post_process(m,A,K);m=De.tokens,se=De.token_type_ids}return{tokens:m,token_type_ids:se}}}class H extends z.Callable{constructor(m){super(),this.config=m,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=m.trim_offsets}static fromConfig(m){if(m===null)return null;switch(m.type){case"WordPiece":return new Je(m);case"Metaspace":return new Er(m);case"ByteLevel":return new Bt(m);case"Replace":return new $(m);case"ByteFallback":return new Q(m);case"Fuse":return new he(m);case"Strip":return new Ye(m);case"Sequence":return new Tt(m);case"CTC":return new ct(m);case"BPEDecoder":return new At(m);default:throw new Error(`Unknown Decoder type: ${m.type}`)}}_call(m){return this.decode(m)}decode(m){return this.decode_chain(m).join("")}decode_chain(m){throw Error("`decode_chain` should be implemented in subclass.")}}class $ extends H{decode_chain(m){const A=_e(this.config.pattern);return A===null?m:m.map(K=>K.replaceAll(A,this.config.content))}}class Q extends H{constructor(m){super(m),this.text_decoder=new TextDecoder}decode_chain(m){const A=[];let K=[];for(const se of m){let pe=null;if(se.length===6&&se.startsWith("<0x")&&se.endsWith(">")){const De=parseInt(se.slice(3,5),16);isNaN(De)||(pe=De)}if(pe!==null)K.push(pe);else{if(K.length>0){const De=this.text_decoder.decode(Uint8Array.from(K));A.push(De),K=[]}A.push(se)}}if(K.length>0){const se=this.text_decoder.decode(Uint8Array.from(K));A.push(se),K=[]}return A}}class he extends H{decode_chain(m){return[m.join("")]}}class Ye extends H{constructor(m){super(m),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(m){return m.map(A=>{let K=0;for(let pe=0;pe(K!==0&&(A.startsWith(this.config.prefix)?A=A.replace(this.config.prefix,""):A=" "+A),this.cleanup&&(A=q(A)),A))}}class Bt extends H{constructor(m){super(m),this.byte_decoder=Ke,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(m){const A=m.join(""),K=new Uint8Array([...A].map(pe=>this.byte_decoder[pe]));return this.text_decoder.decode(K)}decode_chain(m){const A=[];let K=[];for(const se of m)this.added_tokens.find(pe=>pe.content===se)!==void 0?(K.length>0&&(A.push(this.convert_tokens_to_string(K)),K=[]),A.push(se)):K.push(se);return K.length>0&&A.push(this.convert_tokens_to_string(K)),A}}class ct extends H{constructor(m){super(m),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(m){if(m.length===0)return"";const A=[m[0]];for(let pe=1;pepe!==this.pad_token).join("");return this.cleanup&&(se=q(se).replaceAll(this.word_delimiter_token," ").trim()),se}decode_chain(m){return[this.convert_tokens_to_string(m)]}}class Tt extends H{constructor(m){super(m),this.decoders=m.decoders.map(A=>H.fromConfig(A))}decode_chain(m){return this.decoders.reduce((A,K)=>K.decode_chain(A),m)}}class At extends H{constructor(m){super(m),this.suffix=this.config.suffix}decode_chain(m){return m.map((A,K)=>A.replaceAll(this.suffix,K===m.length-1?"":" "))}}class Pt extends H{decode_chain(m){let A="";for(let K=1;KK.normalize("NFKC")).join("~"):m=m.normalize("NFKC"),m}}class Or extends qe{constructor(m){super(),this.tokenizers=m.pretokenizers.map(A=>qe.fromConfig(A))}pre_tokenize_text(m,A){return this.tokenizers.reduce((K,se)=>se.pre_tokenize(K,A),[m])}}class Ur extends qe{constructor(m){super()}pre_tokenize_text(m,A){return m.match(/\w+|[^\w\s]+/g)||[]}}class at extends qe{constructor(m){super()}pre_tokenize_text(m,A){return I(m)}}class U extends qe{constructor(m){super(),this.config=m,this.pattern=_e(this.config.pattern),this.content=this.config.content}pre_tokenize_text(m,A){return this.pattern===null?[m]:[m.replaceAll(this.pattern,this.config.content)]}}const ge=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ae(ue,m,A,K){for(const se of Object.keys(ue)){const pe=m-ue[se].length,De=A(se),wt=new Array(pe).fill(De);ue[se]=K==="right"?(0,me.mergeArrays)(ue[se],wt):(0,me.mergeArrays)(wt,ue[se])}}function et(ue,m){for(const A of Object.keys(ue))ue[A].length=m}class xe extends z.Callable{constructor(A,K){super();Me(this,"return_token_type_ids",!1);Me(this,"padding_side","right");this._tokenizer_config=K,this.normalizer=W.fromConfig(A.normalizer),this.pre_tokenizer=qe.fromConfig(A.pre_tokenizer),this.model=ke.fromConfig(A.model,K),this.post_processor=je.fromConfig(A.post_processor),this.decoder=H.fromConfig(A.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const se of A.added_tokens){const pe=new ve(se);this.added_tokens.push(pe),this.model.tokens_to_ids.set(pe.content,pe.id),this.model.vocab[pe.id]=pe.content,pe.special&&(this.special_tokens.push(pe.content),this.all_special_ids.push(pe.id))}if(this.additional_special_tokens=K.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((se,pe)=>pe.content.length-se.content.length).map(se=>`${se.lstrip?"\\s*":""}(${(0,me.escapeRegExp)(se.content)})${se.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=K.model_max_length,this.remove_space=K.remove_space,this.clean_up_tokenization_spaces=K.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=K.do_lowercase_and_remove_accent??!1,K.padding_side&&(this.padding_side=K.padding_side),this.legacy=!1,this.chat_template=K.chat_template??null,Array.isArray(this.chat_template)){const se=Object.create(null);for(const{name:pe,template:De}of this.chat_template){if(typeof pe!="string"||typeof De!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');se[pe]=De}this.chat_template=se}this._compiled_template_cache=new Map}getToken(...A){for(const K of A){const se=this._tokenizer_config[K];if(se)if(typeof se=="object"){if(se.__type==="AddedToken")return se.content;throw Error(`Unknown token: ${se}`)}else return se}return null}static async from_pretrained(A,{progress_callback:K=null,config:se=null,cache_dir:pe=null,local_files_only:De=!1,revision:wt="main",legacy:xt=null}={}){const Mt=await re(A,{progress_callback:K,config:se,cache_dir:pe,local_files_only:De,revision:wt,legacy:xt});return new this(...Mt)}_call(A,{text_pair:K=null,add_special_tokens:se=!0,padding:pe=!1,truncation:De=null,max_length:wt=null,return_tensor:xt=!0,return_token_type_ids:Mt=null}={}){const Ot=Array.isArray(A);let Yt;if(Ot){if(A.length===0)throw Error("text array must be non-empty");if(K!==null){if(Array.isArray(K)){if(A.length!==K.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Yt=A.map((ar,Dr)=>this._encode_plus(ar,{text_pair:K[Dr],add_special_tokens:se,return_token_type_ids:Mt}))}else Yt=A.map(ar=>this._encode_plus(ar,{add_special_tokens:se,return_token_type_ids:Mt}))}else{if(A==null)throw Error("text may not be null or undefined");if(Array.isArray(K))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Yt=[this._encode_plus(A,{text_pair:K,add_special_tokens:se,return_token_type_ids:Mt})]}if(wt===null?pe==="max_length"?wt=this.model_max_length:wt=(0,Te.max)(Yt.map(ar=>ar.input_ids.length))[0]:De||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),wt=Math.min(wt,this.model_max_length??1/0),pe||De)for(let ar=0;arwt?De&&et(Yt[ar],wt):pe&&Ae(Yt[ar],wt,Dr=>Dr==="input_ids"?this.pad_token_id:0,this.padding_side));const $r={};if(xt){if(!(pe&&De)&&Yt.some(Dr=>{var Jr;for(const ur of Object.keys(Dr))if(Dr[ur].length!==((Jr=Yt[0][ur])==null?void 0:Jr.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 ar=[Yt.length,Yt[0].input_ids.length];for(const Dr of Object.keys(Yt[0]))$r[Dr]=new Ce.Tensor("int64",BigInt64Array.from(Yt.flatMap(Jr=>Jr[Dr]).map(BigInt)),ar)}else{for(const ar of Object.keys(Yt[0]))$r[ar]=Yt.map(Dr=>Dr[ar]);if(!Ot)for(const ar of Object.keys($r))$r[ar]=$r[ar][0]}return $r}_encode_text(A){return A===null?null:(this.added_tokens_regex?A.split(this.added_tokens_regex).filter(pe=>pe):[A]).map((pe,De)=>{if(this.added_tokens.find(xt=>xt.content===pe)!==void 0)return pe;{if(this.remove_space===!0&&(pe=pe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(pe=ie(pe)),this.normalizer!==null&&(pe=this.normalizer(pe)),pe.length===0)return[];const xt=this.pre_tokenizer!==null?this.pre_tokenizer(pe,{section_index:De}):[pe];return this.model(xt)}}).flat()}_encode_plus(A,{text_pair:K=null,add_special_tokens:se=!0,return_token_type_ids:pe=null}={}){const{tokens:De,token_type_ids:wt}=this._tokenize_helper(A,{pair:K,add_special_tokens:se}),xt=this.model.convert_tokens_to_ids(De),Mt={input_ids:xt,attention_mask:new Array(xt.length).fill(1)};return(pe??this.return_token_type_ids)&&wt&&(Mt.token_type_ids=wt),Mt}_tokenize_helper(A,{pair:K=null,add_special_tokens:se=!1}={}){const pe=this._encode_text(A),De=this._encode_text(K);return this.post_processor?this.post_processor(pe,De,{add_special_tokens:se}):{tokens:(0,me.mergeArrays)(pe??[],De??[])}}tokenize(A,{pair:K=null,add_special_tokens:se=!1}={}){return this._tokenize_helper(A,{pair:K,add_special_tokens:se}).tokens}encode(A,{text_pair:K=null,add_special_tokens:se=!0,return_token_type_ids:pe=null}={}){return this._encode_plus(A,{text_pair:K,add_special_tokens:se,return_token_type_ids:pe}).input_ids}batch_decode(A,K={}){return A instanceof Ce.Tensor&&(A=A.tolist()),A.map(se=>this.decode(se,K))}decode(A,K={}){if(A instanceof Ce.Tensor&&(A=D(A)),!Array.isArray(A)||A.length===0||!(0,me.isIntegralNumber)(A[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(A,K)}decode_single(A,{skip_special_tokens:K=!1,clean_up_tokenization_spaces:se=null}){let pe=this.model.convert_ids_to_tokens(A);K&&(pe=pe.filter(wt=>!this.special_tokens.includes(wt)));let De=this.decoder?this.decoder(pe):pe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(De=De.replaceAll(this.decoder.end_of_word_suffix," "),K&&(De=De.trim())),(se??this.clean_up_tokenization_spaces)&&(De=q(De)),De}get_chat_template({chat_template:A=null,tools:K=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const se=this.chat_template;if(A!==null&&Object.hasOwn(se,A))A=se[A];else if(A===null)if(K!==null&&"tool_use"in se)A=se.tool_use;else if("default"in se)A=se.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(se).sort()}.`)}else if(A===null)if(this.chat_template)A=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 A}apply_chat_template(A,{tools:K=null,documents:se=null,chat_template:pe=null,add_generation_prompt:De=!1,tokenize:wt=!0,padding:xt=!1,truncation:Mt=!1,max_length:Ot=null,return_tensor:Yt=!0,return_dict:$r=!1,tokenizer_kwargs:ar={},...Dr}={}){if(pe=this.get_chat_template({chat_template:pe,tools:K}),typeof pe!="string")throw Error(`chat_template must be a string, but got ${typeof pe}`);let Jr=this._compiled_template_cache.get(pe);Jr===void 0&&(Jr=new S.Template(pe),this._compiled_template_cache.set(pe,Jr));const ur=Object.create(null);for(const _n of ge){const wn=this.getToken(_n);wn&&(ur[_n]=wn)}const Sr=Jr.render({messages:A,add_generation_prompt:De,tools:K,documents:se,...ur,...Dr});if(wt){const _n=this._call(Sr,{add_special_tokens:!1,padding:xt,truncation:Mt,max_length:Ot,return_tensor:Yt,...ar});return $r?_n:_n.input_ids}return Sr}}class Xe extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class gt extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class mt extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class $t extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class ft extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class zt extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class Nt extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class Rt extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class Gt extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class be extends xe{}class tt extends xe{}class st extends xe{constructor(A,K){super(A,K);Me(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 qt extends xe{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class wr extends xe{}class Br extends xe{}class Kr extends xe{}class rr extends xe{constructor(m,A){super(m,A),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)),this.lang_to_token=K=>K}_build_translation_inputs(m,A,K){return Sn(this,m,A,K)}}class Wr extends rr{}class Vr extends xe{}class Ln extends xe{constructor(m,A){var pe,De;const K=".,!?…。,、।۔،",se=(De=(pe=m.pre_tokenizer)==null?void 0:pe.pretokenizers[0])==null?void 0:De.pattern;se&&se.Regex===` ?[^(\\s|[${K}])]+`&&(se.Regex=` ?[^\\s${K}]+`),super(m,A)}}const Rr="▁";class Bn extends xe{constructor(A,K){super(A,K);Me(this,"padding_side","left");this.legacy=K.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new cr({replacement:Rr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(A){if(A===null)return null;if(this.legacy||A.length===0)return super._encode_text(A);let K=super._encode_text(Rr+A.replaceAll(Rr," "));return K.length>1&&K[0]===Rr&&this.special_tokens.includes(K[1])&&(K=K.slice(1)),K}}class Cs extends xe{}class Xs extends xe{}class Es extends xe{}class $s extends xe{}class Ss extends xe{}class Gn extends xe{}class ks extends xe{}class Qs extends xe{}class qn extends xe{}function Sn(ue,m,A,K){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const se=K.src_lang,pe=K.tgt_lang;if(!ue.language_codes.includes(pe))throw new Error(`Target language code "${pe}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(se!==void 0){if(!ue.language_codes.includes(se))throw new Error(`Source language code "${se}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const De of ue.post_processor.config.single)if("SpecialToken"in De&&ue.languageRegex.test(De.SpecialToken.id)){De.SpecialToken.id=ue.lang_to_token(se);break}}return K.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(pe)])[0],ue._call(m,A)}class Cn extends xe{constructor(m,A){super(m,A),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)),this.lang_to_token=K=>K}_build_translation_inputs(m,A,K){return Sn(this,m,A,K)}}class ps extends xe{constructor(m,A){super(m,A),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)).map(K=>K.slice(2,-2)),this.lang_to_token=K=>`__${K}__`}_build_translation_inputs(m,A,K){return Sn(this,m,A,K)}}class ts extends xe{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(m,{return_timestamps:A=!1,return_language:K=!1,time_precision:se=null,force_full_sequences:pe=!0}={}){if(se===null)throw Error("Must specify time_precision");let De=null;const wt=A==="word";function xt(){return{language:De,timestamp:[null,null],text:""}}const Mt=[];let Ot=xt(),Yt=0;const $r=this.timestamp_begin;let ar=[],Dr=[],Jr=!1,ur=null;const Sr=new Set(this.all_special_ids);for(const Se of m){const Zr=Se.tokens,xn=wt?Se.token_timestamps:null;let kn=null,Nn=$r;if("stride"in Se){const[Xr,yr,Ar]=Se.stride;if(Yt-=yr,ur=Xr-Ar,yr&&(Nn=yr/se+$r),Ar)for(let Ct=Zr.length-1;Ct>=0;--Ct){const mr=Number(Zr[Ct]);if(mr>=$r){if(kn!==null&&(mr-$r)*se=$r){const Ar=(yr-$r)*se+Yt,Ct=(0,Te.round)(Ar,2);if(kn!==null&&yr>=kn)Jr=!0;else if(Jr||ar.length>0&&yr0?(ar.push(Ht),wt&&Dr.push(en)):ar.every(Xr=>Xr.length===0)&&(Ot=xt(),ar=[],Ht=[],Dr=[],en=[])}if(ar.length>0){if(pe&&A)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[Se,Zr]=this.findLongestCommonSequence(ar,Dr),xn=this.decode(Se);Ot.text=xn,wt&&(Ot.words=this.collateWordTimestamps(Se,Zr,De)),Mt.push(Ot)}let _n=Object.create(null);const wn=Mt.map(Se=>Se.text).join("");if(A||K){for(let Se=0;Se0;let wt=De?[]:null,xt=De?A[0]:null;for(let Mt=1;MtCt===en[mr]&&xt[Zr+mr]<=A[Mt][Nn+mr]).length:Xr=kn.filter((Ct,mr)=>Ct===en[mr]).length;const yr=Se/1e4,Ar=Xr/Se+yr;Xr>1&&Ar>Yt&&(Yt=Ar,$r=[Zr,xn,Nn,Ht])}const[Dr,Jr,ur,Sr]=$r,_n=Math.floor((Jr+Dr)/2),wn=Math.floor((Sr+ur)/2);pe.push(...K.slice(0,_n)),K=Ot.slice(wn),se=K.length,De&&(wt.push(...xt.slice(0,_n)),xt=A[Mt].slice(wn))}return pe.push(...K),De?(wt.push(...xt),[pe,wt]):[pe,[]]}collateWordTimestamps(m,A,K){const[se,pe,De]=this.combineTokensIntoWords(m,K),wt=[];for(let xt=0;xt=se){const wt=((De-se)*K).toFixed(2);pe.push(`<|${wt}|>`),pe.push([])}else pe[pe.length-1].push(De);return pe=pe.map(De=>typeof De=="string"?De:super.decode(De,A)),pe.join("")}splitTokensOnUnicode(m){const A=this.decode(m,{decode_with_timestamps:!0}),K="�",se=[],pe=[],De=[];let wt=[],xt=[],Mt=0;for(let Ot=0;Ot=this.model.tokens_to_ids.get("<|endoftext|>"),Dr=Ot.startsWith(" "),Jr=Ot.trim(),ur=xt.test(Jr);if(ar||Dr||ur||pe.length===0)pe.push(Ot),De.push(Yt),wt.push($r);else{const Sr=pe.length-1;pe[Sr]+=Ot,De[Sr].push(...Yt),wt[Sr].push(...$r)}}return[pe,De,wt]}mergePunctuations(m,A,K,se,pe){const De=structuredClone(m),wt=structuredClone(A),xt=structuredClone(K);let Mt=De.length-2,Ot=De.length-1;for(;Mt>=0;)De[Mt].startsWith(" ")&&se.includes(De[Mt].trim())?(De[Ot]=De[Mt]+De[Ot],wt[Ot]=(0,me.mergeArrays)(wt[Mt],wt[Ot]),xt[Ot]=(0,me.mergeArrays)(xt[Mt],xt[Ot]),De[Mt]="",wt[Mt]=[],xt[Mt]=[]):Ot=Mt,--Mt;for(Mt=0,Ot=1;OtYt),wt.filter(Yt=>Yt.length>0),xt.filter(Yt=>Yt.length>0)]}get_decoder_prompt_ids({language:m=null,task:A=null,no_timestamps:K=!0}={}){const se=[];if(m){const pe=(0,V.whisper_language_to_code)(m),De=this.model.tokens_to_ids.get(`<|${pe}|>`);if(De===void 0)throw new Error(`Unable to find language "${pe}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);se.push(De)}else se.push(null);if(A){if(A=A.toLowerCase(),A!=="transcribe"&&A!=="translate")throw new Error(`Task "${A}" is not supported. Must be one of: ["transcribe", "translate"]`);const pe=this.model.tokens_to_ids.get(`<|${A}|>`);if(pe===void 0)throw new Error(`Unable to find task "${A}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);se.push(pe)}else se.push(null);if(K){const pe=this.model.tokens_to_ids.get("<|notimestamps|>");if(pe===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);se.push(pe)}return se.map((pe,De)=>[De+1,pe]).filter(pe=>pe[1]!==null)}}class hs extends xe{}class fs extends xe{}class rs extends xe{}class Xt extends xe{constructor(m,A){super(m,A),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(K=>this.languageRegex.test(K)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(m){if(m===null)return null;const[A,...K]=m.trim().split(this.languageRegex);if(K.length===0)return super._encode_text(A);if(K.length===2){const[se,pe]=K;return this.supported_language_codes.includes(se)||console.warn(`Unsupported language code "${se}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,me.mergeArrays)([se],super._encode_text(pe))}}}class ms extends xe{}class _s extends xe{}class Ps extends xe{}class As extends xe{}class gs extends xe{}class Is extends xe{constructor(m,A){super(m,A),this.decoder=new Pt({})}}class ws extends xe{}class ns{static async from_pretrained(m,{progress_callback:A=null,config:K=null,cache_dir:se=null,local_files_only:pe=!1,revision:De="main",legacy:wt=null}={}){var $r;const[xt,Mt]=await re(m,{progress_callback:A,config:K,cache_dir:se,local_files_only:pe,revision:De,legacy:wt}),Ot=(($r=Mt.tokenizer_class)==null?void 0:$r.replace(/Fast$/,""))??"PreTrainedTokenizer";let Yt=this.TOKENIZER_CLASS_MAPPING[Ot];return Yt||(console.warn(`Unknown tokenizer class "${Ot}", attempting to construct from base class.`),Yt=xe),new Yt(xt,Mt)}}Me(ns,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:wr,DistilBertTokenizer:be,CamembertTokenizer:tt,DebertaTokenizer:ft,DebertaV2Tokenizer:zt,BertTokenizer:Xe,HerbertTokenizer:Nt,ConvBertTokenizer:Rt,RoFormerTokenizer:Gt,XLMTokenizer:st,ElectraTokenizer:qt,MobileBertTokenizer:mt,SqueezeBertTokenizer:$t,AlbertTokenizer:gt,GPT2Tokenizer:Br,BartTokenizer:Kr,MBartTokenizer:rr,MBart50Tokenizer:Wr,RobertaTokenizer:Vr,WhisperTokenizer:ts,CodeGenTokenizer:hs,CLIPTokenizer:fs,SiglipTokenizer:rs,MarianTokenizer:Xt,BloomTokenizer:Ln,NllbTokenizer:Cn,M2M100Tokenizer:ps,LlamaTokenizer:Bn,CodeLlamaTokenizer:Cs,XLMRobertaTokenizer:Xs,MPNetTokenizer:Es,FalconTokenizer:$s,GPTNeoXTokenizer:Ss,EsmTokenizer:Gn,Wav2Vec2CTCTokenizer:ms,BlenderbotTokenizer:_s,BlenderbotSmallTokenizer:Ps,SpeechT5Tokenizer:As,NougatTokenizer:gs,VitsTokenizer:Is,Qwen2Tokenizer:ks,GemmaTokenizer:Qs,Grok1Tokenizer:qn,CohereTokenizer:ws,PreTrainedTokenizer:xe})},"./src/utils/audio.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{hamming:()=>V,hanning:()=>S,mel_filter_bank:()=>q,read_audio:()=>Ce,spectrogram:()=>I,window_function:()=>L});var z=N("./src/utils/hub.js"),me=N("./src/utils/maths.js"),we=N("./src/utils/core.js"),Te=N("./src/utils/tensor.js");async function Ce(k,de){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const ve=await(await(0,z.getFile)(k)).arrayBuffer(),ke=new AudioContext({sampleRate:de});typeof de>"u"&&console.warn(`No sampling rate provided, using default of ${ke.sampleRate}Hz.`);const ze=await ke.decodeAudioData(ve);let Ie;if(ze.numberOfChannels===2){const Ze=Math.sqrt(2),Ke=ze.getChannelData(0),ut=ze.getChannelData(1);Ie=new Float32Array(Ke.length);for(let ye=0;ye2595*Math.log10(1+k/700),kaldi:k=>1127*Math.log(1+k/700),slaney:(k,de=1e3,ve=15,ke=27/Math.log(6.4))=>k>=de?ve+Math.log(k/de)*ke:3*k/200};function re(k,de="htk"){const ve=P[de];if(!ve)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?ve(k):k.map(ke=>ve(ke))}const ne={htk:k=>700*(10**(k/2595)-1),kaldi:k=>700*(Math.exp(k/1127)-1),slaney:(k,de=1e3,ve=15,ke=Math.log(6.4)/27)=>k>=ve?de*Math.exp(ke*(k-ve)):200*k/3};function _e(k,de="htk"){const ve=ne[de];if(!ve)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?ve(k):k.map(ke=>ve(ke))}function ce(k,de){const ve=Float64Array.from({length:de.length-1},(Ze,Ke)=>de[Ke+1]-de[Ke]),ke=Array.from({length:k.length},()=>new Array(de.length));for(let Ze=0;Zenew Array(k.length));for(let Ze=0;Zek+ke*Ie)}function q(k,de,ve,ke,ze,Ie=null,Ze="htk",Ke=!1){if(Ie!==null&&Ie!=="slaney")throw new Error('norm must be one of null or "slaney"');const ut=re(ve,Ze),ye=re(ke,Ze),W=D(ut,ye,de+2);let fe=_e(W,Ze),$e;if(Ke){const He=ze/(k*2);$e=re(Float64Array.from({length:k},(dt,nt)=>nt*He),Ze),fe=W}else $e=D(0,Math.floor(ze/2),k);const Y=ce($e,fe);if(Ie!==null&&Ie==="slaney")for(let He=0;Heze)throw Error(`frame_length (${ve}) may not be larger than fft_length (${ze})`);if(qe!==ve)throw new Error(`Length of the window (${qe}) must equal frame_length (${ve})`);if(ke<=0)throw new Error("hop_length must be greater than zero");if(Ie===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(Ze){if(Ke!=="reflect")throw new Error(`pad_mode="${Ke}" not implemented yet.`);const H=Math.floor((ze-1)/2)+1;k=te(k,H,H)}let ee=Math.floor(1+Math.floor((k.length-ve)/ke));ot!==null&&eeee?ht&&(Qe=Re):Qe=Ne=Re);const Ue=new me.FFT(ze),je=new Float64Array(ze),lt=new Float64Array(Ue.outputBufferSize),yt=new Float32Array(Pe*Qe);for(let H=0;H=1;--he)je[he]-=ye*je[he-1];je[0]*=1-ye}for(let he=0;heMath.pow(Ke,.85));break;default:throw new Error(`Unknown window type ${de}.`)}if(ve&&(Ze=Ze.subarray(0,k)),ke===null)return Ze;if(k>ke)throw new Error(`Length of the window (${k}) may not be larger than frame_length (${ke})`);return Ze}},"./src/utils/constants.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{GITHUB_ISSUE_URL:()=>z});const z="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{calculateDimensions:()=>R,calculateReflectOffset:()=>re,dispatchCallback:()=>z,escapeRegExp:()=>we,isIntegralNumber:()=>Ce,isTypedArray:()=>Te,len:()=>_e,mergeArrays:()=>V,pick:()=>ne,pop:()=>S,product:()=>P,reverseDictionary:()=>me});function z(ce,D){ce&&ce(D)}function me(ce){return Object.fromEntries(Object.entries(ce).map(([D,q])=>[q,D]))}function we(ce){return ce.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Te(ce){var D,q,te;return((te=(q=(D=ce==null?void 0:ce.prototype)==null?void 0:D.__proto__)==null?void 0:q.constructor)==null?void 0:te.name)==="TypedArray"}function Ce(ce){return Number.isInteger(ce)||typeof ce=="bigint"}function R(ce){const D=[];let q=ce;for(;Array.isArray(q);)D.push(q.length),q=q[0];return D}function S(ce,D,q=void 0){const te=ce[D];if(te!==void 0)return delete ce[D],te;if(q===void 0)throw Error(`Key ${D} does not exist in object.`);return q}function V(...ce){return Array.prototype.concat.apply([],ce)}function P(...ce){return ce.reduce((D,q)=>D.flatMap(te=>q.map(ie=>[te,ie])))}function re(ce,D){return Math.abs((ce+D)%(2*D)-D)}function ne(ce,D){return Object.assign({},...D.map(q=>{if(ce[q]!==void 0)return{[q]:ce[q]}}))}function _e(ce){let D=0;for(const q of ce)++D;return D}},"./src/utils/data-structures.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{CharTrie:()=>me,PriorityQueue:()=>z,TokenLattice:()=>Te});class z{constructor(S=(P,re)=>P>re,V=1/0){this._heap=[],this._comparator=S,this._maxSize=V}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...S){return this.extend(S)}extend(S){for(const V of S)if(this.size0&&this._swap(0,V),this._heap.pop(),this._siftDown(),S}replace(S){const V=this.peek();return this._heap[0]=S,this._siftDown(),V}_parent(S){return(S+1>>>1)-1}_left(S){return(S<<1)+1}_right(S){return S+1<<1}_greater(S,V){return this._comparator(this._heap[S],this._heap[V])}_swap(S,V){const P=this._heap[S];this._heap[S]=this._heap[V],this._heap[V]=P}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(S){for(;S>0&&this._greater(S,this._parent(S));)this._swap(S,this._parent(S)),S=this._parent(S)}_siftDown(){let S=0;for(;this._left(S)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const re=new Ce(this.bosTokenId,0,0,0,0),ne=new Ce(this.eosTokenId,1,this.len,0,0);this.nodes.push(re.clone()),this.nodes.push(ne.clone()),this.beginNodes[this.len].push(ne),this.endNodes[0].push(re)}insert(S,V,P,re){const ne=this.nodes.length,_e=new Ce(re,ne,S,V,P);this.beginNodes[S].push(_e),this.endNodes[S+V].push(_e),this.nodes.push(_e)}viterbi(){const S=this.len;let V=0;for(;V<=S;){if(this.beginNodes[V].length==0)return[];for(let ce of this.beginNodes[V]){ce.prev=null;let D=0,q=null;for(let te of this.endNodes[V]){const ie=te.backtraceScore+ce.score;(q===null||ie>D)&&(q=te.clone(),D=ie)}if(q!==null)ce.prev=q,ce.backtraceScore=D;else return[]}++V}const P=[],ne=this.beginNodes[S][0].prev;if(ne===null)return[];let _e=ne.clone();for(;_e.prev!==null;)P.push(_e.clone()),_e=_e.clone().prev.clone();return P.reverse(),P}piece(S){return this.chars.slice(S.pos,S.pos+S.length).join("")}tokens(){return this.viterbi().map(V=>this.piece(V))}tokenIds(){return this.viterbi().map(V=>V.tokenId)}}class Ce{constructor(S,V,P,re,ne){this.tokenId=S,this.nodeId=V,this.pos=P,this.length=re,this.score=ne,this.prev=null,this.backtraceScore=0}clone(){const S=new Ce(this.tokenId,this.nodeId,this.pos,this.length,this.score);return S.prev=this.prev,S.backtraceScore=this.backtraceScore,S}}},"./src/utils/devices.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{DEVICE_TYPES:()=>z});const z=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":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{DATA_TYPES:()=>Te,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Ce,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>R,isWebGpuFp16Supported:()=>we});var z=N("./src/env.js"),me=N("./src/utils/devices.js");const we=function(){let S;return async function(){if(S===void 0)if(!z.apis.IS_WEBGPU_AVAILABLE)S=!1;else try{S=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{S=!1}return S}}(),Te=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Ce=Object.freeze({[me.DEVICE_TYPES.wasm]:Te.q8}),R=Object.freeze({[Te.fp32]:"",[Te.fp16]:"_fp16",[Te.int8]:"_int8",[Te.uint8]:"_uint8",[Te.q8]:"_quantized",[Te.q4]:"_q4",[Te.q4f16]:"_q4f16",[Te.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{Callable:()=>z});const z=class{constructor(){let me=function(...we){return me._call(...we)};return Object.setPrototypeOf(me,new.target.prototype)}_call(...me){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{getFile:()=>V,getModelFile:()=>ce,getModelJSON:()=>D});var z=N("?7a2c"),me=N("?a42a"),we=N("./src/env.js"),Te=N("./src/utils/core.js");const Ce={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class R{constructor(X){if(this.filePath=X,this.headers=new Headers,this.exists=z.existsSync(X),this.exists){this.status=200,this.statusText="OK";let j=z.statSync(X);this.headers.set("content-length",j.size.toString()),this.updateContentType();let I=this;this.body=new ReadableStream({start(L){I.arrayBuffer().then(k=>{L.enqueue(new Uint8Array(k)),L.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const X=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Ce[X]??"application/octet-stream")}clone(){let X=new R(this.filePath);return X.exists=this.exists,X.status=this.status,X.statusText=this.statusText,X.headers=new Headers(this.headers),X}async arrayBuffer(){return(await z.promises.readFile(this.filePath)).buffer}async blob(){const X=await z.promises.readFile(this.filePath);return new Blob([X],{type:this.headers.get("content-type")})}async text(){return await z.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function S(ie,X=null,j=null){let I;try{I=new URL(ie)}catch{return!1}return!(X&&!X.includes(I.protocol)||j&&!j.includes(I.hostname))}async function V(ie){var X;if(we.env.useFS&&!S(ie,["http:","https:","blob:"]))return new R(ie);if(typeof process<"u"&&((X=process==null?void 0:process.release)==null?void 0:X.name)==="node"){const j=!!(Tn!=null&&Tn.TESTING_REMOTELY),I=we.env.version,L=new Headers;if(L.set("User-Agent",`transformers.js/${I}; is_ci/${j};`),S(ie,["http:","https:"],["huggingface.co","hf.co"])){const de=(Tn==null?void 0:Tn.HF_TOKEN)??(Tn==null?void 0:Tn.HF_ACCESS_TOKEN);de&&L.set("Authorization",`Bearer ${de}`)}return fetch(ie,{headers:L})}else return fetch(ie)}const P={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 re(ie,X,j){if(!j)return null;const I=P[ie]??`Error (${ie}) occurred while trying to load file`;throw Error(`${I}: "${X}".`)}class ne{constructor(X){this.path=X}async match(X){let j=me.join(this.path,X),I=new R(j);if(I.exists)return I}async put(X,j){const I=Buffer.from(await j.arrayBuffer());let L=me.join(this.path,X);try{await z.promises.mkdir(me.dirname(L),{recursive:!0}),await z.promises.writeFile(L,I)}catch(k){console.warn("An error occurred while writing the file to cache:",k)}}}async function _e(ie,...X){for(let j of X)try{let I=await ie.match(j);if(I)return I}catch{continue}}async function ce(ie,X,j=!0,I={}){if(!we.env.allowLocalModels){if(I.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!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,Te.dispatchCallback)(I.progress_callback,{status:"initiate",name:ie,file:X});let L;if(!L&&we.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{L=await caches.open("transformers-cache")}catch($e){console.warn("An error occurred while opening the browser cache:",$e)}}if(!L&&we.env.useFSCache&&(L=new ne(I.cache_dir??we.env.cacheDir)),!L&&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");L=we.env.customCache}const k=I.revision??"main";let de=te(ie,X),ve=te(we.env.localModelPath,de),ke=te(we.env.remoteHost,we.env.remotePathTemplate.replaceAll("{model}",ie).replaceAll("{revision}",encodeURIComponent(k)),X),ze=k==="main"?de:te(ie,k,X),Ie,Ze=L instanceof ne?ze:ke,Ke=!1,ut;L&&(ut=await _e(L,ve,Ze));const ye=ut!==void 0;if(ut===void 0){if(we.env.allowLocalModels)if(S(de,["http:","https:"])){if(I.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${de}.`);if(!we.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${de}.`)}else try{ut=await V(ve),Ie=ve}catch(Y){console.warn(`Unable to load from local path "${ve}": "${Y}"`)}if(ut===void 0||ut.status===404){if(I.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 "${ve}".`);return null}if(ut=await V(ke),ut.status!==200)return re(ut.status,ke,j);Ie=Ze}Ke=L&&typeof Response<"u"&&ut instanceof Response&&ut.status===200}(0,Te.dispatchCallback)(I.progress_callback,{status:"download",name:ie,file:X});const W={status:"progress",name:ie,file:X};let fe;return I.progress_callback?ye&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(fe=new Uint8Array(await ut.arrayBuffer()),(0,Te.dispatchCallback)(I.progress_callback,{...W,progress:100,loaded:fe.length,total:fe.length})):fe=await q(ut,$e=>{(0,Te.dispatchCallback)(I.progress_callback,{...W,...$e})}):fe=new Uint8Array(await ut.arrayBuffer()),Ke&&Ie&&await L.match(Ie)===void 0&&await L.put(Ie,new Response(fe,{headers:ut.headers})).catch($e=>{console.warn(`Unable to add response to browser cache: ${$e}.`)}),(0,Te.dispatchCallback)(I.progress_callback,{status:"done",name:ie,file:X}),fe}async function D(ie,X,j=!0,I={}){let L=await ce(ie,X,j,I);if(L===null)return{};let de=new TextDecoder("utf-8").decode(L);return JSON.parse(de)}async function q(ie,X){const j=ie.headers.get("Content-Length");j===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let I=parseInt(j??"0"),L=new Uint8Array(I),k=0;const de=ie.body.getReader();async function ve(){const{done:ke,value:ze}=await de.read();if(ke)return;let Ie=k+ze.length;if(Ie>I){I=Ie;let Ke=new Uint8Array(I);Ke.set(L),L=Ke}L.set(ze,k),k=Ie;const Ze=k/I*100;return X({progress:Ze,loaded:k,total:I}),ve()}return await ve(),L}function te(...ie){return ie=ie.map((X,j)=>(j&&(X=X.replace(new RegExp("^/"),"")),j!==ie.length-1&&(X=X.replace(new RegExp("/$"),"")),X)),ie.join("/")}},"./src/utils/image.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{RawImage:()=>_e});var z=N("./src/utils/hub.js"),me=N("./src/env.js"),we=N("./src/utils/tensor.js"),Te=N("?2b25");const Ce=typeof self<"u",R=Ce&&self.constructor.name==="DedicatedWorkerGlobalScope";let S,V,P;if(Ce)S=(ce,D)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ce,D)},P=self.createImageBitmap,V=self.ImageData;else if(Te)P=async ce=>{const q=(await ce.metadata()).channels,{data:te,info:ie}=await ce.rotate().raw().toBuffer({resolveWithObject:!0}),X=new _e(new Uint8ClampedArray(te),ie.width,ie.height,ie.channels);return q!==void 0&&q!==ie.channels&&X.convert(q),X};else throw new Error("Unable to load image processing library.");const re={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},ne=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _e{constructor(D,q,te,ie){this.data=D,this.width=q,this.height=te,this.channels=ie}get size(){return[this.width,this.height]}static async read(D){if(D instanceof _e)return D;if(typeof D=="string"||D instanceof URL)return await this.fromURL(D);throw new Error(`Unsupported input type: ${typeof D}`)}static fromCanvas(D){if(!Ce)throw new Error("fromCanvas() is only supported in browser environments.");const te=D.getContext("2d").getImageData(0,0,D.width,D.height).data;return new _e(te,D.width,D.height,4)}static async fromURL(D){const q=await(0,z.getFile)(D);if(q.status!==200)throw new Error(`Unable to read image from "${D}" (${q.status} ${q.statusText})`);const te=await q.blob();return this.fromBlob(te)}static async fromBlob(D){if(Ce){const q=await P(D),te=S(q.width,q.height).getContext("2d");return te.drawImage(q,0,0),new this(te.getImageData(0,0,q.width,q.height).data,q.width,q.height,4)}else{const q=Te(await D.arrayBuffer());return await P(q)}}static fromTensor(D,q="CHW"){if(D.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${D.dims.length} dimensions.`);if(q==="CHW")D=D.transpose(1,2,0);else if(q!=="HWC")throw new Error(`Unsupported channel format: ${q}`);if(!(D.data instanceof Uint8ClampedArray||D.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${D.type}`);switch(D.dims[2]){case 1:case 2:case 3:case 4:return new _e(D.data,D.dims[1],D.dims[0],D.dims[2]);default:throw new Error(`Unsupported number of channels: ${D.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const D=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let q=0,te=0;q=0?L=te:de=-te,ie>=0?k=ie:ve=-ie,I.drawImage(j,L,k,D,q,de,ve,D,q),new _e(I.getImageData(0,0,D,q).data,D,q,4).convert(X)}else{let X=this.toSharp();if(te>=0&&ie>=0)X=X.extract({left:Math.floor(te),top:Math.floor(ie),width:D,height:q});else if(te<=0&&ie<=0){const j=Math.floor(-ie),I=Math.floor(-te);X=X.extend({top:j,left:I,right:D-this.width-I,bottom:q-this.height-j})}else{let j=[0,0],I=0;ie<0?(j[0]=Math.floor(-ie),j[1]=q-this.height-j[0]):I=Math.floor(ie);let L=[0,0],k=0;te<0?(L[0]=Math.floor(-te),L[1]=D-this.width-L[0]):k=Math.floor(te),X=X.extend({top:j[0],bottom:j[1],left:L[0],right:L[1]}).extract({left:k,top:I,width:D,height:q})}return await P(X)}}async toBlob(D="image/png",q=1){if(!Ce)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:D,quality:q})}toTensor(D="CHW"){let q=new we.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(D!=="HWC")if(D==="CHW")q=q.permute(2,0,1);else throw new Error(`Unsupported channel format: ${D}`);return q}toCanvas(){if(!Ce)throw new Error("toCanvas() is only supported in browser environments.");const D=this.clone().rgba(),q=S(D.width,D.height),te=new V(D.data,D.width,D.height);return q.getContext("2d").putImageData(te,0,0),q}_update(D,q,te,ie=null){return this.data=D,this.width=q,this.height=te,ie!==null&&(this.channels=ie),this}clone(){return new _e(this.data.slice(),this.width,this.height,this.channels)}convert(D){if(this.channels===D)return this;switch(D){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(D){if(Ce){if(R)throw new Error("Unable to save an image from a Web Worker.");const q=D.split(".").pop().toLowerCase(),te=ne.get(q)??"image/png",ie=await this.toBlob(te),X=URL.createObjectURL(ie),j=document.createElement("a");j.href=X,j.download=D,j.click(),j.remove()}else{if(me.env.useFS)return await this.toSharp().toFile(D);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Ce)throw new Error("toSharp() is only supported in server-side environments.");return Te(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{FFT:()=>ce,bankers_round:()=>te,cos_sim:()=>R,dot:()=>Ce,dynamic_time_warping:()=>ie,interpolate_data:()=>z,log_softmax:()=>Te,magnitude:()=>S,max:()=>P,medianFilter:()=>D,min:()=>V,permute_data:()=>me,round:()=>q,softmax:()=>we});function z(X,[j,I,L],[k,de],ve="bilinear",ke=!1){const ze=de/L,Ie=k/I,Ze=new X.constructor(k*de*j),Ke=I*L,ut=k*de;for(let ye=0;ye=0;--ke)k[ke]=ze,L[ke]=j[I[ke]],ze*=L[ke];const de=I.map((ke,ze)=>k[I.indexOf(ze)]),ve=new X.constructor(X.length);for(let ke=0;ke=0;--Ie)ze+=Ze%j[Ie]*de[Ie],Ze=Math.floor(Ze/j[Ie]);ve[ze]=X[ke]}return[ve,L]}function we(X){const j=P(X)[0],I=X.map(de=>Math.exp(de-j)),L=I.reduce((de,ve)=>de+ve,0);return I.map(de=>de/L)}function Te(X){const j=P(X)[0];let I=0;for(let de=0;dede-j-L)}function Ce(X,j){let I=0;for(let L=0;Lj+I*I,0))}function V(X){if(X.length===0)throw Error("Array must not be empty");let j=X[0],I=0;for(let L=1;Lj&&(j=X[L],I=L);return[Number(j),I]}function re(X){return X>0&&(X&X-1)===0}class ne{constructor(j){if(this.size=j|0,this.size<=1||!re(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 L=0;LL;L<<=1)++I;this._width=I%2===0?I-1:I,this._bitrev=new Int32Array(1<>>k&3)<>>1);for(let k=0;k>>1]=j[k];return L}toComplexArray(j,I){const L=I||this.createComplexArray();for(let k=0;k>>1],L[k+1]=0;return L}transform(j,I){if(j===I)throw new Error("Input and output buffers must be different");this._transform4(j,I,1)}realTransform(j,I){if(j===I)throw new Error("Input and output buffers must be different");this._realTransform4(j,I,1)}inverseTransform(j,I){if(j===I)throw new Error("Input and output buffers must be different");this._transform4(j,I,-1);for(let L=0;L>=2;ve>=2;ve>>=2){ke=k/ve<<1;const ut=ke>>>2;for(ze=0;ze>>1,ve>>>1)}else for(ze=0,Ie=0;ze>>1,ve>>>1,L)}const Ke=this.table;for(ve>>=2;ve>=2;ve>>=2){ke=k/ve<<1;const ye=ke>>>1,W=ye>>>1,fe=W>>>1;for(ze=0;ze>>1;for(let ye=2;ye>1;++Ze){const Ke=(Ze+1-j)**2/2,ut=Math.sqrt(ze**2+Ie**2)**Ke,ye=Ke*Math.atan2(Ie,ze),W=2*Ze;de[W]=ut*Math.cos(ye),de[W+1]=ut*Math.sin(ye),ve[W]=de[W],ve[W+1]=-de[W+1]}this._slicedChirpBuffer=de.subarray(I,L),this._f=new ne(k>>1),this._f.transform(this._chirpBuffer,ve)}_transform(j,I,L){const k=this._buffer1,de=this._buffer2,ve=this._outBuffer1,ke=this._outBuffer2,ze=this._chirpBuffer,Ie=this._slicedChirpBuffer,Ze=this._a;if(L)for(let Ke=0;Ke>1,W=I[ye];k[Ke]=W*Ie[Ke],k[ut]=W*Ie[ut]}else for(let Ke=0;Ke=X.length&&(ze=2*(X.length-1)-ze),L[ve++]=X[ze]}L.sort(),I[de]=L[k]}return I}function q(X,j){const I=Math.pow(10,j);return Math.round(X*I)/I}function te(X){const j=Math.round(X);return Math.abs(X)%1===.5?j%2===0?j:j-1:j}function ie(X){const j=X.length,I=X[0].length,L=[j+1,I+1],k=Array.from({length:L[0]},()=>Array(L[1]).fill(1/0));k[0][0]=0;const de=Array.from({length:L[0]},()=>Array(L[1]).fill(-1));for(let Ze=1;Ze0||ke>0;)switch(ze.push(ve-1),Ie.push(ke-1),de[ve][ke]){case 0:--ve,--ke;break;case 1:--ve;break;case 2:--ke;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ve}, ${ke}]. Please file a bug report.`)}return ze.reverse(),Ie.reverse(),[ze,Ie]}},"./src/utils/tensor.js":(Ft,Ee,N)=>{N.r(Ee),N.d(Ee,{Tensor:()=>Ce,cat:()=>X,full:()=>ve,full_like:()=>ke,interpolate:()=>V,interpolate_4d:()=>P,layer_norm:()=>D,matmul:()=>re,mean:()=>L,mean_pooling:()=>ce,ones:()=>ze,ones_like:()=>Ie,permute:()=>S,quantize_embeddings:()=>ut,rfft:()=>ne,stack:()=>j,std_mean:()=>I,topk:()=>_e,zeros:()=>Ze,zeros_like:()=>Ke});var z=N("./src/utils/maths.js"),me=N("./src/backends/onnx.js"),we=N("./src/ops/registry.js");const Te=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class Ce{constructor(...W){Me(this,"ort_tensor");return(0,me.isONNXTensor)(W[0])?this.ort_tensor=W[0]:this.ort_tensor=new me.Tensor(W[0],W[1],W[2]),new Proxy(this,{get:(fe,$e)=>{if(typeof $e=="string"){let Y=Number($e);if(Number.isInteger(Y))return fe._getitem(Y)}return fe[$e]},set:(fe,$e,Y)=>fe[$e]=Y})}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,...fe]=this.dims;if(fe.length>0){const $e=fe.reduce((Y,He)=>Y*He);for(let Y=0;Y0){const Y=$e.reduce((He,dt)=>He*dt);return this._subarray(W,Y,$e)}else return new Ce(this.type,[this.data[W]],$e)}indexOf(W){const fe=this.data;for(let $e=0;$eqe)throw new Error(`Invalid slice: ${ht}`);const ee=[Math.max(bt,0),Math.min(qe,this.dims[Re])];$e.push(ee),fe.push(ee[1]-ee[0])}else throw new Error(`Invalid slice: ${ht}`)}const Y=$e.map(([Re,ht])=>ht-Re),He=Y.reduce((Re,ht)=>Re*ht),dt=this.data,nt=new dt.constructor(He),ot=this.stride();for(let Re=0;Re=0;--bt){const ee=Y[bt];ht+=(qe%ee+$e[bt][0])*ot[bt],qe=Math.floor(qe/ee)}nt[Re]=dt[ht]}return new Ce(this.type,nt,fe)}permute(...W){return S(this,W)}transpose(...W){return this.permute(...W)}sum(W=null,fe=!1){return this.norm(1,W,fe)}norm(W="fro",fe=null,$e=!1){if(W==="fro")W=2;else if(typeof W=="string")throw Error(`Unsupported norm: ${W}`);const Y=this.data;if(fe===null){let nt=Y.reduce((ot,Re)=>ot+Re**W,0)**(1/W);return new Ce(this.type,[nt],[])}fe=ie(fe,this.dims.length);const He=this.dims.slice();He[fe]=1;const dt=new Y.constructor(Y.length/this.dims[fe]);for(let nt=0;nt=0;--Re){const qe=this.dims[Re];if(Re!==fe){const ee=ht%qe;ot+=ee*bt,bt*=He[Re]}ht=Math.floor(ht/qe)}dt[ot]+=Y[nt]**W}if(W!==1)for(let nt=0;nt=0;--ot){const bt=this.dims[ot];if(ot!==fe){const qe=Re%bt;nt+=qe*ht,ht*=this.dims[ot]}Re=Math.floor(Re/bt)}Y[dt]/=He[nt]}return this}normalize(W=2,fe=1){return this.clone().normalize_(W,fe)}stride(){return k(this.dims)}squeeze(W=null){return new Ce(this.type,this.data,q(this.dims,W))}squeeze_(W=null){return this.dims=q(this.dims,W),this}unsqueeze(W=null){return new Ce(this.type,this.data,te(this.dims,W))}unsqueeze_(W=null){return this.dims=te(this.dims,W),this}flatten_(W=0,fe=-1){fe=(fe+this.dims.length)%this.dims.length;let $e=this.dims.slice(0,W),Y=this.dims.slice(W,fe+1),He=this.dims.slice(fe+1);return this.dims=[...$e,Y.reduce((dt,nt)=>dt*nt,1),...He],this}flatten(W=0,fe=-1){return this.clone().flatten_(W,fe)}view(...W){let fe=-1;for(let Y=0;Ynt!==fe?He*dt:He,1);W[fe]=$e.length/Y}return new Ce(this.type,$e,W)}neg_(){const W=this.data;for(let fe=0;feHe*dt);if(fe!==$e)throw Error(`cannot reshape array of size ${fe} into shape (${W})`);let Y=ye;for(let He=W.length-1;He>=0;He--)Y=Y.reduce((dt,nt)=>{let ot=dt[dt.length-1];return ot.lengthfe!==1):typeof W=="number"?ye[W]===1&&ye.splice(W,1):Array.isArray(W)&&(ye=ye.filter((fe,$e)=>fe!==1||!W.includes($e))),ye}function te(ye,W){return W=ie(W,ye.length+1),ye=ye.slice(),ye.splice(W,0,1),ye}function ie(ye,W,fe=null,$e=!0){if($e&&(ye<-W||ye>=W))throw new Error(`IndexError: index ${ye} is out of bounds for dimension${fe===null?"":" "+fe} with size ${W}`);return ye<0&&(ye=(ye%W+W)%W),ye}function X(ye,W=0){W=ie(W,ye[0].dims.length);const fe=ye[0].dims.slice();fe[W]=ye.reduce((dt,nt)=>dt+nt.dims[W],0);const $e=fe.reduce((dt,nt)=>dt*nt,1),Y=new ye[0].data.constructor($e),He=ye[0].type;if(W===0){let dt=0;for(const nt of ye){const ot=nt.data;Y.set(ot,dt),dt+=ot.length}}else{let dt=0;for(let nt=0;nt=0;--qe){const Ne=Re[qe];let Qe=ee%Ne;qe===W&&(Qe+=dt),bt+=Qe*Pe,Pe*=fe[qe],ee=Math.floor(ee/Ne)}Y[bt]=ot[ht]}dt+=Re[W]}}return new Ce(He,Y,fe)}function j(ye,W=0){return X(ye.map(fe=>fe.unsqueeze(W)),W)}function I(ye,W=null,fe=1,$e=!1){const Y=ye.data,He=ye.dims;if(W===null){const qe=Y.reduce((Qe,Ue)=>Qe+Ue,0)/Y.length,ee=Math.sqrt(Y.reduce((Qe,Ue)=>Qe+(Ue-qe)**2,0)/(Y.length-fe)),Pe=new Ce(ye.type,[qe],[]);return[new Ce(ye.type,[ee],[]),Pe]}W=ie(W,He.length);const dt=L(ye,W,$e),nt=dt.data,ot=He.slice();ot[W]=1;const Re=new Y.constructor(Y.length/He[W]);for(let bt=0;bt=0;--ee){const Qe=He[ee];if(ee!==W){const Ue=Pe%Qe;qe+=Ue*Ne,Ne*=ot[ee]}Pe=Math.floor(Pe/Qe)}Re[qe]+=(Y[bt]-nt[qe])**2}for(let bt=0;btot+Re,0);return new Ce(ye.type,[nt/$e.length],[])}const Y=ye.dims;W=ie(W,Y.length);const He=Y.slice();He[W]=1;const dt=new $e.constructor($e.length/Y[W]);for(let nt=0;nt<$e.length;++nt){let ot=0;for(let Re=Y.length-1,ht=nt,bt=1;Re>=0;--Re){const qe=Y[Re];if(Re!==W){const ee=ht%qe;ot+=ee*bt,bt*=He[Re]}ht=Math.floor(ht/qe)}dt[ot]+=$e[nt]}if(Y[W]!==1)for(let nt=0;nt=0;--fe)W[fe]=$e,$e*=ye[fe];return W}function de(ye,W,fe,$e){const Y=ye.reduce((He,dt)=>He*dt,1);return new Ce(fe,new $e(Y).fill(W),ye)}function ve(ye,W){let fe,$e;if(typeof W=="number")fe="float32",$e=Float32Array;else if(typeof W=="bigint")fe="int64",$e=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof W}`);return de(ye,W,fe,$e)}function ke(ye,W){return ve(ye.dims,W)}function ze(ye){return de(ye,1n,"int64",BigInt64Array)}function Ie(ye){return ze(ye.dims)}function Ze(ye){return de(ye,0n,"int64",BigInt64Array)}function Ke(ye){return Ze(ye.dims)}function ut(ye,W){if(ye.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ye.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(W))throw new Error("The precision must be either 'binary' or 'ubinary'");const fe=W==="binary",$e=fe?"int8":"uint8",Y=fe?Int8Array:Uint8Array,He=ye.data,dt=new Y(He.length/8);for(let nt=0;nt0?1:0,Re=Math.floor(nt/8),ht=nt%8;dt[Re]|=ot<<7-ht,fe&&ht===0&&(dt[Re]-=128)}return new Ce($e,dt,[ye.dims[0],ye.dims[1]/8])}}},Ks={};function Gr(Ft){var Ee=Ks[Ft];if(Ee!==void 0)return Ee.exports;var N=Ks[Ft]={exports:{}};return es[Ft](N,N.exports,Gr),N.exports}Gr.m=es,(()=>{var Ft=Object.getPrototypeOf?N=>Object.getPrototypeOf(N):N=>N.__proto__,Ee;Gr.t=function(N,z){if(z&1&&(N=this(N)),z&8||typeof N=="object"&&N&&(z&4&&N.__esModule||z&16&&typeof N.then=="function"))return N;var me=Object.create(null);Gr.r(me);var we={};Ee=Ee||[null,Ft({}),Ft([]),Ft(Ft)];for(var Te=z&2&&N;typeof Te=="object"&&!~Ee.indexOf(Te);Te=Ft(Te))Object.getOwnPropertyNames(Te).forEach(Ce=>we[Ce]=()=>N[Ce]);return we.default=()=>N,Gr.d(me,we),me}})(),Gr.d=(Ft,Ee)=>{for(var N in Ee)Gr.o(Ee,N)&&!Gr.o(Ft,N)&&Object.defineProperty(Ft,N,{enumerable:!0,get:Ee[N]})},Gr.o=(Ft,Ee)=>Object.prototype.hasOwnProperty.call(Ft,Ee),Gr.r=Ft=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Ft,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Ft,"__esModule",{value:!0})},(()=>{var Ft;if(typeof self.location.href=="string"&&(Ft=self.location.href),!Ft)throw new Error("Automatic publicPath is not supported in this browser");Ft=Ft.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Gr.p=Ft})(),Gr.b=new URL("./",self.location.href);var c={};/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Gr.r(c),Gr.d(c,{ASTFeatureExtractor:()=>Zt.ASTFeatureExtractor,ASTForAudioClassification:()=>b.ASTForAudioClassification,ASTModel:()=>b.ASTModel,ASTPreTrainedModel:()=>b.ASTPreTrainedModel,AlbertForMaskedLM:()=>b.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>b.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>b.AlbertForSequenceClassification,AlbertModel:()=>b.AlbertModel,AlbertPreTrainedModel:()=>b.AlbertPreTrainedModel,AlbertTokenizer:()=>sr.AlbertTokenizer,AudioClassificationPipeline:()=>qr.AudioClassificationPipeline,AutoConfig:()=>fc.AutoConfig,AutoModel:()=>b.AutoModel,AutoModelForAudioClassification:()=>b.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>b.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>b.AutoModelForCTC,AutoModelForCausalLM:()=>b.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>b.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>b.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>b.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>b.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>b.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>b.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>b.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>b.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>b.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>b.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>b.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>b.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>b.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>b.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>b.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>b.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>b.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>b.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>b.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>b.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>b.AutoModelForVision2Seq,AutoModelForXVector:()=>b.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>b.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Zt.AutoProcessor,AutoTokenizer:()=>sr.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>qr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>b.BartForConditionalGeneration,BartForSequenceClassification:()=>b.BartForSequenceClassification,BartModel:()=>b.BartModel,BartPretrainedModel:()=>b.BartPretrainedModel,BartTokenizer:()=>sr.BartTokenizer,BaseModelOutput:()=>b.BaseModelOutput,BaseStreamer:()=>mc.BaseStreamer,BeitFeatureExtractor:()=>Zt.BeitFeatureExtractor,BeitForImageClassification:()=>b.BeitForImageClassification,BeitModel:()=>b.BeitModel,BeitPreTrainedModel:()=>b.BeitPreTrainedModel,BertForMaskedLM:()=>b.BertForMaskedLM,BertForQuestionAnswering:()=>b.BertForQuestionAnswering,BertForSequenceClassification:()=>b.BertForSequenceClassification,BertForTokenClassification:()=>b.BertForTokenClassification,BertModel:()=>b.BertModel,BertPreTrainedModel:()=>b.BertPreTrainedModel,BertTokenizer:()=>sr.BertTokenizer,BitImageProcessor:()=>Zt.BitImageProcessor,BlenderbotForConditionalGeneration:()=>b.BlenderbotForConditionalGeneration,BlenderbotModel:()=>b.BlenderbotModel,BlenderbotPreTrainedModel:()=>b.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>b.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>b.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>b.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>sr.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>sr.BlenderbotTokenizer,BloomForCausalLM:()=>b.BloomForCausalLM,BloomModel:()=>b.BloomModel,BloomPreTrainedModel:()=>b.BloomPreTrainedModel,BloomTokenizer:()=>sr.BloomTokenizer,CLIPFeatureExtractor:()=>Zt.CLIPFeatureExtractor,CLIPImageProcessor:()=>Zt.CLIPImageProcessor,CLIPModel:()=>b.CLIPModel,CLIPPreTrainedModel:()=>b.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>b.CLIPSegForImageSegmentation,CLIPSegModel:()=>b.CLIPSegModel,CLIPSegPreTrainedModel:()=>b.CLIPSegPreTrainedModel,CLIPTextModel:()=>b.CLIPTextModel,CLIPTextModelWithProjection:()=>b.CLIPTextModelWithProjection,CLIPTokenizer:()=>sr.CLIPTokenizer,CLIPVisionModel:()=>b.CLIPVisionModel,CLIPVisionModelWithProjection:()=>b.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>b.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>b.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>b.CamembertForSequenceClassification,CamembertForTokenClassification:()=>b.CamembertForTokenClassification,CamembertModel:()=>b.CamembertModel,CamembertPreTrainedModel:()=>b.CamembertPreTrainedModel,CamembertTokenizer:()=>sr.CamembertTokenizer,CausalLMOutput:()=>b.CausalLMOutput,CausalLMOutputWithPast:()=>b.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Zt.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>b.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>b.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>b.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Zt.ClapFeatureExtractor,ClapModel:()=>b.ClapModel,ClapPreTrainedModel:()=>b.ClapPreTrainedModel,ClapTextModelWithProjection:()=>b.ClapTextModelWithProjection,CodeGenForCausalLM:()=>b.CodeGenForCausalLM,CodeGenModel:()=>b.CodeGenModel,CodeGenPreTrainedModel:()=>b.CodeGenPreTrainedModel,CodeGenTokenizer:()=>sr.CodeGenTokenizer,CodeLlamaTokenizer:()=>sr.CodeLlamaTokenizer,CohereForCausalLM:()=>b.CohereForCausalLM,CohereModel:()=>b.CohereModel,CoherePreTrainedModel:()=>b.CoherePreTrainedModel,CohereTokenizer:()=>sr.CohereTokenizer,ConvBertForMaskedLM:()=>b.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>b.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>b.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>b.ConvBertForTokenClassification,ConvBertModel:()=>b.ConvBertModel,ConvBertPreTrainedModel:()=>b.ConvBertPreTrainedModel,ConvBertTokenizer:()=>sr.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Zt.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>b.ConvNextForImageClassification,ConvNextImageProcessor:()=>Zt.ConvNextImageProcessor,ConvNextModel:()=>b.ConvNextModel,ConvNextPreTrainedModel:()=>b.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>b.ConvNextV2ForImageClassification,ConvNextV2Model:()=>b.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>b.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Zt.DPTFeatureExtractor,DPTForDepthEstimation:()=>b.DPTForDepthEstimation,DPTImageProcessor:()=>Zt.DPTImageProcessor,DPTModel:()=>b.DPTModel,DPTPreTrainedModel:()=>b.DPTPreTrainedModel,DebertaForMaskedLM:()=>b.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>b.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>b.DebertaForSequenceClassification,DebertaForTokenClassification:()=>b.DebertaForTokenClassification,DebertaModel:()=>b.DebertaModel,DebertaPreTrainedModel:()=>b.DebertaPreTrainedModel,DebertaTokenizer:()=>sr.DebertaTokenizer,DebertaV2ForMaskedLM:()=>b.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>b.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>b.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>b.DebertaV2ForTokenClassification,DebertaV2Model:()=>b.DebertaV2Model,DebertaV2PreTrainedModel:()=>b.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>sr.DebertaV2Tokenizer,DecisionTransformerModel:()=>b.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>b.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>Zt.DeiTFeatureExtractor,DeiTForImageClassification:()=>b.DeiTForImageClassification,DeiTModel:()=>b.DeiTModel,DeiTPreTrainedModel:()=>b.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>b.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>b.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>qr.DepthEstimationPipeline,DetrFeatureExtractor:()=>Zt.DetrFeatureExtractor,DetrForObjectDetection:()=>b.DetrForObjectDetection,DetrForSegmentation:()=>b.DetrForSegmentation,DetrModel:()=>b.DetrModel,DetrObjectDetectionOutput:()=>b.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>b.DetrPreTrainedModel,DetrSegmentationOutput:()=>b.DetrSegmentationOutput,Dinov2ForImageClassification:()=>b.Dinov2ForImageClassification,Dinov2Model:()=>b.Dinov2Model,Dinov2PreTrainedModel:()=>b.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>b.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>b.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>b.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>b.DistilBertForTokenClassification,DistilBertModel:()=>b.DistilBertModel,DistilBertPreTrainedModel:()=>b.DistilBertPreTrainedModel,DistilBertTokenizer:()=>sr.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>qr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Zt.DonutFeatureExtractor,DonutSwinModel:()=>b.DonutSwinModel,DonutSwinPreTrainedModel:()=>b.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>b.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Zt.EfficientNetImageProcessor,EfficientNetModel:()=>b.EfficientNetModel,EfficientNetPreTrainedModel:()=>b.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>b.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>b.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>b.ElectraForSequenceClassification,ElectraForTokenClassification:()=>b.ElectraForTokenClassification,ElectraModel:()=>b.ElectraModel,ElectraPreTrainedModel:()=>b.ElectraPreTrainedModel,ElectraTokenizer:()=>sr.ElectraTokenizer,EosTokenCriteria:()=>so.EosTokenCriteria,EsmForMaskedLM:()=>b.EsmForMaskedLM,EsmForSequenceClassification:()=>b.EsmForSequenceClassification,EsmForTokenClassification:()=>b.EsmForTokenClassification,EsmModel:()=>b.EsmModel,EsmPreTrainedModel:()=>b.EsmPreTrainedModel,EsmTokenizer:()=>sr.EsmTokenizer,FFT:()=>$n.FFT,FalconForCausalLM:()=>b.FalconForCausalLM,FalconModel:()=>b.FalconModel,FalconPreTrainedModel:()=>b.FalconPreTrainedModel,FalconTokenizer:()=>sr.FalconTokenizer,FastViTForImageClassification:()=>b.FastViTForImageClassification,FastViTModel:()=>b.FastViTModel,FastViTPreTrainedModel:()=>b.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>qr.FeatureExtractionPipeline,FeatureExtractor:()=>Zt.FeatureExtractor,FillMaskPipeline:()=>qr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>b.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>b.Florence2PreTrainedModel,Florence2Processor:()=>Zt.Florence2Processor,GLPNFeatureExtractor:()=>Zt.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>b.GLPNForDepthEstimation,GLPNModel:()=>b.GLPNModel,GLPNPreTrainedModel:()=>b.GLPNPreTrainedModel,GPT2LMHeadModel:()=>b.GPT2LMHeadModel,GPT2Model:()=>b.GPT2Model,GPT2PreTrainedModel:()=>b.GPT2PreTrainedModel,GPT2Tokenizer:()=>sr.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>b.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>b.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>b.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>b.GPTJForCausalLM,GPTJModel:()=>b.GPTJModel,GPTJPreTrainedModel:()=>b.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>b.GPTNeoForCausalLM,GPTNeoModel:()=>b.GPTNeoModel,GPTNeoPreTrainedModel:()=>b.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>b.GPTNeoXForCausalLM,GPTNeoXModel:()=>b.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>b.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>sr.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>b.Gemma2ForCausalLM,Gemma2Model:()=>b.Gemma2Model,Gemma2PreTrainedModel:()=>b.Gemma2PreTrainedModel,GemmaForCausalLM:()=>b.GemmaForCausalLM,GemmaModel:()=>b.GemmaModel,GemmaPreTrainedModel:()=>b.GemmaPreTrainedModel,GemmaTokenizer:()=>sr.GemmaTokenizer,Grok1Tokenizer:()=>sr.Grok1Tokenizer,GroupViTModel:()=>b.GroupViTModel,GroupViTPreTrainedModel:()=>b.GroupViTPreTrainedModel,HerbertTokenizer:()=>sr.HerbertTokenizer,HieraForImageClassification:()=>b.HieraForImageClassification,HieraModel:()=>b.HieraModel,HieraPreTrainedModel:()=>b.HieraPreTrainedModel,HubertForCTC:()=>b.HubertForCTC,HubertForSequenceClassification:()=>b.HubertForSequenceClassification,HubertModel:()=>b.HubertModel,HubertPreTrainedModel:()=>b.HubertPreTrainedModel,ImageClassificationPipeline:()=>qr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>qr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Zt.ImageFeatureExtractor,ImageMattingOutput:()=>b.ImageMattingOutput,ImageSegmentationPipeline:()=>qr.ImageSegmentationPipeline,ImageToImagePipeline:()=>qr.ImageToImagePipeline,ImageToTextPipeline:()=>qr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>so.InterruptableStoppingCriteria,JAISLMHeadModel:()=>b.JAISLMHeadModel,JAISModel:()=>b.JAISModel,JAISPreTrainedModel:()=>b.JAISPreTrainedModel,LlamaForCausalLM:()=>b.LlamaForCausalLM,LlamaModel:()=>b.LlamaModel,LlamaPreTrainedModel:()=>b.LlamaPreTrainedModel,LlamaTokenizer:()=>sr.LlamaTokenizer,LlavaForConditionalGeneration:()=>b.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>b.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>b.LongT5ForConditionalGeneration,LongT5Model:()=>b.LongT5Model,LongT5PreTrainedModel:()=>b.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>b.M2M100ForConditionalGeneration,M2M100Model:()=>b.M2M100Model,M2M100PreTrainedModel:()=>b.M2M100PreTrainedModel,M2M100Tokenizer:()=>sr.M2M100Tokenizer,MBart50Tokenizer:()=>sr.MBart50Tokenizer,MBartForCausalLM:()=>b.MBartForCausalLM,MBartForConditionalGeneration:()=>b.MBartForConditionalGeneration,MBartForSequenceClassification:()=>b.MBartForSequenceClassification,MBartModel:()=>b.MBartModel,MBartPreTrainedModel:()=>b.MBartPreTrainedModel,MBartTokenizer:()=>sr.MBartTokenizer,MPNetForMaskedLM:()=>b.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>b.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>b.MPNetForSequenceClassification,MPNetForTokenClassification:()=>b.MPNetForTokenClassification,MPNetModel:()=>b.MPNetModel,MPNetPreTrainedModel:()=>b.MPNetPreTrainedModel,MPNetTokenizer:()=>sr.MPNetTokenizer,MT5ForConditionalGeneration:()=>b.MT5ForConditionalGeneration,MT5Model:()=>b.MT5Model,MT5PreTrainedModel:()=>b.MT5PreTrainedModel,MarianMTModel:()=>b.MarianMTModel,MarianModel:()=>b.MarianModel,MarianPreTrainedModel:()=>b.MarianPreTrainedModel,MarianTokenizer:()=>sr.MarianTokenizer,MaskFormerFeatureExtractor:()=>Zt.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>b.MaskFormerForInstanceSegmentation,MaskFormerModel:()=>b.MaskFormerModel,MaskFormerPreTrainedModel:()=>b.MaskFormerPreTrainedModel,MaskedLMOutput:()=>b.MaskedLMOutput,MaxLengthCriteria:()=>so.MaxLengthCriteria,MistralForCausalLM:()=>b.MistralForCausalLM,MistralModel:()=>b.MistralModel,MistralPreTrainedModel:()=>b.MistralPreTrainedModel,MobileBertForMaskedLM:()=>b.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>b.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>b.MobileBertForSequenceClassification,MobileBertModel:()=>b.MobileBertModel,MobileBertPreTrainedModel:()=>b.MobileBertPreTrainedModel,MobileBertTokenizer:()=>sr.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>Zt.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>b.MobileNetV1ForImageClassification,MobileNetV1Model:()=>b.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>b.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Zt.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>b.MobileNetV2ForImageClassification,MobileNetV2Model:()=>b.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>b.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Zt.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>b.MobileNetV3ForImageClassification,MobileNetV3Model:()=>b.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>b.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Zt.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>b.MobileNetV4ForImageClassification,MobileNetV4Model:()=>b.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>b.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Zt.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>b.MobileViTForImageClassification,MobileViTImageProcessor:()=>Zt.MobileViTImageProcessor,MobileViTModel:()=>b.MobileViTModel,MobileViTPreTrainedModel:()=>b.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>b.MobileViTV2ForImageClassification,MobileViTV2Model:()=>b.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>b.MobileViTV2PreTrainedModel,ModelOutput:()=>b.ModelOutput,Moondream1ForConditionalGeneration:()=>b.Moondream1ForConditionalGeneration,MptForCausalLM:()=>b.MptForCausalLM,MptModel:()=>b.MptModel,MptPreTrainedModel:()=>b.MptPreTrainedModel,MusicgenForCausalLM:()=>b.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>b.MusicgenForConditionalGeneration,MusicgenModel:()=>b.MusicgenModel,MusicgenPreTrainedModel:()=>b.MusicgenPreTrainedModel,NllbTokenizer:()=>sr.NllbTokenizer,NomicBertModel:()=>b.NomicBertModel,NomicBertPreTrainedModel:()=>b.NomicBertPreTrainedModel,NougatImageProcessor:()=>Zt.NougatImageProcessor,NougatTokenizer:()=>sr.NougatTokenizer,OPTForCausalLM:()=>b.OPTForCausalLM,OPTModel:()=>b.OPTModel,OPTPreTrainedModel:()=>b.OPTPreTrainedModel,ObjectDetectionPipeline:()=>qr.ObjectDetectionPipeline,OpenELMForCausalLM:()=>b.OpenELMForCausalLM,OpenELMModel:()=>b.OpenELMModel,OpenELMPreTrainedModel:()=>b.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Zt.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>b.OwlViTForObjectDetection,OwlViTModel:()=>b.OwlViTModel,OwlViTPreTrainedModel:()=>b.OwlViTPreTrainedModel,OwlViTProcessor:()=>Zt.OwlViTProcessor,Owlv2ForObjectDetection:()=>b.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Zt.Owlv2ImageProcessor,Owlv2Model:()=>b.Owlv2Model,Owlv2PreTrainedModel:()=>b.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>b.Phi3ForCausalLM,Phi3Model:()=>b.Phi3Model,Phi3PreTrainedModel:()=>b.Phi3PreTrainedModel,PhiForCausalLM:()=>b.PhiForCausalLM,PhiModel:()=>b.PhiModel,PhiPreTrainedModel:()=>b.PhiPreTrainedModel,Pipeline:()=>qr.Pipeline,PreTrainedModel:()=>b.PreTrainedModel,PreTrainedTokenizer:()=>sr.PreTrainedTokenizer,PretrainedConfig:()=>fc.PretrainedConfig,PretrainedMixin:()=>b.PretrainedMixin,Processor:()=>Zt.Processor,PvtForImageClassification:()=>b.PvtForImageClassification,PvtImageProcessor:()=>Zt.PvtImageProcessor,PvtModel:()=>b.PvtModel,PvtPreTrainedModel:()=>b.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>Zt.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>b.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>b.PyAnnoteModel,PyAnnotePreTrainedModel:()=>b.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Zt.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>b.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>qr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>b.Qwen2ForCausalLM,Qwen2Model:()=>b.Qwen2Model,Qwen2PreTrainedModel:()=>b.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>sr.Qwen2Tokenizer,RTDetrForObjectDetection:()=>b.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Zt.RTDetrImageProcessor,RTDetrModel:()=>b.RTDetrModel,RTDetrObjectDetectionOutput:()=>b.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>b.RTDetrPreTrainedModel,RawImage:()=>Pf.RawImage,ResNetForImageClassification:()=>b.ResNetForImageClassification,ResNetModel:()=>b.ResNetModel,ResNetPreTrainedModel:()=>b.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>b.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>b.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>b.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>b.RoFormerForTokenClassification,RoFormerModel:()=>b.RoFormerModel,RoFormerPreTrainedModel:()=>b.RoFormerPreTrainedModel,RoFormerTokenizer:()=>sr.RoFormerTokenizer,RobertaForMaskedLM:()=>b.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>b.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>b.RobertaForSequenceClassification,RobertaForTokenClassification:()=>b.RobertaForTokenClassification,RobertaModel:()=>b.RobertaModel,RobertaPreTrainedModel:()=>b.RobertaPreTrainedModel,RobertaTokenizer:()=>sr.RobertaTokenizer,SamImageProcessor:()=>Zt.SamImageProcessor,SamImageSegmentationOutput:()=>b.SamImageSegmentationOutput,SamModel:()=>b.SamModel,SamPreTrainedModel:()=>b.SamPreTrainedModel,SamProcessor:()=>Zt.SamProcessor,SapiensFeatureExtractor:()=>Zt.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>b.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>b.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>b.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>b.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Zt.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Zt.SegformerFeatureExtractor,SegformerForImageClassification:()=>b.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>b.SegformerForSemanticSegmentation,SegformerModel:()=>b.SegformerModel,SegformerPreTrainedModel:()=>b.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>b.Seq2SeqLMOutput,SequenceClassifierOutput:()=>b.SequenceClassifierOutput,SiglipImageProcessor:()=>Zt.SiglipImageProcessor,SiglipModel:()=>b.SiglipModel,SiglipPreTrainedModel:()=>b.SiglipPreTrainedModel,SiglipTextModel:()=>b.SiglipTextModel,SiglipTokenizer:()=>sr.SiglipTokenizer,SiglipVisionModel:()=>b.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Zt.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>b.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>b.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>b.SpeechT5HifiGan,SpeechT5Model:()=>b.SpeechT5Model,SpeechT5PreTrainedModel:()=>b.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Zt.SpeechT5Processor,SpeechT5Tokenizer:()=>sr.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>b.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>b.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>b.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>b.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>b.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>sr.SqueezeBertTokenizer,StableLmForCausalLM:()=>b.StableLmForCausalLM,StableLmModel:()=>b.StableLmModel,StableLmPreTrainedModel:()=>b.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>b.Starcoder2ForCausalLM,Starcoder2Model:()=>b.Starcoder2Model,Starcoder2PreTrainedModel:()=>b.Starcoder2PreTrainedModel,StoppingCriteria:()=>so.StoppingCriteria,StoppingCriteriaList:()=>so.StoppingCriteriaList,SummarizationPipeline:()=>qr.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>b.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Zt.Swin2SRImageProcessor,Swin2SRModel:()=>b.Swin2SRModel,Swin2SRPreTrainedModel:()=>b.Swin2SRPreTrainedModel,SwinForImageClassification:()=>b.SwinForImageClassification,SwinModel:()=>b.SwinModel,SwinPreTrainedModel:()=>b.SwinPreTrainedModel,T5ForConditionalGeneration:()=>b.T5ForConditionalGeneration,T5Model:()=>b.T5Model,T5PreTrainedModel:()=>b.T5PreTrainedModel,T5Tokenizer:()=>sr.T5Tokenizer,TableTransformerForObjectDetection:()=>b.TableTransformerForObjectDetection,TableTransformerModel:()=>b.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>b.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>b.TableTransformerPreTrainedModel,Tensor:()=>dn.Tensor,Text2TextGenerationPipeline:()=>qr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>qr.TextClassificationPipeline,TextGenerationPipeline:()=>qr.TextGenerationPipeline,TextStreamer:()=>mc.TextStreamer,TextToAudioPipeline:()=>qr.TextToAudioPipeline,TokenClassificationPipeline:()=>qr.TokenClassificationPipeline,TokenClassifierOutput:()=>b.TokenClassifierOutput,TokenizerModel:()=>sr.TokenizerModel,TrOCRForCausalLM:()=>b.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>b.TrOCRPreTrainedModel,TranslationPipeline:()=>qr.TranslationPipeline,UniSpeechForCTC:()=>b.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>b.UniSpeechForSequenceClassification,UniSpeechModel:()=>b.UniSpeechModel,UniSpeechPreTrainedModel:()=>b.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>b.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>b.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>b.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>b.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>b.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>Zt.ViTFeatureExtractor,ViTForImageClassification:()=>b.ViTForImageClassification,ViTImageProcessor:()=>Zt.ViTImageProcessor,ViTMAEModel:()=>b.ViTMAEModel,ViTMAEPreTrainedModel:()=>b.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>b.ViTMSNForImageClassification,ViTMSNModel:()=>b.ViTMSNModel,ViTMSNPreTrainedModel:()=>b.ViTMSNPreTrainedModel,ViTModel:()=>b.ViTModel,ViTPreTrainedModel:()=>b.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>b.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>b.VitMatteForImageMatting,VitMatteImageProcessor:()=>Zt.VitMatteImageProcessor,VitMattePreTrainedModel:()=>b.VitMattePreTrainedModel,VitsModel:()=>b.VitsModel,VitsModelOutput:()=>b.VitsModelOutput,VitsPreTrainedModel:()=>b.VitsPreTrainedModel,VitsTokenizer:()=>sr.VitsTokenizer,Wav2Vec2BertForCTC:()=>b.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>b.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>b.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>b.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>sr.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Zt.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>b.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>b.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>b.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>b.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>b.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Zt.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>b.WavLMForAudioFrameClassification,WavLMForCTC:()=>b.WavLMForCTC,WavLMForSequenceClassification:()=>b.WavLMForSequenceClassification,WavLMForXVector:()=>b.WavLMForXVector,WavLMModel:()=>b.WavLMModel,WavLMPreTrainedModel:()=>b.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Zt.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>b.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>b.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Zt.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>b.WhisperForConditionalGeneration,WhisperModel:()=>b.WhisperModel,WhisperPreTrainedModel:()=>b.WhisperPreTrainedModel,WhisperProcessor:()=>Zt.WhisperProcessor,WhisperTextStreamer:()=>mc.WhisperTextStreamer,WhisperTokenizer:()=>sr.WhisperTokenizer,XLMForQuestionAnswering:()=>b.XLMForQuestionAnswering,XLMForSequenceClassification:()=>b.XLMForSequenceClassification,XLMForTokenClassification:()=>b.XLMForTokenClassification,XLMModel:()=>b.XLMModel,XLMPreTrainedModel:()=>b.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>b.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>b.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>b.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>b.XLMRobertaForTokenClassification,XLMRobertaModel:()=>b.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>b.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>sr.XLMRobertaTokenizer,XLMTokenizer:()=>sr.XLMTokenizer,XLMWithLMHeadModel:()=>b.XLMWithLMHeadModel,XVectorOutput:()=>b.XVectorOutput,YolosFeatureExtractor:()=>Zt.YolosFeatureExtractor,YolosForObjectDetection:()=>b.YolosForObjectDetection,YolosModel:()=>b.YolosModel,YolosObjectDetectionOutput:()=>b.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>b.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>qr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>qr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>qr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>qr.ZeroShotObjectDetectionPipeline,bankers_round:()=>$n.bankers_round,cat:()=>dn.cat,cos_sim:()=>$n.cos_sim,dot:()=>$n.dot,dynamic_time_warping:()=>$n.dynamic_time_warping,env:()=>kf.env,full:()=>dn.full,full_like:()=>dn.full_like,getKeyValueShapes:()=>fc.getKeyValueShapes,hamming:()=>xi.hamming,hanning:()=>xi.hanning,interpolate:()=>dn.interpolate,interpolate_4d:()=>dn.interpolate_4d,interpolate_data:()=>$n.interpolate_data,is_chinese_char:()=>sr.is_chinese_char,layer_norm:()=>dn.layer_norm,log_softmax:()=>$n.log_softmax,magnitude:()=>$n.magnitude,matmul:()=>dn.matmul,max:()=>$n.max,mean:()=>dn.mean,mean_pooling:()=>dn.mean_pooling,medianFilter:()=>$n.medianFilter,mel_filter_bank:()=>xi.mel_filter_bank,min:()=>$n.min,ones:()=>dn.ones,ones_like:()=>dn.ones_like,permute:()=>dn.permute,permute_data:()=>$n.permute_data,pipeline:()=>qr.pipeline,quantize_embeddings:()=>dn.quantize_embeddings,read_audio:()=>xi.read_audio,rfft:()=>dn.rfft,round:()=>$n.round,softmax:()=>$n.softmax,spectrogram:()=>xi.spectrogram,stack:()=>dn.stack,std_mean:()=>dn.std_mean,topk:()=>dn.topk,window_function:()=>xi.window_function,zeros:()=>dn.zeros,zeros_like:()=>dn.zeros_like});var kf=Gr("./src/env.js"),qr=Gr("./src/pipelines.js"),b=Gr("./src/models.js"),sr=Gr("./src/tokenizers.js"),Zt=Gr("./src/processors.js"),fc=Gr("./src/configs.js"),xi=Gr("./src/utils/audio.js"),Pf=Gr("./src/utils/image.js"),dn=Gr("./src/utils/tensor.js"),$n=Gr("./src/utils/maths.js"),mc=Gr("./src/generation/streamers.js"),so=Gr("./src/generation/stopping_criteria.js");c.ASTFeatureExtractor,c.ASTForAudioClassification,c.ASTModel,c.ASTPreTrainedModel,c.AlbertForMaskedLM,c.AlbertForQuestionAnswering,c.AlbertForSequenceClassification,c.AlbertModel,c.AlbertPreTrainedModel,c.AlbertTokenizer,c.AudioClassificationPipeline,c.AutoConfig,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC,c.AutoModelForCausalLM,c.AutoModelForDepthEstimation,c.AutoModelForDocumentQuestionAnswering,c.AutoModelForImageClassification,c.AutoModelForImageFeatureExtraction,c.AutoModelForImageMatting,c.AutoModelForImageSegmentation,c.AutoModelForImageToImage,c.AutoModelForMaskGeneration,c.AutoModelForMaskedLM,c.AutoModelForNormalEstimation,c.AutoModelForObjectDetection,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation,c.AutoModelForVision2Seq,c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection,c.AutoProcessor,c.AutoTokenizer,c.AutomaticSpeechRecognitionPipeline,c.BartForConditionalGeneration,c.BartForSequenceClassification,c.BartModel,c.BartPretrainedModel,c.BartTokenizer,c.BaseModelOutput,c.BaseStreamer,c.BeitFeatureExtractor,c.BeitForImageClassification,c.BeitModel,c.BeitPreTrainedModel,c.BertForMaskedLM,c.BertForQuestionAnswering,c.BertForSequenceClassification,c.BertForTokenClassification,c.BertModel,c.BertPreTrainedModel,c.BertTokenizer,c.BitImageProcessor,c.BlenderbotForConditionalGeneration,c.BlenderbotModel,c.BlenderbotPreTrainedModel,c.BlenderbotSmallForConditionalGeneration,c.BlenderbotSmallModel,c.BlenderbotSmallPreTrainedModel,c.BlenderbotSmallTokenizer,c.BlenderbotTokenizer,c.BloomForCausalLM,c.BloomModel,c.BloomPreTrainedModel,c.BloomTokenizer,c.CLIPFeatureExtractor,c.CLIPImageProcessor,c.CLIPModel,c.CLIPPreTrainedModel,c.CLIPSegForImageSegmentation,c.CLIPSegModel,c.CLIPSegPreTrainedModel,c.CLIPTextModel,c.CLIPTextModelWithProjection,c.CLIPTokenizer,c.CLIPVisionModel,c.CLIPVisionModelWithProjection,c.CamembertForMaskedLM,c.CamembertForQuestionAnswering,c.CamembertForSequenceClassification,c.CamembertForTokenClassification,c.CamembertModel,c.CamembertPreTrainedModel,c.CamembertTokenizer,c.CausalLMOutput,c.CausalLMOutputWithPast,c.ChineseCLIPFeatureExtractor,c.ChineseCLIPModel,c.ChineseCLIPPreTrainedModel,c.ClapAudioModelWithProjection,c.ClapFeatureExtractor,c.ClapModel,c.ClapPreTrainedModel,c.ClapTextModelWithProjection,c.CodeGenForCausalLM,c.CodeGenModel,c.CodeGenPreTrainedModel,c.CodeGenTokenizer,c.CodeLlamaTokenizer,c.CohereForCausalLM,c.CohereModel,c.CoherePreTrainedModel,c.CohereTokenizer,c.ConvBertForMaskedLM,c.ConvBertForQuestionAnswering,c.ConvBertForSequenceClassification,c.ConvBertForTokenClassification,c.ConvBertModel,c.ConvBertPreTrainedModel,c.ConvBertTokenizer,c.ConvNextFeatureExtractor,c.ConvNextForImageClassification,c.ConvNextImageProcessor,c.ConvNextModel,c.ConvNextPreTrainedModel,c.ConvNextV2ForImageClassification,c.ConvNextV2Model,c.ConvNextV2PreTrainedModel,c.DPTFeatureExtractor,c.DPTForDepthEstimation,c.DPTImageProcessor,c.DPTModel,c.DPTPreTrainedModel,c.DebertaForMaskedLM,c.DebertaForQuestionAnswering,c.DebertaForSequenceClassification,c.DebertaForTokenClassification,c.DebertaModel,c.DebertaPreTrainedModel,c.DebertaTokenizer,c.DebertaV2ForMaskedLM,c.DebertaV2ForQuestionAnswering,c.DebertaV2ForSequenceClassification,c.DebertaV2ForTokenClassification,c.DebertaV2Model,c.DebertaV2PreTrainedModel,c.DebertaV2Tokenizer,c.DecisionTransformerModel,c.DecisionTransformerPreTrainedModel,c.DeiTFeatureExtractor,c.DeiTForImageClassification,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrModel,c.DetrObjectDetectionOutput,c.DetrPreTrainedModel,c.DetrSegmentationOutput,c.Dinov2ForImageClassification,c.Dinov2Model,c.Dinov2PreTrainedModel,c.DistilBertForMaskedLM,c.DistilBertForQuestionAnswering,c.DistilBertForSequenceClassification,c.DistilBertForTokenClassification,c.DistilBertModel,c.DistilBertPreTrainedModel,c.DistilBertTokenizer,c.DocumentQuestionAnsweringPipeline,c.DonutFeatureExtractor,c.DonutSwinModel,c.DonutSwinPreTrainedModel,c.EfficientNetForImageClassification,c.EfficientNetImageProcessor,c.EfficientNetModel,c.EfficientNetPreTrainedModel,c.ElectraForMaskedLM,c.ElectraForQuestionAnswering,c.ElectraForSequenceClassification,c.ElectraForTokenClassification,c.ElectraModel,c.ElectraPreTrainedModel,c.ElectraTokenizer,c.EosTokenCriteria,c.EsmForMaskedLM,c.EsmForSequenceClassification,c.EsmForTokenClassification,c.EsmModel,c.EsmPreTrainedModel,c.EsmTokenizer,c.FFT,c.FalconForCausalLM,c.FalconModel,c.FalconPreTrainedModel,c.FalconTokenizer,c.FastViTForImageClassification,c.FastViTModel,c.FastViTPreTrainedModel,c.FeatureExtractionPipeline,c.FeatureExtractor,c.FillMaskPipeline,c.Florence2ForConditionalGeneration,c.Florence2PreTrainedModel,c.Florence2Processor,c.GLPNFeatureExtractor,c.GLPNForDepthEstimation,c.GLPNModel,c.GLPNPreTrainedModel,c.GPT2LMHeadModel,c.GPT2Model,c.GPT2PreTrainedModel,c.GPT2Tokenizer,c.GPTBigCodeForCausalLM,c.GPTBigCodeModel,c.GPTBigCodePreTrainedModel,c.GPTJForCausalLM,c.GPTJModel,c.GPTJPreTrainedModel,c.GPTNeoForCausalLM,c.GPTNeoModel,c.GPTNeoPreTrainedModel,c.GPTNeoXForCausalLM,c.GPTNeoXModel,c.GPTNeoXPreTrainedModel,c.GPTNeoXTokenizer,c.Gemma2ForCausalLM,c.Gemma2Model,c.Gemma2PreTrainedModel,c.GemmaForCausalLM,c.GemmaModel,c.GemmaPreTrainedModel,c.GemmaTokenizer,c.Grok1Tokenizer,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline,c.InterruptableStoppingCriteria,c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaPreTrainedModel,c.LongT5ForConditionalGeneration,c.LongT5Model,c.LongT5PreTrainedModel,c.M2M100ForConditionalGeneration,c.M2M100Model,c.M2M100PreTrainedModel,c.M2M100Tokenizer,c.MBart50Tokenizer,c.MBartForCausalLM,c.MBartForConditionalGeneration,c.MBartForSequenceClassification,c.MBartModel,c.MBartPreTrainedModel,c.MBartTokenizer,c.MPNetForMaskedLM,c.MPNetForQuestionAnswering,c.MPNetForSequenceClassification,c.MPNetForTokenClassification,c.MPNetModel,c.MPNetPreTrainedModel,c.MPNetTokenizer,c.MT5ForConditionalGeneration,c.MT5Model,c.MT5PreTrainedModel,c.MarianMTModel,c.MarianModel,c.MarianPreTrainedModel,c.MarianTokenizer,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4Model,c.MobileNetV4PreTrainedModel,c.MobileViTFeatureExtractor,c.MobileViTForImageClassification,c.MobileViTImageProcessor,c.MobileViTModel,c.MobileViTPreTrainedModel,c.MobileViTV2ForImageClassification,c.MobileViTV2Model,c.MobileViTV2PreTrainedModel,c.ModelOutput,c.Moondream1ForConditionalGeneration,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.PhiForCausalLM,c.PhiModel,c.PhiPreTrainedModel,c.Pipeline,c.PreTrainedModel,c.PreTrainedTokenizer,c.PretrainedConfig,c.PretrainedMixin,c.Processor,c.PvtForImageClassification,c.PvtImageProcessor,c.PvtModel,c.PvtPreTrainedModel,c.PyAnnoteFeatureExtractor,c.PyAnnoteForAudioFrameClassification,c.PyAnnoteModel,c.PyAnnotePreTrainedModel,c.PyAnnoteProcessor,c.QuestionAnsweringModelOutput,c.QuestionAnsweringPipeline,c.Qwen2ForCausalLM,c.Qwen2Model,c.Qwen2PreTrainedModel,c.Qwen2Tokenizer,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel,c.RawImage,c.ResNetForImageClassification,c.ResNetModel,c.ResNetPreTrainedModel,c.RoFormerForMaskedLM,c.RoFormerForQuestionAnswering,c.RoFormerForSequenceClassification,c.RoFormerForTokenClassification,c.RoFormerModel,c.RoFormerPreTrainedModel,c.RoFormerTokenizer,c.RobertaForMaskedLM,c.RobertaForQuestionAnswering,c.RobertaForSequenceClassification,c.RobertaForTokenClassification,c.RobertaModel,c.RobertaPreTrainedModel,c.RobertaTokenizer,c.SamImageProcessor,c.SamImageSegmentationOutput,c.SamModel,c.SamPreTrainedModel,c.SamProcessor,c.SapiensFeatureExtractor,c.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerModel,c.SegformerPreTrainedModel,c.Seq2SeqLMOutput,c.SequenceClassifierOutput,c.SiglipImageProcessor,c.SiglipModel,c.SiglipPreTrainedModel,c.SiglipTextModel,c.SiglipTokenizer,c.SiglipVisionModel,c.SpeechT5FeatureExtractor,c.SpeechT5ForSpeechToText,c.SpeechT5ForTextToSpeech,c.SpeechT5HifiGan,c.SpeechT5Model,c.SpeechT5PreTrainedModel,c.SpeechT5Processor,c.SpeechT5Tokenizer,c.SqueezeBertForMaskedLM,c.SqueezeBertForQuestionAnswering,c.SqueezeBertForSequenceClassification,c.SqueezeBertModel,c.SqueezeBertPreTrainedModel,c.SqueezeBertTokenizer,c.StableLmForCausalLM,c.StableLmModel,c.StableLmPreTrainedModel,c.Starcoder2ForCausalLM,c.Starcoder2Model,c.Starcoder2PreTrainedModel,c.StoppingCriteria,c.StoppingCriteriaList,c.SummarizationPipeline,c.Swin2SRForImageSuperResolution,c.Swin2SRImageProcessor,c.Swin2SRModel,c.Swin2SRPreTrainedModel,c.SwinForImageClassification,c.SwinModel,c.SwinPreTrainedModel,c.T5ForConditionalGeneration,c.T5Model,c.T5PreTrainedModel,c.T5Tokenizer,c.TableTransformerForObjectDetection,c.TableTransformerModel,c.TableTransformerObjectDetectionOutput,c.TableTransformerPreTrainedModel,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline,c.TextStreamer,c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TrOCRForCausalLM,c.TrOCRPreTrainedModel,c.TranslationPipeline,c.UniSpeechForCTC,c.UniSpeechForSequenceClassification,c.UniSpeechModel,c.UniSpeechPreTrainedModel,c.UniSpeechSatForAudioFrameClassification,c.UniSpeechSatForCTC,c.UniSpeechSatForSequenceClassification,c.UniSpeechSatModel,c.UniSpeechSatPreTrainedModel,c.ViTFeatureExtractor,c.ViTForImageClassification,c.ViTImageProcessor,c.ViTMAEModel,c.ViTMAEPreTrainedModel,c.ViTMSNForImageClassification,c.ViTMSNModel,c.ViTMSNPreTrainedModel,c.ViTModel,c.ViTPreTrainedModel,c.VisionEncoderDecoderModel,c.VitMatteForImageMatting,c.VitMatteImageProcessor,c.VitMattePreTrainedModel,c.VitsModel,c.VitsModelOutput,c.VitsPreTrainedModel,c.VitsTokenizer,c.Wav2Vec2BertForCTC,c.Wav2Vec2BertForSequenceClassification,c.Wav2Vec2BertModel,c.Wav2Vec2BertPreTrainedModel,c.Wav2Vec2CTCTokenizer,c.Wav2Vec2FeatureExtractor,c.Wav2Vec2ForAudioFrameClassification,c.Wav2Vec2ForCTC,c.Wav2Vec2ForSequenceClassification,c.Wav2Vec2Model,c.Wav2Vec2PreTrainedModel,c.Wav2Vec2ProcessorWithLM,c.WavLMForAudioFrameClassification,c.WavLMForCTC,c.WavLMForSequenceClassification,c.WavLMForXVector,c.WavLMModel,c.WavLMPreTrainedModel,c.WeSpeakerFeatureExtractor,c.WeSpeakerResNetModel,c.WeSpeakerResNetPreTrainedModel,c.WhisperFeatureExtractor,c.WhisperForConditionalGeneration,c.WhisperModel,c.WhisperPreTrainedModel,c.WhisperProcessor;var Af=c.WhisperTextStreamer;c.WhisperTokenizer,c.XLMForQuestionAnswering,c.XLMForSequenceClassification,c.XLMForTokenClassification,c.XLMModel,c.XLMPreTrainedModel,c.XLMRobertaForMaskedLM,c.XLMRobertaForQuestionAnswering,c.XLMRobertaForSequenceClassification,c.XLMRobertaForTokenClassification,c.XLMRobertaModel,c.XLMRobertaPreTrainedModel,c.XLMRobertaTokenizer,c.XLMTokenizer,c.XLMWithLMHeadModel,c.XVectorOutput,c.YolosFeatureExtractor,c.YolosForObjectDetection,c.YolosModel,c.YolosObjectDetectionOutput,c.YolosPreTrainedModel,c.ZeroShotAudioClassificationPipeline,c.ZeroShotClassificationPipeline,c.ZeroShotImageClassificationPipeline,c.ZeroShotObjectDetectionPipeline,c.bankers_round,c.cat,c.cos_sim,c.dot,c.dynamic_time_warping,c.env,c.full,c.full_like,c.getKeyValueShapes,c.hamming,c.hanning,c.interpolate,c.interpolate_4d,c.interpolate_data,c.is_chinese_char,c.layer_norm,c.log_softmax,c.magnitude,c.matmul,c.max,c.mean,c.mean_pooling,c.medianFilter,c.mel_filter_bank,c.min,c.ones,c.ones_like,c.permute,c.permute_data;var If=c.pipeline;c.quantize_embeddings,c.read_audio,c.rfft,c.round,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;class wd{constructor(Ee,N){this.tokenizer=Ee,this.model=N}static async getInstance(Ee=null){return this.instance===null&&(this.instance=If(this.task,this.model,{dtype:{encoder_model:this.model==="onnx-community/whisper-large-v3-turbo"?"fp16":"fp32",decoder_model_merged:"q4"},device:"webgpu",progress_callback:Ee})),this.instance}}Me(wd,"task",null),Me(wd,"model",null),Me(wd,"instance",null),self.addEventListener("message",async Ft=>{const Ee=Ft.data;let N=await Ff(Ee);N!==null&&self.postMessage({status:"complete",data:N})});class _c extends wd{}Me(_c,"task","automatic-speech-recognition"),Me(_c,"model",null);const Ff=async({audio:Ft,model:Ee,subtask:N,language:z})=>{const me=Ee.startsWith("distil-whisper/"),we=_c;we.model!==Ee&&(we.model=Ee,we.instance!==null&&((await we.getInstance()).dispose(),we.instance=null));const Te=await we.getInstance(q=>{self.postMessage(q)}),Ce=Te.processor.feature_extractor.config.chunk_length/Te.model.config.max_source_positions,R=[],S=me?20:30,V=me?3:5;let P=0,re,ne=0,_e;const ce=new Af(Te.tokenizer,{time_precision:Ce,on_chunk_start:q=>{const te=(S-V)*P;R.push({text:"",timestamp:[te+q,null],finalised:!1,offset:te})},token_callback_function:q=>{re??(re=performance.now()),ne++>0&&(_e=ne/(performance.now()-re)*1e3)},callback_function:q=>{R.length!==0&&(R.at(-1).text+=q,self.postMessage({status:"update",data:{text:"",chunks:R,tps:_e}}))},on_chunk_end:q=>{const te=R.at(-1);te.timestamp[1]=q+te.offset,te.finalised=!0},on_finalize:()=>{re=null,ne=0,++P}}),D=await Te(Ft,{top_k:0,do_sample:!1,chunk_length_s:S,stride_length_s:V,language:z,task:N,return_timestamps:!0,force_full_sequences:!1,streamer:ce}).catch(q=>(console.error(q),self.postMessage({status:"error",data:q}),null));return{tps:_e,...D}}})();