var u_=Object.defineProperty;var d_=(At,ye,D)=>ye in At?u_(At,ye,{enumerable:!0,configurable:!0,writable:!0,value:D}):At[ye]=D;var Me=(At,ye,D)=>d_(At,typeof ye!="symbol"?ye+"":ye,D);var Ts={},Ef={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(At,ye,D)=>{At.exports=D.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(At,ye,D)=>{D.r(ye),D.d(ye,{Environment:()=>Ve,Interpreter:()=>ut,Template:()=>xt,parse:()=>Ce,tokenize:()=>B});var I=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"}),de=Object.freeze({set:I.Set,for:I.For,in:I.In,is:I.Is,if:I.If,else:I.Else,endif:I.EndIf,elif:I.ElseIf,endfor:I.EndFor,and:I.And,or:I.Or,not:I.Not,"not in":I.NotIn,macro:I.Macro,endmacro:I.EndMacro,true:I.BooleanLiteral,false:I.BooleanLiteral,True:I.BooleanLiteral,False:I.BooleanLiteral}),he=class{constructor(v,H){this.value=v,this.type=H}};function ve(v){return/\w/.test(v)}function xe(v){return/[0-9]/.test(v)}var j=[["{%",I.OpenStatement],["%}",I.CloseStatement],["{{",I.OpenExpression],["}}",I.CloseExpression],["(",I.OpenParen],[")",I.CloseParen],["{",I.OpenCurlyBracket],["}",I.CloseCurlyBracket],["[",I.OpenSquareBracket],["]",I.CloseSquareBracket],[",",I.Comma],[".",I.Dot],[":",I.Colon],["|",I.Pipe],["<=",I.ComparisonBinaryOperator],[">=",I.ComparisonBinaryOperator],["==",I.ComparisonBinaryOperator],["!=",I.ComparisonBinaryOperator],["<",I.ComparisonBinaryOperator],[">",I.ComparisonBinaryOperator],["+",I.AdditiveBinaryOperator],["-",I.AdditiveBinaryOperator],["*",I.MultiplicativeBinaryOperator],["/",I.MultiplicativeBinaryOperator],["%",I.MultiplicativeBinaryOperator],["=",I.Equals]],P=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function L(v,H={}){return v.endsWith(` `)&&(v=v.slice(0,-1)),v=v.replace(/{#.*?#}/gs,"{##}"),H.lstrip_blocks&&(v=v.replace(/^[ \t]*({[#%])/gm,"$1")),H.trim_blocks&&(v=v.replace(/([#%]})\n/g,"$1")),v.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function B(v,H={}){var Je,Nt,yt;const $=[],Y=L(v,H);let fe=0;const nt=bt=>{let Dt="";for(;bt(Y[fe]);){if(Y[fe]==="\\"){if(++fe,fe>=Y.length)throw new SyntaxError("Unexpected end of input");const Pt=Y[fe++],dr=P.get(Pt);if(dr===void 0)throw new SyntaxError(`Unexpected escaped character: ${Pt}`);Dt+=dr;continue}if(Dt+=Y[fe++],fe>=Y.length)throw new SyntaxError("Unexpected end of input")}return Dt};e:for(;fe0){$.push(new he(Pt,I.Text));continue}}nt(Pt=>/\s/.test(Pt));const Dt=Y[fe];if(Dt==="-"||Dt==="+"){const Pt=(Nt=$.at(-1))==null?void 0:Nt.type;if(Pt===I.Text||Pt===void 0)throw new SyntaxError(`Unexpected character: ${Dt}`);switch(Pt){case I.Identifier:case I.NumericLiteral:case I.BooleanLiteral:case I.StringLiteral:case I.CloseParen:case I.CloseSquareBracket:break;default:{++fe;const dr=nt(xe);$.push(new he(`${Dt}${dr}`,dr.length>0?I.NumericLiteral:I.UnaryOperator));continue}}}for(const[Pt,dr]of j)if(Y.slice(fe,fe+Pt.length)===Pt){$.push(new he(Pt,dr)),fe+=Pt.length;continue e}if(Dt==="'"||Dt==='"'){++fe;const Pt=nt(dr=>dr!==Dt);$.push(new he(Pt,I.StringLiteral)),++fe;continue}if(xe(Dt)){const Pt=nt(xe);$.push(new he(Pt,I.NumericLiteral));continue}if(ve(Dt)){const Pt=nt(ve),dr=Object.hasOwn(de,Pt)?de[Pt]:I.Identifier;dr===I.In&&((yt=$.at(-1))==null?void 0:yt.type)===I.Not?($.pop(),$.push(new he("not in",I.NotIn))):$.push(new he(Pt,dr));continue}throw new SyntaxError(`Unexpected character: ${Dt}`)}return $}var q=class{constructor(){Me(this,"type","Statement")}},re=class extends q{constructor(H){super();Me(this,"type","Program");this.body=H}},me=class extends q{constructor(H,$,Y){super();Me(this,"type","If");this.test=H,this.body=$,this.alternate=Y}},ue=class extends q{constructor(H,$,Y,fe){super();Me(this,"type","For");this.loopvar=H,this.iterable=$,this.body=Y,this.defaultBlock=fe}},O=class extends q{constructor(H,$){super();Me(this,"type","Set");this.assignee=H,this.value=$}},J=class extends q{constructor(H,$,Y){super();Me(this,"type","Macro");this.name=H,this.args=$,this.body=Y}},pe=class extends q{constructor(){super(...arguments);Me(this,"type","Expression")}},X=class extends pe{constructor(H,$,Y){super();Me(this,"type","MemberExpression");this.object=H,this.property=$,this.computed=Y}},K=class extends pe{constructor(H,$){super();Me(this,"type","CallExpression");this.callee=H,this.args=$}},V=class extends pe{constructor(H){super();Me(this,"type","Identifier");this.value=H}},E=class extends pe{constructor(H){super();Me(this,"type","Literal");this.value=H}},N=class extends E{constructor(){super(...arguments);Me(this,"type","NumericLiteral")}},k=class extends E{constructor(){super(...arguments);Me(this,"type","StringLiteral")}},le=class extends E{constructor(){super(...arguments);Me(this,"type","BooleanLiteral")}},be=class extends E{constructor(){super(...arguments);Me(this,"type","ArrayLiteral")}},$e=class extends E{constructor(){super(...arguments);Me(this,"type","TupleLiteral")}},De=class extends E{constructor(){super(...arguments);Me(this,"type","ObjectLiteral")}},ze=class extends pe{constructor(H,$,Y){super();Me(this,"type","BinaryExpression");this.operator=H,this.left=$,this.right=Y}},it=class extends pe{constructor(H,$){super();Me(this,"type","FilterExpression");this.operand=H,this.filter=$}},rt=class extends pe{constructor(H,$){super();Me(this,"type","SelectExpression");this.iterable=H,this.test=$}},lt=class extends pe{constructor(H,$,Y){super();Me(this,"type","TestExpression");this.operand=H,this.negate=$,this.test=Y}},_e=class extends pe{constructor(H,$){super();Me(this,"type","UnaryExpression");this.operator=H,this.argument=$}},W=class extends pe{constructor(H=void 0,$=void 0,Y=void 0){super();Me(this,"type","SliceExpression");this.start=H,this.stop=$,this.step=Y}},ce=class extends pe{constructor(H,$){super();Me(this,"type","KeywordArgumentExpression");this.key=H,this.value=$}};function Ce(v){const H=new re([]);let $=0;function Y(Fe,Oe){const ct=v[$++];if(!ct||ct.type!==Fe)throw new Error(`Parser Error: ${Oe}. ${ct.type} !== ${Fe}.`);return ct}function fe(){switch(v[$].type){case I.Text:return Nt();case I.OpenStatement:return yt();case I.OpenExpression:return bt();default:throw new SyntaxError(`Unexpected token type: ${v[$].type}`)}}function nt(...Fe){return $+Fe.length<=v.length&&Fe.some((Oe,ct)=>Oe!==v[$+ct].type)}function Je(...Fe){return $+Fe.length<=v.length&&Fe.every((Oe,ct)=>Oe===v[$+ct].type)}function Nt(){return new k(Y(I.Text,"Expected text token").value)}function yt(){Y(I.OpenStatement,"Expected opening statement token");let Fe;switch(v[$].type){case I.Set:++$,Fe=Dt(),Y(I.CloseStatement,"Expected closing statement token");break;case I.If:++$,Fe=Pt(),Y(I.OpenStatement,"Expected {% token"),Y(I.EndIf,"Expected endif token"),Y(I.CloseStatement,"Expected %} token");break;case I.Macro:++$,Fe=dr(),Y(I.OpenStatement,"Expected {% token"),Y(I.EndMacro,"Expected endmacro token"),Y(I.CloseStatement,"Expected %} token");break;case I.For:++$,Fe=Yr(),Y(I.OpenStatement,"Expected {% token"),Y(I.EndFor,"Expected endfor token"),Y(I.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${v[$].type}`)}return Fe}function bt(){Y(I.OpenExpression,"Expected opening expression token");const Fe=Rr();return Y(I.CloseExpression,"Expected closing expression token"),Fe}function Dt(){const Fe=Rr();if(Je(I.Equals)){++$;const Oe=Dt();return new O(Fe,Oe)}return Fe}function Pt(){var Ut,sr,br,Nr,mr,Er,wr,Cn;const Fe=Rr();Y(I.CloseStatement,"Expected closing statement token");const Oe=[],ct=[];for(;!(((Ut=v[$])==null?void 0:Ut.type)===I.OpenStatement&&(((sr=v[$+1])==null?void 0:sr.type)===I.ElseIf||((br=v[$+1])==null?void 0:br.type)===I.Else||((Nr=v[$+1])==null?void 0:Nr.type)===I.EndIf));)Oe.push(fe());if(((mr=v[$])==null?void 0:mr.type)===I.OpenStatement&&((Er=v[$+1])==null?void 0:Er.type)!==I.EndIf)if(++$,Je(I.ElseIf))Y(I.ElseIf,"Expected elseif token"),ct.push(Pt());else for(Y(I.Else,"Expected else token"),Y(I.CloseStatement,"Expected closing statement token");!(((wr=v[$])==null?void 0:wr.type)===I.OpenStatement&&((Cn=v[$+1])==null?void 0:Cn.type)===I.EndIf);)ct.push(fe());return new me(Fe,Oe,ct)}function dr(){const Fe=Ot();if(Fe.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Oe=tt();Y(I.CloseStatement,"Expected closing statement token");const ct=[];for(;nt(I.OpenStatement,I.EndMacro);)ct.push(fe());return new J(Fe,Oe,ct)}function Cr(Fe=!1){const Oe=Fe?Ot:Rr,ct=[Oe()],Ut=Je(I.Comma);for(;Ut&&(++$,ct.push(Oe()),!!Je(I.Comma)););return Ut?new $e(ct):ct[0]}function Yr(){const Fe=Cr(!0);if(!(Fe instanceof V||Fe instanceof $e))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Fe.type} instead`);Y(I.In,"Expected `in` keyword following loop variable");const Oe=Rr();Y(I.CloseStatement,"Expected closing statement token");const ct=[];for(;nt(I.OpenStatement,I.EndFor)&&nt(I.OpenStatement,I.Else);)ct.push(fe());const Ut=[];if(Je(I.OpenStatement,I.Else))for(++$,++$,Y(I.CloseStatement,"Expected closing statement token");nt(I.OpenStatement,I.EndFor);)Ut.push(fe());return new ue(Fe,Oe,ct,Ut)}function Rr(){return Jr()}function Jr(){const Fe=yn();if(Je(I.If)){++$;const Oe=yn();if(Je(I.Else)){++$;const ct=yn();return new me(Oe,[Fe],[ct])}else return new rt(Fe,Oe)}return Fe}function yn(){let Fe=at();for(;Je(I.Or);){const Oe=v[$];++$;const ct=at();Fe=new ze(Oe,Fe,ct)}return Fe}function at(){let Fe=G();for(;Je(I.And);){const Oe=v[$];++$;const ct=G();Fe=new ze(Oe,Fe,ct)}return Fe}function G(){let Fe;for(;Je(I.Not);){const Oe=v[$];++$;const ct=G();Fe=new _e(Oe,ct)}return Fe??we()}function we(){let Fe=Ie();for(;Je(I.ComparisonBinaryOperator)||Je(I.In)||Je(I.NotIn);){const Oe=v[$];++$;const ct=Ie();Fe=new ze(Oe,Fe,ct)}return Fe}function Ie(){let Fe=ft();for(;Je(I.AdditiveBinaryOperator);){const Oe=v[$];++$;const ct=ft();Fe=new ze(Oe,Fe,ct)}return Fe}function Se(){const Fe=Ct();return Je(I.OpenParen)?Ne(Fe):Fe}function Ne(Fe){let Oe=new K(Fe,tt());return Je(I.OpenParen)&&(Oe=Ne(Oe)),Oe}function tt(){Y(I.OpenParen,"Expected opening parenthesis for arguments list");const Fe=wt();return Y(I.CloseParen,"Expected closing parenthesis for arguments list"),Fe}function wt(){const Fe=[];for(;!Je(I.CloseParen);){let Oe=Rr();if(Je(I.Equals)){if(++$,!(Oe instanceof V))throw new SyntaxError("Expected identifier for keyword argument");const ct=Rr();Oe=new ce(Oe,ct)}Fe.push(Oe),Je(I.Comma)&&++$}return Fe}function mt(){const Fe=[];let Oe=!1;for(;!Je(I.CloseSquareBracket);)Je(I.Colon)?(Fe.push(void 0),++$,Oe=!0):(Fe.push(Rr()),Je(I.Colon)&&(++$,Oe=!0));if(Fe.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Oe){if(Fe.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new W(...Fe)}return Fe[0]}function Ct(){let Fe=Ot();for(;Je(I.Dot)||Je(I.OpenSquareBracket);){const Oe=v[$];++$;let ct;const Ut=Oe.type!==I.Dot;if(Ut)ct=mt(),Y(I.CloseSquareBracket,"Expected closing square bracket");else if(ct=Ot(),ct.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Fe=new X(Fe,ct,Ut)}return Fe}function ft(){let Fe=Lt();for(;Je(I.MultiplicativeBinaryOperator);){const Oe=v[$];++$;const ct=Lt();Fe=new ze(Oe,Fe,ct)}return Fe}function Lt(){let Fe=jt();for(;Je(I.Is);){++$;const Oe=Je(I.Not);Oe&&++$;let ct=Ot();if(ct instanceof le&&(ct=new V(ct.value.toString())),!(ct instanceof V))throw new SyntaxError("Expected identifier for the test");Fe=new lt(Fe,Oe,ct)}return Fe}function jt(){let Fe=Se();for(;Je(I.Pipe);){++$;let Oe=Ot();if(!(Oe instanceof V))throw new SyntaxError("Expected identifier for the filter");Je(I.OpenParen)&&(Oe=Ne(Oe)),Fe=new it(Fe,Oe)}return Fe}function Ot(){const Fe=v[$];switch(Fe.type){case I.NumericLiteral:return++$,new N(Number(Fe.value));case I.StringLiteral:return++$,new k(Fe.value);case I.BooleanLiteral:return++$,new le(Fe.value.toLowerCase()==="true");case I.Identifier:return++$,new V(Fe.value);case I.OpenParen:{++$;const Oe=Cr();if(v[$].type!==I.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${v[$].type} instead`);return++$,Oe}case I.OpenSquareBracket:{++$;const Oe=[];for(;!Je(I.CloseSquareBracket);)Oe.push(Rr()),Je(I.Comma)&&++$;return++$,new be(Oe)}case I.OpenCurlyBracket:{++$;const Oe=new Map;for(;!Je(I.CloseCurlyBracket);){const ct=Rr();Y(I.Colon,"Expected colon between key and value in object literal");const Ut=Rr();Oe.set(ct,Ut),Je(I.Comma)&&++$}return++$,new De(Oe)}default:throw new SyntaxError(`Unexpected token: ${Fe.type}`)}}for(;$=0?(H=(H??(H=0))<0?Math.max(v.length+H,0):Math.min(H,v.length),$=($??($=v.length))<0?Math.max(v.length+$,0):Math.min($,v.length)):(H=(H??(H=v.length-1))<0?Math.max(v.length+H,-1):Math.min(H,v.length-1),$=($??($=-1))<-1?Math.max(v.length+$,-1):Math.min($,v.length-1));const nt=[];for(let Je=H;fe*JeH.toUpperCase())}var Ze=class{constructor(v=void 0){Me(this,"type","RuntimeValue");Me(this,"value");Me(this,"builtins",new Map);this.value=v}__bool__(){return new ht(!!this.value)}},dt=class extends Ze{constructor(){super(...arguments);Me(this,"type","NumericValue")}},Re=class extends Ze{constructor(){super(...arguments);Me(this,"type","StringValue");Me(this,"builtins",new Map([["upper",new Ke(()=>new Re(this.value.toUpperCase()))],["lower",new Ke(()=>new Re(this.value.toLowerCase()))],["strip",new Ke(()=>new Re(this.value.trim()))],["title",new Ke(()=>new Re(ne(this.value)))],["length",new dt(this.value.length)]]))}},ht=class extends Ze{constructor(){super(...arguments);Me(this,"type","BooleanValue")}},Mt=class extends Ze{constructor(){super(...arguments);Me(this,"type","ObjectValue");Me(this,"builtins",new Map([["get",new Ke(([H,$])=>{if(!(H instanceof Re))throw new Error(`Object key must be a string: got ${H.type}`);return this.value.get(H.value)??$??new et})],["items",new Ke(()=>new Z(Array.from(this.value.entries()).map(([H,$])=>new Z([new Re(H),$]))))]]))}__bool__(){return new ht(this.value.size>0)}},Xe=class extends Mt{constructor(){super(...arguments);Me(this,"type","KeywordArgumentsValue")}},Z=class extends Ze{constructor(){super(...arguments);Me(this,"type","ArrayValue");Me(this,"builtins",new Map([["length",new dt(this.value.length)]]))}__bool__(){return new ht(this.value.length>0)}},Ae=class extends Z{constructor(){super(...arguments);Me(this,"type","TupleValue")}},Ke=class extends Ze{constructor(){super(...arguments);Me(this,"type","FunctionValue")}},et=class extends Ze{constructor(){super(...arguments);Me(this,"type","NullValue")}},je=class extends Ze{constructor(){super(...arguments);Me(this,"type","UndefinedValue")}},Ve=class{constructor(v){Me(this,"variables",new Map([["namespace",new Ke(v=>{if(v.length===0)return new Mt(new Map);if(v.length!==1||!(v[0]instanceof Mt))throw new Error("`namespace` expects either zero arguments or a single object argument");return v[0]})]]));Me(this,"tests",new Map([["boolean",v=>v.type==="BooleanValue"],["callable",v=>v instanceof Ke],["odd",v=>{if(v.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${v.type}`);return v.value%2!==0}],["even",v=>{if(v.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${v.type}`);return v.value%2===0}],["false",v=>v.type==="BooleanValue"&&!v.value],["true",v=>v.type==="BooleanValue"&&v.value],["string",v=>v.type==="StringValue"],["number",v=>v.type==="NumericValue"],["integer",v=>v.type==="NumericValue"&&Number.isInteger(v.value)],["iterable",v=>v instanceof Z||v instanceof Re],["lower",v=>{const H=v.value;return v.type==="StringValue"&&H===H.toLowerCase()}],["upper",v=>{const H=v.value;return v.type==="StringValue"&&H===H.toUpperCase()}],["none",v=>v.type==="NullValue"],["defined",v=>v.type!=="UndefinedValue"],["undefined",v=>v.type==="UndefinedValue"],["equalto",(v,H)=>v.value===H.value],["eq",(v,H)=>v.value===H.value]]));this.parent=v}set(v,H){return this.declareVariable(v,_t(H))}declareVariable(v,H){if(this.variables.has(v))throw new SyntaxError(`Variable already declared: ${v}`);return this.variables.set(v,H),H}setVariable(v,H){return this.variables.set(v,H),H}resolve(v){if(this.variables.has(v))return this;if(this.parent)return this.parent.resolve(v);throw new Error(`Unknown variable: ${v}`)}lookupVariable(v){try{return this.resolve(v).variables.get(v)??new je}catch{return new je}}},ut=class{constructor(v){Me(this,"global");this.global=v??new Ve}run(v){return this.evaluate(v,this.global)}evaluateBinaryExpression(v,H){const $=this.evaluate(v.left,H);switch(v.operator.value){case"and":return $.__bool__().value?this.evaluate(v.right,H):$;case"or":return $.__bool__().value?$:this.evaluate(v.right,H)}const Y=this.evaluate(v.right,H);switch(v.operator.value){case"==":return new ht($.value==Y.value);case"!=":return new ht($.value!=Y.value)}if($ instanceof je||Y instanceof je)throw new Error("Cannot perform operation on undefined values");if($ instanceof et||Y instanceof et)throw new Error("Cannot perform operation on null values");if($ instanceof dt&&Y instanceof dt)switch(v.operator.value){case"+":return new dt($.value+Y.value);case"-":return new dt($.value-Y.value);case"*":return new dt($.value*Y.value);case"/":return new dt($.value/Y.value);case"%":return new dt($.value%Y.value);case"<":return new ht($.value":return new ht($.value>Y.value);case">=":return new ht($.value>=Y.value);case"<=":return new ht($.value<=Y.value)}else if($ instanceof Z&&Y instanceof Z)switch(v.operator.value){case"+":return new Z($.value.concat(Y.value))}else if(Y instanceof Z){const fe=Y.value.find(nt=>nt.value===$.value)!==void 0;switch(v.operator.value){case"in":return new ht(fe);case"not in":return new ht(!fe)}}if($ instanceof Re||Y instanceof Re)switch(v.operator.value){case"+":return new Re($.value.toString()+Y.value.toString())}if($ instanceof Re&&Y instanceof Re)switch(v.operator.value){case"in":return new ht(Y.value.includes($.value));case"not in":return new ht(!Y.value.includes($.value))}if($ instanceof Re&&Y instanceof Mt)switch(v.operator.value){case"in":return new ht(Y.value.has($.value));case"not in":return new ht(!Y.value.has($.value))}throw new SyntaxError(`Unknown operator "${v.operator.value}" between ${$.type} and ${Y.type}`)}evaluateArguments(v,H){const $=[],Y=new Map;for(const fe of v)if(fe.type==="KeywordArgumentExpression"){const nt=fe;Y.set(nt.key.value,this.evaluate(nt.value,H))}else{if(Y.size>0)throw new Error("Positional arguments must come before keyword arguments");$.push(this.evaluate(fe,H))}return[$,Y]}evaluateFilterExpression(v,H){const $=this.evaluate(v.operand,H);if(v.filter.type==="Identifier"){const Y=v.filter;if(Y.value==="tojson")return new Re(St($));if($ instanceof Z)switch(Y.value){case"list":return $;case"first":return $.value[0];case"last":return $.value[$.value.length-1];case"length":return new dt($.value.length);case"reverse":return new Z($.value.reverse());case"sort":return new Z($.value.sort((fe,nt)=>{if(fe.type!==nt.type)throw new Error(`Cannot compare different types: ${fe.type} and ${nt.type}`);switch(fe.type){case"NumericValue":return fe.value-nt.value;case"StringValue":return fe.value.localeCompare(nt.value);default:throw new Error(`Cannot compare type: ${fe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Y.value}`)}else if($ instanceof Re)switch(Y.value){case"length":return new dt($.value.length);case"upper":return new Re($.value.toUpperCase());case"lower":return new Re($.value.toLowerCase());case"title":return new Re(ne($.value));case"capitalize":return new Re($.value.charAt(0).toUpperCase()+$.value.slice(1));case"trim":return new Re($.value.trim());case"indent":return new Re($.value.split(` `).map((fe,nt)=>nt===0||fe.length===0?fe:" "+fe).join(` `));case"string":return $;default:throw new Error(`Unknown StringValue filter: ${Y.value}`)}else if($ instanceof dt)switch(Y.value){case"abs":return new dt(Math.abs($.value));default:throw new Error(`Unknown NumericValue filter: ${Y.value}`)}else if($ instanceof Mt)switch(Y.value){case"items":return new Z(Array.from($.value.entries()).map(([fe,nt])=>new Z([new Re(fe),nt])));case"length":return new dt($.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Y.value}`)}throw new Error(`Cannot apply filter "${Y.value}" to type: ${$.type}`)}else if(v.filter.type==="CallExpression"){const Y=v.filter;if(Y.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Y.callee.type}`);const fe=Y.callee.value;if(fe==="tojson"){const[,nt]=this.evaluateArguments(Y.args,H),Je=nt.get("indent")??new et;if(!(Je instanceof dt||Je instanceof et))throw new Error("If set, indent must be a number");return new Re(St($,Je.value))}if($ instanceof Z){switch(fe){case"selectattr":{if($.value.some(Dt=>!(Dt instanceof Mt)))throw new Error("`selectattr` can only be applied to array of objects");if(Y.args.some(Dt=>Dt.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[nt,Je,Nt]=Y.args.map(Dt=>this.evaluate(Dt,H));let yt;if(Je){const Dt=H.tests.get(Je.value);if(!Dt)throw new Error(`Unknown test: ${Je.value}`);yt=Dt}else yt=(...Dt)=>Dt[0].__bool__().value;const bt=$.value.filter(Dt=>{const Pt=Dt.value.get(nt.value);return Pt?yt(Pt,Nt):!1});return new Z(bt)}case"map":{const[,nt]=this.evaluateArguments(Y.args,H);if(nt.has("attribute")){const Je=nt.get("attribute");if(!(Je instanceof Re))throw new Error("attribute must be a string");const Nt=nt.get("default"),yt=$.value.map(bt=>{if(!(bt instanceof Mt))throw new Error("items in map must be an object");return bt.value.get(Je.value)??Nt??new je});return new Z(yt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${fe}`)}else if($ instanceof Re){switch(fe){case"indent":{const[nt,Je]=this.evaluateArguments(Y.args,H),Nt=nt.at(0)??Je.get("width")??new dt(4);if(!(Nt instanceof dt))throw new Error("width must be a number");const yt=nt.at(1)??Je.get("first")??new ht(!1),bt=nt.at(2)??Je.get("blank")??new ht(!1),Dt=$.value.split(` `),Pt=" ".repeat(Nt.value),dr=Dt.map((Cr,Yr)=>!yt.value&&Yr===0||!bt.value&&Cr.length===0?Cr:Pt+Cr);return new Re(dr.join(` `))}}throw new Error(`Unknown StringValue filter: ${fe}`)}else throw new Error(`Cannot apply filter "${fe}" to type: ${$.type}`)}throw new Error(`Unknown filter: ${v.filter.type}`)}evaluateTestExpression(v,H){const $=this.evaluate(v.operand,H),Y=H.tests.get(v.test.value);if(!Y)throw new Error(`Unknown test: ${v.test.value}`);const fe=Y($);return new ht(v.negate?!fe:fe)}evaluateUnaryExpression(v,H){const $=this.evaluate(v.argument,H);switch(v.operator.value){case"not":return new ht(!$.value);default:throw new SyntaxError(`Unknown operator: ${v.operator.value}`)}}evalProgram(v,H){return this.evaluateBlock(v.body,H)}evaluateBlock(v,H){let $="";for(const Y of v){const fe=this.evaluate(Y,H);fe.type!=="NullValue"&&fe.type!=="UndefinedValue"&&($+=fe.value)}return new Re($)}evaluateIdentifier(v,H){return H.lookupVariable(v.value)}evaluateCallExpression(v,H){const[$,Y]=this.evaluateArguments(v.args,H);Y.size>0&&$.push(new Xe(Y));const fe=this.evaluate(v.callee,H);if(fe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${fe.type}`);return fe.value($,H)}evaluateSliceExpression(v,H,$){if(!(v instanceof Z||v instanceof Re))throw new Error("Slice object must be an array or string");const Y=this.evaluate(H.start,$),fe=this.evaluate(H.stop,$),nt=this.evaluate(H.step,$);if(!(Y instanceof dt||Y instanceof je))throw new Error("Slice start must be numeric or undefined");if(!(fe instanceof dt||fe instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(nt instanceof dt||nt instanceof je))throw new Error("Slice step must be numeric or undefined");return v instanceof Z?new Z(ot(v.value,Y.value,fe.value,nt.value)):new Re(ot(Array.from(v.value),Y.value,fe.value,nt.value).join(""))}evaluateMemberExpression(v,H){const $=this.evaluate(v.object,H);let Y;if(v.computed){if(v.property.type==="SliceExpression")return this.evaluateSliceExpression($,v.property,H);Y=this.evaluate(v.property,H)}else Y=new Re(v.property.value);let fe;if($ instanceof Mt){if(!(Y instanceof Re))throw new Error(`Cannot access property with non-string: got ${Y.type}`);fe=$.value.get(Y.value)??$.builtins.get(Y.value)}else if($ instanceof Z||$ instanceof Re)if(Y instanceof dt)fe=$.value.at(Y.value),$ instanceof Re&&(fe=new Re($.value.at(Y.value)));else if(Y instanceof Re)fe=$.builtins.get(Y.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Y.type}`);else{if(!(Y instanceof Re))throw new Error(`Cannot access property with non-string: got ${Y.type}`);fe=$.builtins.get(Y.value)}return fe instanceof Ze?fe:new je}evaluateSet(v,H){const $=this.evaluate(v.value,H);if(v.assignee.type==="Identifier"){const Y=v.assignee.value;H.setVariable(Y,$)}else if(v.assignee.type==="MemberExpression"){const Y=v.assignee,fe=this.evaluate(Y.object,H);if(!(fe instanceof Mt))throw new Error("Cannot assign to member of non-object");if(Y.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");fe.value.set(Y.property.value,$)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(v.assignee)}`);return new et}evaluateIf(v,H){const $=this.evaluate(v.test,H);return this.evaluateBlock($.__bool__().value?v.body:v.alternate,H)}evaluateFor(v,H){const $=new Ve(H);let Y,fe;if(v.iterable.type==="SelectExpression"){const bt=v.iterable;fe=this.evaluate(bt.iterable,$),Y=bt.test}else fe=this.evaluate(v.iterable,$);if(!(fe instanceof Z))throw new Error(`Expected iterable type in for loop: got ${fe.type}`);const nt=[],Je=[];for(let bt=0;btCr.setVariable(v.loopvar.value,Pt);else if(v.loopvar.type==="TupleLiteral"){const Cr=v.loopvar;if(Pt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Pt.type}`);const Yr=Pt;if(Cr.value.length!==Yr.value.length)throw new Error(`Too ${Cr.value.length>Yr.value.length?"few":"many"} items to unpack`);dr=Rr=>{for(let Jr=0;Jr0?nt[bt-1]:new je],["nextitem",bt{var Je;const fe=new Ve(Y);$=$.slice();let nt;((Je=$.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(nt=$.pop());for(let Nt=0;Ntthis.evaluate($,H)));case"TupleLiteral":return new Ae(v.value.map($=>this.evaluate($,H)));case"ObjectLiteral":{const $=new Map;for(const[Y,fe]of v.value){const nt=this.evaluate(Y,H);if(!(nt instanceof Re))throw new Error(`Object keys must be strings: got ${nt.type}`);$.set(nt.value,this.evaluate(fe,H))}return new Mt($)}case"Identifier":return this.evaluateIdentifier(v,H);case"CallExpression":return this.evaluateCallExpression(v,H);case"MemberExpression":return this.evaluateMemberExpression(v,H);case"UnaryExpression":return this.evaluateUnaryExpression(v,H);case"BinaryExpression":return this.evaluateBinaryExpression(v,H);case"FilterExpression":return this.evaluateFilterExpression(v,H);case"TestExpression":return this.evaluateTestExpression(v,H);default:throw new SyntaxError(`Unknown node type: ${v.type}`)}}};function _t(v){switch(typeof v){case"number":return new dt(v);case"string":return new Re(v);case"boolean":return new ht(v);case"undefined":return new je;case"object":return v===null?new et:Array.isArray(v)?new Z(v.map(_t)):new Mt(new Map(Object.entries(v).map(([H,$])=>[H,_t($)])));case"function":return new Ke((H,$)=>{const Y=v(...H.map(fe=>fe.value))??null;return _t(Y)});default:throw new Error(`Cannot convert to runtime value: ${v}`)}}function St(v,H,$){const Y=$??0;switch(v.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(v.value);case"ArrayValue":case"ObjectValue":{const fe=H?" ".repeat(H):"",nt=` `+fe.repeat(Y),Je=nt+fe;if(v.type==="ArrayValue"){const Nt=v.value.map(yt=>St(yt,H,Y+1));return H?`[${Je}${Nt.join(`,${Je}`)}${nt}]`:`[${Nt.join(", ")}]`}else{const Nt=Array.from(v.value.entries()).map(([yt,bt])=>{const Dt=`"${yt}": ${St(bt,H,Y+1)}`;return H?`${Je}${Dt}`:Dt});return H?`{${Nt.join(",")}${nt}}`:`{${Nt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${v.type}`)}}var xt=class{constructor(v){Me(this,"parsed");const H=B(v,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ce(H)}render(v){const H=new Ve;H.set("false",!1),H.set("true",!0),H.set("raise_exception",fe=>{throw new Error(fe)}),H.set("range",We);for(const[fe,nt]of Object.entries(v))H.set(fe,nt);return new ut(H).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(At,ye,D)=>{D.r(ye),D.d(ye,{registerBackend:()=>he,resolveBackendAndExecutionProviders:()=>xe});const I=new Map,de=[],he=(j,P,L)=>{if(P&&typeof P.init=="function"&&typeof P.createInferenceSessionHandler=="function"){const B=I.get(j);if(B===void 0)I.set(j,{backend:P,priority:L});else{if(B.priority>L)return;if(B.priority===L&&B.backend!==P)throw new Error(`cannot register backend "${j}" using priority ${L}`)}if(L>=0){const q=de.indexOf(j);q!==-1&&de.splice(q,1);for(let re=0;re{const P=I.get(j);if(!P)return"backend not found.";if(P.initialized)return P.backend;if(P.aborted)return P.error;{const L=!!P.initPromise;try{return L||(P.initPromise=P.backend.init(j)),await P.initPromise,P.initialized=!0,P.backend}catch(B){return L||(P.error=`${B}`,P.aborted=!0),P.error}finally{delete P.initPromise}}},xe=async j=>{const P=j.executionProviders||[],L=P.map(O=>typeof O=="string"?O:O.name),B=L.length===0?de:L;let q;const re=[],me=new Set;for(const O of B){const J=await ve(O);typeof J=="string"?re.push({name:O,err:J}):(q||(q=J),q===J&&me.add(O))}if(!q)throw new Error(`no available backend found. ERR: ${re.map(O=>`[${O.name}] ${O.err}`).join(", ")}`);for(const{name:O,err:J}of re)L.includes(O)&&console.warn(`removing requested execution provider "${O}" from session options because it is not available: ${J}`);const ue=P.filter(O=>me.has(typeof O=="string"?O:O.name));return[q,new Proxy(j,{get:(O,J)=>J==="executionProviders"?ue:Reflect.get(O,J)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(At,ye,D)=>{D.r(ye),D.d(ye,{registerBackend:()=>I.registerBackend});var I=D("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(At,ye,D)=>{D.r(ye),D.d(ye,{env:()=>he});var I=D("./node_modules/onnxruntime-common/dist/esm/version.js");let de="warning";const he={wasm:{},webgl:{},webgpu:{},versions:{common:I.version},set logLevel(ve){if(ve!==void 0){if(typeof ve!="string"||["verbose","info","warning","error","fatal"].indexOf(ve)===-1)throw new Error(`Unsupported logging level: ${ve}`);de=ve}},get logLevel(){return de}};Object.defineProperty(he,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(At,ye,D)=>{D.r(ye),D.d(ye,{env:()=>de});var I=D("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const de=I.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(At,ye,D)=>{D.r(ye),D.d(ye,{InferenceSession:()=>he.InferenceSession,TRACE:()=>xe.TRACE,TRACE_FUNC_BEGIN:()=>xe.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>xe.TRACE_FUNC_END,Tensor:()=>ve.Tensor,TrainingSession:()=>j.TrainingSession,env:()=>de.env,registerBackend:()=>I.registerBackend});var I=D("./node_modules/onnxruntime-common/dist/esm/backend.js"),de=D("./node_modules/onnxruntime-common/dist/esm/env.js"),he=D("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),ve=D("./node_modules/onnxruntime-common/dist/esm/tensor.js");D("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),D("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var xe=D("./node_modules/onnxruntime-common/dist/esm/trace.js");D("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),D("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var j=D("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(At,ye,D)=>{D.r(ye),D.d(ye,{InferenceSession:()=>ve});var I=D("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),de=D("./node_modules/onnxruntime-common/dist/esm/tensor.js"),he=D("./node_modules/onnxruntime-common/dist/esm/trace.js");class ve{constructor(j){this.handler=j}async run(j,P,L){(0,he.TRACE_FUNC_BEGIN)();const B={};let q={};if(typeof j!="object"||j===null||j instanceof de.Tensor||Array.isArray(j))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let re=!0;if(typeof P=="object"){if(P===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(P instanceof de.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(P)){if(P.length===0)throw new TypeError("'fetches' cannot be an empty array.");re=!1;for(const O of P){if(typeof O!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(O)===-1)throw new RangeError(`'fetches' contains invalid output name: ${O}.`);B[O]=null}if(typeof L=="object"&&L!==null)q=L;else if(typeof L<"u")throw new TypeError("'options' must be an object.")}else{let O=!1;const J=Object.getOwnPropertyNames(P);for(const pe of this.outputNames)if(J.indexOf(pe)!==-1){const X=P[pe];(X===null||X instanceof de.Tensor)&&(O=!0,re=!1,B[pe]=X)}if(O){if(typeof L=="object"&&L!==null)q=L;else if(typeof L<"u")throw new TypeError("'options' must be an object.")}else q=P}}else if(typeof P<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const O of this.inputNames)if(typeof j[O]>"u")throw new Error(`input '${O}' is missing in 'feeds'.`);if(re)for(const O of this.outputNames)B[O]=null;const me=await this.handler.run(j,B,q),ue={};for(const O in me)if(Object.hasOwnProperty.call(me,O)){const J=me[O];J instanceof de.Tensor?ue[O]=J:ue[O]=new de.Tensor(J.type,J.data,J.dims)}return(0,he.TRACE_FUNC_END)(),ue}async release(){return this.handler.dispose()}static async create(j,P,L,B){(0,he.TRACE_FUNC_BEGIN)();let q,re={};if(typeof j=="string"){if(q=j,typeof P=="object"&&P!==null)re=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(j instanceof Uint8Array){if(q=j,typeof P=="object"&&P!==null)re=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(j instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&j instanceof SharedArrayBuffer){const J=j;let pe=0,X=j.byteLength;if(typeof P=="object"&&P!==null)re=P;else if(typeof P=="number"){if(pe=P,!Number.isSafeInteger(pe))throw new RangeError("'byteOffset' must be an integer.");if(pe<0||pe>=J.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${J.byteLength}).`);if(X=j.byteLength-pe,typeof L=="number"){if(X=L,!Number.isSafeInteger(X))throw new RangeError("'byteLength' must be an integer.");if(X<=0||pe+X>J.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${J.byteLength-pe}].`);if(typeof B=="object"&&B!==null)re=B;else if(typeof B<"u")throw new TypeError("'options' must be an object.")}else if(typeof L<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof P<"u")throw new TypeError("'options' must be an object.");q=new Uint8Array(J,pe,X)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[me,ue]=await(0,I.resolveBackendAndExecutionProviders)(re),O=await me.createInferenceSessionHandler(q,ue);return(0,he.TRACE_FUNC_END)(),new ve(O)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(At,ye,D)=>{D.r(ye),D.d(ye,{InferenceSession:()=>de});var I=D("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const de=I.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(At,ye,D)=>{D.r(ye)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(At,ye,D)=>{D.r(ye)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(At,ye,D)=>{D.r(ye),D.d(ye,{tensorToDataURL:()=>I,tensorToImageData:()=>de});const I=(he,ve)=>{const xe=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);xe.width=he.dims[3],xe.height=he.dims[2];const j=xe.getContext("2d");if(j!=null){let P,L;(ve==null?void 0:ve.tensorLayout)!==void 0&&ve.tensorLayout==="NHWC"?(P=he.dims[2],L=he.dims[3]):(P=he.dims[3],L=he.dims[2]);const B=(ve==null?void 0:ve.format)!==void 0?ve.format:"RGB",q=ve==null?void 0:ve.norm;let re,me;q===void 0||q.mean===void 0?re=[255,255,255,255]:typeof q.mean=="number"?re=[q.mean,q.mean,q.mean,q.mean]:(re=[q.mean[0],q.mean[1],q.mean[2],0],q.mean[3]!==void 0&&(re[3]=q.mean[3])),q===void 0||q.bias===void 0?me=[0,0,0,0]:typeof q.bias=="number"?me=[q.bias,q.bias,q.bias,q.bias]:(me=[q.bias[0],q.bias[1],q.bias[2],0],q.bias[3]!==void 0&&(me[3]=q.bias[3]));const ue=L*P;let O=0,J=ue,pe=ue*2,X=-1;B==="RGBA"?(O=0,J=ue,pe=ue*2,X=ue*3):B==="RGB"?(O=0,J=ue,pe=ue*2):B==="RBG"&&(O=0,pe=ue,J=ue*2);for(let K=0;K{const xe=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let j;if(xe!=null){let P,L,B;(ve==null?void 0:ve.tensorLayout)!==void 0&&ve.tensorLayout==="NHWC"?(P=he.dims[2],L=he.dims[1],B=he.dims[3]):(P=he.dims[3],L=he.dims[2],B=he.dims[1]);const q=ve!==void 0&&ve.format!==void 0?ve.format:"RGB",re=ve==null?void 0:ve.norm;let me,ue;re===void 0||re.mean===void 0?me=[255,255,255,255]:typeof re.mean=="number"?me=[re.mean,re.mean,re.mean,re.mean]:(me=[re.mean[0],re.mean[1],re.mean[2],255],re.mean[3]!==void 0&&(me[3]=re.mean[3])),re===void 0||re.bias===void 0?ue=[0,0,0,0]:typeof re.bias=="number"?ue=[re.bias,re.bias,re.bias,re.bias]:(ue=[re.bias[0],re.bias[1],re.bias[2],0],re.bias[3]!==void 0&&(ue[3]=re.bias[3]));const O=L*P;if(ve!==void 0&&(ve.format!==void 0&&B===4&&ve.format!=="RGBA"||B===3&&ve.format!=="RGB"&&ve.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const J=4;let pe=0,X=1,K=2,V=3,E=0,N=O,k=O*2,le=-1;q==="RGBA"?(E=0,N=O,k=O*2,le=O*3):q==="RGB"?(E=0,N=O,k=O*2):q==="RBG"&&(E=0,k=O,N=O*2),j=xe.createImageData(P,L);for(let be=0;be{D.r(ye)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(At,ye,D)=>{D.r(ye),D.d(ye,{bufferToTensor:()=>de,tensorFromGpuBuffer:()=>xe,tensorFromImage:()=>he,tensorFromPinnedBuffer:()=>j,tensorFromTexture:()=>ve});var I=D("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const de=(P,L)=>{if(P===void 0)throw new Error("Image buffer must be defined");if(L.height===void 0||L.width===void 0)throw new Error("Image height and width must be defined");if(L.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:B,width:q}=L,re=L.norm??{mean:255,bias:0};let me,ue;typeof re.mean=="number"?me=[re.mean,re.mean,re.mean,re.mean]:me=[re.mean[0],re.mean[1],re.mean[2],re.mean[3]??255],typeof re.bias=="number"?ue=[re.bias,re.bias,re.bias,re.bias]:ue=[re.bias[0],re.bias[1],re.bias[2],re.bias[3]??0];const O=L.format!==void 0?L.format:"RGBA",J=L.tensorFormat!==void 0&&L.tensorFormat!==void 0?L.tensorFormat:"RGB",pe=B*q,X=J==="RGBA"?new Float32Array(pe*4):new Float32Array(pe*3);let K=4,V=0,E=1,N=2,k=3,le=0,be=pe,$e=pe*2,De=-1;O==="RGB"&&(K=3,V=0,E=1,N=2,k=-1),J==="RGBA"?De=pe*3:J==="RBG"?(le=0,$e=pe,be=pe*2):J==="BGR"&&($e=0,be=pe,le=pe*2);for(let it=0;it{const B=typeof HTMLImageElement<"u"&&P instanceof HTMLImageElement,q=typeof ImageData<"u"&&P instanceof ImageData,re=typeof ImageBitmap<"u"&&P instanceof ImageBitmap,me=typeof P=="string";let ue,O=L??{};const J=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},pe=X=>X instanceof HTMLCanvasElement||X instanceof OffscreenCanvas?X.getContext("2d"):null;if(B){const X=J();X.width=P.width,X.height=P.height;const K=pe(X);if(K!=null){let V=P.height,E=P.width;if(L!==void 0&&L.resizedHeight!==void 0&&L.resizedWidth!==void 0&&(V=L.resizedHeight,E=L.resizedWidth),L!==void 0){if(O=L,L.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");O.tensorFormat="RGBA",O.height=V,O.width=E}else O.tensorFormat="RGBA",O.height=V,O.width=E;K.drawImage(P,0,0),ue=K.getImageData(0,0,E,V).data}else throw new Error("Can not access image data")}else if(q){let X,K;if(L!==void 0&&L.resizedWidth!==void 0&&L.resizedHeight!==void 0?(X=L.resizedHeight,K=L.resizedWidth):(X=P.height,K=P.width),L!==void 0&&(O=L),O.format="RGBA",O.height=X,O.width=K,L!==void 0){const V=J();V.width=K,V.height=X;const E=pe(V);if(E!=null)E.putImageData(P,0,0),ue=E.getImageData(0,0,K,X).data;else throw new Error("Can not access image data")}else ue=P.data}else if(re){if(L===void 0)throw new Error("Please provide image config with format for Imagebitmap");const X=J();X.width=P.width,X.height=P.height;const K=pe(X);if(K!=null){const V=P.height,E=P.width;return K.drawImage(P,0,0,E,V),ue=K.getImageData(0,0,E,V).data,O.height=V,O.width=E,de(ue,O)}else throw new Error("Can not access image data")}else{if(me)return new Promise((X,K)=>{const V=J(),E=pe(V);if(!P||!E)return K();const N=new Image;N.crossOrigin="Anonymous",N.src=P,N.onload=()=>{V.width=N.width,V.height=N.height,E.drawImage(N,0,0,V.width,V.height);const k=E.getImageData(0,0,V.width,V.height);O.height=V.height,O.width=V.width,X(de(k.data,O))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ue!==void 0)return de(ue,O);throw new Error("Input data provided is not supported - aborted tensor creation")},ve=(P,L)=>{const{width:B,height:q,download:re,dispose:me}=L,ue=[1,q,B,4];return new I.Tensor({location:"texture",type:"float32",texture:P,dims:ue,download:re,dispose:me})},xe=(P,L)=>{const{dataType:B,dims:q,download:re,dispose:me}=L;return new I.Tensor({location:"gpu-buffer",type:B??"float32",gpuBuffer:P,dims:q,download:re,dispose:me})},j=(P,L,B)=>new I.Tensor({location:"cpu-pinned",type:P,data:L,dims:B??[L.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(At,ye,D)=>{D.r(ye)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(At,ye,D)=>{D.r(ye),D.d(ye,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>de,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>I,checkTypedArray:()=>ve});const I=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),de=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let he=!1;const ve=()=>{if(!he){he=!0;const xe=typeof BigInt64Array<"u"&&BigInt64Array.from,j=typeof BigUint64Array<"u"&&BigUint64Array.from,P=typeof Float16Array<"u"&&Float16Array.from;xe&&(I.set("int64",BigInt64Array),de.set(BigInt64Array,"int64")),j&&(I.set("uint64",BigUint64Array),de.set(BigUint64Array,"uint64")),P?(I.set("float16",Float16Array),de.set(Float16Array,"float16")):I.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(At,ye,D)=>{D.r(ye),D.d(ye,{Tensor:()=>xe});var I=D("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),de=D("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),he=D("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),ve=D("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class xe{constructor(P,L,B){(0,he.checkTypedArray)();let q,re;if(typeof P=="object"&&"location"in P)switch(this.dataLocation=P.location,q=P.type,re=P.dims,P.location){case"cpu-pinned":{const ue=he.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(q);if(!ue)throw new TypeError(`unsupported type "${q}" to create tensor from pinned buffer`);if(!(P.data instanceof ue))throw new TypeError(`buffer should be of type ${ue.name}`);this.cpuData=P.data;break}case"texture":{if(q!=="float32")throw new TypeError(`unsupported type "${q}" to create tensor from texture`);this.gpuTextureData=P.texture,this.downloader=P.download,this.disposer=P.dispose;break}case"gpu-buffer":{if(q!=="float32"&&q!=="float16"&&q!=="int32"&&q!=="int64"&&q!=="uint32"&&q!=="uint8"&&q!=="bool")throw new TypeError(`unsupported type "${q}" to create tensor from gpu buffer`);this.gpuBufferData=P.gpuBuffer,this.downloader=P.download,this.disposer=P.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ue,O;if(typeof P=="string")if(q=P,O=B,P==="string"){if(!Array.isArray(L))throw new TypeError("A string tensor's data must be a string array.");ue=L}else{const J=he.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(P);if(J===void 0)throw new TypeError(`Unsupported tensor type: ${P}.`);if(Array.isArray(L)){if(P==="float16"&&J===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");P==="uint64"||P==="int64"?ue=J.from(L,BigInt):ue=J.from(L)}else if(L instanceof J)ue=L;else throw new TypeError(`A ${q} tensor's data must be type of ${J}`)}else if(O=L,Array.isArray(P)){if(P.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const J=typeof P[0];if(J==="string")q="string",ue=P;else if(J==="boolean")q="bool",ue=Uint8Array.from(P);else throw new TypeError(`Invalid element type of data array: ${J}.`)}else{const J=he.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(P.constructor);if(J===void 0)throw new TypeError(`Unsupported type for tensor data: ${P.constructor}.`);q=J,ue=P}if(O===void 0)O=[ue.length];else if(!Array.isArray(O))throw new TypeError("A tensor's dims must be a number array");re=O,this.cpuData=ue,this.dataLocation="cpu"}const me=(0,ve.calculateSize)(re);if(this.cpuData&&me!==this.cpuData.length)throw new Error(`Tensor's size(${me}) does not match data length(${this.cpuData.length}).`);this.type=q,this.dims=re,this.size=me}static async fromImage(P,L){return(0,de.tensorFromImage)(P,L)}static fromTexture(P,L){return(0,de.tensorFromTexture)(P,L)}static fromGpuBuffer(P,L){return(0,de.tensorFromGpuBuffer)(P,L)}static fromPinnedBuffer(P,L,B){return(0,de.tensorFromPinnedBuffer)(P,L,B)}toDataURL(P){return(0,I.tensorToDataURL)(this,P)}toImageData(P){return(0,I.tensorToImageData)(this,P)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(P){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const L=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=L,P&&this.disposer&&(this.disposer(),this.disposer=void 0),L}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(P){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,ve.tensorReshape)(this,P)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(At,ye,D)=>{D.r(ye),D.d(ye,{calculateSize:()=>de,tensorReshape:()=>he});var I=D("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const de=ve=>{let xe=1;for(let j=0;j{switch(ve.location){case"cpu":return new I.Tensor(ve.type,ve.data,xe);case"cpu-pinned":return new I.Tensor({location:"cpu-pinned",data:ve.data,type:ve.type,dims:xe});case"texture":return new I.Tensor({location:"texture",texture:ve.texture,type:ve.type,dims:xe});case"gpu-buffer":return new I.Tensor({location:"gpu-buffer",gpuBuffer:ve.gpuBuffer,type:ve.type,dims:xe});default:throw new Error(`tensorReshape: tensor location ${ve.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(At,ye,D)=>{D.r(ye),D.d(ye,{Tensor:()=>de});var I=D("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const de=I.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(At,ye,D)=>{D.r(ye),D.d(ye,{TRACE:()=>de,TRACE_FUNC_BEGIN:()=>ve,TRACE_FUNC_END:()=>xe});var I=D("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const de=(j,P)=>{(typeof I.env.trace>"u"?!I.env.wasm.trace:!I.env.trace)||console.timeStamp(`${j}::ORT::${P}`)},he=(j,P)=>{var q;const L=((q=new Error().stack)==null?void 0:q.split(/\r\n|\r|\n/g))||[];let B=!1;for(let re=0;re{(typeof I.env.trace>"u"?!I.env.wasm.trace:!I.env.trace)||he("BEGIN",j)},xe=j=>{(typeof I.env.trace>"u"?!I.env.wasm.trace:!I.env.trace)||he("END",j)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(At,ye,D)=>{D.r(ye),D.d(ye,{TrainingSession:()=>ve});var I=D("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),de=D("./node_modules/onnxruntime-common/dist/esm/tensor.js");const he="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class ve{constructor(j,P,L){this.handler=j,this.hasOptimizerModel=P,this.hasEvalModel=L}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(j,P){const L=j.evalModel||"",B=j.optimizerModel||"",q=P||{},[re,me]=await(0,I.resolveBackendAndExecutionProviders)(q);if(re.createTrainingSessionHandler){const ue=await re.createTrainingSessionHandler(j.checkpointState,j.trainModel,L,B,me);return new ve(ue,!!j.optimizerModel,!!j.evalModel)}else throw new Error(he)}typeNarrowingForRunStep(j,P,L,B,q){const re={};let me={};if(typeof L!="object"||L===null||L instanceof de.Tensor||Array.isArray(L))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ue=!0;if(typeof B=="object"){if(B===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(B instanceof de.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(B)){if(B.length===0)throw new TypeError("'fetches' cannot be an empty array.");ue=!1;for(const O of B){if(typeof O!="string")throw new TypeError("'fetches' must be a string array or an object.");if(P.indexOf(O)===-1)throw new RangeError(`'fetches' contains invalid output name: ${O}.`);re[O]=null}if(typeof q=="object"&&q!==null)me=q;else if(typeof q<"u")throw new TypeError("'options' must be an object.")}else{let O=!1;const J=Object.getOwnPropertyNames(B);for(const pe of P)if(J.indexOf(pe)!==-1){const X=B[pe];(X===null||X instanceof de.Tensor)&&(O=!0,ue=!1,re[pe]=X)}if(O){if(typeof q=="object"&&q!==null)me=q;else if(typeof q<"u")throw new TypeError("'options' must be an object.")}else me=B}}else if(typeof B<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const O of j)if(typeof L[O]>"u")throw new Error(`input '${O}' is missing in 'feeds'.`);if(ue)for(const O of P)re[O]=null;return[re,me]}convertHandlerReturnTypeToMapOfTensors(j){const P={};for(const L in j)if(Object.hasOwnProperty.call(j,L)){const B=j[L];B instanceof de.Tensor?P[L]=B:P[L]=new de.Tensor(B.type,B.data,B.dims)}return P}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(j,P,L){const[B,q]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,j,P,L),re=await this.handler.runTrainStep(j,B,q);return this.convertHandlerReturnTypeToMapOfTensors(re)}async runOptimizerStep(j){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(j||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(j,P,L){if(this.hasEvalModel){const[B,q]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,j,P,L),re=await this.handler.runEvalStep(j,B,q);return this.convertHandlerReturnTypeToMapOfTensors(re)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(j=!0){return this.handler.getParametersSize(j)}async loadParametersBuffer(j,P=!0){const L=await this.getParametersSize(P);if(j.length!==4*L)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(j,P)}async getContiguousParameters(j=!0){return this.handler.getContiguousParameters(j)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(At,ye,D)=>{D.r(ye),D.d(ye,{TrainingSession:()=>de});var I=D("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const de=I.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(At,ye,D)=>{D.r(ye),D.d(ye,{version:()=>I});const I="1.19.2"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(At,ye,D)=>{D.r(ye),D.d(ye,{InferenceSession:()=>xt,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>je,TRACE_FUNC_END:()=>Ve,Tensor:()=>Z,TrainingSession:()=>yt,default:()=>Gf,env:()=>k,registerBackend:()=>me});/*! * ONNX Runtime Web v1.21.0-dev.20241024-d9ca84ef96 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var I=Object.defineProperty,de=Object.getOwnPropertyDescriptor,he=Object.getOwnPropertyNames,ve=Object.prototype.hasOwnProperty,xe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),j=(e,t)=>()=>(e&&(t=e(e=0)),t),P=(e,t)=>{for(var r in t)I(e,r,{get:t[r],enumerable:!0})},L=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of he(t))!ve.call(e,i)&&i!==r&&I(e,i,{get:()=>t[i],enumerable:!(n=de(t,i))||n.enumerable});return e},B=e=>L(I({},"__esModule",{value:!0}),e),q,re,me,ue,O,J=j(()=>{q=new Map,re=[],me=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=q.get(e);if(n===void 0)q.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let i=re.indexOf(e);i!==-1&&re.splice(i,1);for(let a=0;a{let t=q.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},O=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?re:r,i,a=[],s=new Set;for(let d of n){let c=await ue(d);typeof c=="string"?a.push({name:d,err:c}):(i||(i=c),i===c&&s.add(d))}if(!i)throw new Error(`no available backend found. ERR: ${a.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:c}of a)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${c}`);let u=t.filter(d=>s.has(typeof d=="string"?d:d.name));return[i,new Proxy(e,{get:(d,c)=>c==="executionProviders"?u:Reflect.get(d,c)})]}}),pe=j(()=>{J()}),X,K=j(()=>{X="1.20.0-dev.20241016-2b8fc5529b"}),V,E,N=j(()=>{K(),V="warning",E={wasm:{},webgl:{},webgpu:{},versions:{common:X},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);V=e}},get logLevel(){return V}},Object.defineProperty(E,"logLevel",{enumerable:!0})}),k,le=j(()=>{N(),k=E}),be,$e,De=j(()=>{be=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let i,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let s=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,d,c;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?c=[0,0,0,0]:typeof u.bias=="number"?c=[u.bias,u.bias,u.bias,u.bias]:(c=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(c[3]=u.bias[3]));let g=a*i,m=0,l=g,T=g*2,x=-1;s==="RGBA"?(m=0,l=g,T=g*2,x=g*3):s==="RGB"?(m=0,l=g,T=g*2):s==="RBG"&&(m=0,T=g,l=g*2);for(let C=0;C{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let i,a,s;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[1],s=e.dims[3]):(i=e.dims[3],a=e.dims[2],s=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,c,g;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean=="number"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?g=[0,0,0,0]:typeof d.bias=="number"?g=[d.bias,d.bias,d.bias,d.bias]:(g=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(g[3]=d.bias[3]));let m=a*i;if(t!==void 0&&(t.format!==void 0&&s===4&&t.format!=="RGBA"||s===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,T=0,x=1,C=2,z=3,U=0,A=m,ee=m*2,te=-1;u==="RGBA"?(U=0,A=m,ee=m*2,te=m*3):u==="RGB"?(U=0,A=m,ee=m*2):u==="RBG"&&(U=0,ee=m,A=m*2),n=r.createImageData(i,a);for(let ie=0;ie{Xe(),ze=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,i=t.norm??{mean:255,bias:0},a,s;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?s=[i.bias,i.bias,i.bias,i.bias]:s=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*n,g=d==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),m=4,l=0,T=1,x=2,C=3,z=0,U=c,A=c*2,ee=-1;u==="RGB"&&(m=3,l=0,T=1,x=2,C=-1),d==="RGBA"?ee=c*3:d==="RBG"?(z=0,A=c,U=c*2):d==="BGR"&&(A=0,U=c,z=c*2);for(let te=0;te{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",s,u=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=g=>typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(r){let g=d();g.width=e.width,g.height=e.height;let m=c(g);if(m!=null){let l=e.height,T=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,T=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=l,u.width=T}else u.tensorFormat="RGBA",u.height=l,u.width=T;m.drawImage(e,0,0),s=m.getImageData(0,0,T,l).data}else throw new Error("Can not access image data")}else if(n){let g,m;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,m=t.resizedWidth):(g=e.height,m=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=g,u.width=m,t!==void 0){let l=d();l.width=m,l.height=g;let T=c(l);if(T!=null)T.putImageData(e,0,0),s=T.getImageData(0,0,m,g).data;else throw new Error("Can not access image data")}else s=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=d();g.width=e.width,g.height=e.height;let m=c(g);if(m!=null){let l=e.height,T=e.width;return m.drawImage(e,0,0,T,l),s=m.getImageData(0,0,T,l).data,u.height=l,u.width=T,ze(s,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((g,m)=>{let l=d(),T=c(l);if(!e||!T)return m();let x=new Image;x.crossOrigin="Anonymous",x.src=e,x.onload=()=>{l.width=x.width,l.height=x.height,T.drawImage(x,0,0,l.width,l.height);let C=T.getImageData(0,0,l.width,l.height);u.height=l.height,u.width=l.width,g(ze(C.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return ze(s,u);throw new Error("Input data provided is not supported - aborted tensor creation")},rt=(e,t)=>{let{width:r,height:n,download:i,dispose:a}=t,s=[1,n,r,4];return new Mt({location:"texture",type:"float32",texture:e,dims:s,download:i,dispose:a})},lt=(e,t)=>{let{dataType:r,dims:n,download:i,dispose:a}=t;return new Mt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:i,dispose:a})},_e=(e,t)=>{let{dataType:r,dims:n,download:i,dispose:a}=t;return new Mt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:i,dispose:a})},W=(e,t,r)=>new Mt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Ce,We,ot,ne,Ze=j(()=>{Ce=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),We=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ot=!1,ne=()=>{if(!ot){ot=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(Ce.set("int64",BigInt64Array),We.set(BigInt64Array,"int64")),t&&(Ce.set("uint64",BigUint64Array),We.set(BigUint64Array,"uint64")),r?(Ce.set("float16",Float16Array),We.set(Float16Array,"float16")):Ce.set("float16",Uint16Array)}}}),dt,Re,ht=j(()=>{Xe(),dt=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Mt(e.type,e.data,t);case"cpu-pinned":return new Mt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Mt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Mt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Mt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Mt,Xe=j(()=>{De(),ce(),Ze(),ht(),Mt=class{constructor(e,t,r){ne();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let s=Ce.get(n);if(!s)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof s))throw new TypeError(`buffer should be of type ${s.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");s=t}else{let d=Ce.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&d===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${d.name} as data.`);e==="uint64"||e==="int64"?s=d.from(t,BigInt):s=d.from(t)}else if(t instanceof d)s=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")s=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${d}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")n="string",s=e;else if(d==="boolean")n="bool",s=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",s=Uint8Array.from(e);else{let d=We.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=d,s=e}if(u===void 0)u=[s.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");i=u,this.cpuData=s,this.dataLocation="cpu"}let a=dt(i);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=a}static async fromImage(e,t){return it(e,t)}static fromTexture(e,t){return rt(e,t)}static fromGpuBuffer(e,t){return lt(e,t)}static fromMLTensor(e,t){return _e(e,t)}static fromPinnedBuffer(e,t,r){return W(e,t,r)}toDataURL(e){return be(this,e)}toImageData(e){return $e(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Re(this,e)}}}),Z,Ae=j(()=>{Xe(),Z=Mt}),Ke,et,je,Ve,ut=j(()=>{N(),Ke=(e,t)=>{(typeof E.trace>"u"?!E.wasm.trace:!E.trace)||console.timeStamp(`${e}::ORT::${t}`)},et=(e,t)=>{var i;let r=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof E.trace>"u"?!E.wasm.trace:!E.trace)||et("BEGIN",e)},Ve=e=>{(typeof E.trace>"u"?!E.wasm.trace:!E.trace)||et("END",e)}}),_t,St=j(()=>{J(),Ae(),ut(),_t=class Sf{constructor(t){this.handler=t}async run(t,r,n){je();let i={},a={};if(typeof t!="object"||t===null||t instanceof Z||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Z)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);i[c]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,g=Object.getOwnPropertyNames(r);for(let m of this.outputNames)if(g.indexOf(m)!==-1){let l=r[m];(l===null||l instanceof Z)&&(c=!0,s=!1,i[m]=l)}if(c){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(s)for(let c of this.outputNames)i[c]=null;let u=await this.handler.run(t,i,a),d={};for(let c in u)if(Object.hasOwnProperty.call(u,c)){let g=u[c];g instanceof Z?d[c]=g:d[c]=new Z(g.type,g.data,g.dims)}return Ve(),d}async release(){return this.handler.dispose()}static async create(t,r,n,i){je();let a,s={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let g=t,m=0,l=t.byteLength;if(typeof r=="object"&&r!==null)s=r;else if(typeof r=="number"){if(m=r,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(l=t.byteLength-m,typeof n=="number"){if(l=n,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||m+l>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-m}].`);if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(g,m,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await O(s),c=await u.createInferenceSessionHandler(a,d);return Ve(),new Sf(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),xt,v=j(()=>{St(),xt=_t}),H=j(()=>{}),$=j(()=>{}),Y=j(()=>{}),fe=j(()=>{}),nt,Je,Nt=j(()=>{J(),Ae(),nt="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Je=class Pf{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let n=t.evalModel||"",i=t.optimizerModel||"",a=r||{},[s,u]=await O(a);if(s.createTrainingSessionHandler){let d=await s.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,i,u);return new Pf(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(nt)}typeNarrowingForRunStep(t,r,n,i,a){let s={},u={};if(typeof n!="object"||n===null||n instanceof Z||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof Z)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let c of i){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);s[c]=null}if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,g=Object.getOwnPropertyNames(i);for(let m of r)if(g.indexOf(m)!==-1){let l=i[m];(l===null||l instanceof Z)&&(c=!0,d=!1,s[m]=l)}if(c){if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else u=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of t)if(typeof n[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(d)for(let c of r)s[c]=null;return[s,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let i=t[n];i instanceof Z?r[n]=i:r[n]=new Z(i.type,i.data,i.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[i,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),s=await this.handler.runTrainStep(t,i,a);return this.convertHandlerReturnTypeToMapOfTensors(s)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[i,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),s=await this.handler.runEvalStep(t,i,a);return this.convertHandlerReturnTypeToMapOfTensors(s)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),yt,bt=j(()=>{Nt(),yt=Je}),Dt={};P(Dt,{InferenceSession:()=>xt,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>je,TRACE_FUNC_END:()=>Ve,Tensor:()=>Z,TrainingSession:()=>yt,env:()=>k,registerBackend:()=>me});var Pt=j(()=>{pe(),le(),v(),Ae(),H(),$(),ut(),Y(),fe(),bt()}),dr=j(()=>{}),Cr={};P(Cr,{default:()=>Jr});var Yr,Rr,Jr,yn=j(()=>{var e;Kp(),Er(),Ot(),Yr="ort-wasm-proxy-worker",Rr=((e=globalThis.self)==null?void 0:e.name)===Yr,Rr&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Nr(n.wasm).then(()=>{Oc(n).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})})},i=>{postMessage({type:r,err:i})});break;case"init-ep":{let{epName:i,env:a}=n;zc(a,i).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})});break}case"copy-from":{let{buffer:i}=n,a=oc(i);postMessage({type:r,out:a});break}case"create":{let{model:i,options:a}=n;Dc(i,a).then(s=>{postMessage({type:r,out:s})},s=>{postMessage({type:r,err:s})});break}case"release":Lc(n),postMessage({type:r});break;case"run":{let{sessionId:i,inputIndices:a,inputs:s,outputIndices:u,options:d}=n;Rc(i,a,s,u,new Array(u.length).fill(null),d).then(c=>{c.some(g=>g[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:c},jc([...s,...c]))},c=>{postMessage({type:r,err:c})});break}case"end-profiling":Nc(n),postMessage({type:r});break;default:}}catch(i){postMessage({type:r,err:i})}}),Jr=Rr?null:t=>new Worker(t??Ne,{type:"module",name:Yr})}),at={};P(at,{default:()=>Ie});var G,we,Ie,Se=j(()=>{var e;we=(G=import.meta.url,async function(t={}){function r(){return hr.buffer!=Qt.buffer&&fn(),Qt}function n(){return hr.buffer!=Qt.buffer&&fn(),xr}function i(){return hr.buffer!=Qt.buffer&&fn(),qe}function a(){return hr.buffer!=Qt.buffer&&fn(),vt}function s(){return hr.buffer!=Qt.buffer&&fn(),rr}function u(){return hr.buffer!=Qt.buffer&&fn(),Br}function d(){return hr.buffer!=Qt.buffer&&fn(),nn}function c(){return hr.buffer!=Qt.buffer&&fn(),dc}var g,m,l=Object.assign({},t),T=new Promise((o,h)=>{g=o,m=h}),x=typeof window=="object",C=typeof importScripts=="function",z=C&&self.name=="em-pthread";l.mountExternalData=(o,h)=>{o.startsWith("./")&&(o=o.substring(2)),(l.Eb||(l.Eb=new Map)).set(o,h)},l.unmountExternalData=()=>{delete l.Eb};var U=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let A=()=>{let o=(w,M,S)=>(...se)=>{let He=us,st=M==null?void 0:M();se=w(...se);let It=M==null?void 0:M();return st!==It&&(w=It,S(st),M=S=null),us!=He?new Promise((Rt,Zt)=>{op={resolve:Rt,reject:Zt}}):se},h=w=>async(...M)=>{var S;try{if(l.Fb)throw Error("Session already started");let se=l.Fb={fc:M[0],errors:[]},He=await w(...M);if(l.Fb!==se)throw Error("Session mismatch");(S=l.Gb)==null||S.flush();let st=se.errors;if(0Rt),0l._OrtCreateSession,w=>l._OrtCreateSession=w),l._OrtRun=h(o(l._OrtRun,()=>l._OrtRun,w=>l._OrtRun=w)),l._OrtRunWithBinding=h(o(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,w=>l._OrtRunWithBinding=w)),l._OrtBindInput=o(l._OrtBindInput,()=>l._OrtBindInput,w=>l._OrtBindInput=w),A=void 0};l.jsepInit=(o,h)=>{if(A==null||A(),o==="webgpu"){[l.Gb,l.Ub,l.Yb,l.Nb,l.Xb,l.jb,l.Zb,l.bc,l.Vb,l.Wb,l.$b]=h;let w=l.Gb;l.jsepRegisterBuffer=(M,S,se,He)=>w.registerBuffer(M,S,se,He),l.jsepGetBuffer=M=>w.getBuffer(M),l.jsepCreateDownloader=(M,S,se)=>w.createDownloader(M,S,se),l.jsepOnCreateSession=M=>{w.onCreateSession(M)},l.jsepOnReleaseSession=M=>{w.onReleaseSession(M)},l.jsepOnRunStart=M=>w.onRunStart(M),l.cc=(M,S)=>{w.upload(M,S)}}else if(o==="webnn"){[l.Gb,l.ac,l.Ob,l.jsepEnsureTensor,l.dc,l.jsepDownloadTensor]=h,l.jsepReleaseTensorId=l.Ob;let w=l.Gb;l.jsepOnRunStart=M=>w.onRunStart(M),l.jsepRegisterMLContext=(M,S)=>{w.registerMLContext(M,S)},l.jsepOnReleaseSession=M=>{w.onReleaseSession(M)},l.jsepCreateMLTensorDownloader=(M,S)=>w.createMLTensorDownloader(M,S),l.jsepRegisterMLTensor=(M,S,se)=>w.registerMLTensor(M,S,se),l.qc=(M,S,se,He,st)=>w.registerMLConstant(M,S,se,He,st,l.Eb)}};var ee,te,ie=Object.assign({},l),Ee="./this.program",Pe=(o,h)=>{throw h},Ye="";(x||C)&&(C?Ye=self.location.href:typeof document<"u"&&document.currentScript&&(Ye=document.currentScript.src),G&&(Ye=G),Ye=Ye.startsWith("blob:")?"":Ye.substr(0,Ye.replace(/[?#].*/,"").lastIndexOf("/")+1),C&&(te=o=>{var h=new XMLHttpRequest;return h.open("GET",o,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),ee=(o,h,w)=>{var M=new XMLHttpRequest;M.open("GET",o,!0),M.responseType="arraybuffer",M.onload=()=>{M.status==200||M.status==0&&M.response?h(M.response):w()},M.onerror=w,M.send(null)});var Ft,Bt=console.log.bind(console),ar=console.error.bind(console),nr=Bt,Ht=ar;if(Object.assign(l,ie),ie=null,z){let o=function(h){try{var w=h.data,M=w.cmd;if(M==="load"){let S=[];self.onmessage=se=>S.push(se),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let se of S)o(se);self.onmessage=o};for(let se of w.handlers)l[se]&&!l[se].proxy||(l[se]=(...He)=>{postMessage({Mb:"callHandler",oc:se,args:He})},se=="print"&&(nr=l[se]),se=="printErr"&&(Ht=l[se]));hr=w.wasmMemory,fn(),kr(w.wasmModule)}else if(M==="run"){cp(w.pthread_ptr,0,0,1,0,0),sp(w.pthread_ptr),Kf(),gh(),jr||(mf(),jr=!0);try{Xf(w.start_routine,w.arg)}catch(S){if(S!="unwind")throw S}}else M==="cancel"?so()&&vc(-1):w.target!=="setimmediate"&&(M==="checkMailbox"?jr&&hc():M&&(Ht(`worker: received unknown command ${M}`),Ht(w)))}catch(S){throw _f(),S}};var kr,jr=!1;Ht=function(...h){h=h.join(" "),console.error(h)},self.alert=function(...h){postMessage({Mb:"alert",text:h.join(" "),rc:so()})},l.instantiateWasm=(h,w)=>new Promise(M=>{kr=S=>{S=new WebAssembly.Instance(S,ph()),w(S),M()}}),self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=o}l.wasmBinary&&(Ft=l.wasmBinary);var hr,Fr,Gt,Qt,xr,qe,vt,rr,Br,nn,an,Hs,dc,En=!1;function fn(){var o=hr.buffer;l.HEAP8=Qt=new Int8Array(o),l.HEAP16=qe=new Int16Array(o),l.HEAPU8=xr=new Uint8Array(o),l.HEAPU16=vt=new Uint16Array(o),l.HEAP32=rr=new Int32Array(o),l.HEAPU32=Br=new Uint32Array(o),l.HEAPF32=nn=new Float32Array(o),l.HEAPF64=dc=new Float64Array(o),l.HEAP64=an=new BigInt64Array(o),l.HEAPU64=Hs=new BigUint64Array(o)}if(!z){if(!((hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof U))throw Ht("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");fn()}var _i=[],dn=[],vn=[],Gn=0,Ks=null;function cc(){if(--Gn==0&&Ks){var o=Ks;Ks=null,o()}}function to(o){throw Ht(o="Aborted("+o+")"),En=!0,Gt=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),m(o),o}var qc,lh=o=>o.startsWith("data:application/octet-stream;base64,"),uh=o=>o.startsWith("file://");function dh(o){if(o==qc&&Ft)return new Uint8Array(Ft);if(te)return te(o);throw"both async and sync fetching of the wasm failed"}function ch(o,h,w){return function(M){if(!Ft&&(x||C)){if(typeof fetch=="function"&&!uh(M))return fetch(M,{credentials:"same-origin"}).then(S=>{if(!S.ok)throw`failed to load wasm binary file at '${M}'`;return S.arrayBuffer()}).catch(()=>dh(M));if(ee)return new Promise((S,se)=>{ee(M,He=>S(new Uint8Array(He)),se)})}return Promise.resolve().then(()=>dh(M))}(o).then(M=>WebAssembly.instantiate(M,h)).then(w,M=>{Ht(`failed to asynchronously prepare wasm: ${M}`),to(M)})}function ph(){return{a:{O:Hf,Aa:qf,b:Yf,aa:Mh,B:Th,qa:Ch,Y:kh,_:Eh,ra:Sh,oa:Ph,ha:Ah,na:Ih,L:Fh,Z:Oh,W:zh,pa:Dh,X:Lh,wa:Zf,F:Jf,Q:em,P:rm,E:sm,u:im,q:am,G:om,A:fm,R:mm,ua:_m,ka:gm,U:wm,ba:ym,H:bm,ja:sp,ta:Mm,t:vm,x:Cm,n:$m,l:Em,c:rp,o:Sm,j:Im,w:Fm,p:Om,g:zm,s:Dm,m:Lm,e:Bm,k:Rm,i:Nm,h:jm,d:Vm,ea:Um,fa:Wm,ga:Gm,ca:Yh,da:Zh,T:qm,f:Hm,D:Km,I:Xm,M:Qm,y:Ym,sa:Zm,V:Jm,v:ef,z:e_,N:t_,S:r_,za:n_,ya:s_,la:nf,ma:sf,$:Yc,C:af,K:of,ia:lf,J:uf,a:hr,xa:Qc,va:pf,r:o_}}}var Hc={867364:(o,h,w,M,S)=>{if(l===void 0||!l.Eb)return 1;if((o=wn(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=l.Eb.get(o)))return 2;if(M>>>=0,(h>>>=0)+(w>>>=0)>o.byteLength)return 3;try{let se=o.subarray(h,h+w);switch(S){case 0:n().set(se,M>>>0);break;case 1:l.cc(M,se);break;default:return 4}return 0}catch{return 4}},868047:(o,h,w)=>{l.dc(o,n().subarray(h>>>0,h+w>>>0))},868110:()=>l.ac(),868151:o=>{l.Ob(o)},868187:()=>{l.Vb()},868218:()=>{l.Wb()},868247:()=>{l.$b()},868272:o=>l.Ub(o),868305:o=>l.Yb(o),868337:(o,h,w)=>{l.Nb(o,h,w,!0)},868376:(o,h,w)=>{l.Nb(o,h,w)},868409:()=>typeof wasmOffsetConverter<"u",868466:o=>{l.jb("Abs",o,void 0)},868517:o=>{l.jb("Neg",o,void 0)},868568:o=>{l.jb("Floor",o,void 0)},868621:o=>{l.jb("Ceil",o,void 0)},868673:o=>{l.jb("Reciprocal",o,void 0)},868731:o=>{l.jb("Sqrt",o,void 0)},868783:o=>{l.jb("Exp",o,void 0)},868834:o=>{l.jb("Erf",o,void 0)},868885:o=>{l.jb("Sigmoid",o,void 0)},868940:(o,h,w)=>{l.jb("HardSigmoid",o,{alpha:h,beta:w})},869019:o=>{l.jb("Log",o,void 0)},869070:o=>{l.jb("Sin",o,void 0)},869121:o=>{l.jb("Cos",o,void 0)},869172:o=>{l.jb("Tan",o,void 0)},869223:o=>{l.jb("Asin",o,void 0)},869275:o=>{l.jb("Acos",o,void 0)},869327:o=>{l.jb("Atan",o,void 0)},869379:o=>{l.jb("Sinh",o,void 0)},869431:o=>{l.jb("Cosh",o,void 0)},869483:o=>{l.jb("Asinh",o,void 0)},869536:o=>{l.jb("Acosh",o,void 0)},869589:o=>{l.jb("Atanh",o,void 0)},869642:o=>{l.jb("Tanh",o,void 0)},869694:o=>{l.jb("Not",o,void 0)},869745:(o,h,w)=>{l.jb("Clip",o,{min:h,max:w})},869814:o=>{l.jb("Clip",o,void 0)},869866:(o,h)=>{l.jb("Elu",o,{alpha:h})},869924:o=>{l.jb("Gelu",o,void 0)},869976:o=>{l.jb("Relu",o,void 0)},870028:(o,h)=>{l.jb("LeakyRelu",o,{alpha:h})},870092:(o,h)=>{l.jb("ThresholdedRelu",o,{alpha:h})},870162:(o,h)=>{l.jb("Cast",o,{to:h})},870220:o=>{l.jb("Add",o,void 0)},870271:o=>{l.jb("Sub",o,void 0)},870322:o=>{l.jb("Mul",o,void 0)},870373:o=>{l.jb("Div",o,void 0)},870424:o=>{l.jb("Pow",o,void 0)},870475:o=>{l.jb("Equal",o,void 0)},870528:o=>{l.jb("Greater",o,void 0)},870583:o=>{l.jb("GreaterOrEqual",o,void 0)},870645:o=>{l.jb("Less",o,void 0)},870697:o=>{l.jb("LessOrEqual",o,void 0)},870756:(o,h,w,M,S)=>{l.jb("ReduceMean",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},870915:(o,h,w,M,S)=>{l.jb("ReduceMax",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871073:(o,h,w,M,S)=>{l.jb("ReduceMin",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871231:(o,h,w,M,S)=>{l.jb("ReduceProd",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871390:(o,h,w,M,S)=>{l.jb("ReduceSum",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871548:(o,h,w,M,S)=>{l.jb("ReduceL1",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871705:(o,h,w,M,S)=>{l.jb("ReduceL2",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},871862:(o,h,w,M,S)=>{l.jb("ReduceLogSum",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},872023:(o,h,w,M,S)=>{l.jb("ReduceSumSquare",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},872187:(o,h,w,M,S)=>{l.jb("ReduceLogSumExp",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},872351:o=>{l.jb("Where",o,void 0)},872404:(o,h,w)=>{l.jb("Transpose",o,{perm:h?Array.from(s().subarray(h>>>0,w>>>0)):[]})},872512:(o,h,w,M)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:wn(w),format:M?"NHWC":"NCHW"})},872645:(o,h,w,M)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:wn(w),format:M?"NHWC":"NCHW"})},872778:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be,Mr)=>{l.jb("ConvTranspose",o,{format:It?"NHWC":"NCHW",autoPad:h,dilations:[w],group:M,kernelShape:[S],pads:[se,He],strides:[st],wIsConst:()=>!!r()[Rt>>>0],outputPadding:Zt?Array.from(s().subarray(Zt>>>0,Tr>>>0)):[],outputShape:Vr?Array.from(s().subarray(Vr>>>0,Be>>>0)):[],activation:wn(Mr)})},873179:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be)=>{l.jb("ConvTranspose",o,{format:st?"NHWC":"NCHW",autoPad:h,dilations:Array.from(s().subarray(w>>>0,2+(w>>>0)>>>0)),group:M,kernelShape:Array.from(s().subarray(S>>>0,2+(S>>>0)>>>0)),pads:Array.from(s().subarray(se>>>0,4+(se>>>0)>>>0)),strides:Array.from(s().subarray(He>>>0,2+(He>>>0)>>>0)),wIsConst:()=>!!r()[It>>>0],outputPadding:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],outputShape:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[],activation:wn(Be)})},873744:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be,Mr)=>{l.jb("ConvTranspose",o,{format:It?"NHWC":"NCHW",autoPad:h,dilations:[w],group:M,kernelShape:[S],pads:[se,He],strides:[st],wIsConst:()=>!!r()[Rt>>>0],outputPadding:Zt?Array.from(s().subarray(Zt>>>0,Tr>>>0)):[],outputShape:Vr?Array.from(s().subarray(Vr>>>0,Be>>>0)):[],activation:wn(Mr)})},874145:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be)=>{l.jb("ConvTranspose",o,{format:st?"NHWC":"NCHW",autoPad:h,dilations:Array.from(s().subarray(w>>>0,2+(w>>>0)>>>0)),group:M,kernelShape:Array.from(s().subarray(S>>>0,2+(S>>>0)>>>0)),pads:Array.from(s().subarray(se>>>0,4+(se>>>0)>>>0)),strides:Array.from(s().subarray(He>>>0,2+(He>>>0)>>>0)),wIsConst:()=>!!r()[It>>>0],outputPadding:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],outputShape:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[],activation:wn(Be)})},874710:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},874801:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:M,storage_order:S,dilations:se?Array.from(s().subarray(se>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,It>>>0)):[],pads:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],strides:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[]})},875216:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},875307:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:M,storage_order:S,dilations:se?Array.from(s().subarray(se>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,It>>>0)):[],pads:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],strides:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[]})},875722:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},875809:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:M,storage_order:S,dilations:se?Array.from(s().subarray(se>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,It>>>0)):[],pads:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],strides:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[]})},876220:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},876307:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:M,storage_order:S,dilations:se?Array.from(s().subarray(se>>>0,He>>>0)):[],kernel_shape:st?Array.from(s().subarray(st>>>0,It>>>0)):[],pads:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],strides:Tr?Array.from(s().subarray(Tr>>>0,Vr>>>0)):[]})},876718:(o,h,w,M,S)=>{l.jb("Gemm",o,{alpha:h,beta:w,transA:M,transB:S})},876822:o=>{l.jb("MatMul",o,void 0)},876876:(o,h,w,M)=>{l.jb("ArgMax",o,{keepDims:!!h,selectLastIndex:!!w,axis:M})},876984:(o,h,w,M)=>{l.jb("ArgMin",o,{keepDims:!!h,selectLastIndex:!!w,axis:M})},877092:(o,h)=>{l.jb("Softmax",o,{axis:h})},877155:(o,h)=>{l.jb("Concat",o,{axis:h})},877215:(o,h,w,M,S)=>{l.jb("Split",o,{axis:h,numOutputs:w,splitSizes:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},877355:o=>{l.jb("Expand",o,void 0)},877409:(o,h)=>{l.jb("Gather",o,{axis:Number(h)})},877480:(o,h)=>{l.jb("GatherElements",o,{axis:Number(h)})},877559:(o,h,w,M,S,se,He,st,It,Rt,Zt)=>{l.jb("Resize",o,{antialias:h,axes:w?Array.from(s().subarray(w>>>0,M>>>0)):[],coordinateTransformMode:wn(S),cubicCoeffA:se,excludeOutside:He,extrapolationValue:st,keepAspectRatioPolicy:wn(It),mode:wn(Rt),nearestMode:wn(Zt)})},877905:(o,h,w,M,S,se,He)=>{l.jb("Slice",o,{starts:h?Array.from(s().subarray(h>>>0,w>>>0)):[],ends:M?Array.from(s().subarray(M>>>0,S>>>0)):[],axes:se?Array.from(s().subarray(se>>>0,He>>>0)):[]})},878121:o=>{l.jb("Tile",o,void 0)},878173:(o,h,w)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:w?"NHWC":"NCHW"})},878287:(o,h,w)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:w?"NHWC":"NCHW"})},878401:o=>{l.jb("Range",o,void 0)},878454:(o,h)=>{l.jb("Einsum",o,{equation:wn(h)})},878535:(o,h,w,M,S)=>{l.jb("Pad",o,{mode:h,value:w,pads:M?Array.from(s().subarray(M>>>0,S>>>0)):[]})},878662:(o,h,w,M,S,se)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:w,spatial:!!S,trainingMode:!!M,format:se?"NHWC":"NCHW"})},878831:(o,h,w,M,S,se)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:w,spatial:!!S,trainingMode:!!M,format:se?"NHWC":"NCHW"})},879e3:(o,h,w)=>{l.jb("CumSum",o,{exclusive:Number(h),reverse:Number(w)})},879097:(o,h,w)=>{l.jb("DequantizeLinear",o,{axis:h,blockSize:w})},879187:(o,h,w,M,S,se,He,st,It)=>{l.jb("Attention",o,{numHeads:h,isUnidirectional:w,maskFilterValue:M,scale:S,doRotary:se,qkvHiddenSizes:He?Array.from(s().subarray(Number(st)>>>0,Number(st)+He>>>0)):[],pastPresentShareBuffer:!!It})},879459:o=>{l.jb("BiasAdd",o,void 0)},879514:o=>{l.jb("BiasSplitGelu",o,void 0)},879575:o=>{l.jb("FastGelu",o,void 0)},879631:(o,h,w,M,S,se,He,st,It,Rt,Zt,Tr,Vr,Be,Mr,rn)=>{l.jb("Conv",o,{format:Tr?"NHWC":"NCHW",auto_pad:h,dilations:w?Array.from(s().subarray(w>>>0,M>>>0)):[],group:S,kernel_shape:se?Array.from(s().subarray(se>>>0,He>>>0)):[],pads:st?Array.from(s().subarray(st>>>0,It>>>0)):[],strides:Rt?Array.from(s().subarray(Rt>>>0,Zt>>>0)):[],w_is_const:()=>!!r()[Vr>>>0],activation:wn(Be),activation_params:Mr?Array.from(d().subarray(Mr>>>0,rn>>>0)):[]})},880127:o=>{l.jb("Gelu",o,void 0)},880179:(o,h,w,M,S,se,He,st,It)=>{l.jb("GroupQueryAttention",o,{numHeads:h,kvNumHeads:w,scale:M,softcap:S,doRotary:se,rotaryInterleaved:He,smoothSoftmax:st,localWindowSize:It})},880396:(o,h,w,M)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:w,simplified:!!M})},880507:(o,h,w,M)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:w,simplified:!!M})},880618:(o,h,w,M,S,se)=>{l.jb("MatMulNBits",o,{k:h,n:w,accuracyLevel:M,bits:S,blockSize:se})},880745:(o,h,w,M,S,se)=>{l.jb("MultiHeadAttention",o,{numHeads:h,isUnidirectional:w,maskFilterValue:M,scale:S,doRotary:se})},880904:(o,h)=>{l.jb("QuickGelu",o,{alpha:h})},880968:(o,h,w,M,S)=>{l.jb("RotaryEmbedding",o,{interleaved:!!h,numHeads:w,rotaryEmbeddingDim:M,scale:S})},881107:(o,h,w)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!w})},881209:(o,h,w)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!w})},881311:(o,h,w,M)=>{l.jb("GatherBlockQuantized",o,{gatherAxis:h,quantizeAxis:w,blockSize:M})},881432:o=>{l.Zb(o)},881466:(o,h)=>l.bc(o,h,l.Fb.fc,l.Fb.errors)};function qf(o,h,w){return qh(async()=>{await l.Xb(o,h,w)})}function Hf(){return typeof wasmOffsetConverter<"u"}function Kc(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var Xc=o=>{o.terminate(),o.onmessage=()=>{}},hh=o=>{Xs.length==0&&(yh(),wh(Xs[0]));var h=Xs.pop();if(!h)return 6;wi.push(h),os[o.Ab]=h,h.Ab=o.Ab;var w={cmd:"run",start_routine:o.hc,arg:o.Qb,pthread_ptr:o.Ab};return h.postMessage(w,o.mc),0},gi=0,Zr=(o,h,...w)=>{for(var M=2*w.length,S=fp(),se=hp(8*M),He=se>>>3,st=0;st>>0]=It)}return o=gf(o,0,M,se,h),xc(S),o};function Qc(o){if(z)return Zr(0,1,o);if(Gt=o,!(0{if(Gt=o,z)throw fh(o),"unwind";Qc(o)},Xs=[],wi=[],mh=[],os={},_h=o=>{var h=o.Ab;delete os[h],Xs.push(o),wi.splice(wi.indexOf(o),1),o.Ab=0,pp(h)};function gh(){mh.forEach(o=>o())}var wh=o=>new Promise(h=>{o.onmessage=S=>{var se=(S=S.data).cmd;if(S.targetThread&&S.targetThread!=so()){var He=os[S.targetThread];He?He.postMessage(S,S.transferList):Ht(`Internal error! Worker sent a message "${se}" to target pthread ${S.targetThread}, but that thread no longer exists!`)}else se==="checkMailbox"?hc():se==="spawnThread"?hh(S):se==="cleanupThread"?_h(os[S.thread]):se==="killThread"?(S=S.thread,se=os[S],delete os[S],Xc(se),pp(S),wi.splice(wi.indexOf(se),1),se.Ab=0):se==="cancelThread"?os[S.thread].postMessage({cmd:"cancel"}):se==="loaded"?(o.loaded=!0,h(o)):se==="alert"?alert(`Thread ${S.threadId}: ${S.text}`):S.target==="setimmediate"?o.postMessage(S):se==="callHandler"?l[S.handler](...S.args):se&&Ht(`worker sent an unknown command ${se}`)},o.onerror=S=>{throw Ht(`worker sent an error! ${S.filename}:${S.lineno}: ${S.message}`),S};var w,M=[];for(w of[])l.hasOwnProperty(w)&&M.push(w);o.postMessage({cmd:"load",handlers:M,wasmMemory:hr,wasmModule:Fr})});function yh(){var o=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Xs.push(o)}var pc=o=>{for(;0{var o=so(),h=u()[o+52>>>2>>>0];o=u()[o+56>>>2>>>0],yf(h,h-o),xc(h)},Xf=(o,h)=>{gi=0,o=bf(o,h),0>>=0);throw h>>>=0,w>>>=0,u()[M.Jb+16>>>2>>>0]=0,u()[M.Jb+4>>>2>>>0]=h,u()[M.Jb+8>>>2>>>0]=w,o}function bh(o,h,w,M){return z?Zr(2,1,o,h,w,M):Mh(o,h,w,M)}function Mh(o,h,w,M){if(o>>>=0,h>>>=0,w>>>=0,M>>>=0,U===void 0)return Ht("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var S=[];return z&&S.length===0?bh(o,h,w,M):(o={hc:w,Ab:o,Qb:M,mc:S},z?(o.Mb="spawnThread",postMessage(o,S),0):hh(o))}var vh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,xh=(o,h,w)=>{var M=(h>>>=0)+w;for(w=h;o[w]&&!(w>=M);)++w;if(16(S=(240&S)==224?(15&S)<<12|se<<6|He:(7&S)<<18|se<<12|He<<6|63&o[h++])?M+=String.fromCharCode(S):(S-=65536,M+=String.fromCharCode(55296|S>>10,56320|1023&S))}}else M+=String.fromCharCode(S)}return M},wn=(o,h)=>(o>>>=0)?xh(n(),o,h):"";function Th(o,h,w){return z?Zr(3,1,o,h,w):0}function Ch(o,h){if(z)return Zr(4,1,o,h)}var Zc=o=>{for(var h=0,w=0;w=M?h++:2047>=M?h+=2:55296<=M&&57343>=M?(h+=4,++w):h+=3}return h},$h=(o,h,w,M)=>{if(!(0>>=0;M=w+M-1;for(var se=0;se=He&&(He=65536+((1023&He)<<10)|1023&o.charCodeAt(++se)),127>=He){if(w>=M)break;h[w++>>>0]=He}else{if(2047>=He){if(w+1>=M)break;h[w++>>>0]=192|He>>6}else{if(65535>=He){if(w+2>=M)break;h[w++>>>0]=224|He>>12}else{if(w+3>=M)break;h[w++>>>0]=240|He>>18,h[w++>>>0]=128|He>>12&63}h[w++>>>0]=128|He>>6&63}h[w++>>>0]=128|63&He}}return h[w>>>0]=0,w-S},ro=(o,h,w)=>$h(o,n(),h,w);function kh(o,h){if(z)return Zr(5,1,o,h)}function Eh(o,h,w){if(z)return Zr(6,1,o,h,w)}function Sh(o,h,w){return z?Zr(7,1,o,h,w):0}function Ph(o,h){if(z)return Zr(8,1,o,h)}function Ah(o,h,w){if(z)return Zr(9,1,o,h,w)}function Ih(o,h,w,M){if(z)return Zr(10,1,o,h,w,M)}function Fh(o,h,w,M){if(z)return Zr(11,1,o,h,w,M)}function Oh(o,h,w,M){if(z)return Zr(12,1,o,h,w,M)}function zh(o){if(z)return Zr(13,1,o)}function Dh(o,h){if(z)return Zr(14,1,o,h)}function Lh(o,h,w){if(z)return Zr(15,1,o,h,w)}var Bh,Qs,Zf=()=>{to("")},ls=o=>{for(var h="";n()[o>>>0];)h+=Bh[n()[o++>>>0]];return h},Jc={},ep={};function vs(o,h,w={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(M,S,se={}){var He=S.name;if(!M)throw new Qs(`type "${He}" must have a positive integer typeid pointer`);if(ep.hasOwnProperty(M)){if(se.Sb)return;throw new Qs(`Cannot register type '${He}' twice`)}ep[M]=S,Jc.hasOwnProperty(M)&&(S=Jc[M],delete Jc[M],S.forEach(st=>st()))}(o,h,w)}var Rh=(o,h,w)=>{switch(h){case 1:return w?M=>r()[M>>>0]:M=>n()[M>>>0];case 2:return w?M=>i()[M>>>1>>>0]:M=>a()[M>>>1>>>0];case 4:return w?M=>s()[M>>>2>>>0]:M=>u()[M>>>2>>>0];case 8:return w?M=>an[M>>>3]:M=>Hs[M>>>3];default:throw new TypeError(`invalid integer width (${h}): ${o}`)}};function Jf(o,h,w){w>>>=0,vs(o>>>=0,{name:h=ls(h>>>0),fromWireType:M=>M,toWireType:function(M,S){if(typeof S!="bigint"&&typeof S!="number")throw S=S===null?"null":(M=typeof S)=="object"||M==="array"||M==="function"?S.toString():""+S,new TypeError(`Cannot convert "${S}" to ${this.name}`);return typeof S=="number"&&(S=BigInt(S)),S},argPackAdvance:Ys,readValueFromPointer:Rh(h,w,h.indexOf("u")==-1),Db:null})}var Ys=8;function em(o,h,w,M){vs(o>>>=0,{name:h=ls(h>>>0),fromWireType:function(S){return!!S},toWireType:function(S,se){return se?w:M},argPackAdvance:Ys,readValueFromPointer:function(S){return this.fromWireType(n()[S>>>0])},Db:null})}var tp=[],xs=[];function rp(o){9<(o>>>=0)&&--xs[o+1]==0&&(xs[o]=void 0,tp.push(o))}var qn=o=>{if(!o)throw new Qs("Cannot use deleted val. handle = "+o);return xs[o]},Hn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=tp.pop()||xs.length;return xs[h]=o,xs[h+1]=1,h}};function np(o){return this.fromWireType(u()[o>>>2>>>0])}var tm={name:"emscripten::val",fromWireType:o=>{var h=qn(o);return rp(o),h},toWireType:(o,h)=>Hn(h),argPackAdvance:Ys,readValueFromPointer:np,Db:null};function rm(o){return vs(o>>>0,tm)}var nm=(o,h)=>{switch(h){case 4:return function(w){return this.fromWireType(d()[w>>>2>>>0])};case 8:return function(w){return this.fromWireType(c()[w>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${o}`)}};function sm(o,h,w){w>>>=0,vs(o>>>=0,{name:h=ls(h>>>0),fromWireType:M=>M,toWireType:(M,S)=>S,argPackAdvance:Ys,readValueFromPointer:nm(h,w),Db:null})}function im(o,h,w,M,S){if(o>>>=0,w>>>=0,h=ls(h>>>0),S===-1&&(S=4294967295),S=st=>st,M===0){var se=32-8*w;S=st=>st<>>se}var He=h.includes("unsigned")?function(st,It){return It>>>0}:function(st,It){return It};vs(o,{name:h,fromWireType:S,toWireType:He,argPackAdvance:Ys,readValueFromPointer:Rh(h,w,M!==0),Db:null})}function am(o,h,w){function M(se){var He=u()[se>>>2>>>0];return se=u()[se+4>>>2>>>0],new S(r().buffer,se,He)}var S=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];vs(o>>>=0,{name:w=ls(w>>>0),fromWireType:M,argPackAdvance:Ys,readValueFromPointer:M},{Sb:!0})}function om(o,h){o>>>=0;var w=(h=ls(h>>>0))==="std::string";vs(o,{name:h,fromWireType:function(M){var S=u()[M>>>2>>>0],se=M+4;if(w)for(var He=se,st=0;st<=S;++st){var It=se+st;if(st==S||n()[It>>>0]==0){if(He=wn(He,It-He),Rt===void 0)var Rt=He;else Rt+="\0",Rt+=He;He=It+1}}else{for(Rt=Array(S),st=0;st>>0]);Rt=Rt.join("")}return ds(M),Rt},toWireType:function(M,S){S instanceof ArrayBuffer&&(S=new Uint8Array(S));var se=typeof S=="string";if(!(se||S instanceof Uint8Array||S instanceof Uint8ClampedArray||S instanceof Int8Array))throw new Qs("Cannot pass non-string to std::string");var He=w&&se?Zc(S):S.length,st=Mc(4+He+1),It=st+4;if(u()[st>>>2>>>0]=He,w&&se)ro(S,It,He+1);else if(se)for(se=0;se>>0]=Rt}else for(se=0;se>>0]=S[se];return M!==null&&M.push(ds,st),st},argPackAdvance:Ys,readValueFromPointer:np,Db(M){ds(M)}})}var Nh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,lm=(o,h)=>{for(var w=o>>1,M=w+h/2;!(w>=M)&&a()[w>>>0];)++w;if(32<(w<<=1)-o&&Nh)return Nh.decode(n().slice(o,w));for(w="",M=0;!(M>=h/2);++M){var S=i()[o+2*M>>>1>>>0];if(S==0)break;w+=String.fromCharCode(S)}return w},um=(o,h,w)=>{if(w??(w=2147483647),2>w)return 0;var M=h;w=(w-=2)<2*o.length?w/2:o.length;for(var S=0;S>>1>>>0]=se,h+=2}return i()[h>>>1>>>0]=0,h-M},dm=o=>2*o.length,cm=(o,h)=>{for(var w=0,M="";!(w>=h/4);){var S=s()[o+4*w>>>2>>>0];if(S==0)break;++w,65536<=S?(S-=65536,M+=String.fromCharCode(55296|S>>10,56320|1023&S)):M+=String.fromCharCode(S)}return M},pm=(o,h,w)=>{if(h>>>=0,w??(w=2147483647),4>w)return 0;var M=h;w=M+w-4;for(var S=0;S=se&&(se=65536+((1023&se)<<10)|1023&o.charCodeAt(++S)),s()[h>>>2>>>0]=se,(h+=4)+4>w)break}return s()[h>>>2>>>0]=0,h-M},hm=o=>{for(var h=0,w=0;w=M&&++w,h+=4}return h};function fm(o,h,w){if(o>>>=0,h>>>=0,w=ls(w>>>=0),h===2)var M=lm,S=um,se=dm,He=st=>a()[st>>>1>>>0];else h===4&&(M=cm,S=pm,se=hm,He=st=>u()[st>>>2>>>0]);vs(o,{name:w,fromWireType:st=>{for(var It,Rt=u()[st>>>2>>>0],Zt=st+4,Tr=0;Tr<=Rt;++Tr){var Vr=st+4+Tr*h;Tr!=Rt&&He(Vr)!=0||(Zt=M(Zt,Vr-Zt),It===void 0?It=Zt:(It+="\0",It+=Zt),Zt=Vr+h)}return ds(st),It},toWireType:(st,It)=>{if(typeof It!="string")throw new Qs(`Cannot pass non-string to C++ string type ${w}`);var Rt=se(It),Zt=Mc(4+Rt+h);return u()[Zt>>>2>>>0]=Rt/h,S(It,Zt+4,Rt+h),st!==null&&st.push(ds,Zt),Zt},argPackAdvance:Ys,readValueFromPointer:np,Db(st){ds(st)}})}function mm(o,h){vs(o>>>=0,{Tb:!0,name:h=ls(h>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var _m=()=>1;function gm(o){cp(o>>>0,!C,1,!x,131072,!1),gh()}var jh=o=>{if(!En)try{if(o(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(s(),o>>>2,o).value.then(hc),o+=128,Atomics.store(s(),o>>>2,1))}var hc=()=>{var o=so();o&&(sp(o),jh(wf))};function wm(o,h){(o>>>=0)==h>>>0?setTimeout(hc):z?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=os[o])&&o.postMessage({cmd:"checkMailbox"})}var ip=[];function ym(o,h,w,M,S){for(h>>>=0,M/=2,ip.length=M,w=S>>>0>>>3,S=0;S>>0];return(h?Hc[h]:l_[o])(...ip)}function bm(o){o>>>=0,z?postMessage({cmd:"cleanupThread",thread:o}):_h(os[o])}function Mm(o){}var ap=(o,h)=>{var w=ep[o];if(w===void 0)throw o=ff(o),w=ls(o),ds(o),new Qs(`${h} has unknown type ${w}`);return w},Vh=(o,h,w)=>{var M=[];return o=o.toWireType(M,w),M.length&&(u()[h>>>2>>>0]=Hn(M)),o};function vm(o,h,w){return h>>>=0,w>>>=0,o=qn(o>>>0),h=ap(h,"emval::as"),Vh(h,w,o)}var fc=o=>{try{o()}catch(h){to(h)}},Zs=0,us=null,Uh=0,mc=[],Wh={},Gh={},xm=0,op=null,Tm=[];function qh(o){return function(h){if(!En){if(Zs===0){var w=!1,M=!1;h((S=0)=>{if(!En&&(Uh=S,w=!0,M)){Zs=2,fc(()=>xf(us)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),S=!1;try{var se=function(){var It=s()[us+8>>>2>>>0];return It=Xt[Gh[It]],--gi,It()}()}catch(It){se=It,S=!0}var He=!1;if(!us){var st=op;st&&(op=null,(S?st.reject:st.resolve)(se),He=!0)}if(S&&!He)throw se}}),M=!0,w||(Zs=1,us=function(){var S=Mc(65548),se=S+12;u()[S>>>2>>>0]=se,u()[S+4>>>2>>>0]=se+65536,se=mc[0];var He=Wh[se];return He===void 0&&(He=xm++,Wh[se]=He,Gh[He]=se),se=He,s()[S+8>>>2>>>0]=se,S}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),fc(()=>Mf(us)))}else Zs===2?(Zs=0,fc(Tf),ds(us),us=null,Tm.forEach(jh)):to(`invalid state: ${Zs}`);return Uh}}(h=>{o().then(h)})}function Cm(o){return o>>>=0,qh(()=>(o=qn(o)).then(Hn))}var _c=[];function $m(o,h,w,M){return w>>>=0,M>>>=0,(o=_c[o>>>0])(null,h=qn(h>>>0),w,M)}var km={},gc=o=>{var h=km[o];return h===void 0?ls(o):h};function Em(o,h,w,M,S){return w>>>=0,M>>>=0,S>>>=0,(o=_c[o>>>0])(h=qn(h>>>0),h[w=gc(w)],M,S)}var Hh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Sm(o){return(o>>>=0)==0?Hn(Hh()):(o=gc(o),Hn(Hh()[o]))}var Pm=o=>{var h=_c.length;return _c.push(o),h},Am=(o,h)=>{for(var w=Array(o),M=0;M>>2>>>0],"parameter "+M);return w},Kh=(o,h)=>Object.defineProperty(h,"name",{value:o});function Im(o,h,w){var M=(h=Am(o,h>>>0)).shift();o--;var S=`return function (obj, func, destructorsRef, args) { `,se=0,He=[];w===0&&He.push("obj");for(var st=["retType"],It=[M],Rt=0;RtZt.name).join(", ")}) => ${M.name}>`,Pm(Kh(w,o))}function Fm(o){return o=gc(o>>>0),Hn(l[o])}function Om(o,h){return h>>>=0,o=qn(o>>>0),h=qn(h),Hn(o[h])}function zm(o){9<(o>>>=0)&&(xs[o+1]+=1)}function Dm(){return Hn([])}function Lm(o){o=qn(o>>>0);for(var h=Array(o.length),w=0;w>>0))}function Rm(){return Hn({})}function Nm(o){for(var h=qn(o>>>=0);h.length;){var w=h.pop();h.pop()(w)}rp(o)}function jm(o,h,w){h>>>=0,w>>>=0,o=qn(o>>>0),h=qn(h),w=qn(w),o[h]=w}function Vm(o,h){return h>>>=0,o=(o=ap(o>>>0,"_emval_take_value")).readValueFromPointer(h),Hn(o)}function Um(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),s()[h>>>2>>>0]=o.getUTCSeconds(),s()[h+4>>>2>>>0]=o.getUTCMinutes(),s()[h+8>>>2>>>0]=o.getUTCHours(),s()[h+12>>>2>>>0]=o.getUTCDate(),s()[h+16>>>2>>>0]=o.getUTCMonth(),s()[h+20>>>2>>>0]=o.getUTCFullYear()-1900,s()[h+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,s()[h+28>>>2>>>0]=o}var no=o=>o%4==0&&(o%100!=0||o%400==0),Xh=[0,31,60,91,121,152,182,213,244,274,305,335],Qh=[0,31,59,90,120,151,181,212,243,273,304,334];function Wm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),s()[h>>>2>>>0]=o.getSeconds(),s()[h+4>>>2>>>0]=o.getMinutes(),s()[h+8>>>2>>>0]=o.getHours(),s()[h+12>>>2>>>0]=o.getDate(),s()[h+16>>>2>>>0]=o.getMonth(),s()[h+20>>>2>>>0]=o.getFullYear()-1900,s()[h+24>>>2>>>0]=o.getDay();var w=(no(o.getFullYear())?Xh:Qh)[o.getMonth()]+o.getDate()-1|0;s()[h+28>>>2>>>0]=w,s()[h+36>>>2>>>0]=-60*o.getTimezoneOffset(),w=new Date(o.getFullYear(),6,1).getTimezoneOffset();var M=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(w!=M&&o.getTimezoneOffset()==Math.min(M,w)),s()[h+32>>>2>>>0]=o}function Gm(o){o>>>=0;var h=new Date(s()[o+20>>>2>>>0]+1900,s()[o+16>>>2>>>0],s()[o+12>>>2>>>0],s()[o+8>>>2>>>0],s()[o+4>>>2>>>0],s()[o>>>2>>>0],0),w=s()[o+32>>>2>>>0],M=h.getTimezoneOffset(),S=new Date(h.getFullYear(),6,1).getTimezoneOffset(),se=new Date(h.getFullYear(),0,1).getTimezoneOffset(),He=Math.min(se,S);return 0>w?s()[o+32>>>2>>>0]=+(S!=se&&He==M):0>>2>>>0]=h.getDay(),w=(no(h.getFullYear())?Xh:Qh)[h.getMonth()]+h.getDate()-1|0,s()[o+28>>>2>>>0]=w,s()[o>>>2>>>0]=h.getSeconds(),s()[o+4>>>2>>>0]=h.getMinutes(),s()[o+8>>>2>>>0]=h.getHours(),s()[o+12>>>2>>>0]=h.getDate(),s()[o+16>>>2>>>0]=h.getMonth(),s()[o+20>>>2>>>0]=h.getYear(),o=h.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Yh(o,h,w,M,S,se,He){return z?Zr(16,1,o,h,w,M,S,se,He):-52}function Zh(o,h,w,M,S,se){if(z)return Zr(17,1,o,h,w,M,S,se)}function qm(o,h,w,M){o>>>=0,h>>>=0,w>>>=0,M>>>=0;var S=new Date().getFullYear(),se=new Date(S,0,1),He=new Date(S,6,1);S=se.getTimezoneOffset();var st=He.getTimezoneOffset(),It=Math.max(S,st);u()[o>>>2>>>0]=60*It,s()[h>>>2>>>0]=+(S!=st),se=(o=Rt=>Rt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(se),He=o(He),st{lp.length=0;for(var w;w=n()[o++>>>0];){var M=w!=105;h+=(M&=w!=112)&&h%8?4:0,lp.push(w==112?u()[h>>>2>>>0]:w==106?an[h>>>3]:w==105?s()[h>>>2>>>0]:c()[h>>>3>>>0]),h+=M?8:4}return lp};function Hm(o,h,w){return o>>>=0,h=Jh(h>>>0,w>>>0),Hc[o](...h)}function Km(o,h,w){return o>>>=0,h=Jh(h>>>0,w>>>0),Hc[o](...h)}var Xm=()=>{},Qm=()=>Date.now();function Ym(o,h){return Ht(wn(o>>>0,h>>>0))}var ef,Zm=()=>{throw gi+=1,"unwind"};function Jm(){return 4294901760}ef=()=>performance.timeOrigin+performance.now();var e_=()=>navigator.hardwareConcurrency;function t_(){return to("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function r_(o){o>>>=0;var h=n().length;if(o<=h||4294901760=w;w*=2){var M=h*(1+.2/w);M=Math.min(M,o+100663296);var S=Math;M=Math.max(o,M);e:{S=(S.min.call(S,4294901760,M+(65536-M%65536)%65536)-hr.buffer.byteLength+65535)/65536;try{hr.grow(S),fn();var se=1;break e}catch{}se=void 0}if(se)return!0}return!1}var wc=()=>(to("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Cd={},tf=o=>{o.forEach(h=>{wc()})};function n_(){var o=Error().stack.toString().split(` `);return o[0]=="Error"&&o.shift(),tf(o),Cd.Pb=wc(),Cd.ec=o,Cd.Pb}function s_(o,h,w){if(o>>>=0,h>>>=0,Cd.Pb==o)var M=Cd.ec;else(M=Error().stack.toString().split(` `))[0]=="Error"&&M.shift(),tf(M);for(var S=3;M[S]&&wc()!=o;)++S;for(o=0;o>>2>>>0]=wc();return o}var up,dp={},rf=()=>{if(!up){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",_:Ee};for(o in dp)dp[o]===void 0?delete h[o]:h[o]=dp[o];var w=[];for(o in h)w.push(`${o}=${h[o]}`);up=w}return up};function nf(o,h){if(z)return Zr(18,1,o,h);o>>>=0,h>>>=0;var w=0;return rf().forEach((M,S)=>{var se=h+w;for(S=u()[o+4*S>>>2>>>0]=se,se=0;se>>0]=M.charCodeAt(se);r()[S>>>0]=0,w+=M.length+1}),0}function sf(o,h){if(z)return Zr(19,1,o,h);o>>>=0,h>>>=0;var w=rf();u()[o>>>2>>>0]=w.length;var M=0;return w.forEach(S=>M+=S.length+1),u()[h>>>2>>>0]=M,0}function af(o){return z?Zr(20,1,o):52}function of(o,h,w,M){return z?Zr(21,1,o,h,w,M):52}function lf(o,h,w,M){return z?Zr(22,1,o,h,w,M):70}var i_=[null,[],[]];function uf(o,h,w,M){if(z)return Zr(23,1,o,h,w,M);h>>>=0,w>>>=0,M>>>=0;for(var S=0,se=0;se>>2>>>0],st=u()[h+4>>>2>>>0];h+=8;for(var It=0;It>>0],Zt=i_[o];Rt===0||Rt===10?((o===1?nr:Ht)(xh(Zt,0)),Zt.length=0):Zt.push(Rt)}S+=st}return u()[M>>>2>>>0]=S,0}var df=[31,29,31,30,31,30,31,31,30,31,30,31],cf=[31,28,31,30,31,30,31,31,30,31,30,31],a_=(o,h)=>{r().set(o,h>>>0)};function pf(o,h,w,M){function S(Be,Mr,rn){for(Be=typeof Be=="number"?Be.toString():Be||"";Be.length$f?-1:0<$f?1:0}var yi;return(yi=rn(Be.getFullYear()-Mr.getFullYear()))===0&&(yi=rn(Be.getMonth()-Mr.getMonth()))===0&&(yi=rn(Be.getDate()-Mr.getDate())),yi}function st(Be){switch(Be.getDay()){case 0:return new Date(Be.getFullYear()-1,11,29);case 1:return Be;case 2:return new Date(Be.getFullYear(),0,3);case 3:return new Date(Be.getFullYear(),0,2);case 4:return new Date(Be.getFullYear(),0,1);case 5:return new Date(Be.getFullYear()-1,11,31);case 6:return new Date(Be.getFullYear()-1,11,30)}}function It(Be){var Mr=Be.Bb;for(Be=new Date(new Date(Be.Cb+1900,0,1).getTime());0yi-Be.getDate())){Be.setDate(Be.getDate()+Mr);break}Mr-=yi-Be.getDate()+1,Be.setDate(1),11>rn?Be.setMonth(rn+1):(Be.setMonth(0),Be.setFullYear(Be.getFullYear()+1))}return rn=new Date(Be.getFullYear()+1,0,4),Mr=st(new Date(Be.getFullYear(),0,4)),rn=st(rn),0>=He(Mr,Be)?0>=He(rn,Be)?Be.getFullYear()+1:Be.getFullYear():Be.getFullYear()-1}o>>>=0,h>>>=0,w>>>=0,M>>>=0;var Rt=u()[M+40>>>2>>>0];for(var Zt in M={kc:s()[M>>>2>>>0],jc:s()[M+4>>>2>>>0],Hb:s()[M+8>>>2>>>0],Lb:s()[M+12>>>2>>>0],Ib:s()[M+16>>>2>>>0],Cb:s()[M+20>>>2>>>0],ub:s()[M+24>>>2>>>0],Bb:s()[M+28>>>2>>>0],sc:s()[M+32>>>2>>>0],ic:s()[M+36>>>2>>>0],lc:Rt?wn(Rt):""},w=wn(w),Rt={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})w=w.replace(new RegExp(Zt,"g"),Rt[Zt]);var Tr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Vr="January February March April May June July August September October November December".split(" ");for(Zt in Rt={"%a":Be=>Tr[Be.ub].substring(0,3),"%A":Be=>Tr[Be.ub],"%b":Be=>Vr[Be.Ib].substring(0,3),"%B":Be=>Vr[Be.Ib],"%C":Be=>se((Be.Cb+1900)/100|0,2),"%d":Be=>se(Be.Lb,2),"%e":Be=>S(Be.Lb,2," "),"%g":Be=>It(Be).toString().substring(2),"%G":It,"%H":Be=>se(Be.Hb,2),"%I":Be=>((Be=Be.Hb)==0?Be=12:12{for(var Mr=0,rn=0;rn<=Be.Ib-1;Mr+=(no(Be.Cb+1900)?df:cf)[rn++]);return se(Be.Lb+Mr,3)},"%m":Be=>se(Be.Ib+1,2),"%M":Be=>se(Be.jc,2),"%n":()=>` `,"%p":Be=>0<=Be.Hb&&12>Be.Hb?"AM":"PM","%S":Be=>se(Be.kc,2),"%t":()=>" ","%u":Be=>Be.ub||7,"%U":Be=>se(Math.floor((Be.Bb+7-Be.ub)/7),2),"%V":Be=>{var Mr=Math.floor((Be.Bb+7-(Be.ub+6)%7)/7);if(2>=(Be.ub+371-Be.Bb-2)%7&&Mr++,Mr)Mr==53&&((rn=(Be.ub+371-Be.Bb)%7)==4||rn==3&&no(Be.Cb)||(Mr=1));else{Mr=52;var rn=(Be.ub+7-Be.Bb-1)%7;(rn==4||rn==5&&no(Be.Cb%400-1))&&Mr++}return se(Mr,2)},"%w":Be=>Be.ub,"%W":Be=>se(Math.floor((Be.Bb+7-(Be.ub+6)%7)/7),2),"%y":Be=>(Be.Cb+1900).toString().substring(2),"%Y":Be=>Be.Cb+1900,"%z":Be=>{var Mr=0<=(Be=Be.ic);return Be=Math.abs(Be)/60,(Mr?"+":"-")+("0000"+(Be/60*100+Be%60)).slice(-4)},"%Z":Be=>Be.lc,"%%":()=>"%"},w=w.replace(/%%/g,"\0\0"),Rt)w.includes(Zt)&&(w=w.replace(new RegExp(Zt,"g"),Rt[Zt](M)));return Zt=function(Be){var Mr=Array(Zc(Be)+1);return $h(Be,Mr,0,Mr.length),Mr}(w=w.replace(/\0\0/g,"%")),Zt.length>h?0:(a_(Zt,o),Zt.length-1)}function o_(o,h,w,M){return pf(o>>>0,h>>>0,w>>>0,M>>>0)}z||function(){for(var o=l.numThreads-1;o--;)yh();_i.unshift(()=>{Gn++,function(h){z?h():Promise.all(Xs.map(wh)).then(h)}(()=>cc())})}();for(var hf=Array(256),yc=0;256>yc;++yc)hf[yc]=String.fromCharCode(yc);Bh=hf,Qs=l.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},l.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},xs.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>xs.length/2-5-tp.length;var l_=[Qc,fh,bh,Th,Ch,kh,Eh,Sh,Ph,Ah,Ih,Fh,Oh,zh,Dh,Lh,Yh,Zh,nf,sf,af,of,lf,uf],Xt=function(){function o(w,M){return Xt=w.exports,Xt=function(){var S=Xt,se={};for(let[He,st]of Object.entries(S))se[He]=typeof st=="function"?(...It)=>{mc.push(He);try{return st(...It)}finally{En||(mc.pop(),us&&Zs===1&&mc.length===0&&(Zs=0,gi+=1,fc(vf),typeof Fibers<"u"&&Fibers.tc()))}}:st;return se}(),Xt=function(){var S=Xt,se=st=>It=>st(It)>>>0,He=st=>()=>st()>>>0;return(S=Object.assign({},S)).Ca=se(S.Ca),S.fb=He(S.fb),S.hb=se(S.hb),S.emscripten_main_runtime_thread_id=He(S.emscripten_main_runtime_thread_id),S.sb=se(S.sb),S.tb=He(S.tb),S}(),mh.push(Xt.ib),dn.unshift(Xt.Ba),Fr=M,cc(),Xt}var h=ph();if(Gn++,l.instantiateWasm)try{return l.instantiateWasm(h,o)}catch(w){Ht(`Module.instantiateWasm callback failed with error: ${w}`),m(w)}return qc||(qc=l.locateFile?lh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ye):Ye+"ort-wasm-simd-threaded.jsep.wasm":new URL(D("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),D.b).href),function(w,M){var S=qc;return Ft||typeof WebAssembly.instantiateStreaming!="function"||lh(S)||uh(S)||typeof fetch!="function"?ch(S,w,M):fetch(S,{credentials:"same-origin"}).then(se=>WebAssembly.instantiateStreaming(se,w).then(M,function(He){return Ht(`wasm streaming compile failed: ${He}`),Ht("falling back to ArrayBuffer instantiation"),ch(S,w,M)}))}(h,function(w){o(w.instance,w.module)}).catch(m),{}}(),ff=o=>(ff=Xt.Ca)(o),mf=()=>(mf=Xt.Da)();l._OrtInit=(o,h)=>(l._OrtInit=Xt.Ea)(o,h),l._OrtGetLastError=(o,h)=>(l._OrtGetLastError=Xt.Fa)(o,h),l._OrtCreateSessionOptions=(o,h,w,M,S,se,He,st,It,Rt)=>(l._OrtCreateSessionOptions=Xt.Ga)(o,h,w,M,S,se,He,st,It,Rt),l._OrtAppendExecutionProvider=(o,h)=>(l._OrtAppendExecutionProvider=Xt.Ha)(o,h),l._OrtAddFreeDimensionOverride=(o,h,w)=>(l._OrtAddFreeDimensionOverride=Xt.Ia)(o,h,w),l._OrtAddSessionConfigEntry=(o,h,w)=>(l._OrtAddSessionConfigEntry=Xt.Ja)(o,h,w),l._OrtReleaseSessionOptions=o=>(l._OrtReleaseSessionOptions=Xt.Ka)(o),l._OrtCreateSession=(o,h,w)=>(l._OrtCreateSession=Xt.La)(o,h,w),l._OrtReleaseSession=o=>(l._OrtReleaseSession=Xt.Ma)(o),l._OrtGetInputOutputCount=(o,h,w)=>(l._OrtGetInputOutputCount=Xt.Na)(o,h,w),l._OrtGetInputName=(o,h)=>(l._OrtGetInputName=Xt.Oa)(o,h),l._OrtGetOutputName=(o,h)=>(l._OrtGetOutputName=Xt.Pa)(o,h),l._OrtFree=o=>(l._OrtFree=Xt.Qa)(o),l._OrtCreateTensor=(o,h,w,M,S,se)=>(l._OrtCreateTensor=Xt.Ra)(o,h,w,M,S,se),l._OrtGetTensorData=(o,h,w,M,S)=>(l._OrtGetTensorData=Xt.Sa)(o,h,w,M,S),l._OrtReleaseTensor=o=>(l._OrtReleaseTensor=Xt.Ta)(o),l._OrtCreateRunOptions=(o,h,w,M)=>(l._OrtCreateRunOptions=Xt.Ua)(o,h,w,M),l._OrtAddRunConfigEntry=(o,h,w)=>(l._OrtAddRunConfigEntry=Xt.Va)(o,h,w),l._OrtReleaseRunOptions=o=>(l._OrtReleaseRunOptions=Xt.Wa)(o),l._OrtCreateBinding=o=>(l._OrtCreateBinding=Xt.Xa)(o),l._OrtBindInput=(o,h,w)=>(l._OrtBindInput=Xt.Ya)(o,h,w),l._OrtBindOutput=(o,h,w,M)=>(l._OrtBindOutput=Xt.Za)(o,h,w,M),l._OrtClearBoundOutputs=o=>(l._OrtClearBoundOutputs=Xt._a)(o),l._OrtReleaseBinding=o=>(l._OrtReleaseBinding=Xt.$a)(o),l._OrtRunWithBinding=(o,h,w,M,S)=>(l._OrtRunWithBinding=Xt.ab)(o,h,w,M,S),l._OrtRun=(o,h,w,M,S,se,He,st)=>(l._OrtRun=Xt.bb)(o,h,w,M,S,se,He,st),l._OrtEndProfiling=o=>(l._OrtEndProfiling=Xt.cb)(o),l._JsepOutput=(o,h,w)=>(l._JsepOutput=Xt.db)(o,h,w),l._JsepGetNodeName=o=>(l._JsepGetNodeName=Xt.eb)(o);var bc,so=()=>(so=Xt.fb)(),ds=l._free=o=>(ds=l._free=Xt.gb)(o),Mc=l._malloc=o=>(Mc=l._malloc=Xt.hb)(o),cp=(o,h,w,M,S,se)=>(cp=Xt.kb)(o,h,w,M,S,se),_f=()=>(_f=Xt.lb)(),gf=(o,h,w,M,S)=>(gf=Xt.mb)(o,h,w,M,S),pp=o=>(pp=Xt.nb)(o),vc=o=>(vc=Xt.ob)(o),wf=()=>(wf=Xt.pb)(),yf=(o,h)=>(yf=Xt.qb)(o,h),xc=o=>(xc=Xt.rb)(o),hp=o=>(hp=Xt.sb)(o),fp=()=>(fp=Xt.tb)(),bf=l.dynCall_ii=(o,h)=>(bf=l.dynCall_ii=Xt.vb)(o,h),Mf=o=>(Mf=Xt.wb)(o),vf=()=>(vf=Xt.xb)(),xf=o=>(xf=Xt.yb)(o),Tf=()=>(Tf=Xt.zb)();function Cf(){0fp(),l.stackRestore=o=>xc(o),l.stackAlloc=o=>hp(o),l.UTF8ToString=wn,l.stringToUTF8=ro,l.lengthBytesUTF8=Zc,Ks=function o(){bc||Cf(),bc||(Ks=o)},Cf(),T}),Ie=we,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&we()}),Ne,tt,wt,mt,Ct,ft,Lt,jt,Ot=j(()=>{var e,t;dr(),Ne=import.meta.url??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),tt=typeof location>"u"?void 0:location.origin,wt=(r,n)=>{try{let i=n??Ne;return(i?new URL(r,i):new URL(r)).origin===tt}catch{return!1}},mt=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Ct=(yn(),B(Cr)).default,ft=async()=>{if(!Ne)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(wt(Ne))return[void 0,Ct()];let r=await mt(Ne);return[r,Ct(r)]},Lt=(Se(),B(at)).default,jt=async(r,n,i)=>[void 0,Lt]}),Fe,Oe,ct,Ut,sr,br,Nr,mr,Er=j(()=>{Ot(),Oe=!1,ct=!1,Ut=!1,sr=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},br=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Nr=async e=>{if(Oe)return Promise.resolve();if(ct)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ut)throw new Error("previous call to 'initializeWebAssembly()' failed.");ct=!0;let t=e.initTimeout,r=e.numThreads;if(!br())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=sr();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let i=e.wasmPaths,a=typeof i=="string"?i:void 0,s=i==null?void 0:i.mjs,u=(s==null?void 0:s.href)??s,d=i==null?void 0:i.wasm,c=(d==null?void 0:d.href)??d,g=e.wasmBinary,[m,l]=await jt(u,a,r>1),T=!1,x=[];if(t>0&&x.push(new Promise(C=>{setTimeout(()=>{T=!0,C()},t)})),x.push(new Promise((C,z)=>{let U={numThreads:r};g?U.wasmBinary=g:(c||a)&&(U.locateFile=(A,ee)=>c??(a??ee)+A),l(U).then(A=>{ct=!1,Oe=!0,Fe=A,C(),m&&URL.revokeObjectURL(m)},A=>{ct=!1,Ut=!0,z(A)})})),await Promise.race(x),T)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},mr=()=>{if(Oe&&Fe)return Fe;throw new Error("WebAssembly is not initialized yet.")}}),wr,Cn,Ur,cs=j(()=>{Er(),wr=(e,t)=>{let r=mr(),n=r.lengthBytesUTF8(e)+1,i=r._malloc(n);return r.stringToUTF8(e,i,n),t.push(i),i},Cn=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([i,a])=>{let s=t?t+i:i;if(typeof a=="object")Cn(a,s+".",r,n);else if(typeof a=="string"||typeof a=="number")n(s,a.toString());else if(typeof a=="boolean")n(s,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Ur=e=>{let t=mr(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let i=t.HEAP32[n/4],a=t.HEAPU32[n/4+1],s=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${s}`)}finally{t.stackRestore(r)}}}),Cs,Kn=j(()=>{Er(),cs(),Cs=e=>{let t=mr(),r=0,n=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(i.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=wr(e.tag,n)),r=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),r===0&&Ur("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Cn(e.extra,"",new WeakSet,(s,u)=>{let d=wr(s,n),c=wr(u,n);t._OrtAddRunConfigEntry(r,d,c)!==0&&Ur(`Can't set a run config entry: ${s} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(s=>t._free(s)),a}}}),$s,ks,Es,Ss,Ps,es=j(()=>{Er(),cs(),$s=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},ks=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Es=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Ss=(e,t,r)=>{for(let n of t){let i=typeof n=="string"?n:n.name;switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let s=n==null?void 0:n.deviceType;if(s){let u=wr("deviceType",r),d=wr(s,r);mr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Ur(`Can't set a session config entry: 'deviceType' - ${s}.`)}}break;case"webgpu":if(i="JS",typeof n!="string"){let s=n;if(s!=null&&s.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let u=wr("preferredLayout",r),d=wr(s.preferredLayout,r);mr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Ur(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=wr(i,r);mr()._OrtAppendExecutionProvider(e,a)!==0&&Ur(`Can't append execution provider: ${i}.`)}},Ps=e=>{let t=mr(),r=0,n=[],i=e||{};Es(i);try{let a=$s(i.graphOptimizationLevel??"all"),s=ks(i.executionMode??"sequential"),u=typeof i.logId=="string"?wr(i.logId,n):0,d=i.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let g=typeof i.optimizedModelFilePath=="string"?wr(i.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,s,!!i.enableProfiling,0,u,d,c,g),r===0&&Ur("Can't create session options."),i.executionProviders&&Ss(r,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let m=wr("enableGraphCapture",n),l=wr(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,m,l)!==0&&Ur(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[m,l]of Object.entries(i.freeDimensionOverrides)){if(typeof m!="string")throw new Error(`free dimension override name must be a string: ${m}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let T=wr(m,n);t._OrtAddFreeDimensionOverride(r,T,l)!==0&&Ur(`Can't set a free dimension override: ${m} - ${l}.`)}return i.extra!==void 0&&Cn(i.extra,"",new WeakSet,(m,l)=>{let T=wr(m,n),x=wr(l,n);t._OrtAddSessionConfigEntry(r,T,x)!==0&&Ur(`Can't set a session config entry: ${m} - ${l}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(s=>t._free(s)),a}}}),Xn,Sn,Bn,ps,Dn,hs,fs,ms,Yt=j(()=>{Xn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},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}`)}},Bn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((i,a)=>i*a,1);return r>0?Math.ceil(n*r):void 0},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}`)}},Dn=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",ms=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}`)}}}),ts,As=j(()=>{dr(),ts=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let d=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let s=0;for(;;){let{done:u,value:d}=await i.read();if(u)break;let c=d.byteLength;new Uint8Array(a,s,c).set(d),s+=c}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Is,_s,Fs,Os,rs,zs,ae,_=j(()=>{Yt(),Is=["V","I","W","E","F"],_s=(e,t)=>{console.log(`[${Is[e]},${new Date().toISOString()}]${t}`)},rs=(e,t)=>{Fs=e,Os=t},zs=(e,t)=>{let r=Dn(e),n=Dn(Fs);r>=n&&_s(r,typeof t=="function"?t():t)},ae=(...e)=>{Os&&zs(...e)}}),F,Q=j(()=>{Yt(),F=(e,t)=>new(ps(t))(e)}),oe=j(()=>{}),ge,Ge,gt,$t,Tt,zt,er,Sr,lr,Wr=j(()=>{_(),oe(),ge=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Ge=[],gt=e=>Math.ceil(e/16)*16,$t=e=>{for(let t=0;tTt++,er=async(e,t,r,n)=>{let i=gt(r),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=e.getCommandEncoder();e.endComputePass(),s.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(u,0,r)),d}else return new Uint8Array(u.slice(0,r))}finally{a.destroy()}},Sr=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of ge)Ge.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let r=t.buffer,n=t.byteOffset,i=t.byteLength,a=gt(i),s=this.storageCache.get(e);if(!s)throw new Error("gpu data for uploading does not exist");if(s.originalSize!==i)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${i}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(r,n,i)),u.unmap();let c=this.backend.getCommandEncoder();this.backend.endComputePass(),c.copyBufferToBuffer(u,0,s.gpuData.buffer,0,a),ae("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(u)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=gt(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,i)}registerExternalBuffer(e,t,r){let n;if(r){if(n=r[0],e===r[1])return ae("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else n=zt();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),ae("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),ae("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=$t(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let u=(i?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let s={id:zt(),type:0,buffer:n};return this.storageCache.set(s.id,{gpuData:s,originalSize:e}),ae("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${s.id}`),s}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=this.storageCache.get(e);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return ae("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("data does not exist");await er(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=ge.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(ae("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.storageCache=new Map)}},lr=(...e)=>new Sr(...e)}),en,or,Pr=j(()=>{en=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},or=e=>new en(e)}),mn,bn,ke,tn,on,Pn,Rn,Kt=j(()=>{mn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},bn=class{static calcShape(e,t,r=!1){let n=e.length,i=t.length;if(n===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),s=new Array(a);if(r){if(n<2||i<2)return;let u=mn.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(u===void 0)return;[s[a-2],s[a-1]]=u}for(let u=r?3:1;u<=a;u++){let d=n-u<0?1:e[n-u],c=i-u<0?1:t[i-u];if(d!==c&&d>1&&c>1)return;let g=Math.max(d,c);if(d&&c)s[a-u]=Math.max(d,c);else{if(g>1)return;s[a-u]=0}}return s}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let i=1;i<=r;i++)if(e[r-i]!==1&&e[r-i]!==t[n-i])return!1;return!0}},ke=class Tc{static size(t){return Tc.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let i=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){i[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");i[a]=1,r/=t[a],a--}for(a--;a>=0;a--)i[a]=t[a];return i}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Tc.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 Tc.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let i=1;for(let a=r;a=0;--i)n[i]=n[i+1]*t[i+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((i,a)=>i+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,i)=>n===r[i])}},tn=class kd{static adjustPoolAttributes(t,r,n,i,a,s){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||s[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,i,a,s,u){if(u){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{Yt(),Kt(),pn=64,Kr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},fr=(e,t=1)=>{let r=Kr(e,t);return typeof r=="string"?r:r[0]},Or=(e,t=1)=>{let r=Kr(e,t);return typeof r=="string"?r:r[1]},kt=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:ke.computeStrides(r)})}),t},_r=e=>e%4===0?4:e%2===0?2:1,ns=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Qn=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Nn=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,Wt=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Js=(e,t,r,n,i)=>{let a=typeof r=="number",s=a?r:r.length,u=[...new Array(s).keys()],d=s<2?"u32":s<=4?`vec${s}`:`array`,c=Kr(t,i),g=typeof c=="string"?c:c[1],m=typeof c=="string"?c:c[0],l={indices:d,value:g,storage:m,tensor:t},T=qe=>typeof qe=="string"?qe:`${qe}u`,x={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},C=a?"uniforms.":"",z=`${C}${e}_shape`,U=`${C}${e}_strides`,A="";for(let qe=0;qe ${l.indices} { var indices: ${l.indices}; var current = offset; ${A} return indices; }`,te=qe=>(x.offsetToIndices=!0,s<2?qe:`o2i_${e}(${qe})`),ie=[];if(s>=2)for(let qe=s-1;qe>=0;qe--)ie.push(`${Wt(U,qe,s)} * (indices[${qe}])`);let Ee=s<2?"":` fn i2o_${e}(indices: ${l.indices}) -> u32 { return ${ie.join("+")}; }`,Pe=qe=>(x.indicesToOffset=!0,s<2?qe:`i2o_${e}(${qe})`),Ye=(...qe)=>s===0?"0u":`${l.indices}(${qe.map(T).join(",")})`,Ft=(qe,vt)=>s<2?`${qe}`:`${Wt(qe,vt,s)}`,Bt=(qe,vt,rr)=>s<2?`${qe}=${rr};`:`${Wt(qe,vt,s)}=${rr};`,ar={},nr=(qe,vt)=>{x.broadcastedIndicesToOffset=!0;let rr=`${vt.name}broadcastedIndicesTo${e}Offset`;if(rr in ar)return`${rr}(${qe})`;let Br=[];for(let nn=s-1;nn>=0;nn--){let an=vt.indicesGet("outputIndices",nn+vt.rank-s);Br.push(`${Ft(U,nn)} * (${an} % ${Ft(z,nn)})`)}return ar[rr]=`fn ${rr}(outputIndices: ${vt.type.indices}) -> u32 { return ${Br.length>0?Br.join("+"):"0u"}; }`,`${rr}(${qe})`},Ht=(qe,vt)=>(()=>{if(l.storage===l.value)return`${e}[${qe}]=${vt};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${qe}]=vec2(u32(${vt}), select(0u, 0xFFFFFFFFu, ${vt} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${qe}]=vec2(u32(${vt}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${qe}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${vt}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),kr=qe=>(()=>{if(l.storage===l.value)return`${e}[${qe}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${qe}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${qe}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${qe}] & 0xFFu), bool(${e}[${qe}] & 0xFF00u), bool(${e}[${qe}] & 0xFF0000u), bool(${e}[${qe}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),jr=s<2?"":` fn get_${e}ByIndices(indices: ${l.indices}) -> ${g} { return ${kr(`i2o_${e}(indices)`)}; }`,hr=s<2?"":(()=>{let qe=u.map(rr=>`d${rr}: u32`).join(", "),vt=u.map(rr=>`d${rr}`).join(", ");return` fn get_${e}(${qe}) -> ${g} { return get_${e}ByIndices(${Ye(vt)}); }`})(),Fr=(...qe)=>{if(qe.length!==s)throw new Error(`indices length must be ${s}`);let vt=qe.map(T).join(",");return s===0?kr("0u"):s===1?kr(vt[0]):(x.get=!0,x.getByIndices=!0,x.indicesToOffset=!0,`get_${e}(${vt})`)},Gt=qe=>s<2?kr(qe):(x.getByIndices=!0,x.indicesToOffset=!0,`get_${e}ByIndices(${qe})`),Qt=s<2?"":` fn set_${e}ByIndices(indices: ${l.indices}, value: ${g}) { ${Ht(`i2o_${e}(indices)`,"value")} }`,xr=s<2?"":(()=>{let qe=u.map(rr=>`d${rr}: u32`).join(", "),vt=u.map(rr=>`d${rr}`).join(", ");return` fn set_${e}(${qe}, value: ${g}) { set_${e}ByIndices(${Ye(vt)}, value); }`})();return{impl:()=>{let qe=[],vt=!1;return x.offsetToIndices&&(qe.push(ee),vt=!0),x.indicesToOffset&&(qe.push(Ee),vt=!0),x.broadcastedIndicesToOffset&&(Object.values(ar).forEach(rr=>qe.push(rr)),vt=!0),x.set&&(qe.push(xr),vt=!0),x.setByIndices&&(qe.push(Qt),vt=!0),x.get&&(qe.push(hr),vt=!0),x.getByIndices&&(qe.push(jr),vt=!0),!a&&vt&&qe.unshift(`const ${z} = ${l.indices}(${r.join(",")});`,`const ${U} = ${l.indices}(${ke.computeStrides(r).join(",")});`),qe.join(` `)},type:l,offsetToIndices:te,indicesToOffset:Pe,broadcastedIndicesToOffset:nr,indices:Ye,indicesGet:Ft,indicesSet:Bt,set:(...qe)=>{if(qe.length!==s+1)throw new Error(`indices length must be ${s}`);let vt=qe[s];if(typeof vt!="string")throw new Error("value must be string");let rr=qe.slice(0,s).map(T).join(",");return s===0?Ht("0u",vt):s===1?Ht(rr[0],vt):(x.set=!0,x.setByIndices=!0,x.indicesToOffset=!0,`set_${e}(${rr}, ${vt})`)},setByOffset:Ht,setByIndices:(qe,vt)=>s<2?Ht(qe,vt):(x.setByIndices=!0,x.indicesToOffset=!0,`set_${e}ByIndices(${qe}, ${vt});`),get:Fr,getByOffset:kr,getByIndices:Gt,usage:n,name:e,strides:U,shape:z,rank:s}},Qe=(e,t,r,n=1)=>Js(e,t,r,"input",n),qt=(e,t,r,n=1)=>Js(e,t,r,"output",n),bi=(e,t,r,n=1)=>Js(e,t,r,"internal",n),Mi=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=pn){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,s=i?`let global_idx = global_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) fn main(${a}) { ${s} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",n=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let i=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${i}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},ao=(e,t)=>new Mi(e,t),gs=(e,t)=>{let r=e.length,n=[];for(let i=0;i1&&s===1&&n.unshift(a)}return n}}),oo,vi,ss,lo,Ed,xn,Sd,uo,jn=j(()=>{Yt(),Kt(),Pr(),pr(),oo=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},vi=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,ss=(e,t)=>ke.sortBasedOnPerm(e,vi(e.length,t)),lo=(e,t,r,n)=>{let i=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`;for(let a=0;a{let r=[],n=[];for(let i=0;i{let r=e.dataType,n=e.dims.length,i=vi(n,t),a=ss(e.dims,i),{newShape:s,newPerm:u}=Ed(e.dims,i),d=ke.areEqual(u,[2,3,1]),c=ke.areEqual(u,[3,1,2]),g=s.length===2&&u[0]>u[1]||d||c,m=g?s:e.dims,l=a;g&&(m=d?[s[0],s[1]*s[2]]:c?[s[0]*s[1],s[2]]:s,l=[m[1],m[0]]);let T=Qe("a",r,m.length),x=qt("output",r,l.length),C=16,z;return g?z=U=>` ${U.registerUniform("output_size","u32").declareVariables(T,x)} var tile : array, ${C}>; ${U.mainStart([C,C,1])} let stride = (uniforms.output_shape[1] - 1) / ${C} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${C}u + local_id.x; let input_row = workgroup_id_x * ${C}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${T.getByIndices(`${T.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${C}u + local_id.x; let output_row = workgroup_id_y * ${C}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${x.setByIndices(`${x.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`:z=U=>` ${U.registerUniform("output_size","u32").declareVariables(T,x)} ${lo(i,n,T,x)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${x.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${x.setByOffset("global_idx",T.getByIndices("aIndices"))} }`,{name:g?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let U=ke.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:g?{x:Math.ceil(l[1]/C),y:Math.ceil(l[0]/C)}:{x:Math.ceil(U/64)},programUniforms:[{type:12,data:U},...kt(m,l)]}},getShaderSource:z}},Sd=(e,t)=>{oo(e.inputs),e.compute(xn(e.inputs[0],t.perm))},uo=e=>or({perm:e.perm})}),co,po,ho,fo,mo,xi,_o,go,Ti,wo,An,Ci,yo,bo,$i,Mo,vo,ki,xo,To,Ei,Pd=j(()=>{Yt(),Kt(),pr(),Bi(),jn(),co={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"},po={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},ho={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},fo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},mo=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,i]},_o=(e,t)=>{let r=e.length+t.length,n=[],i=0;for(let a=0;a{for(let r=0;r{let r=[];if(!go(e,t)){for(let n=0;nr.push(n))}return r},wo=(e,t,r,n,i,a,s)=>{let u=r[0].dims,d=ke.size(a),c=ke.size(s),g=Qe("_A",r[0].dataType,u),m=qt("output",i,a),l=32,T=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:x=>` ${x.registerUniform("reduceSize","u32").declareVariables(g,m)} ${T} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${x.mainStart(l)} let outputIndex = global_idx / ${l}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${ho[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${l}) { let candidate = f32(${g.getByOffset("offset + k")}); bestValue = ${co[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 = ${po[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${m.setByOffset("outputIndex",`${n==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${fo[n]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:d},programUniforms:[{type:12,data:c}]})}},An=(e,t,r,n)=>{let i=e.inputs.length===1?r:Pi(e.inputs,r),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((T,x)=>x));let s=ke.normalizeAxes(a,e.inputs[0].dims.length),u=s,d=e.inputs[0],c=Ti(u,e.inputs[0].dims.length);c.length>0&&(d=e.compute(xn(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],u=mo(u.length,d.dims.length));let[g,m]=xi(d.dims,u),l=g;i.keepDims&&(l=_o(g,s)),e.compute(wo(t,{hint:i.cacheKey,inputDependencies:["type"]},[d],n,e.inputs[0].dataType,l,m),{inputs:[d]})},Ci=(e,t)=>{An(e,"ReduceMeanShared",t,"mean")},yo=(e,t)=>{An(e,"ReduceL1Shared",t,"l1")},bo=(e,t)=>{An(e,"ReduceL2Shared",t,"l2")},$i=(e,t)=>{An(e,"ReduceLogSumExpShared",t,"logSumExp")},Mo=(e,t)=>{An(e,"ReduceMaxShared",t,"max")},vo=(e,t)=>{An(e,"ReduceMinShared",t,"min")},ki=(e,t)=>{An(e,"ReduceProdShared",t,"prod")},xo=(e,t)=>{An(e,"ReduceSumShared",t,"sum")},To=(e,t)=>{An(e,"ReduceSumSquareShared",t,"sumSquare")},Ei=(e,t)=>{An(e,"ReduceLogSumShared",t,"logSum")}}),In,Si,ei,Pi,$n,Co,$o,Ai,ko,Eo,Ii,So,Po,Fi,Ao,Fn,Oi,Io,Fo,zi,Oo,zo,Di,Do,Lo,Li,Bi=j(()=>{Yt(),Kt(),Pr(),pr(),Pd(),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.")},Si=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ei=(e,t,r,n,i,a,s=!1,u=!1)=>{let d=[],c=r[0].dims,g=c.length,m=ke.normalizeAxes(i,g),l=!u&&m.length===0;c.forEach((C,z)=>{l||m.indexOf(z)>=0?s&&d.push(1):d.push(C)});let T=d.length,x=ke.size(d);return{name:e,shaderCache:t,getShaderSource:C=>{let z=[],U=Qe("_A",r[0].dataType,g),A=qt("output",a,T),ee=n(U,A,m),te=ee[2];for(let ie=0,Ee=0;ie=0?(s&&Ee++,te=`for(var j${ie}: u32 = 0; j${ie} < ${c[ie]}; j${ie}++) { ${ee[2].includes("last_index")?`let last_index = j${ie};`:""} ${U.indicesSet("input_indices",ie,`j${ie}`)} ${te} }`):(z.push(`${U.indicesSet("input_indices",ie,A.indicesGet("output_indices",Ee))};`),Ee++);return` ${C.registerUniform("output_size","u32").declareVariables(U,A)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${U.type.indices}; let output_indices = ${A.offsetToIndices("global_idx")}; ${z.join(` `)} ${ee[0]} // init ops for reduce max/min ${ee[1]} ${te} ${ee[3]} ${ee.length===4?A.setByOffset("global_idx","value"):ee.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:d,dataType:a}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:[{type:12,data:x},...kt(c,d)]})}},Pi=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),or({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},$n=(e,t,r,n)=>{let i=e.inputs,a=i.length===1?r:Pi(i,r);e.compute(ei(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?Si:n,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Co=(e,t)=>{In(e.inputs),$n(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},$o=(e,t)=>{In(e.inputs),$n(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Ai=(e,t)=>{In(e.inputs),$n(e,"ReduceL2",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},ko=(e,t)=>{In(e.inputs),$n(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Eo=(e,t)=>{In(e.inputs),$n(e,"ReduceMax",t,(r,n,i)=>{let a=[];for(let s=0;s=0||i.length===0)&&a.push(r.indicesSet("input_indices",s,0));return[`${a.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},Ii=(e,t)=>{In(e.inputs),$n(e,"ReduceMean",t,(r,n,i)=>{let a=1;for(let s=0;s=0||i.length===0)&&(a*=e.inputs[0].dims[s]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},So=(e,t)=>{In(e.inputs),$n(e,"ReduceMin",t,(r,n,i)=>{let a=[];for(let s=0;s=0||i.length===0)&&a.push(`input_indices[${s}] = 0;`);return[`${a.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},Po=(e,t)=>{In(e.inputs),$n(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Fi=(e,t)=>{In(e.inputs),$n(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Ao=(e,t)=>{In(e.inputs),$n(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;`,""])},Fn=(e,t,r)=>{if(t.length===0)return r;let n=1,i=1;for(let a=0;a1024},Oi=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ii(e,t):Ci(e,t)},Io=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$o(e,t):yo(e,t)},Fo=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ai(e,t):bo(e,t)},zi=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ko(e,t):$i(e,t)},Oo=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Eo(e,t):Mo(e,t)},zo=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?So(e,t):vo(e,t)},Di=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Po(e,t):ki(e,t)},Do=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fi(e,t):xo(e,t)},Lo=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ao(e,t):To(e,t)},Li=(e,t)=>{Fn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Co(e,t):Ei(e,t)}}),Ri,Ni,Bo,ji,Ro=j(()=>{Yt(),Pr(),Bi(),Ri=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Ni=(e,t)=>{Ri(e.inputs);let r=(n,i,a)=>{let s=[];for(let u=0;u=0||a.length===0)&&s.push(`input_indices[${u}] = 0;`);return[`${s.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(ei("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Bo=(e,t)=>{Ri(e.inputs);let r=(n,i,a)=>{let s=[];for(let u=0;u=0||a.length===0)&&s.push(`input_indices[${u}] = 0;`);return[`${s.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(ei("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ji=e=>or(e)}),No,ti,Vi,jo,Vo,ws,Uo,Wo,ri=j(()=>{Yt(),Kt(),oe(),pr(),No=(e,t)=>{let r=e[0],n=e[1],i=e[2],a=e[3],s=e[4],u=e[5];if(s&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],c=r.dims[1],g=r.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==g)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let m=i.dims[0]/3,l=m,T=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ee of t.qkvHiddenSizes)if(ee%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");m=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],T=t.qkvHiddenSizes[2]}let x=c;if(m!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==m+l+T)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let C=0;if(s){if(l!==T)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(s.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(s.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(C=s.dims[3])}let z=x+C,U=-1,A=0;if(a)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==t.numHeads||u.dims[2]!==c||u.dims[3]!==z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:c,pastSequenceLength:C,kvSequenceLength:x,totalSequenceLength:z,maxSequenceLength:U,inputHiddenSize:g,hiddenSize:m,vHiddenSize:T,headSize:Math.floor(m/t.numHeads),vHeadSize:Math.floor(T/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:A,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ti=(e,t,r)=>t&&e?` let total_sequence_length_input = u32(${t.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; var past_sequence_length: u32 = 0; if (is_first_prompt == false) { past_sequence_length = total_sequence_length - sequence_length; } `:` ${r?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; `,Vi=(e,t,r,n,i,a,s,u)=>{let d=_r(s?1:a),c=64,g=a/d;g{let A=qt("x",e.dataType,e.dims,d),ee=[A],te=s?Qe("seq_lens",s.dataType,s.dims):void 0;te&&ee.push(te);let ie=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;ie&&ee.push(ie);let Ee=Or(e.dataType),Pe=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${U.registerUniforms(Pe).declareVariables(...ee)} ${U.mainStart([c,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; ${ti(te,ie,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${s?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; var thread_max_vector = ${x}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${x}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(d){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${d}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${c}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${x}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${x}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(d){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${d}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${c}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${A.type.value}(${Ee}(1.0) / ${Ee}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${x}(x[offset + i]); x[offset + i] = ${A.type.value}(exp(f32input - max_value) / sum); } } ${s?` for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${A.type.value}(${Ee}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${T};${d}`,inputDependencies:C},getShaderSource:z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/c),y:i,z:t*r},programUniforms:l})}},jo=(e,t,r,n,i,a,s,u,d)=>{let c=s+a.kvSequenceLength,g=[a.batchSize,a.numHeads,a.sequenceLength,c],m=e>1&&n,l=a.kvNumHeads?a.kvNumHeads:a.numHeads,T=m?[a.batchSize,l,c,a.headSize]:void 0,x=a.nReps?a.nReps:1,C=a.scale===0?1/Math.sqrt(a.headSize):a.scale,z=_r(a.headSize),U=a.headSize/z,A=12,ee={x:Math.ceil(c/A),y:Math.ceil(a.sequenceLength/A),z:a.batchSize*a.numHeads},te=[{type:12,data:a.sequenceLength},{type:12,data:U},{type:12,data:c},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:C},{type:12,data:s},{type:12,data:a.kvSequenceLength},{type:12,data:x}],ie=m&&n&&ke.size(n.dims)>0,Ee=["type","type"];ie&&Ee.push("type"),i&&Ee.push("type"),u&&Ee.push("type"),d&&Ee.push("type");let Pe=[{dims:g,dataType:t.dataType,gpuDataType:0}];m&&Pe.push({dims:T,dataType:t.dataType,gpuDataType:0});let Ye=Ft=>{let Bt=Qe("q",t.dataType,t.dims,z),ar=Qe("key",r.dataType,r.dims,z),nr=[Bt,ar];if(ie){let Qt=Qe("past_key",n.dataType,n.dims,z);nr.push(Qt)}i&&nr.push(Qe("attention_bias",i.dataType,i.dims));let Ht=u?Qe("seq_lens",u.dataType,u.dims):void 0;Ht&&nr.push(Ht);let kr=d?Qe("total_sequence_length_input",d.dataType,d.dims):void 0;kr&&nr.push(kr);let jr=qt("output",t.dataType,g),hr=[jr];m&&hr.push(qt("present_key",t.dataType,T,z));let Fr=Or(1,z),Gt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${A}u; var tileQ: array<${Bt.type.storage}, ${A*A}>; var tileK: array<${Bt.type.storage}, ${A*A}>; ${Ft.registerUniforms(Gt).declareVariables(...nr,...hr)} ${Ft.mainStart([A,A,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${x===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${x===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; ${ti(Ht,kr,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${ie&&m?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${m?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} var value = ${Fr}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${ie&&m?` if (n + local_id.y < past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; }`:` if (n + local_id.y < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; }`} ${m?`if (n + local_id.y < present_sequence_length) { present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${Fr}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { let headOffset = workgroup_id.z * uniforms.M * uniforms.N; let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(z){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${z}`)}})()}; output[outputIdx] = ${jr.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${z};${i!==void 0};${n!==void 0};${e}`,inputDependencies:Ee},getRunData:()=>({outputs:Pe,dispatchGroup:ee,programUniforms:te}),getShaderSource:Ye}},Vo=(e,t,r,n,i,a,s=void 0,u=void 0)=>{let d=a+i.kvSequenceLength,c=i.nReps?i.nReps:1,g=i.vHiddenSize*c,m=e>1&&n,l=i.kvNumHeads?i.kvNumHeads:i.numHeads,T=m?[i.batchSize,l,d,i.headSize]:void 0,x=[i.batchSize,i.sequenceLength,g],C=12,z={x:Math.ceil(i.vHeadSize/C),y:Math.ceil(i.sequenceLength/C),z:i.batchSize*i.numHeads},U=[{type:12,data:i.sequenceLength},{type:12,data:d},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:g},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:c}],A=m&&n&&ke.size(n.dims)>0,ee=["type","type"];A&&ee.push("type"),s&&ee.push("type"),u&&ee.push("type");let te=[{dims:x,dataType:t.dataType,gpuDataType:0}];m&&te.push({dims:T,dataType:t.dataType,gpuDataType:0});let ie=Ee=>{let Pe=Qe("probs",t.dataType,t.dims),Ye=Qe("v",r.dataType,r.dims),Ft=[Pe,Ye];A&&Ft.push(Qe("past_value",n.dataType,n.dims));let Bt=s?Qe("seq_lens",s.dataType,s.dims):void 0;s&&Ft.push(Bt);let ar=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&Ft.push(ar);let nr=[qt("output",t.dataType,x)];m&&nr.push(qt("present_value",t.dataType,T));let Ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${C}u; var tileQ: array<${Pe.type.value}, ${C*C}>; var tileV: array<${Pe.type.value}, ${C*C}>; ${Ee.registerUniforms(Ht).declareVariables(...Ft,...nr)} ${Ee.mainStart([C,C,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; ${ti(Bt,ar,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${A&&m?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${m?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} var value = ${Pe.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${A&&m?` if (w + local_id.y < past_sequence_length) { tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; } `:` if (w + local_id.y < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; }`} ${m?` if (w + local_id.y < present_sequence_length) { present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + headIdx * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:ee},getRunData:()=>({outputs:te,dispatchGroup:z,programUniforms:U}),getShaderSource:ie}},ws=(e,t,r,n,i,a,s,u,d,c,g=void 0,m=void 0)=>{let l=Math.min(e.outputCount,1+(s?1:0)+(u?1:0)),T=l>1?c.pastSequenceLength:0,x=T+c.kvSequenceLength,C=d&&ke.size(d.dims)>0?d:void 0,z=[t,r];l>1&&s&&ke.size(s.dims)>0&&z.push(s),C&&z.push(C),g&&z.push(g),m&&z.push(m);let U=e.compute(jo(l,t,r,s,C,c,T,g,m),{inputs:z,outputs:l>1?[-1,1]:[-1]})[0];e.compute(Vi(U,c.batchSize,c.numHeads,T,c.sequenceLength,x,g,m),{inputs:g&&m?[U,g,m]:[U],outputs:[]});let A=[U,n];l>1&&u&&ke.size(u.dims)>0&&A.push(u),g&&A.push(g),m&&A.push(m),e.compute(Vo(l,U,n,u,c,T,g,m),{inputs:A,outputs:l>1?[0,2]:[0]})},Uo=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,s=12,u={x:Math.ceil(t.headSize/s),y:Math.ceil(t.sequenceLength/s),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:n},{type:12,data:i},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],g=m=>{let l=qt("output_q",d[0].dataType,r),T=qt("output_k",d[0].dataType,r),x=qt("output_v",d[0].dataType,r),C=Qe("input",d[0].dataType,d[0].dims),z=Qe("weight",d[1].dataType,d[1].dims),U=Qe("bias",d[2].dataType,d[2].dims),A=C.type.storage,ee=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${s}u; var tileInput: array<${A}, ${s*s}>; var tileWeightQ: array<${A}, ${s*s}>; var tileWeightK: array<${A}, ${s*s}>; var tileWeightV: array<${A}, ${s*s}>; ${m.registerUniforms(ee).declareVariables(C,z,U,l,T,x)} ${m.mainStart([s,s,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${A}(0); var valueK = ${A}(0); var valueV = ${A}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:c}),getShaderSource:g},{inputs:d,outputs:[-1,-1,-1]})},Wo=(e,t)=>{let r=No(e.inputs,t),[n,i,a]=Uo(e,r);return ws(e,n,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}}),Go,qo,Ui,Ho,Ad=j(()=>{Pt(),Yt(),Kt(),Pr(),pr(),Go=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,i,a)=>{let s=i.length;if(s!==n.length)throw new Error(`${a}: num dimensions != ${s}`);i.forEach((u,d)=>{if(u!==n[d])throw new Error(`${a}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},qo=(e,t)=>{let{epsilon:r,spatial:n,format:i}=t,a=e[0].dims,s=n?_r(a[a.length-1]):1,u=i==="NHWC"&&a.length>1?s:1,d=ke.size(a)/s,c=n,g=c?a.length:a,m=Qe("x",e[0].dataType,e[0].dims,s),l=Qe("scale",e[1].dataType,e[1].dims,u),T=Qe("bias",e[2].dataType,e[2].dims,u),x=Qe("inputMean",e[3].dataType,e[3].dims,u),C=Qe("inputVar",e[4].dataType,e[4].dims,u),z=qt("y",e[0].dataType,g,s),U=()=>{let ee="";if(n)ee=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${s}`:"outputIndices[1]"};`;else if(i==="NCHW")ee=` ${z.indicesSet("outputIndices","0","0")} let cOffset = ${z.indicesToOffset("outputIndices")};`;else{ee=`var cIndices = ${l.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let te=1;te` const epsilon = ${r}; ${ee.registerUniform("outputSize","u32").declareVariables(m,l,T,x,C,z)} ${ee.mainStart()} ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${z.offsetToIndices(`global_idx * ${s}`)}; ${U()} let scale = ${l.getByOffset("cOffset")}; let bias = ${T.getByOffset("cOffset")}; let inputMean = ${x.getByOffset("cOffset")}; let inputVar = ${C.getByOffset("cOffset")}; let x = ${m.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${z.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${s}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:A,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c?[{type:12,data:d},...kt(a)]:[{type:12,data:d}]})}},Ui=e=>or(e),Ho=(e,t)=>{let{inputs:r,outputCount:n}=e,i=Ui({...t,outputCount:n});if(k.webgpu.validateInputContent&&Go(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(qo(r,i))}}),Wi,Ko,Xo,Qo=j(()=>{Kt(),pr(),Wi=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")},Ko=e=>{let t=e[0].dims,r=e[0].dims[2],n=ke.size(t)/4,i=e[0].dataType,a=Qe("input",i,t,4),s=Qe("bias",i,[r],4),u=Qe("residual",i,t,4),d=qt("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:c=>` const channels = ${r}u / 4; ${c.declareVariables(a,s,u,d)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${a.getByOffset("global_idx")} + ${s.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; ${d.setByOffset("global_idx","value")} }`}},Xo=e=>{Wi(e.inputs),e.compute(Ko(e.inputs))}}),Yo,vr,Gi,Zo,Jo,el,tl,qi,rl,nl,sl,il,Hi,al,ol,ll,Ds,Ki,ni,ul,Xi,dl,cl,Qi,pl,hl,Yi,fl,ml,Zi,_l,gl,si,wl,yl,ii,Ji,ea,ai,bl,Ml,vl,ta,xl,Tl,ra=j(()=>{Yt(),Kt(),Pr(),pr(),Yo=(e,t,r,n,i,a,s)=>{let u=Math.ceil(t/4),d="";typeof i=="string"?d=`${i}(a)`:d=i("a");let c=Qe("inputData",r,[u],4),g=qt("outputData",n,[u],4),m=[{name:"vec_size",type:"u32"}];return s&&m.push(...s),` ${e.registerUniforms(m).declareVariables(c,g)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${c.getByOffset("global_idx")}; ${g.setByOffset("global_idx",d)} }`},vr=(e,t,r,n,i,a=e.dataType,s,u)=>{let d=[{type:12,data:Math.ceil(ke.size(e.dims)/4)}];return s&&d.push(...s),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:c=>Yo(c,ke.size(e.dims),e.dataType,a,r,n,u),getRunData:c=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(ke.size(c[0].dims)/64/4)},programUniforms:d})}},Gi=e=>{e.compute(vr(e.inputs[0],"Abs","abs"))},Zo=e=>{e.compute(vr(e.inputs[0],"Acos","acos"))},Jo=e=>{e.compute(vr(e.inputs[0],"Acosh","acosh"))},el=e=>{e.compute(vr(e.inputs[0],"Asin","asin"))},tl=e=>{e.compute(vr(e.inputs[0],"Asinh","asinh"))},qi=e=>{e.compute(vr(e.inputs[0],"Atan","atan"))},rl=e=>{e.compute(vr(e.inputs[0],"Atanh","atanh"))},nl=e=>or(e),sl=(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))},il=e=>{let t,r,n=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return or({min:t,max:r})},Hi=(e,t)=>{let r=t||il(e.inputs),n=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},al=e=>{e.compute(vr(e.inputs[0],"Ceil","ceil"))},ol=e=>{e.compute(vr(e.inputs[0],"Cos","cos"))},ll=e=>{e.compute(vr(e.inputs[0],"Cosh","cosh"))},Ds=e=>or(e),Ki=(e,t)=>{let r=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` const elu_alpha_ = ${r}(${t.alpha}); fn elu_f32(a: ${r}) -> ${r} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,t.cacheKey))},ni=(e="f32")=>` const r0: ${e} = 0.3275911; const r1: ${e} = 0.254829592; const r2: ${e} = -0.284496736; const r3: ${e} = 1.421413741; const r4: ${e} = -1.453152027; const r5: ${e} = 1.061405429; fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,ul=e=>{let t=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,ni(t)))},Xi=e=>{e.compute(vr(e.inputs[0],"Exp","exp"))},dl=e=>{e.compute(vr(e.inputs[0],"Floor","floor"))},cl=e=>{let t=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,ni(t)))},Qi=(e,t)=>{let r=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},pl=e=>{e.compute(vr(e.inputs[0],"Not",t=>`!${t}`))},hl=e=>{e.compute(vr(e.inputs[0],"Neg",t=>`-${t}`))},Yi=e=>{e.compute(vr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},fl=e=>{let t=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},ml=e=>{e.compute(vr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Zi=e=>or(e),_l=(e,t)=>{let r=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},gl=e=>{e.compute(vr(e.inputs[0],"Sin","sin"))},si=e=>{e.compute(vr(e.inputs[0],"Sinh","sinh"))},wl=e=>{e.compute(vr(e.inputs[0],"Sqrt","sqrt"))},yl=e=>{e.compute(vr(e.inputs[0],"Tan","tan"))},ii=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ji=e=>{e.compute(vr(e.inputs[0],"Tanh",ii))},ea=(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 ${ii("v")}; } `,ai=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,bl=e=>{let t=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"FastGelu",ai,ea(t),void 0,e.inputs[0].dataType))},Ml=(e,t)=>{let r=Or(e.inputs[0].dataType);return e.compute(vr(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},vl=e=>{e.compute(vr(e.inputs[0],"Log","log"))},ta=(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; } `,xl=e=>`quick_gelu_impl(${e})`,Tl=(e,t)=>{let r=Or(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"QuickGelu",xl,ta(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),na,Cl,$l,kl=j(()=>{Kt(),pr(),ra(),na=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")},Cl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Qe("input",e[0].dataType,e[0].dims,4),n=Qe("bias",e[0].dataType,[e[0].dims[2]],4),i=qt("output",e[0].dataType,t,4),a=ke.size(t)/4,s=fr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${u.declareVariables(r,n,i)} ${ni(s)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${i.setByOffset("global_idx","valueLeft * geluRight")} }`}},$l=e=>{na(e.inputs),e.compute(Cl(e.inputs))}}),El,Sl,kn,Pl,Al,sa,Il,Fl,ia,Ol,zl,aa,Dl,Id=j(()=>{Yt(),Kt(),pr(),El=(e,t,r,n,i,a,s,u,d,c,g,m)=>{let l,T;typeof u=="string"?l=T=(A,ee)=>`${u}((${A}),(${ee}))`:typeof u=="function"?l=T=u:(l=u.scalar,T=u.vector);let x=qt("outputData",g,n.length,4),C=Qe("aData",d,t.length,4),z=Qe("bData",c,r.length,4),U;if(i)if(a){let A=ke.size(t)===1,ee=ke.size(r)===1,te=t.length>0&&t[t.length-1]%4===0,ie=r.length>0&&r[r.length-1]%4===0;A||ee?U=x.setByOffset("global_idx",T(A?`${C.type.value}(${C.getByOffset("0")}.x)`:C.getByOffset("global_idx"),ee?`${z.type.value}(${z.getByOffset("0")}.x)`:z.getByOffset("global_idx"))):U=` let outputIndices = ${x.offsetToIndices("global_idx * 4u")}; let offsetA = ${C.broadcastedIndicesToOffset("outputIndices",x)}; let offsetB = ${z.broadcastedIndicesToOffset("outputIndices",x)}; ${x.setByOffset("global_idx",T(s||te?C.getByOffset("offsetA / 4u"):`${C.type.value}(${C.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||ie?z.getByOffset("offsetB / 4u"):`${z.type.value}(${z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else U=x.setByOffset("global_idx",T(C.getByOffset("global_idx"),z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let A=(ee,te,ie="")=>{let Ee=`aData[indexA${te}][componentA${te}]`,Pe=`bData[indexB${te}][componentB${te}]`;return` let outputIndices${te} = ${x.offsetToIndices(`global_idx * 4u + ${te}u`)}; let offsetA${te} = ${C.broadcastedIndicesToOffset(`outputIndices${te}`,x)}; let offsetB${te} = ${z.broadcastedIndicesToOffset(`outputIndices${te}`,x)}; let indexA${te} = offsetA${te} / 4u; let indexB${te} = offsetB${te} / 4u; let componentA${te} = offsetA${te} % 4u; let componentB${te} = offsetB${te} % 4u; ${ee}[${te}] = ${ie}(${l(Ee,Pe)}); `};g===9?U=` var data = vec4(0); ${A("data",0,"u32")} ${A("data",1,"u32")} ${A("data",2,"u32")} ${A("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:U=` ${A("outputData[global_idx]",0)} ${A("outputData[global_idx]",1)} ${A("outputData[global_idx]",2)} ${A("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(C,z,x)} ${m??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${U} }`},Sl=(e,t,r,n,i,a,s=r.dataType)=>{let u=!ke.areEqual(r.dims,n.dims),d=r.dims,c=ke.size(r.dims),g=!1,m=!1,l=[u];if(u){let T=bn.calcShape(r.dims,n.dims,!1);if(!T)throw new Error("Can't perform binary op on the given tensors");d=T,c=ke.size(d);let x=ke.size(r.dims)===1,C=ke.size(n.dims)===1,z=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,U=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;l.push(x),l.push(C),l.push(z),l.push(U);let A=1;for(let ee=1;eeT.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:T=>El(T,r.dims,n.dims,d,g,u,m,i,r.dataType,n.dataType,s,a),getRunData:()=>({outputs:[{dims:d,dataType:s}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil(ke.size(d)/4)},...kt(r.dims,n.dims,d)]})}},kn=(e,t,r,n,i,a)=>{e.compute(Sl(t,i??"",e.inputs[0],e.inputs[1],r,n,a))},Pl=e=>{kn(e,"Add",(t,r)=>`${t}+${r}`)},Al=e=>{kn(e,"Div",(t,r)=>`${t}/${r}`)},sa=e=>{kn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Il=e=>{kn(e,"Mul",(t,r)=>`${t}*${r}`)},Fl=e=>{let t=Qe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;kn(e,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { return ${t}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},ia=e=>{kn(e,"Sub",(t,r)=>`${t}-${r}`)},Ol=e=>{kn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},zl=e=>{kn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},aa=e=>{kn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Dl=e=>{kn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),Ll,Bl,oi,Rl,Nl,jl,Fd=j(()=>{Yt(),Kt(),Pr(),pr(),Ll=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],i=n.dataType,a=n.dims.length;e.forEach((s,u)=>{if(u!==r){if(s.dataType!==i)throw new Error("input tensors should be one type");if(s.dims.length!==a)throw new Error("input tensors should have the same shape");s.dims.forEach((d,c)=>{if(c!==t&&d!==n.dims[c])throw new Error("non concat dimensions must match")})}})},Bl=(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; }`,oi=(e,t)=>{let r=e.length,n=[];for(let i=0;i{let i=ke.size(r),a=new Array(e.length),s=new Array(e.length),u=0,d=[],c=[],g=[{type:12,data:i}];for(let C=0;C`uniforms.sizeInConcatAxis${C}`).join(","),x=C=>` ${(()=>{C.registerUniform("outputSize","u32");for(let z=0;z(${T}); ${l} -= sizeInConcatAxis[inputIndex - 1u]; } ${oi(s,m)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:g}),getShaderSource:x}},Nl=(e,t)=>{let r=e.inputs,n=r[0].dims,i=ke.normalizeAxis(t.axis,n.length);Ll(r,i);let a=n.slice();a[i]=r.reduce((u,d)=>u+(d.dims.length>i?d.dims[i]:0),0);let s=r.filter(u=>ke.size(u.dims)>0);e.compute(Rl(s,i,a,r[0].dataType),{inputs:s})},jl=e=>or({axis:e.axis})}),Yn,Vn,Zn,oa,Un=j(()=>{Yt(),Kt(),Yn=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Vn=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},Zn=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},oa=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)||[Pn,Rn];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),hn,la,li=j(()=>{hn=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},la=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),ua,da=j(()=>{ua=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)); } `}),Vl,Ul,Ls,ca,Wl,Bs,Gl,pa,Rs=j(()=>{Yt(),Kt(),pr(),Un(),li(),Vl=(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":""}); `,Ul=(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];"} }`,Ls=(e,t,r="f32",n,i=!1,a=32,s=!1,u=32)=>{let d=t[1]*e[1],c=t[0]*e[0],g=i?d:a,m=i?a:d,l=g/t[0],T=a/t[1];if(!((i&&l===4&&e[1]===4||!i&&(l===3||l===4))&&g%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${l} must be 3 or 4. tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${g/l}>, ${m}>; var mm_Bsub: array, ${c/e[0]}>, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${l}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${s?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${d}; let num_tiles = ${s?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${s?`i32(globalId.z) * ${u}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${T}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${Vl(i,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${T}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${l===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Ul(i,l)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},ca=(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":""}); `,Wl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Bs=(e,t,r="f32",n,i=!1,a=32,s=!1,u=32,d=!1)=>{let c=e[1]*t[1],g=e[0]*t[0],m=i?c:a,l=i?a:c;if(!(l%t[1]===0&&m%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let T=l/t[1],x=m/t[0],C=a/t[1],z=d?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${c}; let globalColStart = i32(workgroupId.x) * ${g}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) { ${ca(i,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${g}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${c}; let tileRowA = i32(localId.y) * ${T}; let tileColA = i32(localId.x) * ${x}; let tileRowB = i32(localId.y) * ${C}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${T}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${x}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${ca(i,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${C}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Wl(i)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${l}>; var mm_Bsub : array, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${s?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${s?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${s?`i32(globalId.z) * ${u}`:"0"}; var acc : array, rowPerThread>; ${z} } `},Gl=(e,t,r,n,i,a=!1)=>{let[s,u,d]=i,[c,g,m,l]=n,T=gs(s,d),x=gs(u,d),C=fr(n[0].type.tensor),z=()=>{let A=g.rank,ee=c.rank,te=`var aIndices: ${g.type.indices};`;for(let ie=A-2-1,Ee=ee-1;ie>=0;ie--,Ee--)te+=` aIndices[${ie}] = ${ee>1?`batchIndices[${Ee}]`:"batchIndices"};`;return T.forEach(ie=>{te+=` aIndices[${ie}] = 0;`}),te+=` aIndices[${A-2}] = u32(row); aIndices[${A-1}] = u32(colIn);`,te},U=()=>{let A=m.rank,ee=c.rank,te=`var bIndices: ${m.type.indices};`;for(let ie=A-2-1,Ee=ee-1;ie>=0;ie--,Ee--)te+=` bIndices[${ie}] = ${ee>1?`batchIndices[${Ee}]`:"batchIndices"};`;return x.forEach(ie=>{te+=` bIndices[${ie}] = 0;`}),te+=` bIndices[${A-2}] = u32(row); bIndices[${A-1}] = u32(colIn);`,te};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${c.type.indices}) -> ${hn(e,C)} { var value = ${hn(e,C)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${z()} value = ${g.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${c.type.indices}) -> ${hn(e,C)} { var value = ${hn(e,C)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${U()} value = ${m.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${hn(e,C)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${a?"bias[colIn]":`${hn(e,C)}(bias[row])`};`:""} ${r} ${l.setByIndices("vec3(coords)","value")} } } `},pa=(e,t,r,n,i=!1,a)=>{let s=e[0].dims,u=e[1].dims,d=s.slice(0,-2),c=u.slice(0,-2),g=n?n.slice(0,-2):r.slice(0,-2),m=ke.size(g),l=s[s.length-2],T=s[s.length-1],x=u[u.length-1],C=T%4===0&&x%4===0,z=l<=8?[4,1,1]:[4,4,1],U=[8,8,1],A=[Math.ceil(x/U[0]/z[0]),Math.ceil(l/U[1]/z[1]),Math.ceil(m/U[2]/z[2])],ee=C?4:1,te=[...d,l,T/ee],ie=te.length,Ee=[...c,T,x/ee],Pe=Ee.length,Ye=[m,l,x/ee],Ft=[{type:6,data:l},{type:6,data:x},{type:6,data:T}];Vn(t,Ft),Ft.push(...kt(g,te,Ee));let Bt=["rank","rank"],ar=e.length>2;ar&&(Ft.push(...kt(e[2].dims)),Bt.push("rank")),Ft.push(...kt(Ye));let nr=Ht=>{let kr=g.length,jr=bi("batchDims",e[0].dataType,kr,1),hr=fr(e[0].dataType),Fr=Qe("a",e[0].dataType,ie,ee),Gt=Qe("b",e[1].dataType,Pe,ee),Qt=qt("result",e[0].dataType,Ye.length,ee),xr=[Fr,Gt];if(ar){let nn=i?ee:1;xr.push(Qe("bias",e[2].dataType,e[2].dims.length,nn))}let qe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Zn(t,qe);let vt=fr(Qt.type.tensor),rr=Yn(t,Qt.type.value,vt),Br=Gl(ee,ar,rr,[jr,Fr,Gt,Qt],[d,c,g],i);return` ${Ht.registerUniforms(qe).registerInternalVariables(jr).declareVariables(...xr,Qt)} ${Br} ${C?Ls(z,U,hr,jr):Bs(z,U,hr,jr)} `};return{name:"MatMul",shaderCache:{hint:`${z};${t.activation};${C};${i}`,inputDependencies:Bt},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:Ft}),getShaderSource:nr}}}),ql,Hl,Od=j(()=>{Yt(),_(),pr(),Un(),li(),da(),Rs(),ql=(e,t,r,n,i=!1,a,s=4,u=4,d=4,c="f32")=>{let g=Ft=>{switch(Ft){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Ft} is not supported.`)}},m=Ft=>{switch(Ft){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Ft} is not supported.`)}},l=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,T=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,x=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",C=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",z=e?"row":"col",U=e?"col":"row",A=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${z} / outWidth; let outCol = ${z} % outWidth; let WRow = ${U} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${U} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${U} % inChannels; var resData = ${hn(s,c)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${x} && xCol >= 0 && xCol < ${C}) { ${l} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${g(s)} } return resData;`,ee=e?t&&n?` let col = colIn * ${s}; ${A}`:` let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${A} } return ${hn(s,c)}(0.0);`:n&&r?` let col = colIn * ${s}; ${A}`:` let col = colIn * ${s}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${A} } return ${hn(s,c)}(0.0);`,te=`${m(u)}`,ie=hn(d,c),Ee=hn(e?s:u,c),Pe=hn(e?u:s,c),Ye=Yn(a,ie,c);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ee} { ${e?ee:te} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Pe} { ${e?te:ee} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${ie}) { let col = colIn * ${d}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${T} ${la(i)} ${Ye} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Hl=(e,t,r,n,i,a,s,u,d)=>{let c=t.format==="NHWC",g=c?e[0].dims[3]:e[0].dims[1],m=r[0],l=c?r[2]:r[3],T=c?r[1]:r[2],x=c?r[3]:r[1],C=c&&(g%4===0||g%3===0)&&x%4===0,z=c?x:l*T,U=c?l*T:x,A=[8,8,1],ee=n<=8?[4,1,1]:[4,4,1],te=[Math.ceil(z/A[0]/ee[0]),Math.ceil(U/A[1]/ee[1]),Math.ceil(m/A[2]/ee[2])];ae("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${te}`);let ie=C?c&&g%4!==0?3:4:1,Ee=A[1]*ee[1],Pe=A[0]*ee[0],Ye=Math.max(A[0]*ie,A[1]),Ft=n%Ee===0,Bt=i%Pe===0,ar=a%Ye===0,nr=C?[ie,4,4]:[1,1,1],Ht=[{type:6,data:n},{type:6,data:i},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Vn(t,Ht),Ht.push(...kt(e[0].dims,e[1].dims));let kr=["rank","rank"];s&&(Ht.push(...kt(e[2].dims)),kr.push("rank")),Ht.push(...kt(r));let jr=hr=>{let Fr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Zn(t,Fr);let Gt=C?4:1,Qt=fr(e[0].dataType),xr=` fn setOutputAtIndex(flatIndex : i32, value : ${C?`vec4<${Qt}>`:Qt}) { result[flatIndex] = ${C?`vec4<${Qt}>`:Qt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${C?`vec4<${Qt}>`:Qt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${C?"/ 4":""}, value); }`,qe=Qe("x",e[0].dataType,e[0].dims.length,ie===3?1:ie),vt=Qe("w",e[1].dataType,e[1].dims.length,Gt),rr=[qe,vt],Br=qt("result",e[0].dataType,r.length,Gt);if(s){let nn=Qe("bias",e[2].dataType,e[2].dims.length,Gt);rr.push(nn),xr+=` fn getBiasByOutputCoords(coords : vec4) -> ${C?`vec4<${Qt}>`:Qt} { return bias[coords.${c?"w":"y"}${C?"/ 4":""}]; }`}return` ${ua("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${hr.registerUniforms(Fr).declareVariables(...rr,Br)} ${xr} ${ql(c,Ft,Bt,ar,s,t,nr[0],nr[1],nr[2],Qt)} ${C?Ls(ee,A,Qt,void 0,!c,Ye):Bs(ee,A,Qt,void 0,!c,Ye,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${ie};${C};${Ft};${Bt};${ar};${Ee};${Pe};${Ye}`,inputDependencies:kr},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:te[0],y:te[1],z:te[2]},programUniforms:Ht}),getShaderSource:jr}}}),Kl,ha,Ns,fa,ma,Xl,_a,Ql,zd=j(()=>{Yt(),_(),Kt(),pr(),Un(),li(),Kl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Ns=(e,t)=>t<=1?e:e+(e-1)*(t-1),fa=(e,t,r,n=1)=>{let i=Ns(t,n);return Math.floor((e[0]*(r-1)-r+i)/2)},ma=(e,t,r,n,i)=>{i==null&&(i=fa(e,t[0],n[0]));let a=[0,0,0,r];for(let s=0;s<3;s++)e[s]+2*i>=t[s]&&(a[s]=Math.trunc((e[s]-t[s]+2*i)/n[s]+1));return a},Xl=(e,t,r,n,i,a,s,u,d,c)=>{let g,m,l,T;if(e==="VALID"&&(e=0),typeof e=="number"){g={top:e,bottom:e,left:e,right:e,front:e,back:e};let x=ma([t,r,n,1],[u,d,c],1,[i,a,s],e);m=x[0],l=x[1],T=x[2]}else if(Array.isArray(e)){if(!e.every((C,z,U)=>C===U[0]))throw Error(`Unsupported padding parameter: ${e}`);g={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let x=ma([t,r,n,1],[u,d,c],1,[i,a,s],e[0]);m=x[0],l=x[1],T=x[2]}else if(e==="SAME_UPPER"){m=Math.ceil(t/i),l=Math.ceil(r/a),T=Math.ceil(n/s);let x=(m-1)*i+u-t,C=(l-1)*a+d-r,z=(T-1)*s+c-n,U=Math.floor(x/2),A=x-U,ee=Math.floor(C/2),te=C-ee,ie=Math.floor(z/2),Ee=z-ie;g={top:ee,bottom:te,left:ie,right:Ee,front:U,back:A}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:g,outDepth:m,outHeight:l,outWidth:T}},_a=(e,t,r,n,i,a=!1,s="channelsLast")=>{let u,d,c,g,m;if(s==="channelsLast")[u,d,c,g,m]=e;else if(s==="channelsFirst")[u,m,d,c,g]=e;else throw new Error(`Unknown dataFormat ${s}`);let[l,,T,x,C]=t,[z,U,A]=ha(r),[ee,te,ie]=ha(n),Ee=Ns(T,ee),Pe=Ns(x,te),Ye=Ns(C,ie),{padInfo:Ft,outDepth:Bt,outHeight:ar,outWidth:nr}=Xl(i,d,c,g,z,U,A,Ee,Pe,Ye),Ht=a?l*m:l,kr=[0,0,0,0,0];return s==="channelsFirst"?kr=[u,Ht,Bt,ar,nr]:s==="channelsLast"&&(kr=[u,Bt,ar,nr,Ht]),{batchSize:u,dataFormat:s,inDepth:d,inHeight:c,inWidth:g,inChannels:m,outDepth:Bt,outHeight:ar,outWidth:nr,outChannels:Ht,padInfo:Ft,strideDepth:z,strideHeight:U,strideWidth:A,filterDepth:T,filterHeight:x,filterWidth:C,effectiveFilterDepth:Ee,effectiveFilterHeight:Pe,effectiveFilterWidth:Ye,dilationDepth:ee,dilationHeight:te,dilationWidth:ie,inShape:e,outShape:kr,filterShape:t}},Ql=(e,t,r,n,i,a)=>{let s=a==="channelsLast";s?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],d={x:r.map((z,U)=>U)},c=[Math.ceil(Kl(d.x.map(z=>r[z]))/u[0]),1,1];ae("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let g=1,m=ke.size(r),l=[{type:12,data:m},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];Vn(t,l),l.push(...kt(e[0].dims,e[1].dims));let T=["rank","rank"],x=e.length===3;x&&(l.push(...kt(e[2].dims)),T.push("rank")),l.push(...kt(r));let C=z=>{let U=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Zn(t,U);let A=1,ee=fr(e[0].dataType),te=Qe("x",e[0].dataType,e[0].dims.length,g),ie=Qe("W",e[1].dataType,e[1].dims.length,A),Ee=[te,ie],Pe=qt("result",e[0].dataType,r.length,A),Ye="";if(x){let ar=Qe("bias",e[2].dataType,e[2].dims.length,A);Ee.push(ar),Ye+=` fn getBiasByOutputCoords(coords : array) -> ${ee} { return bias[${s?Wt("coords",4,5):Wt("coords",1,5)}]; }`}let Ft=hn(g,ee),Bt=Yn(t,Ft,ee);return` ${Ye} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${te.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${ie.getByIndices("aIndices")}; } ${z.registerUniforms(U).declareVariables(...Ee,Pe)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Pe.offsetToIndices("global_idx")}; let batch = ${Wt("coords",0,te.rank)}; let d2 = ${s?Wt("coords",te.rank-1,te.rank):Wt("coords",1,te.rank)}; let xFRCCorner = vec3(${s?Wt("coords",1,te.rank):Wt("coords",2,te.rank)}, ${s?Wt("coords",2,te.rank):Wt("coords",3,te.rank)}, ${s?Wt("coords",3,te.rank):Wt("coords",4,te.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${s?Wt("uniforms.x_shape",1,te.rank):Wt("uniforms.x_shape",2,te.rank)}; let xShapeZ = ${s?Wt("uniforms.x_shape",2,te.rank):Wt("uniforms.x_shape",3,te.rank)}; let xShapeW = ${s?Wt("uniforms.x_shape",3,te.rank):Wt("uniforms.x_shape",4,te.rank)}; let xShapeU = ${s?Wt("uniforms.x_shape",4,te.rank):Wt("uniforms.x_shape",1,te.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${s?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${s?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${s?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${s?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${x?"value = value + getBiasByOutputCoords(coords)":""}; ${Bt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${s};${g};${x}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:l}),getShaderSource:C}}}),Jn,Yl,Dd=j(()=>{Yt(),Kt(),pr(),Un(),Jn=(e,t,r,n)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",s=e[0].dims,u=e[1].dims,d=t.format==="NHWC",c=d?r[3]:r[1],g=c/t.group,m=d&&g>=4?_r(c):1,l=ke.size(r)/m,T=[{type:12,data:l},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:g}];Vn(t,T),T.push(...kt(s,[u[0],u[1],u[2],u[3]/m]));let x=i?["rank","rank","rank"]:["rank","rank"];T.push(...kt([r[0],r[1],r[2],r[3]/m]));let C=z=>{let U=qt("output",e[0].dataType,r.length,m),A=fr(U.type.tensor),ee=Yn(t,U.type.value,A),te=Qe("x",e[0].dataType,s.length),ie=Qe("w",e[1].dataType,u.length,m),Ee=[te,ie];i&&Ee.push(Qe("b",e[2].dataType,e[2].dims,m));let Pe=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Zn(t,Pe);let Ye=d?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { continue; } for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; let xVal = ${te.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${ie.get("wHeight","wWidth","wInChannel","output_channel")}; value += xVal * wVal; } } } `:` for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { continue; } let xVal = ${te.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${ie.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${z.registerUniforms(Pe).declareVariables(...Ee,U)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${U.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${d?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${m} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; var value: ${U.type.value} = ${U.type.value}(0); ${Ye} ${a} ${ee} ${U.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${m}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:T}),getShaderSource:C}},Yl=(e,t,r,n)=>{let i=e.length>2,a=_r(r[3]),s=_r(r[2]),u=ke.size(r)/a/s,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],g=[r[0],r[1],r[2],r[3]/a],m=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Vn(t,m),m.push(...kt(d,c,g));let l=(s-1)*t.strides[1]+c[1],T=x=>{let C=qt("output",e[0].dataType,g.length,a),z=fr(C.type.tensor),U=Yn(t,C.type.value,z),A=Qe("x",e[0].dataType,d.length,a),ee=Qe("w",e[1].dataType,c.length,a),te=[A,ee];i&&te.push(Qe("b",e[2].dataType,e[2].dims,a));let ie=i?"value += b[output_channel];":"",Ee=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Zn(t,Ee),` ${x.registerUniforms(Ee).declareVariables(...te,C)} ${x.mainStart()} ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${s}u; let col = (index1 % width1) * ${s}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${A.type.value}, ${l}>; var values: array<${C.type.value}, ${s}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${l}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${A.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${A.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { let w_val = ${ee.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${s}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${s}u; i++) { var value = values[i]; ${ie} ${U} ${C.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${s};${l};${c[0]};${c[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:m}),getShaderSource:T}}}),ga,Zl,wa,Jl=j(()=>{Yt(),Kt(),Rs(),pr(),Un(),ga=(e,t,r,n,i=!1,a)=>{let s=e[0].dims,u=e[1].dims,d=s[s.length-2],c=u[u.length-1],g=s[s.length-1],m=_r(c),l=_r(g),T=_r(d),x=ke.size(r)/m/T,C=e.length>2,z=n?n.slice(0,-2):r.slice(0,-2),U=[ke.size(z),d,c],A=[{type:12,data:x},{type:12,data:d},{type:12,data:c},{type:12,data:g}];Vn(t,A),A.push(...kt(z,s,u)),C&&A.push(...kt(e[2].dims)),A.push(...kt(U));let ee=te=>{let ie=bi("batch_dims",e[0].dataType,z.length),Ee=Qe("a",e[0].dataType,s.length,l),Pe=Qe("b",e[1].dataType,u.length,m),Ye=qt("output",e[0].dataType,U.length,m),Ft=fr(Ye.type.tensor),Bt=Yn(t,Ye.type.value,Ft),ar=[Ee,Pe],nr="";if(C){let xr=i?m:1;ar.push(Qe("bias",e[2].dataType,e[2].dims.length,xr)),nr=`${i?`value += bias[col / ${xr}];`:`value += ${Ye.type.value}(bias[row + i]);`}`}let Ht=s.slice(0,-2),kr=u.slice(0,-2),jr=gs(Ht,z),hr=gs(kr,z),Fr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Zn(t,Fr);let Gt=(xr,qe)=>{let vt=xr.rank,rr=xr.name;if(vt===2)return`var ${rr}_indices = ${xr.type.indices}(0u, 0u);`;let Br=ie.rank,nn=`var ${rr}_indices: ${xr.type.indices};`;for(let an=vt-2-1,Hs=Br-1;an>=0;an--,Hs--)nn+=` ${rr}_indices[${an}] = ${Br>1?`batch_indices[${Hs}]`:"batch_indices"};`;return qe.forEach(an=>{nn+=` ${rr}_indices[${an}] = 0;`}),nn+=`${rr}_indices[${vt-2}] = 0u; ${rr}_indices[${vt-1}] = 0u;`,nn},Qt=()=>{let xr=`var a_data: ${Ee.type.value};`;for(let qe=0;qe; for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { ${Qt()} } for (var i = 0u; i < ${T}u; i++) { var value = values[i]; ${nr} ${Bt} let cur_indices = ${Ye.type.indices}(batch, row + i, col); let offset = ${Ye.indicesToOffset("cur_indices")}; ${Ye.setByOffset(`offset / ${m}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${l};${T};${i}`,inputDependencies:C?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:A}),getShaderSource:ee}},Zl=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.")},wa=e=>{Zl(e.inputs);let t=bn.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&n<8?e.compute(ga(e.inputs,{activation:""},t)):e.compute(pa(e.inputs,{activation:""},t))}}),eu,ui,tu,ys,ya,ba,ru,js,Ma,Ld=j(()=>{Kt(),Od(),zd(),Rs(),Dd(),Un(),Jl(),jn(),eu=(e,t,r,n,i,a)=>{let s=e[0],u=e.slice(a?1:2,a?3:4),d=u.length,c=t[0],g=t.slice(2).map((l,T)=>l+(l-1)*(r[T]-1)),m=u.map((l,T)=>l+n[T]+n[T+d]).map((l,T)=>Math.floor((l-g[T]+i[T])/i[T]));return m.splice(0,0,s),m.splice(a?3:1,0,c),m},ui=[2,3,1,0],tu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ys=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=oa(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,a=e.group,s=e.kernel_shape,u=e.pads,d=e.strides,c=e.w_is_const();return{autoPad:n,format:r,dilations:i,group:a,kernelShape:s,pads:u,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},ba=(e,t,r,n)=>{let i=r.format==="NHWC",a=eu(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,i);if(r.group!==1){let Ee=[t[0]];if(i){let Pe=e.kernelCustomData.wT??e.compute(xn(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Pe),Ee.push(Pe)}else Ee.push(t[1]);t.length===3&&Ee.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(Yl(Ee,r,a,n),{inputs:Ee}):e.compute(Jn(Ee,r,a,n),{inputs:Ee});return}let s=t.length===3,u=t[0].dims[i?1:2],d=t[0].dims[i?2:3],c=t[0].dims[i?3:1],g=t[1].dims[2],m=t[1].dims[3],l=a[i?1:2],T=a[i?2:3],x=a[i?3:1],C=i&&g===u&&m===d&&r.pads[0]===0&&r.pads[1]===0;if(C||g===1&&m===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let Ee=a[0],Pe,Ye,Ft,Bt=[];if(i){let Ht=e.kernelCustomData.wT??e.compute(xn(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ht),C){let kr=u*d*c;Pe=t[0].reshape([1,Ee,kr]),Ye=Ht.reshape([1,kr,x]),Ft=[1,Ee,x]}else Pe=t[0].reshape([Ee,u*d,c]),Ye=Ht.reshape([1,c,x]),Ft=[Ee,l*T,x];Bt.push(Pe),Bt.push(Ye)}else Pe=t[0].reshape([Ee,c,u*d]),Ye=t[1].reshape([1,x,c]),Ft=[Ee,x,l*T],Bt.push(Ye),Bt.push(Pe);s&&Bt.push(t[2]);let ar=Ft[2],nr=Bt[0].dims[Bt[0].dims.length-1];ar<8&&nr<8?e.compute(ga(Bt,r,a,Ft,i,n),{inputs:Bt}):e.compute(pa(Bt,r,a,Ft,i,n),{inputs:Bt});return}let z=!0,U=e.kernelCustomData.wT??e.compute(xn(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=U);let A=[t[0],U];s&&A.push(t[2]);let ee=i?l*T:x,te=i?x:l*T,ie=g*m*c;e.compute(Hl(A,r,a,ee,te,ie,s,z,n),{inputs:A})},ru=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),s=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=ys({...t,pads:i,strides:a,dilations:s,kernelShape:u},n);ba(e,n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},js=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",i=ys(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,s=_a(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(Ql(t,i,s.outShape,[s.filterDepth,s.filterHeight,s.filterWidth],[s.padInfo.front,s.padInfo.top,s.padInfo.left],n))},Ma=(e,t)=>{if(tu(e.inputs,t),e.inputs[0].dims.length===3)ru(e,t);else if(e.inputs[0].dims.length===5)js(e,e.inputs,t);else{let r=ys(t,e.inputs);ba(e,e.inputs,r)}}}),nu,su,va=j(()=>{Yt(),_(),pr(),Un(),li(),da(),Rs(),nu=(e,t=!1,r,n,i=4)=>{let a=z=>{switch(z){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${n}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${z} is not supported.`)}},s=e?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,u=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,d=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",c=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",g=e?"row":"col",m=e?"col":"row",l=` let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${g} / outWidth; let outCol = ${g} % outWidth; let WRow = ${m} / (uniforms.filter_dims[1] * inChannels); let WCol = ${m} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) { return ${n}(0.0); } if (xC < 0.0 || xC >= f32(${c}) || fract(xC) > 0.0) { return ${n}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${m} % inChannels; ${s} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,T=e?` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${l} } return ${n}(0.0);`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${l} } return ${n}(0.0);`,x=` let col = colIn * ${i}; let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${a(i)} } return ${n}(0.0); `,C=Yn(r,n);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?T:x} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?x:T} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${u} ${la(t)} ${C} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value; } }`},su=(e,t,r,n,i,a,s,u)=>{let d=t.format==="NHWC",c=d?e[0].dims[3]:e[0].dims[1],g=r[0],m=d?r[2]:r[3],l=d?r[1]:r[2],T=d?r[3]:r[1],x=d&&c%4===0&&c%3&&T%4===0,C=d?T:m*l,z=d?m*l:T,U=[8,8,1],A=n<=8?[4,1,1]:[4,4,1],ee=[Math.ceil(C/U[0]/A[0]),Math.ceil(z/U[1]/A[1]),Math.ceil(g/U[2]/A[2])];ae("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ee}`);let te=x?4:1,ie=Math.max(U[0]*te,U[1]),Ee=x?4:1,Pe=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],Ye=[Pe[0]+(t.dilations[0]<=1?0:(Pe[0]-1)*(t.dilations[0]-1)),Pe[1]+(t.dilations[1]<=1?0:(Pe[1]-1)*(t.dilations[1]-1))],Ft=[Ye[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),Ye[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Bt=[{type:6,data:n},{type:6,data:i},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Pe},{type:6,data:Ft}];Vn(t,Bt),Bt.push(...kt(e[0].dims,e[1].dims));let ar=["rank","rank"];s&&(Bt.push(...kt(e[2].dims)),ar.push("rank")),Bt.push(...kt(r));let nr=Ht=>{let kr=Qe("x",e[0].dataType,e[0].dims.length,Ee),jr=Qe("w",e[1].dataType,e[1].dims.length,1),hr=qt("result",e[0].dataType,r.length,Ee),Fr=[kr,jr],Gt="";if(s){let qe=Qe("bias",e[2].dataType,e[2].dims.length,Ee);Fr.push(qe),Gt+=` fn getBiasByOutputCoords(coords : vec4) -> ${qe.type.value} { return bias[coords.${d?"w":"y"}${x?"/ 4":""}]; }`}let Qt=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:Pe.length},{name:"pads",type:"i32",length:Ft.length}];Zn(t,Qt);let xr=fr(e[0].dataType,1);if(xr!=="f16"&&xr!=="f32")throw new Error(`elemType ${xr} is not supported.`);return` ${ua("uniforms.result_strides")} ${Ht.registerUniforms(Qt).declareVariables(...Fr,hr)}; ${Gt} ${nu(d,s,t,kr.type.value,te)} ${x?Ls(A,U,xr,void 0,!d,ie):Bs(A,U,xr,void 0,!d,ie,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${A};${U};${x}`,inputDependencies:ar},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ee[0],y:ee[1],z:ee[2]},programUniforms:Bt}),getShaderSource:nr}}}),iu,xa,Bd=j(()=>{Yt(),_(),Kt(),pr(),iu=(e,t,r,n,i,a=!1,s,u,d=!1)=>{let c=d?1:2,g=d?2:3,m=d?3:1,l=a?2:1,T=` fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${s}>`:s}) { result[flatIndex] = ${a?`vec4<${s}>`:s}(value); }`;n&&(T+=` fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${s}>`:s} { return bias[coords.${d?"w":"y"}${a?"/ 4":""}]; }`);let x=a?4:1,C=Qe("W",t[1].dataType,t[1].dims.length,x),z=Qe("Dy",t[0].dataType,t[0].dims.length,x),U=[z,C];n&&U.push(Qe("bias",t[2].dataType,[r[m]].length,x));let A=qt("result",t[0].dataType,r.length,x),ee=`{ let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${i?"global_id.y":"workgroup_id.y"} * ${l}; let d1: u32 = ${i?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${l}>; for (var i = 0; i < ${l}; i++) { dotProd[i] = vec4<${s}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${s}(dyCorner.x) + ${s}(wR)) / ${s}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${s}(dyCorner.y) + ${s}(wC)) / ${s}(uniforms.strides.y); let dyC2 = (${s}(dyCorner.y) + 1.0 + ${s}(wC)) / ${s}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${s}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${z.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${z.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${m}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${z.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${C.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${z.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${s}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${l}; i = i + 1) { let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${s}>(0.0)`}; ${A.set("batch","r","c + i","d1","value")}; } }`,te=` let outputIndices = ${A.offsetToIndices("global_idx")}; let batch = ${A.indicesGet("outputIndices",0)}; let d1 = ${A.indicesGet("outputIndices",m)}; let r = ${A.indicesGet("outputIndices",c)}; let c = ${A.indicesGet("outputIndices",g)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${s}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${s}(dyRCorner) + ${s}(wR)) / ${s}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[${c}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${s}(dyCCorner) + ${s}(wC)) / ${s}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[${g}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${d?z.get("batch","idyR","idyC","inputChannel"):z.get("batch","inputChannel","idyR","idyC")}; let wValue = ${C.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${n?"bias[d1]":`${s}(0.0)`}; ${A.setByOffset("global_idx","value")}; `;return` ${e.registerUniforms(u).declareVariables(...U,A)} ${T} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${a?ee:te}}`},xa=(e,t,r)=>{let n=e.length>2,i=t.outputShape,a=ke.size(i),s=[Math.ceil(a/64),1,1];ae("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let u=t.format==="NHWC",d=["rank","rank"],c=[t.strides[0],t.strides[1]],g=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],m=[t.dilations[0],t.dilations[1]],l=[g[0]+(t.dilations[0]<=1?0:(t.kernelShape[u?1:2]-1)*(t.dilations[0]-1)),g[1]+(t.dilations[1]<=1?0:(t.kernelShape[u?2:3]-1)*(t.dilations[1]-1))],T=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],x=!1,C=t.group,z=e[1].dims,U=z[0]/C,A=z[1],ee=[{type:12,data:a},{type:12,data:c},{type:12,data:g},{type:12,data:m},{type:12,data:l},{type:6,data:T},{type:12,data:U},{type:12,data:A},...kt(e[0].dims,e[1].dims)];n&&(ee.push(...kt(e[2].dims)),d.push("rank")),ee.push(...kt(i));let te=s[1]===1&&s[2]===1,ie=Ee=>{let Pe=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:c.length},{name:"filter_dims",type:"u32",length:g.length},{name:"dilations",type:"u32",length:g.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:T.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ye=fr(e[0].dataType);return`${iu(Ee,e,i,n,te,x,Ye,Pe,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:r?r(i):i,dataType:e[0].dataType}],programUniforms:ee}),getShaderSource:ie}}}),Rd,au,ou,Ta,bs,lu,uu,du,cu,pu,Ca=j(()=>{va(),Bd(),Un(),jn(),Rd=(e,t,r,n,i,a)=>(e-1)*t+r+(n-1)*i+1-a,au=(e,t,r,n,i)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[i]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[i]=a)},ou=(e,t,r,n,i,a,s,u,d,c)=>{let g=e.length-2,m=c.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((m,l)=>m*l,1)===0){r.length=0;for(let m=2;mm+l,0)===0){let m=t[0].dims.length-2;d=new Array(m).fill(1)}let c=e.strides.slice();if(c.reduce((m,l)=>m+l,0)===0){let m=t[0].dims.length-2;c=new Array(m).fill(1)}ou(u,r,d,e.autoPad,e.group,i,c,n,s,a);let g=Object.assign({},e);return Object.assign(g,{kernelShape:r,pads:i,outputPadding:s,outputShape:a,dilations:d,strides:c}),g},bs=e=>{let t=oa(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,a=e.group,s=e.kernelShape,u=e.pads,d=e.strides,c=e.wIsConst(),g=e.outputPadding,m=e.outputShape;return{autoPad:n,format:r,dilations:i,group:a,kernelShape:s,outputPadding:g,outputShape:m,pads:u,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},lu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((s,u)=>s+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((s,u)=>s+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((s,u)=>s+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((s,u)=>s+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},uu=[2,3,1,0],du=(e,t,r)=>{let n=Ta(r,t),i=r.format==="NHWC",a=n.outputShape,s=a[i?3:1],u=t[0].dims[i?3:1];if(n.group!==1||s===1&&u===1){e.compute(xa(t,n));return}let d=a[i?1:2],c=a[i?2:3],g=t[1].dims[2],m=t[1].dims[3],l=i?d*c:s,T=i?s:d*c,x=g*m*u,C=!0,z=e.kernelCustomData.wT??e.compute(xn(t[1],uu),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=z);let U=[t[0],z],A=t.length===3;A&&(!i&&t[2].dims.length===1?U.push(t[2].reshape([t[2].dims[0],1,1])):U.push(t[2])),e.compute(su(U,n,a,l,T,x,A,C),{inputs:U})},cu=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let s=t.strides;(s.length===0||s[0]===0)&&(s=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],s=[1].concat(s),a=[1].concat(a),i=[1].concat(i);let d=Ta({...t,pads:u,strides:s,dilations:a,kernelShape:i},n);e.compute(xa(n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]]))},pu=(e,t)=>{lu(e.inputs,t),e.inputs[0].dims.length===3?cu(e,t):du(e,e.inputs,t)}}),Nd,hu,fu,jd=j(()=>{Yt(),Kt(),Pr(),pr(),Nd=(e,t,r,n)=>{let i=ke.size(t),a=t.length,s=Qe("input",e,a),u=qt("output",e,a),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),c=ke.normalizeAxis(d,a),g=m=>{let l=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,T=Wt("uniforms.input_shape","uniforms.axis",a),x=n.reverse?l+(n.exclusive?" + 1":""):"0",C=n.reverse?T:l+(n.exclusive?"":" + 1");return` ${m.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,u)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${u.offsetToIndices("global_idx")}; var sum = ${u.type.value}(0); let first : i32 = ${x}; let last : i32 = ${C}; for (var i : i32 = first; i < last; i++) { ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${s.getByIndices("inputIndices")}; } ${u.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:c},...kt(t,t)]}),getShaderSource:g}},hu=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(Nd(n,r,i,t),{inputs:[0]})},fu=e=>{let t=e.exclusive===1,r=e.reverse===1;return or({exclusive:t,reverse:r})}}),mu,_u,$a,gu,wu,yu=j(()=>{Yt(),Kt(),Pr(),pr(),mu=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.")},_u=(e,t,r,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let a=0;a{let r,n,i,a,s,u,d=t.format==="NHWC",c=t.blocksize,g=t.mode==="DCR";d?([r,n,i,a]=e.dims,s=g?[r,n,i,c,c,a/c**2]:[r,n,i,a/c**2,c,c],u=g?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],s=g?[r,c,c,a/c**2,n,i]:[r,a/c**2,c,c,n,i],u=g?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let m=e.reshape(s),l=m.dims.length,T=e.dataType,x=Qe("a",T,l),C=qt("output",T,l),z=U=>` ${U.registerUniform("output_size","u32").declareVariables(x,C)} ${_u(u,l,x,C)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${C.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${C.setByOffset("global_idx",x.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:U=>{let A=d?[r,n*c,i*c,a/c**2]:[r,a/c**2,n*c,i*c],ee=ke.size(A),te=m.dims,ie=ke.sortBasedOnPerm(te,u);return{outputs:[{dims:A,dataType:U[0].dataType}],dispatchGroup:{x:Math.ceil(ee/64)},programUniforms:[{type:12,data:ee},...kt(te,ie)]}},getShaderSource:z}},gu=(e,t)=>{mu(e.inputs),e.compute($a(e.inputs[0],t))},wu=e=>or({blocksize:e.blocksize,mode:e.mode,format:e.format})}),di,Vs,ci,bu,Mu,pi,vu,ka,xu,Tu,Ea,Sa=j(()=>{Yt(),Kt(),Pr(),pr(),di="[a-zA-Z]|\\.\\.\\.",Vs="("+di+")+",ci="^"+Vs+"$",bu="("+Vs+",)*"+Vs,Mu="^"+bu+"$",pi=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)}},vu=class{constructor(e,t){var i;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(Mu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,s)=>{let u=e[s].dims.slice();if(!a.match(RegExp(ci)))throw new Error("Invalid LHS term");let d=this.processTerm(a,!0,u,s);this.lhs.push(d)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,s])=>s.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Vs)))throw new Error("Invalid RHS");(i=n.match(RegExp(di,"g")))==null||i.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let s=this.symbolToInfo.get(a);if(s===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(s.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let i=r.length,a=!1,s=[],u=0;if(!e.match(RegExp(ci))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(di,"g")),c=new pi(n);return d==null||d.forEach((g,m)=>{if(g==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let l=i-d.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(s=r.slice(u,u+l),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=s;else throw new Error("Ellipsis must be specified in the LHS");for(let T=0;Te+"_max",xu=(e,t,r,n)=>{let i=e.map(c=>c.length).map((c,g)=>Qe(`input${g}`,t,c)),a=ke.size(n),s=qt("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(c=>!r.rhs.symbolToIndices.has(c)),d=c=>{let g=[],m="var prod = 1.0;",l="var sum = 0.0;",T="sum += prod;",x=[],C=[],z=[],U=[],A=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((te,ie)=>{var Ee;if(r.rhs.symbolToIndices.has(ie)){let Pe=(Ee=r.rhs.symbolToIndices.get(ie))==null?void 0:Ee[0];Pe!==void 0&&r.lhs.forEach((Ye,Ft)=>{if(te.inputIndices.includes(Ft)){let Bt=Ye.symbolToIndices.get(ie);if(Bt===void 0)throw new Error("Invalid symbol error");Bt.forEach(ar=>{g.push(`${i[Ft].indicesSet(`input${Ft}Indices`,ar,s.indicesGet("outputIndices",Pe))}`)})}})}else r.lhs.forEach((Pe,Ye)=>{if(te.inputIndices.includes(Ye)){let Ft=Pe.symbolToIndices.get(ie);if(Ft===void 0)throw new Error("Invalid symbol error");Ft.forEach(Bt=>{x.push(`${i[Ye].indicesSet(`input${Ye}Indices`,Bt,`${ie}`)}`)}),U.push(`prod *= ${i[Ye].getByIndices(`input${Ye}Indices`)};`)}}),C.push(`for(var ${ie}: u32 = 0; ${ie} < uniforms.${ka(ie)}; ${ie}++) {`),z.push("}")});let ee=A?[...g,`let sum = ${i.map((te,ie)=>te.getByIndices(`input${ie}Indices`)).join(" * ")};`]:[...g,l,...C,...x,m,...U,T,...z];return` ${c.registerUniforms(u.map(te=>({name:`${ka(te)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,s)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${s.offsetToIndices("global_idx")}; ${i.map((te,ie)=>`var input${ie}Indices: ${i[ie].type.indices};`).join(` `)} ${ee.join(` `)}; ${s.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=u.filter(m=>r.symbolToInfo.has(m)).map(m=>{var l;return{type:12,data:((l=r.symbolToInfo.get(m))==null?void 0:l.dimValue)||0}});c.push({type:12,data:a});let g=e.map((m,l)=>[...kt(m)]).reduce((m,l)=>m.concat(l),c);return g.push(...kt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:g}},getShaderSource:d}},Tu=(e,t)=>{let r=new vu(e.inputs,t.equation),n=r.outputDims,i=e.inputs.map((a,s)=>a.dims);e.compute(xu(i,e.inputs[0].dataType,r,n))},Ea=e=>{let t=e.equation.replace(/\s+/g,"");return or({equation:t})}}),Vd,Pa,Cu,Aa,$u,Ud=j(()=>{Yt(),Kt(),pr(),Vd=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let i=0;ie.length>t.length?Pa(e,t):Pa(t,e),Aa=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Cu(t,r),i=e[0].dataType,a=i===9?4:1,s=Math.ceil(ke.size(n)/a),u=c=>{let g=Qe("input",i,t.length,a),m=qt("output",i,n.length,a),l;if(i===9){let T=(x,C,z="")=>` let outputIndices${C} = ${m.offsetToIndices(`outputOffset + ${C}u`)}; let offset${C} = ${g.broadcastedIndicesToOffset(`outputIndices${C}`,m)}; let index${C} = offset${C} / 4u; let component${C} = offset${C} % 4u; ${x}[${C}] = ${z}(${g.getByOffset(`index${C}`)}[component${C}]); `;l=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${T("data",0,"u32")} ${T("data",1,"u32")} ${T("data",2,"u32")} ${T("data",3,"u32")} ${m.setByOffset("global_idx","data")} }`}else l=` let outputIndices = ${m.offsetToIndices("global_idx")}; let inputOffset = ${g.broadcastedIndicesToOffset("outputIndices",m)}; ${m.setByOffset("global_idx",g.getByOffset("inputOffset"))} }`;return` ${c.registerUniform("vec_size","u32").declareVariables(g,m)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${l}`},d=[{type:12,data:s},...kt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d})}},$u=e=>{Vd(e.inputs),e.compute(Aa(e.inputs),{inputs:[0]})}}),Ia,ku,Wd=j(()=>{Yt(),Kt(),pr(),ra(),Ia=e=>{let t=e[0].dataType,r=ke.size(e[0].dims),n=ke.size(e[1].dims),i=n%4===0,a=s=>{let u=Qe("x",t,[1],4),d=Qe("bias",t,[1],4),c=qt("y",t,[1],4),g=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],m=T=>` let bias${T}_offset: u32 = (global_idx * 4 + ${T}) % uniforms.bias_size; let bias${T} = ${d.getByOffset(`bias${T}_offset / 4`)}[bias${T}_offset % 4];`,l=i?` let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${m(0)}${m(1)}${m(2)}${m(3)} let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${s.registerUniforms(g).declareVariables(u,d,c)} ${ea(Or(t))} ${s.mainStart(pn)} ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${u.getByOffset("global_idx")}; ${l} let x_in = x + bias; ${c.setByOffset("global_idx",ai("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:s=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/pn/4)}})}},ku=e=>{e.inputs.length<2||ke.size(e.inputs[1].dims)===0?bl(e):e.compute(Ia(e.inputs))}}),Fa,Gd,qd,Oa,Eu=j(()=>{Yt(),Kt(),Pr(),pr(),Fa=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Gd=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,a=ke.normalizeAxis(t.axis,i),s=r.slice(0);s.splice(a,1,...n);let u=r[a],d=e[0].dataType===9?4:1,c=Math.ceil(ke.size(s)/d),g=[{type:12,data:c},{type:6,data:u},{type:12,data:a},...kt(e[0].dims,e[1].dims,s)],m=l=>{let T=Qe("data",e[0].dataType,e[0].dims.length,d),x=Qe("inputIndices",e[1].dataType,e[1].dims.length),C=qt("output",e[0].dataType,s.length,d),z=A=>{let ee=n.length,te=`var indicesIndices${A} = ${x.type.indices}(0);`;for(let ie=0;ie1?`indicesIndices${A}[${ie}]`:`indicesIndices${A}`} = ${s.length>1?`outputIndices${A}[uniforms.axis + ${ie}]`:`outputIndices${A}`};`;te+=` var idx${A} = ${x.getByIndices(`indicesIndices${A}`)}; if (idx${A} < 0) { idx${A} = idx${A} + uniforms.axisDimLimit; } var dataIndices${A} : ${T.type.indices}; `;for(let ie=0,Ee=0;ie1?`dataIndices${A}[${ie}]`:`dataIndices${A}`} = u32(idx${A});`,Ee+=ee):(te+=`${i>1?`dataIndices${A}[${ie}]`:`dataIndices${A}`} = ${s.length>1?`outputIndices${A}[${Ee}]`:`outputIndices${A}`};`,Ee++);return te},U;if(e[0].dataType===9){let A=(ee,te,ie="")=>` let outputIndices${te} = ${C.offsetToIndices(`outputOffset + ${te}u`)}; ${z(te)}; let offset${te} = ${T.indicesToOffset(`dataIndices${te}`)}; let index${te} = offset${te} / 4u; let component${te} = offset${te} % 4u; ${ee}[${te}] = ${ie}(${T.getByOffset(`index${te}`)}[component${te}]); `;U=` let outputOffset = global_idx * ${d}; var value = vec4(0); ${A("value",0,"u32")} ${A("value",1,"u32")} ${A("value",2,"u32")} ${A("value",3,"u32")} ${C.setByOffset("global_idx","value")} `}else U=` let outputIndices = ${C.offsetToIndices("global_idx")}; ${z("")}; let value = ${T.getByIndices("dataIndices")}; ${C.setByOffset("global_idx","value")}; `;return` ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(T,x,C)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${U} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:m}},qd=e=>or({axis:e.axis}),Oa=(e,t)=>{let r=e.inputs;Fa(r),e.compute(Gd(e.inputs,t))}}),Su,Pu,za,Au,Hd=j(()=>{Yt(),Kt(),Pr(),pr(),Su=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=ke.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,i=e[0],a=e[2],s=e.length===4?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map((u,d)=>d===r?Math.ceil(u/n)===a.dims[d]:u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(s){if(s.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(s.dims.length!==a.dims.length||!s.dims.map((u,d)=>u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Pu=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,a=ke.normalizeAxis(t.gatherAxis,i),s=ke.normalizeAxis(t.quantizeAxis,i),u=r.slice(0);u.splice(a,1,...n);let d=ke.size(u),c=e[2].dataType,g=e[0].dataType===22,m=[{type:12,data:d},{type:12,data:s},{type:12,data:a},{type:12,data:t.blockSize},...kt(...e.map((T,x)=>T.dims),u)],l=T=>{let x=Qe("data",e[0].dataType,e[0].dims.length),C=Qe("inputIndices",e[1].dataType,e[1].dims.length),z=Qe("scales",e[2].dataType,e[2].dims.length),U=e.length>3?Qe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,A=qt("output",c,u.length),ee=[x,C,z];U&&ee.push(U);let te=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${T.registerUniforms(te).declareVariables(...ee,A)} ${T.mainStart()} let output_indices = ${A.offsetToIndices("global_idx")}; var indices_indices = ${C.type.indices}(0); ${n.length>1?` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${A.indicesGet("output_indices","uniforms.gather_axis + i")}; ${C.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${A.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${x.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${A.indicesGet("output_indices","i")}; ${x.indicesSet("data_indices","i","index")}; } var index_from_indices = ${C.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${r[a]}; } ${x.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { let index = ${A.indicesGet("output_indices",`i + ${n.length} - 1`)}; ${x.indicesSet("data_indices","i","index")}; } let data_offset = ${x.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${x.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${z.getByIndices("scale_indices")}; ${U?` let zero_point_indices = scale_indices; let zero_point_offset = ${U.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${U.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${Or(c)}(quantized_data - zero_point) * scale; ${A.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((T,x)=>x!==1).map(T=>T.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(T,x)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:c}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m}),getShaderSource:l}},za=(e,t)=>{let r=e.inputs;Su(r,t),e.compute(Pu(e.inputs,t))},Au=e=>or({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Da,Iu,Fu,La,Kd=j(()=>{Yt(),Kt(),Pr(),pr(),Da=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.`)},Iu=(e,t)=>{let r=e[0].dims,n=e[0].dataType,i=r.length,a=e[1].dims,s=e[1].dataType,u=ke.normalizeAxis(t.axis,i),d=r[u],c=a.slice(0),g=ke.size(c),m=Qe("input",n,i),l=Qe("indicesInput",s,a.length),T=qt("output",n,c.length),x=[{type:12,data:g},{type:6,data:d},{type:12,data:u}];return x.push(...kt(r,a,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:x}),getShaderSource:C=>` ${C.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,l,T)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${T.offsetToIndices("global_idx")}; var idx = ${l.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${m.type.indices}(outputIndices); ${m.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${m.getByIndices("inputIndices")}; ${T.setByOffset("global_idx","value")}; }`}},Fu=e=>or({axis:e.axis}),La=(e,t)=>{let r=e.inputs;Da(r),e.compute(Iu(e.inputs,t))}}),Ou,zu,Du,zr,Cc=j(()=>{Yt(),Kt(),pr(),Ou=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")},zu=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[i,a,s]=on.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[i,a];if(!u)throw new Error("Can't use gemm on the given tensors");let d=ke.size(u),c=[{type:12,data:d},{type:12,data:i},{type:12,data:a},{type:12,data:s},{type:1,data:t.alpha},{type:1,data:t.beta}],g=["type","type"];e.length===3&&(c.push(...kt(e[2].dims)),g.push("rank")),c.push(...kt(u));let m=l=>{let T="";t.transA&&t.transB?T="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?T="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?T="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(T="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let x=t.alpha===1?"":"value *= uniforms.alpha;",C=Qe("a",e[0].dataType,e[0].dims),z=Qe("b",e[1].dataType,e[1].dims),U=C.type.value,A=null,ee=[C,z];e.length===3&&(A=Qe("c",e[2].dataType,e[2].dims.length),ee.push(A));let te=qt("output",e[0].dataType,u.length);ee.push(te);let ie=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${l.registerUniforms(ie).declareVariables(...ee)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${U}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${T} } ${x} ${A!=null?`let cOffset = ${A.broadcastedIndicesToOffset("vec2(m, n)",te)}; value += ${U}(uniforms.beta) * ${A.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:m}},Du=e=>{let t=e.transA,r=e.transB,n=e.alpha,i=e.beta;return{transA:t,transB:r,alpha:n,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},zr=(e,t)=>{Ou(e.inputs),e.compute(zu(e.inputs,t))}}),Mn,Xd,Ba,Ra,Lu,Us,Bu,Na=j(()=>{Yt(),Kt(),Pr(),oe(),ri(),pr(),jn(),Mn=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Xd=(e,t)=>{let r=e[0],n=Mn(e,1),i=Mn(e,2),a=Mn(e,3),s=Mn(e,4),u=Mn(e,5),d=Mn(e,6),c=Mn(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let g=r.dims[0],m=r.dims[1],l=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],T=m,x=0,C=0,z=Math.floor(l/t.numHeads);if(d&&c&&ke.size(d.dims)&&ke.size(c.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==g||d.dims[1]!==t.numHeads||d.dims[3]!==z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==g||c.dims[1]!==t.numHeads||c.dims[3]!==z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');x=d.dims[2],C=d.dims[2]}else if(d&&ke.size(d.dims)||c&&ke.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let U;if(n&&ke.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');U=2,T=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');U=5,T=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');U=0,T=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');U=3}if(a&&ke.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let A=x+T,ee=0;if(s&&ke.size(s.dims)>0){ee=8;let Pe=s.dims;throw Pe.length===1?Pe[0]===g?ee=1:Pe[0]===3*g+2&&(ee=3):Pe.length===2&&Pe[0]===g&&Pe[1]===A&&(ee=5),ee===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let te=!1,ie=l;if(i&&ke.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(T!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ie=i.dims[2]}else{if(T!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');ie=i.dims[1]*i.dims[3],te=!0}}let Ee=!1;if(s&&ke.size(s.dims)>0)throw new Error("Key padding mask is not supported");if(u&&ke.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==g||u.dims[1]!==t.numHeads||u.dims[2]!==m||u.dims[3]!==A)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:g,sequenceLength:m,pastSequenceLength:x,kvSequenceLength:T,totalSequenceLength:A,maxSequenceLength:C,inputHiddenSize:0,hiddenSize:l,vHiddenSize:ie,headSize:z,vHeadSize:Math.floor(ie/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ee,scale:t.scale,broadcastResPosBias:Ee,passPastInKv:te,qkvFormat:U}},Ba=e=>or({...e}),Ra=or({perm:[0,2,1,3]}),Lu=(e,t,r,n,i,a,s)=>{let u=[n,i,a],d=ke.size(u),c=[{type:12,data:d},{type:12,data:s},{type:12,data:a}],g=m=>{let l=qt("qkv_with_bias",t.dataType,u),T=Qe("qkv",t.dataType,u),x=Qe("bias",r.dataType,u),C=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${m.registerUniforms(C).declareVariables(T,x,l)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:g},{inputs:[t,r],outputs:[-1]})[0]},Us=(e,t,r,n,i,a,s,u)=>{let d=a;if(s&&ke.size(s.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Lu(e,a,s,t,n,r*i,u),d=d.reshape([t,n,r,i]),r===1||n===1?d:e.compute(xn(d,Ra.perm),{inputs:[d],outputs:[-1]})[0]}else return a.dims.length===3&&(d=a.reshape([t,n,r,i])),r===1||n===1?d:e.compute(xn(d,Ra.perm),{inputs:[d],outputs:[-1]})[0]},Bu=(e,t)=>{let r=Xd(e.inputs,t),n=e.inputs[0],i=Mn(e.inputs,1),a=Mn(e.inputs,2),s=Mn(e.inputs,3),u=Mn(e.inputs,4),d=Mn(e.inputs,5),c=Mn(e.inputs,6),g=Mn(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let m=i&&a&&i.dims.length===4&&a.dims.length===4,l=Us(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,s,0);if(m)return ws(e,l,i,a,u,void 0,c,g,d,r);if(!i||!a)throw new Error("key and value must be provided");let T=Us(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,s,r.hiddenSize),x=Us(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,s,2*r.hiddenSize);ws(e,l,T,x,u,void 0,c,g,d,r)}}),ja,Ru,Nu,Va,ju,Qd,Vu,Uu=j(()=>{Yt(),Kt(),Pr(),pr(),ja=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Ru=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),n=r.length),or({numOutputs:n,axis:t.axis,splitSizes:r})},Nu=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Wt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Va=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=ke.size(r),i=e[0].dataType,a=ke.normalizeAxis(t.axis,r.length),s=new Array(t.numOutputs),u=Qe("input",i,r.length),d=new Array(t.numOutputs),c=[],g=[],m=0,l=[{type:12,data:n}];for(let x=0;x` ${x.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...s)} ${Nu(d.length)} ${Va(s)} ${x.mainStart()} ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${u.offsetToIndices("global_idx")}; var index = ${u.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Wt("uniforms.size_in_split_axis","output_number - 1u",d.length)}; ${u.indicesSet("indices",a,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:T,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:l})}},Qd=(e,t)=>{ja(e.inputs);let r=e.inputs.length===1?t:Ru(e.inputs,t);e.compute(ju(e.inputs,r),{inputs:[0]})},Vu=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return or({axis:t,numOutputs:n,splitSizes:r})}}),Wu,Gu,Ua,qu,Yd=j(()=>{Pr(),ri(),Na(),Uu(),jn(),Wu=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=e[0],n=e[1],i=e[2],a=e[3],s=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,d=r.dims[0],c=r.dims[1],g=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],m=c,l=0,T=!n||n.dims.length===0,x=Math.floor(T?g/(t.numHeads+2*t.kvNumHeads):g/t.numHeads);T&&(g=x*t.numHeads);let C=a&&a.dims.length!==0,z=s&&s.dims.length!==0;if(C&&a.dims.length===4&&a.dims[0]===d&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===x)throw new Error("BSNH pastKey/pastValue is not supported");if(C&&z){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(s.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=a.dims[2]}else if(C||z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let U=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');m=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');m=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==x)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');m=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');U=3}let A=0,ee=!1,te=t.kvNumHeads?x*t.kvNumHeads:g;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(m!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');te=i.dims[2]}else{if(m!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');te=i.dims[1]*i.dims[3],ee=!0}}let ie=e.length>4?e[5]:void 0;if(ie&&ie.dims.length!==1&&ie.dims[0]!==d)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:d,sequenceLength:c,pastSequenceLength:l,kvSequenceLength:m,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:g,vHiddenSize:te,headSize:x,vHeadSize:Math.floor(te/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:A,scale:t.scale,broadcastResPosBias:!1,passPastInKv:ee,qkvFormat:U}},Gu=or({perm:[0,2,1,3]}),Ua=(e,t,r)=>{let n=t,i=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,i,r.headSize]),n=e.compute(xn(n,Gu.perm),{inputs:[n],outputs:[-1]})[0]),n},qu=(e,t)=>{var z;let r=Wu(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((z=e.inputs[1])==null?void 0:z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,s=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,g=r.kvNumHeads?r.kvNumHeads:r.numHeads,m=or({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,g*r.headSize,g*r.headSize]}),[l,T,x]=!i&&!a?e.compute(ju([n],m),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,a],C=Us(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,l,void 0,0);ws(e,C,Ua(e,T,r),Ua(e,x,r),void 0,void 0,s,u,void 0,r,d,c)}}),Wa,Hu,Ku,Xu,Zd=j(()=>{Yt(),Kt(),jn(),pr(),Wa=(e,t,r,n,i,a,s,u)=>{let d=_r(a),c=d===1?"f32":`vec${d}f`,g=d===1?"vec2f":`mat2x${d}f`,m=i*s,l=[i,s,a/d],T=[i,s,2],x=["rank","type","type"],C=[];C.push(...kt(l,T));let z=U=>{let A=Qe("x",t.dataType,3,d),ee=Qe("scale",r.dataType,r.dims),te=Qe("bias",n.dataType,n.dims),ie=qt("output",1,3,2),Ee=[A,ee,te,ie],Pe=64;return` var workgroup_shared : array<${g}, ${Pe}>; const workgroup_size = ${Pe}u; ${U.declareVariables(...Ee)} ${U.mainStart(Pe)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${c}(0); var squared_sum = ${c}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${c}(${A.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${g}(sum, squared_sum); workgroupBarrier(); for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { if (local_idx < currSize) { workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; } workgroupBarrier(); } if (local_idx == 0) { let sum_final = ${Nn("workgroup_shared[0][0]",d)} / f32(hight * ${d}); let squared_sum_final = ${Nn("workgroup_shared[0][1]",d)} / f32(hight * ${d}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:T,dataType:1}],dispatchGroup:{x:m},programUniforms:C}),getShaderSource:z},{inputs:[t,r,n],outputs:[-1]})[0]},Hu=(e,t,r)=>{let n=t[0].dims,i=n,a=2,s=n[0],u=n[1],d=ke.sizeFromDimension(n,a),c=_r(d),g=ke.size(i)/c,m=Wa(e,t[0],t[1],t[2],s,d,u,r.epsilon),l=[s,u,d/c],T=[s,u],x=["type","none"],C=z=>{let U=Qe("x",t[0].dataType,l.length,c),A=Qe("scale_shift",1,T.length,2),ee=qt("output",t[0].dataType,l.length,c),te=[U,A,ee];return` ${z.registerUniform("output_size","u32").declareVariables(...te)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${ee.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${A.getByIndices("vec2(batch, channel)")}; let value = ${U.getByOffset("global_idx")} * ${ee.type.value}(scale_shift.x) + ${ee.type.value}(scale_shift.y); ${ee.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...kt(l,T,l)]}),getShaderSource:C},{inputs:[t[0],m]})},Ku=(e,t,r)=>{let n=t[0].dims,i=n,a=n[0],s=n[n.length-1],u=ke.sizeFromDimension(n,1)/s,d=_r(s),c=ke.size(i)/d,g=[{type:12,data:u},{type:12,data:Math.floor(s/d)}],m=["type","type"],l=[0,n.length-1];for(let z=0;z{let U=fr(t[0].dataType),A=d===1?"vec2f":`mat${d}x2f`,ee=Ee=>{let Pe=Ee===0?"x":"y",Ye=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${U}(${Ye}(scale.${Pe}))`;case 2:return`vec2<${U}>(${Ye}(scale[0].${Pe}, scale[1].${Pe}))`;case 4:return`vec4<${U}>(${Ye}(scale[0].${Pe}, scale[1].${Pe}, scale[2].${Pe}, scale[3].${Pe}))`;default:throw new Error(`Not supported compoents ${d}`)}},te=Qe("input",t[0].dataType,t[0].dims,d),ie=qt("output",t[0].dataType,i,d);return` @group(0) @binding(0) var input : array<${te.type.storage}>; @group(0) @binding(1) var scale_input : array<${A}>; @group(0) @binding(2) var output : array<${ie.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${z.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${ee(0)}, ${ee(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:C},{inputs:[t[0],x]})},Xu=(e,t)=>{t.format==="NHWC"?Ku(e,e.inputs,t):Hu(e,e.inputs,t)}}),Qu,Yu,Zu,Jd=j(()=>{Yt(),Kt(),pr(),Qu=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Yu=(e,t,r)=>{let n=t.simplified,i=e[0].dims,a=e[1],s=!n&&e[2],u=i,d=ke.normalizeAxis(t.axis,i.length),c=ke.sizeToDimension(i,d),g=ke.sizeFromDimension(i,d),m=ke.size(a.dims),l=s?ke.size(s.dims):0;if(m!==g||s&&l!==g)throw new Error(`Size of X.shape()[axis:] == ${g}. Size of scale and bias (if provided) must match this. Got scale size of ${m} and bias size of ${l}`);let T=[];for(let ie=0;ie1,A=r>2,ee=ie=>{let Ee=fr(e[0].dataType),Pe=[Qe("x",e[0].dataType,e[0].dims,x),Qe("scale",a.dataType,a.dims,x)];s&&Pe.push(Qe("bias",s.dataType,s.dims,x)),Pe.push(qt("output",e[0].dataType,u,x)),U&&Pe.push(qt("mean_data_output",1,T)),A&&Pe.push(qt("inv_std_output",1,T));let Ye=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${ie.registerUniforms(Ye).declareVariables(...Pe)} ${ie.mainStart()} ${ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${ns("f32",x)}; var mean_square_vector = ${ns("f32",x)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Qn(Ee,x,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Nn("mean_vector",x)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Nn("mean_square_vector",x)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Qn(Ee,x,"x[j + offset]")}; let f32scale = ${Qn(Ee,x,"scale[j]")}; output[j + offset] = ${Pe[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${s?`+ ${Qn(Ee,x,"bias[j]")}`:""} ); } ${U?"mean_data_output[global_idx] = mean":""}; ${A?"inv_std_output[global_idx] = inv_std_dev":""}; }`},te=[{dims:u,dataType:e[0].dataType}];return U&&te.push({dims:T,dataType:1}),A&&te.push({dims:T,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${x};${r};${n}`,inputDependencies:C},getRunData:()=>({outputs:te,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:z}),getShaderSource:ee}},Zu=(e,t)=>{Qu(e.inputs),e.compute(Yu(e.inputs,t,e.outputCount))}}),Ju,ec,Ga,ed,td,tc=j(()=>{Yt(),Kt(),Pr(),pr(),Ju=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,s=e[1];if(!ke.areEqual(s.dims,[t.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(ke.size(u)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,c=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(ke.size(d)!==c)throw new Error("zeroPoints input size error.")}},ec=(e,t)=>{let r=e[0].dims,n=r.length,i=r[n-2],a=t.k,s=t.n,u=r.slice(0,n-2),d=ke.size(u),c=e[1].dims[2]/4,g=e[0].dataType,m=_r(t.k),l=_r(c),T=_r(s),x=u.concat([i,s]),C=i>1&&s/T%2===0?2:1,z=ke.size(x)/T/C,U=64,A=[],ee=[d,i,a/m],te=ke.convertShape(e[1].dims).slice();te.splice(-1,1,c/l),A.push(...kt(ee)),A.push(...kt(te)),A.push(...kt(e[2].dims)),e.length===4&&A.push(...kt(ke.convertShape(e[3].dims)));let ie=[d,i,s/T];A.push(...kt(ie));let Ee=Pe=>{let Ye=ee.length,Ft=Qe("a",e[0].dataType,Ye,m),Bt=Qe("b",12,te.length,l),ar=Qe("scales",e[2].dataType,e[2].dims.length),nr=[Ft,Bt,ar],Ht=e.length===4?Qe("zero_points",12,e[3].dims.length):void 0;Ht&&nr.push(Ht);let kr=ie.length,jr=qt("output",e[0].dataType,kr,T),hr=fr(e[0].dataType),Fr=(()=>{switch(m){case 1:return`array<${hr}, 8>`;case 2:return`mat4x2<${hr}>`;case 4:return`mat2x4<${hr}>`;default:throw new Error(`${m}-component is not supported.`)}})(),Gt=()=>{let qe=` // reuse a data var input_offset = ${Ft.indicesToOffset(`${Ft.type.indices}(batch, row, word_offset)`)}; var a_data: ${Fr}; for (var j: u32 = 0; j < ${8/m}; j++) { a_data[j] = ${Ft.getByOffset("input_offset")}; input_offset++; } `;for(let vt=0;vt> 4) & b_mask); b_quantized_values = ${Fr}(${Array.from({length:4},(rr,Br)=>`${hr}(b_value_lower[${Br}]), ${hr}(b_value_upper[${Br}])`).join(", ")}); b_dequantized_values = ${m===1?`${Fr}(${Array.from({length:8},(rr,Br)=>`(b_quantized_values[${Br}] - ${Ht?`zero_point${vt}`:"zero_point"}) * scale${vt}`).join(", ")});`:`(b_quantized_values - ${Fr}(${Array(8).fill(`${Ht?`zero_point${vt}`:"zero_point"}`).join(",")})) * scale${vt};`}; workgroup_shared[local_id.x * ${C} + ${Math.floor(vt/T)}]${T>1?`[${vt%T}]`:""} += ${Array.from({length:8/m},(rr,Br)=>`${m===1?`a_data[${Br}] * b_dequantized_values[${Br}]`:`dot(a_data[${Br}], b_dequantized_values[${Br}])`}`).join(" + ")}; `;return qe},Qt=()=>{let qe=` var col_index = col * ${T}; ${Ht?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${hr}(8);`} `;for(let vt=0;vt> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${Ht.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${vt} = ${hr}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return qe},xr=()=>{let qe=`col_index = col * ${T};`;for(let vt=0;vt; var b_value_upper: vec4; var b_quantized_values: ${Fr}; var b_dequantized_values: ${Fr};`,qe};return` var workgroup_shared: array<${jr.type.value}, ${C*U}>; ${Pe.declareVariables(...nr,jr)} ${Pe.mainStart([U,1,1])} let output_indices = ${jr.offsetToIndices(`(global_idx / ${U}) * ${C}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${U}) { //process one block var word_offset: u32 = block * ${t.blockSize/m}; ${Qt()} for (var word: u32 = 0; word < ${c}; word += ${l}) { ${xr()} for (var i: u32 = 0; i < ${l}; i++) { ${Gt()} word_offset += ${8/m}; } } } workgroupBarrier(); if (local_id.x < ${C}) { var output_value: ${jr.type.value} = ${jr.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${U}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${C}; } ${jr.setByIndices(`${jr.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${m};${l};${T};${C};${U}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:x,dataType:g}],dispatchGroup:{x:z},programUniforms:A}),getShaderSource:Ee}},Ga=(e,t)=>{let r=e[0].dims,n=r.length,i=r[n-2],a=t.k,s=t.n,u=r.slice(0,n-2),d=ke.size(u),c=e[1].dims[2]/4,g=e[0].dataType,m=_r(t.k),l=_r(c),T=u.concat([i,s]),x=128,C=s%8===0?8:s%4===0?4:1,z=x/C,U=z*l*8,A=U/m,ee=U/t.blockSize,te=ke.size(T)/C,ie=[],Ee=[d,i,a/m],Pe=ke.convertShape(e[1].dims).slice();Pe.splice(-1,1,c/l),ie.push(...kt(Ee)),ie.push(...kt(Pe)),ie.push(...kt(e[2].dims)),e.length===4&&ie.push(...kt(ke.convertShape(e[3].dims)));let Ye=[d,i,s];ie.push(...kt(Ye));let Ft=Bt=>{let ar=Ee.length,nr=Qe("a",e[0].dataType,ar,m),Ht=Qe("b",12,Pe.length,l),kr=Qe("scales",e[2].dataType,e[2].dims.length),jr=[nr,Ht,kr],hr=e.length===4?Qe("zero_points",12,e[3].dims.length):void 0;hr&&jr.push(hr);let Fr=Ye.length,Gt=qt("output",e[0].dataType,Fr),Qt=fr(e[0].dataType),xr=()=>{switch(m){case 1:return` let a_data0 = vec4<${Qt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Qt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${Qt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Qt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${m}-component is not supported.`)}};return` var sub_a: array<${nr.type.value}, ${A}>; var inter_results: array, ${C}>; ${Bt.declareVariables(...jr,Gt)} ${Bt.mainStart([z,C,1])} let output_indices = ${Gt.offsetToIndices(`workgroup_index * ${C}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let n_blocks_per_col = uniforms.b_shape[1]; let num_tiles = (n_blocks_per_col - 1) / ${ee} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${A}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${A}; a_offset += ${x}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${nr.getByIndices(`${nr.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${nr.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${ee} + local_id.x; ${hr?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${hr.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Qt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Qt}(8);`} let scale = ${kr.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${Ht.getByIndices(`${Ht.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/m}; for (var i: u32 = 0; i < ${l}; i++) { ${xr()} let b_value = ${l===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${Qt}>(${Array.from({length:4},(qe,vt)=>`${Qt}(b_value_lower[${vt}]), ${Qt}(b_value_upper[${vt}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Qt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(qe,vt)=>`${`dot(a_data${vt}, b_dequantized_values[${vt}])`}`).join(" + ")}; word_offset += ${8/m}; } workgroupBarrier(); } if (local_idx < ${C}) { var output_value: ${Gt.type.value} = ${Gt.type.value}(0); for (var b = 0u; b < ${z}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${Gt.setByIndices(`${Gt.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${m};${l};${z};${C}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:T,dataType:g}],dispatchGroup:{x:te},programUniforms:ie}),getShaderSource:Ft}},ed=(e,t)=>{Ju(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Ga(e.inputs,t)):e.compute(ec(e.inputs,t))},td=e=>or(e)}),rd,nd,sd,id,ad,od,ld,ud,dd,rc=j(()=>{Yt(),Kt(),pr(),rd=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].")}},nd=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Wt("uniforms.pads",i,r)}; if (k < 0) { break; } if (k >= i32(${Wt("uniforms.x_shape",i,t)})) { break; } offset += k * i32(${Wt("uniforms.x_strides",i,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `},sd=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Wt("uniforms.pads",i,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Wt("uniforms.x_shape",i,t)}) - 1); k = k % _2n_1; if(k >= i32(${Wt("uniforms.x_shape",i,t)})) { k = _2n_1 - k; } } offset += k * i32(${Wt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},id=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Wt("uniforms.pads",i,r)}; if (k < 0) { k = 0; } if (k >= i32(${Wt("uniforms.x_shape",i,t)})) { k = i32(${Wt("uniforms.x_shape",i,t)}) - 1; } offset += k * i32(${Wt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},ad=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Wt("uniforms.pads",i,r)}; if (k < 0) { k += i32(${Wt("uniforms.x_shape",i,t)}]); } if (k >= i32(${Wt("uniforms.x_shape",i,t)})) { k -= i32(${Wt("uniforms.x_shape",i,t)}); } offset += k * i32(${Wt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},od=(e,t,r)=>{switch(r.mode){case 0:return nd(e,t,r.pads.length);case 1:return sd(e,t,r.pads.length);case 2:return id(e,t,r.pads.length);case 3:return ad(e,t,r.pads.length);default:throw new Error("Invalid mode")}},ld=(e,t)=>{let r=ke.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=ke.size(r),a=[{type:12,data:i},{type:6,data:t.pads}],s=e.length>=3&&e[2].data;t.mode===0&&a.push({type:s?e[2].dataType:1,data:t.value}),a.push(...kt(e[0].dims,r));let u=["rank"],d=c=>{let g=qt("output",e[0].dataType,r.length),m=Qe("x",e[0].dataType,n.length),l=m.type.value,T=od(g,n.length,t),x=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&x.push({name:"constant_value",type:s?l:"f32"}),` ${c.registerUniforms(x).declareVariables(m,g)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${g.offsetToIndices("global_idx")}; var value = ${l}(0); ${T} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${s}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ke.size(r)/64)},programUniforms:a}),getShaderSource:d}},ud=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;da[Number(d)]=Number(u));let s=[];return a.forEach(u=>s.push(u)),{mode:t.mode,value:n,pads:s}}else return t},dd=(e,t)=>{rd(e.inputs);let r=ud(e.inputs,t);e.compute(ld(e.inputs,r),{inputs:[0]})}}),Ws,qa,Ha,Ka,Xa,cd,pd,Qa,Ya,hd,fd,Za,md,_d,gd,cr,wd,sn,ln,_n=j(()=>{Pt(),Yt(),Kt(),pr(),Ws=e=>{if(k.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},qa=(e,t,r)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),u=t.strides.slice(),d=a?t.dilations.slice():[],c=t.pads.slice();tn.adjustPoolAttributes(r,i,s,u,d,c);let g=tn.computePoolOutputShape(r,i,u,d,s,c,t.autoPad),m=Object.assign({},t);a?Object.assign(m,{kernelShape:s,strides:u,pads:c,dilations:d,cacheKey:t.cacheKey}):Object.assign(m,{kernelShape:s,strides:u,pads:c,cacheKey:t.cacheKey});let l=g.slice();return l.push(l.splice(1,1)[0]),[m,n?l:g]},Ha=(e,t)=>{let r=t.format==="NHWC",n=ke.size(e),i=ke.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:i}],s=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],c=t.pads[t.pads.length/2-1],g=t.pads[t.pads.length-1],m=!!(c+g);a.push({type:12,data:u},{type:12,data:d},{type:12,data:c},{type:12,data:g}),s.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(t.kernelShape.length===2){let T=t.kernelShape[t.kernelShape.length-2],x=t.strides[t.strides.length-2],C=t.pads[t.pads.length/2-2],z=t.pads[t.pads.length-2];l=!!(C+z),a.push({type:12,data:T},{type:12,data:x},{type:12,data:C},{type:12,data:z}),s.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,s,!0,m,l]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=ke.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),s.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((c,g)=>c+g);return[a,s,!!d,!1,!1]}},Ka=(e,t,r,n,i,a,s,u,d,c,g,m)=>{let l=i.format==="NHWC",T=t.type.value,x=qt("output",t.type.tensor,n);if(i.kernelShape.length<=2){let C="",z="",U="",A=r-(l?2:1);if(g?C=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${A}] = indices[${A}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${A}] < 0 || xIndices[${A}] >= uniforms.x_shape[${A}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:C=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${A}] = indices[${A}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`,i.kernelShape.length===2){let ee=r-(l?3:2);m?z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ee}] = indices[${ee}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${ee}] < 0 || xIndices[${ee}] >= uniforms.x_shape[${ee}]) { pad += i32(uniforms.kw); continue; } `:z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ee}] = indices[${ee}] * uniforms.sh - uniforms.phStart + j; `,U=` } `}return` ${e.registerUniforms(d).declareVariables(t,x)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${x.offsetToIndices("global_idx")}; var xIndices = ${x.offsetToIndices("global_idx")}; var value = ${T}(${u}); var pad = 0; ${z} ${C} ${U} ${s} output[global_idx] = value; }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let C=i.kernelShape.length,z=i.pads.length,U="";return c?U=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:U=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} `,` ${e.registerUniforms(d).declareVariables(t,x)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${x.offsetToIndices("global_idx")}; var xIndices = ${x.offsetToIndices("global_idx")}; var offsets: array; var value = ${T}(${u}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${C-1}u; j++) { offsets[j] = offset / ${Wt("uniforms.kernelStrides","j",C)}; offset -= offsets[j] * ${Wt("uniforms.kernelStrides","j",C)}; } offsets[${C-1}] = offset; isPad = false; for (var j = ${r-C}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${Wt("uniforms.strides",`j - ${r-C}u`,C)} + offsets[j - ${r-C}u] - ${Wt("uniforms.pads","j - 2u",z)}; ${U} } ${s} output[global_idx] = value; }`}},Xa=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,cd=e=>`${Xa(e)};${e.countIncludePad}`,pd=e=>`${Xa(e)};${e.storageOrder};${e.dilations}`,Qa=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Ya=(e,t,r,n)=>{let[i,a]=qa(t,n,r),s=Qe("x",t.dataType,t.dims.length),u=s.type.value,d="value += x_val;",c="";i.countIncludePad?c+=`value /= ${u}(uniforms.kernelSize);`:c+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[g,m,l,T,x]=Ha(a,i);g.push(...kt(t.dims,a));let C=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${l};${T};${x}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ke.size(a)/64)},programUniforms:g}),getShaderSource:z=>Ka(z,s,t.dims.length,a.length,i,d,c,0,m,l,T,x)}},hd=e=>{let t=e.count_include_pad!==0,r=Qa(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:cd(n)}},fd=(e,t)=>{Ws(e.inputs),e.compute(Ya("AveragePool",e.inputs[0],!1,t))},Za={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},md=e=>{let t=e.format;return{format:t,...Za,cacheKey:t}},_d=(e,t)=>{Ws(e.inputs),e.compute(Ya("GlobalAveragePool",e.inputs[0],!0,t))},gd=(e,t,r,n)=>{let[i,a]=qa(t,n,r),s=` value = max(x_val, value); `,u="",d=Qe("x",t.dataType,t.dims.length),c=["rank"],[g,m,l,T,x]=Ha(a,i);return g.push(...kt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${l};${T};${x}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ke.size(a)/64)},programUniforms:g}),getShaderSource:C=>Ka(C,d,t.dims.length,a.length,i,s,u,t.dataType===10?-65504:-1e5,m,l,T,x)}},cr=(e,t)=>{Ws(e.inputs),e.compute(gd("MaxPool",e.inputs[0],!1,t))},wd=e=>{let t=e.storage_order,r=e.dilations,n=Qa(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:r,...n,cacheKey:""};return{...i,cacheKey:pd(i)}},sn=e=>{let t=e.format;return{format:t,...Za,cacheKey:t}},ln=(e,t)=>{Ws(e.inputs),e.compute(gd("GlobalMaxPool",e.inputs[0],!0,t))}}),is,nc,yd,bd,f=j(()=>{Yt(),Kt(),Pr(),pr(),is=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((i,a)=>a===t.axis||i===e[0].dims[a]).reduce((i,a)=>i&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},nc=(e,t)=>{let r=ke.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,a=e[0].dims,s=e[1].dataType,u=ke.size(a),d=n===3||n===2,c=d?[Math.ceil(ke.size(e[0].dims)/4)]:e[0].dims,g=e[1].dims,m=e.length>2?e[2]:void 0,l=m?d?[Math.ceil(ke.size(m.dims)/4)]:m.dims:void 0,T=g.length===0||g.length===1&&g[0]===1,x=T===!1&&g.length===1,C=_r(u),z=T&&(!d||C===4),U=z?C:1,A=z&&!d?C:1,ee=Qe("input",d?12:n,c.length,A),te=Qe("scale",s,g.length),ie=m?Qe("zero_point",d?12:n,l.length):void 0,Ee=qt("output",s,a.length,U),Pe=[ee,te];ie&&Pe.push(ie);let Ye=[c,g];m&&Ye.push(l);let Ft=[{type:12,data:u/U},{type:12,data:r},{type:12,data:t.blockSize},...kt(...Ye,a)],Bt=ar=>{let nr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${ar.registerUniforms(nr).declareVariables(...Pe,Ee)} ${ar.mainStart()} ${ar.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${Ee.offsetToIndices("global_idx")}; // Set input x ${d?` let input = ${ee.getByOffset("global_idx / 4")}; let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${U===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ee.getByOffset("global_idx")};`}; // Set scale input ${T?`let scale_value= ${te.getByOffset("0")}`:x?` let scale_index = ${Ee.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${te.getByOffset("scale_index")};`:` var scale_indices: ${te.type.indices} = output_indices; let index = ${te.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${te.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${te.getByIndices("scale_indices")};`}; // Set zero-point input ${ie?T?d?` let zero_point_input = ${ie.getByOffset("0")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${ie.getByOffset("0")}`:x?d?` let zero_point_index = ${Ee.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${ie.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${Ee.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${ie.getByOffset("zero_point_index")};`:d?` let zero_point_offset = ${te.indicesToOffset("scale_indices")}; let zero_point_input = ${ie.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${ie.getByIndices("scale_indices")};`:`let zero_point_value = ${d?i?"i32":"u32":ee.type.value}(0);`}; // Compute and write output ${Ee.setByOffset("global_idx",`${Ee.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:ie?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Bt,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(u/U/64),y:1,z:1},programUniforms:Ft})}},yd=(e,t)=>{is(e.inputs,t),e.compute(nc(e.inputs,t))},bd=e=>or({axis:e.axis,blockSize:e.blockSize})}),b,R,Te,Ue=j(()=>{Pt(),Yt(),pr(),b=(e,t,r)=>{let n=e===t,i=et&&r>0;if(n||i||a)throw new Error("Range these inputs' contents are invalid.")},R=(e,t,r,n)=>{let i=Math.abs(Math.ceil((t-e)/r)),a=[i],s=i,u=[{type:12,data:s},{type:n,data:e},{type:n,data:r},...kt(a)],d=c=>{let g=qt("output",n,a.length),m=g.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:m},{name:"delta",type:m}];return` ${c.registerUniforms(l).declareVariables(g)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${m}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},Te=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&&b(t,r,n),e.compute(R(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),Le,pt,Et,Vt,tr,Ar,Dr,yr,ir,Ir,$r,gr,Lr,Tn,un,Gr,Xr,Qr,gn,as=j(()=>{Yt(),Kt(),Pr(),pr(),Le=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},pt=(e,t,r)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((i,a)=>n[i]=e[a]),n},Et=(e,t,r,n,i,a)=>{let[s,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(s>0&&e.length>s&&e[s].dims.length>0)e[s].getFloat32Array().forEach(g=>a.push(g));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach(g=>n.push(g)),n.length!==0&&n.length!==c&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Le(n,t),t.axes.length>0&&pt(n,t.axes,c).forEach((g,m)=>n[m]=g)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(g=>i.push(Number(g))),i.length!==0&&i.length!==c&&r>=18&&i.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof i<"u"&&n.length>0&&i.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Vt=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${t}(roiStart) * ${t}(lengthOriginal - 1) + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / ${t}(lengthResized - 1); } else { return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",tr=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Ar=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),i=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,s)=>{n[a]=i[s],n[s+r]=i[t.length+s]}),n):i},Dr=(e,t,r,n)=>{let i=[];if(r.length>0)if(n.length>0){if(e.forEach(a=>i.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,s)=>i[a]=r[s])}else r.forEach(a=>i.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((a,s)=>Math.round(a*t[s]))}return i},yr=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.axes.forEach(a=>i[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),i.forEach((a,s)=>i[s]=Math.round(a*t[s]))),i},ir=(e,t,r,n,i)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${Wt("uniforms.scales","i",n)}; var roi_low = ${Wt("uniforms.roi","i",i)}; var roi_hi = ${Wt("uniforms.roi",`i + ${t.length}`,i)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Wt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Wt("uniforms.output_shape","i",r.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,Ir=(e,t,r,n,i,a,s)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${Wt("uniforms.scales","i",i)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Wt("uniforms.roi","i",a)}; var roi_hi = ${Wt("uniforms.roi",`i + ${r.length}`,a)}; var input_shape_i = ${Wt("uniforms.input_shape","i",r.length)}; var output_shape_i = ${Wt("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${s} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,$r=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${Wt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,gr=(e,t,r,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",Lr=(e,t,r,n,i)=>{let[a,s,u,d]=r.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",s,`max(0, min(row, ${r[s]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; ${gr(e,d,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${c} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${c} = originalIndices[${s}]; var col:${c} = originalIndices[${u}]; ${n?`if (row < 0 || row > (${r[s]} - 1) || col < 0 || col > (${r[u]} - 1)) { return ${i}; }`:""}; row = max(0, min(row, ${r[s]} - 1)); col = max(0, min(col, ${r[u]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${r.length>2?`u32(originalIndices[${d}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${c} = getInputValue(batch, channel, row1, col1); var x12: ${c} = getInputValue(batch, channel, row1, col2); var x21: ${c} = getInputValue(batch, channel, row2, col1); var x22: ${c} = getInputValue(batch, channel, row2, col2); var dx1: ${c} = abs(row - ${c}(row1)); var dx2: ${c} = abs(${c}(row2) - row); var dy1: ${c} = abs(col - ${c}(col1)); var dy2: ${c} = abs(${c}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},Tn=(e,t,r,n,i,a,s,u,d,c)=>{let g=r.length===2,[m,l]=g?[0,1]:[2,3],T=e.type.value,x=C=>{let z=C===m?"row":"col";return` fn ${z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${T} { var output_index = ${t.indicesGet("output_indices",C)}; var originalIdx: ${T} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[C]}, ${n[C]}, ${r[C]}, ${a[C]}, ${a[C]} + ${r.length}); var fractOriginalIdx: ${T} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${u} && (originalIdx < 0 || originalIdx > (${r[C]} - 1))) { return ${d}; } var data: array<${T}, 4> = array<${T}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${z}: ${T} = originalIdx + ${T}(i); if (${z} < 0 || ${z} >= ${r[C]}) { ${c?`coefs[i + 1] = 0.0; continue;`:u?`return ${d};`:`${z} = max(0, min(${z}, ${r[C]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",C,`u32(${z})`)}; data[i + 1] = ${C===m?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${x(m)}; ${x(l)}; fn getCubicInterpolationCoefs(s: ${T}) -> array<${T}, 4> { var absS = abs(s); var coeffs: array<${T}, 4> = array<${T}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${T} = 1.0 - absS; var twoMinusAbsS: ${T} = 2.0 - absS; var onePlusAbsS: ${T} = 1.0 + absS; coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s}; coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1; coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s}; return coeffs; } fn cubicInterpolation1D(x: array<${T}, 4>, coefs: array<${T}, 4>) -> ${T} { var coefsSum: ${T} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${T} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},un=(e,t,r,n,i)=>{let[a,s,u,d,c]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],g=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${g} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",s,`max(0, min(depth, ${r[s]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(width, ${r[d]} - 1))`)}; ${gr(e,c,a,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${g} = originalIndices[${s}]; var height:${g} = originalIndices[${u}]; var width:${g} = originalIndices[${d}]; ${n?`if (depth < 0 || depth > (${r[s]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { return ${i}; }`:""}; depth = max(0, min(depth, ${r[s]} - 1)); height = max(0, min(height, ${r[u]} - 1)); width = max(0, min(width, ${r[d]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${r.length>3?`u32(originalIndices[${c}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${g} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${g} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${g} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${g} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${g} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${g} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${g} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${g} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${g} = abs(depth - ${g}(depth1)); var dx2: ${g} = abs(${g}(depth2) - depth); var dy1: ${g} = abs(height - ${g}(height1)); var dy2: ${g} = abs(${g}(height2) - height); var dz1: ${g} = abs(width - ${g}(width1)); var dz2: ${g} = abs(${g}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},Gr=(e,t,r,n,i,a)=>{let s=e.dims,u=Ar(a,t.axes,s.length),d=Dr(s,n,i,t.axes),c=n.slice();n.length===0&&(c=s.map((A,ee)=>A===0?1:d[ee]/A),t.keepAspectRatioPolicy!=="stretch"&&(d=yr(s,c,t)));let g=qt("output",e.dataType,d.length),m=Qe("input",e.dataType,s.length),l=ke.size(d),T=s.length===d.length&&s.every((A,ee)=>A===d[ee]),x=t.coordinateTransformMode==="tf_crop_and_resize",C=t.extrapolationValue,z=m.type.value,U=A=>` ${T?"":` ${Vt(t.coordinateTransformMode,z)}; ${(()=>{switch(t.mode){case"nearest":return` ${$r(m,s)}; ${tr(t.nearestMode,r,z)}; ${Ir(m,g,s,d,c.length,u.length,x)}; `;case"linear":return` ${ir(g,s,d,c.length,u.length)}; ${(()=>{if(s.length===2||s.length===4)return`${Lr(m,g,s,x,C)}`;if(s.length===3||s.length===5)return`${un(m,g,s,x,C)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(s.length===2||s.length===4)return`${Tn(m,g,s,d,c,u,t.cubicCoeffA,x,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${A.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",u.length).declareVariables(m,g)} ${A.mainStart()} ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${T?"output[global_idx] = input[global_idx];":` let output_indices = ${g.offsetToIndices("global_idx")}; var input_indices: ${m.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${m.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${s.length===2||s.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${c.length>0?c:""}|${i.length>0?i:""}|${u.length>0?u:""}|${T}|${s}`,inputDependencies:["rank"]},getShaderSource:U,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:c},{type:1,data:u},...kt(s,d)]})}},Xr=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Qr=(e,t)=>{let r=[],n=[],i=[],a=Xr(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Et(e.inputs,t,a,r,n,i),e.compute(Gr(e.inputs[0],t,a,r,n,i),{inputs:[0]})},gn=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,s=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return or({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:a,extrapolationValue:s,keepAspectRatioPolicy:u,mode:d,nearestMode:c})}}),hi,Ja,$c,Wn=j(()=>{Yt(),Kt(),Pr(),pr(),hi=(e,t)=>{let[r,n,i,a]=e,{numHeads:s,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!ke.areEqual(n.dims,[])&&!ke.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!ke.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&s===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],c=r.dims[r.dims.length-2],g=i.dims[0],m=ke.sizeFromDimension(r.dims,1)/c,l=u===0?i.dims[1]*2:m/s;if(u>l)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(c!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(l/2!==i.dims[1]&&u/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(c>g)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Ja=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:i,scale:a}=t,s=e[0].dims[0],u=ke.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],c=u/d,g=e[2].dims[1],m=i===0?g*2:c/n,l=new Array(s,d,c/m,m-g),T=ke.computeStrides(l),x=[{type:1,data:a},{type:12,data:l},{type:12,data:T},...e[0].dims.length===3?new Array({type:12,data:[u,c,m,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,m,d*m,1]}):[],...kt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],C=z=>{let U=Qe("input",e[0].dataType,e[0].dims.length),A=Qe("position_ids",e[1].dataType,e[1].dims.length),ee=Qe("cos_cache",e[2].dataType,e[2].dims.length),te=Qe("sin_cache",e[3].dataType,e[3].dims.length),ie=qt("output",e[0].dataType,e[0].dims.length);return z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:T.length},{name:"input_output_strides",type:"u32",length:T.length}]),` ${z.declareVariables(U,A,ee,te,ie)} ${z.mainStart(pn)} let half_rotary_emb_dim = uniforms.${ee.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${z.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${A.broadcastedIndicesToOffset("bsnh.xy",qt("",A.type.tensor,2))}; let position_id = u32(${A.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); let j = i + select(half_rotary_emb_dim, 1, ${r}); let re = ${U.getByOffset("i")} * ${ee.get("position_id","bsnh[3]")} - ${U.getByOffset("j")} * ${te.get("position_id","bsnh[3]")}; ${ie.setByOffset("i","re")} let im = ${U.getByOffset("i")} * ${te.get("position_id","bsnh[3]")} + ${U.getByOffset("j")} * ${ee.get("position_id","bsnh[3]")}; ${ie.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${ie.setByOffset("k",U.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:or({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:C,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ke.size(l)/pn)},programUniforms:x})}},$c=(e,t)=>{hi(e.inputs,t),e.compute(Ja(e.inputs,t))}}),Ms,sc,ic,kc=j(()=>{Yt(),Kt(),pr(),Ms=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let s=e[3];if(s.dims.length!==1)throw new Error("Beta must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let s=e[4];if(s.dims.length!==1)throw new Error("Bias must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},sc=(e,t,r,n)=>{let i=t.simplified,a=e[0].dims,s=ke.size(a),u=a,d=s,c=a.slice(-1)[0],g=n?a.slice(0,-1).concat(1):[],m=!i&&e.length>3,l=e.length>4,T=n&&r>1,x=n&&r>2,C=r>3,z=64,U=_r(c),A=[{type:12,data:d},{type:12,data:U},{type:12,data:c},{type:1,data:t.epsilon}],ee=ie=>{let Ee=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Pe=[Qe("x",e[0].dataType,e[0].dims,U),Qe("skip",e[1].dataType,e[1].dims,U),Qe("gamma",e[2].dataType,e[2].dims,U)];m&&Pe.push(Qe("beta",e[3].dataType,e[3].dims,U)),l&&Pe.push(Qe("bias",e[4].dataType,e[4].dims,U)),Pe.push(qt("output",e[0].dataType,u,U)),T&&Pe.push(qt("mean_output",1,g)),x&&Pe.push(qt("inv_std_output",1,g)),C&&Pe.push(qt("input_skip_bias_sum",e[0].dataType,u,U));let Ye=fr(e[0].dataType),Ft=fr(1,U);return` ${ie.registerUniforms(Ee).declareVariables(...Pe)} var sum_shared : array<${Ft}, ${z}>; var sum_squared_shared : array<${Ft}, ${z}>; ${ie.mainStart([z,1,1])} let ix = local_id.x; let iy = global_id.x / ${z}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${z}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${z-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${l?"bias[offset1d + i]":Ye+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${C?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Qn(Ye,U,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${z}; for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { reduce_size = curr_size + (reduce_size & 1); if (ix < curr_size) { sum_shared[ix] += sum_shared[ix + reduce_size]; sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; } workgroupBarrier(); } let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; let mean = ${Nn("sum",U)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Nn("square_sum",U)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); ${T?"mean_output[global_idx] = mean;":""} ${x?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${i?"":`- ${Ye}(mean)`}) * ${Ye}(inv_std_dev) * gamma[offset1d + i] ${m?"+ beta[offset1d + i]":""}; } }`},te=[{dims:u,dataType:e[0].dataType}];return r>1&&te.push({dims:g,dataType:1}),r>2&&te.push({dims:g,dataType:1}),r>3&&te.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${U};${T};${x};${C}`,inputDependencies:e.map((ie,Ee)=>"type")},getShaderSource:ee,getRunData:()=>({outputs:te,dispatchGroup:{x:Math.ceil(d/c)},programUniforms:A})}},ic=(e,t)=>{Ms(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(sc(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Md,vd,gp,Ec,wp,yp,bp,Mp,If=j(()=>{Yt(),Kt(),Pr(),pr(),Md=(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`)})},vd=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},gp=(e,t)=>{if(e.length>1){let r=vd(e,1),n=vd(e,2),i=vd(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),or({starts:r,ends:n,axes:i})}else return t},Ec=(e,t,r,n,i)=>{let a=e;return e<0&&(a+=r[n[t]]),i[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},wp=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${Wt("uniforms.input_shape","i",r.length)}; let steps_i = ${Wt("uniforms.steps","i",r.length)}; let signs_i = ${Wt("uniforms.signs","i",r.length)}; let starts_i = ${Wt("uniforms.starts","i",r.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,yp=(e,t)=>{let r=e[0].dims,n=ke.size(r),i=t.axes.length>0?ke.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=vd(e,4);a.forEach(U=>U!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let s=t.starts.map((U,A)=>Ec(U,A,r,i,a)),u=t.ends.map((U,A)=>Ec(U,A,r,i,a));if(i.length!==s.length||i.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let U=0;UMath.sign(U));a.forEach((U,A,ee)=>{if(U<0){let te=(u[A]-s[A])/U,ie=s[A],Ee=ie+te*a[A];s[A]=Ee,u[A]=ie,ee[A]=-U}});let c=r.slice(0);i.forEach((U,A)=>{c[U]=Math.ceil((u[U]-s[U])/a[U])});let g={dims:c,dataType:e[0].dataType},m=qt("output",e[0].dataType,c.length),l=Qe("input",e[0].dataType,e[0].dims.length),T=ke.size(c),x=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:a.length}],C=[{type:12,data:T},{type:12,data:s},{type:6,data:d},{type:12,data:a},...kt(e[0].dims,c)],z=U=>` ${U.registerUniforms(x).declareVariables(l,m)} ${wp(l,m,r)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${m.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${m.setByOffset("global_idx",l.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${s.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:z,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:C})}},bp=(e,t)=>{Md(e.inputs,t);let r=gp(e.inputs,t);e.compute(yp(e.inputs,r),{inputs:[0]})},Mp=e=>{let t=e.starts,r=e.ends,n=e.axes;return or({starts:t,ends:r,axes:n})}}),vp,xp,Tp,Cp,Ff=j(()=>{Yt(),Kt(),Pr(),jn(),pr(),vp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},xp=(e,t)=>{let r=e.inputs[0],n=r.dims,i=ke.size(n),a=64,s=n.length,u=ke.normalizeAxis(t.axis,s),d=uYe),g[u]=s-1,g[s-1]=u,c=e.compute(xn(r,g),{inputs:[r],outputs:[-1]})[0]):c=r;let m=c.dims,l=m[s-1],T=i/l,x=_r(l),C=l/x,z=(Pe,Ye)=>Ye===4?`max(max(${Pe}.x, ${Pe}.y), max(${Pe}.z, ${Pe}.w))`:Ye===2?`max(${Pe}.x, ${Pe}.y)`:Ye===3?`max(max(${Pe}.x, ${Pe}.y), ${Pe}.z)`:Pe,U=Qe("x",c.dataType,c.dims,x),A=qt("result",c.dataType,c.dims,x),ee=U.type.value,te=fr(c.dataType)==="f32"?`var threadMax = ${ee}(-3.402823e+38f);`:`var threadMax = ${ee}(-65504.0h);`,ie=Pe=>` var rowMaxShared : ${ee}; var rowSumShared : ${ee}; var threadShared : array<${ee}, ${a}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${ee} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${ee}) { let index = row * row_stride + col; result[index] = value; } ${Pe.registerUniform("packedCols","i32").declareVariables(U,A)} ${Pe.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${a}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${te} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${ee}(${z("threadShared[0]",x)}); } workgroupBarrier(); // find the rows sum var threadSum = ${ee}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; } threadShared[lindex] = threadSum; workgroupBarrier(); for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { if (lindex < currSize) { threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; } workgroupBarrier(); } if (lindex == 0) { rowSumShared = ${ee}(${Nn("threadShared[0]",x)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`,Ee=e.compute({name:"Softmax",shaderCache:{hint:`${x}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:c.dataType}],dispatchGroup:{x:T},programUniforms:[{type:6,data:C}]}),getShaderSource:ie},{inputs:[c],outputs:[d?-1:0]})[0];d&&e.compute(xn(Ee,g),{inputs:[Ee]})},Tp=(e,t)=>{vp(e.inputs),xp(e,t)},Cp=e=>or({axis:e.axis})}),Sc,$p,kp,Ep,Sp,Of=j(()=>{Yt(),Kt(),pr(),Sc=e=>Array.from(e.getBigInt64Array(),Number),$p=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Sc(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")},kp=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Sc(e[1]),i=kp(r,n),a=ke.size(i),s=e[0].dataType,u=Qe("input",s,r.length),d=qt("output",s,i.length),c=g=>` const inputShape = ${u.indices(...r)}; ${g.registerUniform("output_size","u32").declareVariables(u,d)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${d.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; for (var i = 0; i < ${r.length}; i++) { let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i; ${u.indicesSet("input_indices","i","input_dim_value")} } ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...kt(e[0].dims,i)]}),getShaderSource:c}},Sp=e=>{$p(e.inputs),e.compute(Ep(e.inputs),{inputs:[0]})}}),Pp,Ap,Ip,zf=j(()=>{Yt(),Kt(),pr(),Pp=(e,t,r,n,i)=>{let a=qt("output_data",i,r.length,4),s=Qe("a_data",t[1].dataType,t[1].dims.length,4),u=Qe("b_data",t[2].dataType,t[2].dims.length,4),d=Qe("c_data",t[0].dataType,t[0].dims.length,4),c,g=(m,l,T)=>`select(${l}, ${m}, ${T})`;if(!n)c=a.setByOffset("global_idx",g(s.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let m=(l,T,x="")=>{let C=`a_data[index_a${T}][component_a${T}]`,z=`b_data[index_b${T}][component_b${T}]`,U=`bool(c_data[index_c${T}] & (0xffu << (component_c${T} * 8)))`;return` let output_indices${T} = ${a.offsetToIndices(`global_idx * 4u + ${T}u`)}; let offset_a${T} = ${s.broadcastedIndicesToOffset(`output_indices${T}`,a)}; let offset_b${T} = ${u.broadcastedIndicesToOffset(`output_indices${T}`,a)}; let offset_c${T} = ${d.broadcastedIndicesToOffset(`output_indices${T}`,a)}; let index_a${T} = offset_a${T} / 4u; let index_b${T} = offset_b${T} / 4u; let index_c${T} = offset_c${T} / 4u; let component_a${T} = offset_a${T} % 4u; let component_b${T} = offset_b${T} % 4u; let component_c${T} = offset_c${T} % 4u; ${l}[${T}] = ${x}(${g(C,z,U)}); `};i===9?c=` var data = vec4(0); ${m("data",0,"u32")} ${m("data",1,"u32")} ${m("data",2,"u32")} ${m("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` ${m("output_data[global_idx]",0)} ${m("output_data[global_idx]",1)} ${m("output_data[global_idx]",2)} ${m("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(d,s,u,a)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${c} }`},Ap=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,i=e[1].dataType,a=!(ke.areEqual(t,r)&&ke.areEqual(r,n)),s=t,u=ke.size(t);if(a){let c=bn.calcShape(bn.calcShape(t,r,!1),n,!1);if(!c)throw new Error("Can't perform where op on the given tensors");s=c,u=ke.size(s)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Pp(c,e,s,a,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...kt(n,t,r,s)]})}},Ip=e=>{e.compute(Ap(e.inputs))}}),Fp,Df=j(()=>{Ro(),ri(),Ad(),Qo(),kl(),Id(),Fd(),Ld(),Ca(),jd(),yu(),Sa(),Ud(),Wd(),Eu(),Hd(),Kd(),Cc(),Yd(),Zd(),Jd(),Jl(),tc(),Na(),rc(),_n(),f(),Ue(),Bi(),as(),Wn(),kc(),If(),Ff(),Uu(),Of(),jn(),ra(),zf(),Fp=new Map([["Abs",[Gi]],["Acos",[Zo]],["Acosh",[Jo]],["Add",[Pl]],["ArgMax",[Bo,ji]],["ArgMin",[Ni,ji]],["Asin",[el]],["Asinh",[tl]],["Atan",[qi]],["Atanh",[rl]],["Attention",[Wo]],["AveragePool",[fd,hd]],["BatchNormalization",[Ho]],["BiasAdd",[Xo]],["BiasSplitGelu",[$l]],["Cast",[sl,nl]],["Ceil",[al]],["Clip",[Hi]],["Concat",[Nl,jl]],["Conv",[Ma,ya]],["ConvTranspose",[pu,bs]],["Cos",[ol]],["Cosh",[ll]],["CumSum",[hu,fu]],["DepthToSpace",[gu,wu]],["DequantizeLinear",[yd,bd]],["Div",[Al]],["Einsum",[Tu,Ea]],["Elu",[Ki,Ds]],["Equal",[sa]],["Erf",[ul]],["Exp",[Xi]],["Expand",[$u]],["FastGelu",[ku]],["Floor",[dl]],["FusedConv",[Ma,ya]],["Gather",[Oa,qd]],["GatherElements",[La,Fu]],["GatherBlockQuantized",[za,Au]],["Gelu",[cl]],["Gemm",[zr,Du]],["GlobalAveragePool",[_d,md]],["GlobalMaxPool",[ln,sn]],["Greater",[Ol]],["GreaterOrEqual",[aa]],["GroupQueryAttention",[qu]],["HardSigmoid",[_l,Zi]],["InstanceNormalization",[Xu]],["LayerNormalization",[Zu]],["LeakyRelu",[Qi,Ds]],["Less",[zl]],["LessOrEqual",[Dl]],["Log",[vl]],["MatMul",[wa]],["MatMulNBits",[ed,td]],["MaxPool",[cr,wd]],["Mul",[Il]],["MultiHeadAttention",[Bu,Ba]],["Neg",[hl]],["Not",[pl]],["Pad",[dd]],["Pow",[Fl]],["QuickGelu",[Tl,Ds]],["Range",[Te]],["Reciprocal",[Yi]],["ReduceMin",[zo]],["ReduceMean",[Oi]],["ReduceMax",[Oo]],["ReduceSum",[Do]],["ReduceProd",[Di]],["ReduceL1",[Io]],["ReduceL2",[Fo]],["ReduceLogSum",[Li]],["ReduceLogSumExp",[zi]],["ReduceSumSquare",[Lo]],["Relu",[fl]],["Resize",[Qr,gn]],["RotaryEmbedding",[$c]],["Sigmoid",[ml]],["Sin",[gl]],["Sinh",[si]],["Slice",[bp,Mp]],["SkipLayerNormalization",[ic]],["Split",[Qd,Vu]],["Sqrt",[wl]],["Softmax",[Tp,Cp]],["Sub",[ia]],["Tan",[yl]],["Tanh",[Ji]],["ThresholdedRelu",[Ml,Ds]],["Tile",[Sp]],["Transpose",[Sd,uo]],["Where",[Ip]]])}),Op,Lf=j(()=>{Pt(),_(),pr(),Op=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,i){je(e.programInfo.name);let a=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let c of t)u.push({binding:u.length,resource:{buffer:c.buffer}});for(let c of r)u.push({binding:u.length,resource:{buffer:c.buffer}});i&&u.push({binding:u.length,resource:i});let d=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:d,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}s.setPipeline(e.computePipeline),s.setBindGroup(0,d),s.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ve(e.programInfo.name)}dispose(){}build(e,t){je(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let i=ao(t,this.backend.device.limits),a=e.getShaderSource(i),s=`${n.join(` `)} ${i.additionalImplementations} ${a}`,u=r.createShaderModule({code:s,label:e.name});ae("verbose",()=>`[WebGPU] ${e.name} shader code: ${s}`);let d=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Ve(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&r<=i&&n<=i)return[t,r,n];let a=t*r*n,s=Math.ceil(Math.sqrt(a));if(s>i){if(s=Math.ceil(Math.cbrt(a)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}else return[s,s,1]}}}),zp,Dp,Lp,Bp,Bf=j(()=>{Pt(),Yt(),_(),Q(),Wr(),Df(),Lf(),zp=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{var i,a;let n=e.name;return(i=e.shaderCache)!=null&&i.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${zp(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Lp=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Bp=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};t.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&r.push("timestamp-query"),t.features.has("shader-f16")&&r.push("shader-f16"),this.device=await t.requestDevice(n),this.adapterInfo=new Lp(t.info||await t.requestAdapterInfo()),this.gpuDataManager=lr(this),this.programManager=new Op(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,rs(e.logLevel,!!e.debug),this.device.onuncapturederror=i=>{i.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${i.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;je(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=T);let C=Number(T-this.queryTimeBase),z=Number(x-this.queryTimeBase);if(!Number.isSafeInteger(C)||!Number.isSafeInteger(z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map(U=>({dims:U.dims,dataType:Sn(U.dataType)})),outputsMetadata:l.map(U=>({dims:U.dims,dataType:Sn(U.dataType)})),kernelId:s,kernelType:d,kernelName:c,programName:g,startTime:C,endTime:z});else{let U="";m.forEach((ee,te)=>{U+=`input[${te}]: [${ee.dims}] | ${Sn(ee.dataType)}, `});let A="";l.forEach((ee,te)=>{A+=`output[${te}]: [${ee.dims}] | ${Sn(ee.dataType)}, `}),console.log(`[profiling] kernel "${s}|${d}|${c}|${g}" ${U}${A}execution time: ${z-C} ns`)}Ke("GPU",`${g}::${T}::${x}`)}e.unmap(),this.pendingQueries.delete(e)}),Ve()}run(e,t,r,n,i,a){je(e.name);let s=[];for(let A=0;Aee):r;if(g.length!==u.length)throw new Error(`Output size ${g.length} must be equal to ${u.length}.`);let m=[],l=[];for(let A=0;A=a)throw new Error(`Invalid output index: ${g[A]}`);if(g[A]===-3)continue;let ee=g[A]===-1,te=g[A]===-2,ie=ee||te?i(u[A].dataType,u[A].dims):n(g[A],u[A].dataType,u[A].dims);if(m.push(ie),ie.data===0)continue;let Ee=this.gpuDataManager.get(ie.data);if(!Ee)throw new Error(`no GPU data for output: ${ie.data}`);if(ee&&this.temporaryData.push(Ee),te){let Pe=this.kernelPersistentData.get(this.currentKernelId);Pe||(Pe=[],this.kernelPersistentData.set(this.currentKernelId,Pe)),Pe.push(Ee)}l.push(Ee)}if(s.length!==t.length||l.length!==m.length){if(l.length===0)return Ve(e.name),m;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let T;if(c){let A=0,ee=[];c.forEach(Pe=>{let Ye=typeof Pe.data=="number"?[Pe.data]:Pe.data;if(Ye.length===0)return;let Ft=Pe.type===10?2:4,Bt,ar;Pe.type===10?(ar=Ye.length>4?16:Ye.length>2?8:Ye.length*Ft,Bt=Ye.length>4?16:Ft*Ye.length):(ar=Ye.length<=2?Ye.length*Ft:16,Bt=16),A=Math.ceil(A/ar)*ar,ee.push(A);let nr=Pe.type===10?8:4;A+=Ye.length>4?Math.ceil(Ye.length/nr)*Bt:Ye.length*Ft});let te=16;A=Math.ceil(A/te)*te;let ie=new ArrayBuffer(A);c.forEach((Pe,Ye)=>{let Ft=ee[Ye],Bt=typeof Pe.data=="number"?[Pe.data]:Pe.data;if(Pe.type===6)new Int32Array(ie,Ft,Bt.length).set(Bt);else if(Pe.type===12)new Uint32Array(ie,Ft,Bt.length).set(Bt);else if(Pe.type===10)new Uint16Array(ie,Ft,Bt.length).set(Bt);else if(Pe.type===1)new Float32Array(ie,Ft,Bt.length).set(Bt);else throw new Error(`Unsupported uniform type: ${Sn(Pe.type)}`)});let Ee=this.gpuDataManager.create(A,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ee.buffer,0,ie,0,A),this.gpuDataManager.release(Ee.id),T={offset:0,size:A,buffer:Ee.buffer}}let x=this.programManager.normalizeDispatchGroupSize(d),C=x[1]===1&&x[2]===1,z=Dp(e,t,C),U=this.programManager.getArtifact(z);if(U||(U=this.programManager.build(e,x),this.programManager.setArtifact(z,U),ae("info",()=>`[artifact] key: ${z}, programName: ${e.name}`)),c&&U.uniformVariablesInfo){if(c.length!==U.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${U.uniformVariablesInfo.length}, got ${c.length} in program "${U.programInfo.name}".`);for(let A=0;A`[ProgramManager] run "${e.name}" (key=${z}) with ${x[0]}x${x[1]}x${x[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let A={kernelId:this.currentKernelId,programName:U.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push(A),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(A)}return this.programManager.run(U,s,l,x,T),Ve(e.name),m}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,n){let i=Fp.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let i=n.kernelType,a=n.kernelName,s=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),ae("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),s(t,u[1]),0}catch(c){return r.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${c}`)),1}finally{d&&r.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${a}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),s=this.gpuDataManager.registerExternalBuffer(r,n,a);return i.set(t,[s,r]),s}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let n=await er(this,e,t);return F(n.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){ae("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){ae("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ae("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Rp,Pc,Ac,Ic,Np,jp,Rf=j(()=>{_(),Rp=1,Pc=()=>Rp++,Ac=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}destroy(){ae("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.every((r,n)=>r===t[n])}},Ic=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&this.tensorManager.releaseTensor(this.tensorWrapper)}async ensureTensor(e,t,r){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;r&&(this.activeUpload=new Uint8Array(await this.wrapper.read())),this.tensorManager.releaseTensor(this.wrapper)}let n=MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,!0,!0),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper){this.wrapper.write(e);return}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Np=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Pc();return this.tensorTrackersById.set(e,new Ic(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n){ae("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${n}}`);let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(t,r,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){ae("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,n){let i=Pc(),a=new Ac({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(i,new Ic(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,r,n,i){let a=this.backend.currentSessionId;for(let[d,c]of this.freeTensors.entries())if(c.sameTypeAndShape(e,t)){let g=this.freeTensors.splice(d,1)[0];return g.sessionId=a,g}let s=this.backend.currentContext;ae("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let u=await s.createTensor({dataType:e,shape:t,dimensions:t,usage:r,writable:n,readable:i});return new Ac({sessionId:a,context:s,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},jp=(...e)=>new Np(...e)}),Fc,Vp,Nf=j(()=>{Yt(),Er(),Q(),Rf(),_(),Fc=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Vp=class{constructor(e){this.tensorManager=jp(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,rs(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);r.delete(e),r.size===0&&this.sessionIdsByMLContext.delete(t)}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ae("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n){let i=Fc.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,r,n)}uploadTensor(e,t){if(!mr().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ae("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return F(r,t)}}registerMLTensor(e,t,r){let n=Fc.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,n,r);return ae("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${r}} -> {tensorId: ${i}}`),i}registerMLConstant(e,t,r,n,i,a){if(!a)throw new Error("External mounted files are not available.");let s=e;e.startsWith("./")&&(s=e.substring(2));let u=a.get(s);if(!u)throw new Error(`File with name ${s} not found in preloaded files.`);if(t+r>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let d=u.slice(t,t+r).buffer,c;switch(i.dataType){case"float32":c=new Float32Array(d);break;case"float16":c=new Uint16Array(d);break;case"int32":c=new Int32Array(d);break;case"uint32":c=new Uint32Array(d);break;case"int64":c=new BigInt64Array(d);break;case"uint64":c=new BigUint64Array(d);break;case"int8":c=new Int8Array(d);break;case"uint8":c=new Uint8Array(d);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return ae("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),n.constant(i,c)}flush(){}}}),Up={};P(Up,{init:()=>Gp});var ac,Wp,Gp,jf=j(()=>{Yt(),Bf(),_(),Kt(),Nf(),ac=class Af{constructor(t,r,n,i){this.module=t,this.dataType=r,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=ke.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=ke.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=ke.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=ke.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(ke.size(t)!==ke.size(this.dims))throw new Error("Invalid new shape");return new Af(this.module,this.dataType,this.data,t)}},Wp=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.HEAPU32,i=r>>>2;this.opKernelContext=n[i++];let a=n[i++];this.outputCount=n[i++],this.customDataOffset=n[i++],this.customDataSize=n[i++];let s=[];for(let u=0;utypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(u,d,c)=>new ac(this.module,d,this.output(u,c),c),a=(u,d)=>{let c=Bn(u,d);if(!c)throw new Error(`Unsupported data type: ${u}`);let g=c>0?this.backend.gpuDataManager.create(c).id:0;return new ac(this.module,u,g,d)};return this.backend.run(e,r,n,i,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),i=n>>2;this.module.HEAPU32[i++]=t.length;for(let a=0;a{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Bp;await a.initialize(r,n),i("webgpu",[a,s=>a.alloc(s),s=>a.free(s),(s,u,d,c=!1)=>{if(c)ae("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${u}, size=${d}`),a.memcpy(s,u);else{ae("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${u}, size=${d}`);let g=t.HEAPU8.subarray(s>>>0,(s>>>0)+d);a.upload(u,g)}},async(s,u,d)=>{ae("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${s}, dataOffset=${u}, size=${d}`),await a.download(s,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+d))},(s,u,d)=>a.createKernel(s,u,d,t.UTF8ToString(t._JsepGetNodeName(u))),s=>a.releaseKernel(s),(s,u,d,c)=>{ae("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${s}, contextDataOffset=${u}`);let g=new Wp(t,a,u);return a.computeKernel(s,g,c)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new Vp(r);i("webnn",[a,()=>a.reserveTensorId(),s=>a.releaseTensorId(s),async(s,u,d,c)=>a.ensureTensor(s,u,d,c),(s,u)=>{a.uploadTensor(s,u)},async(s,u)=>a.downloadTensor(s,u)])}}}),qp,Oc,zc,Gs,Hp,oc,Dc,Lc,Bc,Rc,Nc,jc,Kp=j(()=>{Kn(),es(),Yt(),Er(),cs(),As(),qp=(e,t)=>{mr()._OrtInit(e,t)!==0&&Ur("Can't initialize onnxruntime.")},Oc=async e=>{qp(e.wasm.numThreads,Dn(e.logLevel))},zc=async(e,t)=>{{let r=(jf(),B(Up)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",mr(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",mr(),e)}}},Gs=new Map,Hp=e=>{let t=mr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Ur("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},oc=e=>{let t=mr(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Dc=async(e,t)=>{var m,l,T;let r,n,i=mr();Array.isArray(e)?[r,n]=e:e.buffer===i.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=oc(e);let a=0,s=0,u=0,d=[],c=[],g=[];try{if([s,d]=Ps(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let ie=[];for(let Ee of t.externalData){let Pe=typeof Ee=="string"?Ee:Ee.path;ie.push(ts(typeof Ee=="string"?Ee:Ee.data).then(Ye=>{i.mountExternalData(Pe,Ye)}))}await Promise.all(ie)}for(let ie of(t==null?void 0:t.executionProviders)??[])if((typeof ie=="string"?ie:ie.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,i.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof ie!="string"){let Ee=ie,Pe=Ee==null?void 0:Ee.context,Ye=Ee==null?void 0:Ee.gpuDevice,Ft=Ee==null?void 0:Ee.deviceType,Bt=Ee==null?void 0:Ee.powerPreference;Pe?i.currentContext=Pe:Ye?i.currentContext=await navigator.ml.createContext(Ye):i.currentContext=await navigator.ml.createContext({deviceType:Ft,powerPreference:Bt})}else i.currentContext=await navigator.ml.createContext();break}a=await i._OrtCreateSession(r,n,s),a===0&&Ur("Can't create a session."),(m=i.jsepOnCreateSession)==null||m.call(i),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[x,C]=Hp(a),z=!!(t!=null&&t.enableGraphCapture),U=[],A=[],ee=[];for(let ie=0;ieie==="gpu-buffer"||ie==="ml-tensor")&&(u=i._OrtCreateBinding(a),u===0&&Ur("Can't create IO binding."),te={handle:u,outputPreferredLocations:ee,outputPreferredLocationsEncoded:ee.map(ie=>ms(ie))}),Gs.set(a,[a,c,g,te,z,!1]),[a,U,A]}catch(x){throw c.forEach(C=>i._OrtFree(C)),g.forEach(C=>i._OrtFree(C)),u!==0&&i._OrtReleaseBinding(u),a!==0&&i._OrtReleaseSession(a),x}finally{i._free(r),s!==0&&i._OrtReleaseSessionOptions(s),d.forEach(x=>i._free(x)),(T=i.unmountExternalData)==null||T.call(i)}},Lc=e=>{var d;let t=mr(),r=Gs.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,a,s,u]=r;s&&(u&&t._OrtClearBoundOutputs(s.handle),t._OrtReleaseBinding(s.handle)),(d=t.jsepOnReleaseSession)==null||d.call(t,e),i.forEach(c=>t._OrtFree(c)),a.forEach(c=>t._OrtFree(c)),t._OrtReleaseSession(n),Gs.delete(e)},Bc=(e,t,r,n,i,a=!1)=>{if(!e){t.push(0);return}let s=mr(),u=e[0],d=e[1],c=e[3],g,m;if(u==="string"&&(c==="gpu-buffer"||c==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&c!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(c==="gpu-buffer"){let x=e[2].gpuBuffer;m=Bn(Xn(u),d);let C=s.jsepRegisterBuffer;if(!C)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=C(n,i,x,m)}else if(c==="ml-tensor"){let x=e[2].mlTensor;m=Bn(Xn(u),d);let C=s.jsepRegisterMLTensor;if(!C)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=C(x,Xn(u),d)}else{let x=e[2];if(Array.isArray(x)){m=4*x.length,g=s._malloc(m),r.push(g);let C=g/4;for(let z=0;zs.HEAP32[x++]=z);let C=s._OrtCreateTensor(Xn(u),g,m,T,d.length,ms(c));C===0&&Ur(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(C)}finally{s.stackRestore(l)}},Rc=async(e,t,r,n,i,a)=>{var Bt,ar;let s=mr(),u=Gs.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=u[0],c=u[1],g=u[2],m=u[3],l=u[4],T=u[5],x=t.length,C=n.length,z=0,U=[],A=[],ee=[],te=[],ie=s.stackSave(),Ee=s.stackAlloc(x*4),Pe=s.stackAlloc(x*4),Ye=s.stackAlloc(C*4),Ft=s.stackAlloc(C*4);try{(Bt=s.jsepOnRunStart)==null||Bt.call(s,d),[z,U]=Cs(a);for(let Gt=0;Gtdn*vn,1);rr=Sn(an);let _i=m==null?void 0:m.outputPreferredLocations[n[Gt]];if(rr==="string"){if(_i==="gpu-buffer"||_i==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let dn=[],vn=Br/4;for(let Gn=0;Gn0){let dn=s.jsepGetBuffer;if(!dn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let vn=dn(Br),Gn=Bn(an,fn);if(Gn===void 0||!hs(rr))throw new Error(`Unsupported data type: ${rr}`);vt=!0,Fr.push([rr,En,{gpuBuffer:vn,download:s.jsepCreateDownloader(vn,Gn,rr),dispose:()=>{s._OrtReleaseTensor(Qt)}},"gpu-buffer"])}else if(_i==="ml-tensor"&&fn>0){let dn=s.jsepEnsureTensor;if(!dn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Bn(an,fn)===void 0||!fs(rr))throw new Error(`Unsupported data type: ${rr}`);let vn=await dn(Br,an,En,!1);vt=!0,Fr.push([rr,En,{mlTensor:vn,download:s.jsepCreateMLTensorDownloader(Br,rr),dispose:()=>{s.jsepReleaseTensorId(Br),s._OrtReleaseTensor(Qt)}},"ml-tensor"])}else{let dn=ps(rr),vn=new dn(fn);new Uint8Array(vn.buffer,vn.byteOffset,vn.byteLength).set(s.HEAPU8.subarray(Br,Br+vn.byteLength)),Fr.push([rr,En,vn,"cpu"])}}finally{s.stackRestore(xr),rr==="string"&&Br&&s._free(Br),vt||s._OrtReleaseTensor(Qt)}}return m&&!l&&(s._OrtClearBoundOutputs(m.handle),Gs.set(e,[d,c,g,m,l,!1])),Fr}finally{s.stackRestore(ie),A.forEach(nr=>s._OrtReleaseTensor(nr)),ee.forEach(nr=>s._OrtReleaseTensor(nr)),te.forEach(nr=>s._free(nr)),z!==0&&s._OrtReleaseRunOptions(z),U.forEach(nr=>s._free(nr))}},Nc=e=>{let t=mr(),r=Gs.get(e);if(!r)throw new Error("invalid session id");let n=r[0],i=t._OrtEndProfiling(n);i===0&&Ur("Can't get an profile file name."),t._OrtFree(i)},jc=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),qs,On,eo,xd,Td,lc,Vc,uc,fi,mi,Xp,Qp,Yp,Zp,Jp,eh,th,rh,nh=j(()=>{Pt(),Kp(),Er(),Ot(),qs=()=>!!k.wasm.proxy&&typeof document<"u",eo=!1,xd=!1,Td=!1,uc=new Map,fi=(e,t)=>{let r=uc.get(e);r?r.push(t):uc.set(e,[t])},mi=()=>{if(eo||!xd||Td||!On)throw new Error("worker not ready")},Xp=e=>{switch(e.data.type){case"init-wasm":eo=!1,e.data.err?(Td=!0,Vc[1](e.data.err)):(xd=!0,Vc[0]()),lc&&(URL.revokeObjectURL(lc),lc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=uc.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Qp=async()=>{if(!xd){if(eo)throw new Error("multiple calls to 'initWasm()' detected.");if(Td)throw new Error("previous call to 'initWasm()' failed.");if(eo=!0,qs())return new Promise((e,t)=>{On==null||On.terminate(),ft().then(([r,n])=>{try{On=n,On.onerror=a=>t(a),On.onmessage=Xp,Vc=[e,t];let i={type:"init-wasm",in:k};On.postMessage(i),lc=r}catch(i){t(i)}},t)});try{await Nr(k.wasm),await Oc(k),xd=!0}catch(e){throw Td=!0,e}finally{eo=!1}}},Yp=async e=>{if(qs())return mi(),new Promise((t,r)=>{fi("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:k}};On.postMessage(n)});await zc(k,e)},Zp=async e=>qs()?(mi(),new Promise((t,r)=>{fi("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};On.postMessage(n,[e.buffer])})):oc(e),Jp=async(e,t)=>{if(qs()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return mi(),new Promise((r,n)=>{fi("create",[r,n]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),On.postMessage(i,a)})}else return Dc(e,t)},eh=async e=>{if(qs())return mi(),new Promise((t,r)=>{fi("release",[t,r]);let n={type:"release",in:e};On.postMessage(n)});Lc(e)},th=async(e,t,r,n,i,a)=>{if(qs()){if(r.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return mi(),new Promise((s,u)=>{fi("run",[s,u]);let d=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:a}};On.postMessage(c,jc(d))})}else return Rc(e,t,r,n,i,a)},rh=async e=>{if(qs())return mi(),new Promise((t,r)=>{fi("end-profiling",[t,r]);let n={type:"end-profiling",in:e};On.postMessage(n)});Nc(e)}}),Uc,sh,ih,Vf=j(()=>{Pt(),nh(),Yt(),dr(),As(),Uc=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},sh=e=>{switch(e[3]){case"cpu":return new Z(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!hs(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:i}=e[2];return Z.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!fs(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:i}=e[2];return Z.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},ih=class{async fetchModelAndCopyToWasmMemory(e){return Zp(await ts(e))}async loadModel(e,t){je();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await Jp(r,t),Ve()}async dispose(){return eh(this.sessionId)}async run(e,t,r){je();let n=[],i=[];Object.entries(e).forEach(m=>{let l=m[0],T=m[1],x=this.inputNames.indexOf(l);if(x===-1)throw new Error(`invalid input '${l}'`);n.push(T),i.push(x)});let a=[],s=[];Object.entries(t).forEach(m=>{let l=m[0],T=m[1],x=this.outputNames.indexOf(l);if(x===-1)throw new Error(`invalid output '${l}'`);a.push(T),s.push(x)});let u=n.map((m,l)=>Uc(m,()=>`input "${this.inputNames[i[l]]}"`)),d=a.map((m,l)=>m?Uc(m,()=>`output "${this.outputNames[s[l]]}"`):null),c=await th(this.sessionId,i,u,s,d,r),g={};for(let m=0;mGc,initializeFlags:()=>Wc,wasmBackend:()=>oh});var Wc,Gc,oh,Uf=j(()=>{Pt(),nh(),Vf(),Ot(),Wc=()=>{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"?xe("node:os").cpus().length:navigator.hardwareConcurrency;k.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Gc=class{async init(e){Wc(),await Qp(),await Yp(e)}async createInferenceSessionHandler(e,t){let r=new ih;return await r.loadModel(e,t),Promise.resolve(r)}},oh=new Gc});Pt(),Pt(),Pt();var Wf="1.21.0-dev.20241024-d9ca84ef96",Gf=Dt;{let e=(Uf(),B(ah)).wasmBackend;me("webgpu",e,5),me("webnn",e,5),me("cpu",e,10),me("wasm",e,10)}Object.defineProperty(k.versions,"web",{value:Wf,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */},"./src/backends/onnx.js":(At,ye,D)=>{var I;D.r(ye),D.d(ye,{Tensor:()=>xe.Tensor,createInferenceSession:()=>O,deviceToExecutionProviders:()=>me,isONNXProxy:()=>X,isONNXTensor:()=>J});var de=D("./src/env.js"),he=D("?2ce3"),ve=D("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),xe=D("./node_modules/onnxruntime-common/dist/esm/index.js");const j=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),P=[];let L,B;const q=Symbol.for("onnxruntime");if(q in globalThis)B=globalThis[q];else if(de.apis.IS_NODE_ENV){switch(B=he??(I||(I=D.t(he,2))),process.platform){case"win32":P.push("dml");break;case"linux":process.arch==="x64"&&P.push("cuda");break}P.push("cpu"),L=["cpu"]}else B=ve,de.apis.IS_WEBNN_AVAILABLE&&P.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),de.apis.IS_WEBGPU_AVAILABLE&&P.push("webgpu"),P.push("wasm"),L=["wasm"];const re=B.InferenceSession;function me(K=null){if(!K)return L;switch(K){case"auto":return P;case"gpu":return P.filter(V=>["webgpu","cuda","dml","webnn-gpu"].includes(V))}if(P.includes(K))return[j[K]??K];throw new Error(`Unsupported device: "${K}". Should be one of: ${P.join(", ")}.`)}let ue=null;async function O(K,V,E){ue&&await ue;const N=re.create(K,V);ue??(ue=N);const k=await N;return k.config=E,k}function J(K){return K instanceof B.Tensor}const pe=B==null?void 0:B.env;pe!=null&&pe.wasm&&(pe.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${de.env.version}/dist/`,pe.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(pe.wasm.numThreads=1)),pe!=null&&pe.webgpu&&(pe.webgpu.powerPreference="high-performance");function X(){var K;return(K=pe==null?void 0:pe.wasm)==null?void 0:K.proxy}de.env.backends.onnx=pe},"./src/configs.js":(At,ye,D)=>{D.r(ye),D.d(ye,{AutoConfig:()=>P,PretrainedConfig:()=>j,getKeyValueShapes:()=>xe});var I=D("./src/utils/core.js"),de=D("./src/utils/hub.js");async function he(L,B){return await(0,de.getModelJSON)(L,"config.json",!0,B)}function ve(L){const B={};let q={};switch(L.model_type){case"llava":case"paligemma":case"florence2":q=ve(L.text_config);break;case"moondream1":q=ve(L.phi_config);break;case"musicgen":q=ve(L.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":B.num_heads="n_head",B.num_layers="n_layer",B.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":B.num_heads="num_attention_heads",B.num_layers="num_hidden_layers",B.hidden_size="hidden_size";break;case"llama":case"olmo":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":B.num_heads="num_key_value_heads",B.num_layers="num_hidden_layers",B.hidden_size="hidden_size",B.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":B.num_heads="num_key_value_heads",B.num_layers="num_hidden_layers",B.dim_kv="head_dim";break;case"openelm":B.num_heads="num_kv_heads",B.num_layers="num_transformer_layers",B.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":B.num_heads="num_heads",B.num_layers="num_layers",B.hidden_size="hidden_size";break;case"bloom":B.num_heads="n_head",B.num_layers="n_layer",B.hidden_size="hidden_size";break;case"mpt":B.num_heads="n_heads",B.num_layers="n_layers",B.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":B.num_decoder_layers="num_decoder_layers",B.num_decoder_heads="num_heads",B.decoder_dim_kv="d_kv",B.num_encoder_layers="num_layers",B.num_encoder_heads="num_heads",B.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":B.num_decoder_layers="decoder_layers",B.num_decoder_heads="decoder_attention_heads",B.decoder_hidden_size="d_model",B.num_encoder_layers="encoder_layers",B.num_encoder_heads="encoder_attention_heads",B.encoder_hidden_size="d_model";break;case"speecht5":B.num_decoder_layers="decoder_layers",B.num_decoder_heads="decoder_attention_heads",B.decoder_hidden_size="hidden_size",B.num_encoder_layers="encoder_layers",B.num_encoder_heads="encoder_attention_heads",B.encoder_hidden_size="hidden_size";break;case"trocr":B.num_encoder_layers=B.num_decoder_layers="decoder_layers",B.num_encoder_heads=B.num_decoder_heads="decoder_attention_heads",B.encoder_hidden_size=B.decoder_hidden_size="d_model";break;case"musicgen_decoder":B.num_encoder_layers=B.num_decoder_layers="num_hidden_layers",B.num_encoder_heads=B.num_decoder_heads="num_attention_heads",B.encoder_hidden_size=B.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const me=ve(L.decoder),ue="num_decoder_layers"in me,O=(0,I.pick)(L,["model_type","is_encoder_decoder"]);return ue?(O.num_decoder_layers=me.num_decoder_layers,O.num_decoder_heads=me.num_decoder_heads,O.decoder_hidden_size=me.decoder_hidden_size,O.num_encoder_layers=me.num_encoder_layers,O.num_encoder_heads=me.num_encoder_heads,O.encoder_hidden_size=me.encoder_hidden_size):(O.num_layers=me.num_layers,O.num_heads=me.num_heads,O.hidden_size=me.hidden_size),O}const re={...q,...(0,I.pick)(L,["model_type","multi_query","is_encoder_decoder"])};for(const me in B)re[me]=L[B[me]];return re}function xe(L,{prefix:B="past_key_values"}={}){const q={},re=L.normalized_config,me=1;if(re.is_encoder_decoder&&"num_encoder_heads"in re&&"num_decoder_heads"in re){const ue=re.encoder_dim_kv??re.encoder_hidden_size/re.num_encoder_heads,O=re.decoder_dim_kv??re.decoder_hidden_size/re.num_decoder_heads,J=[me,re.num_encoder_heads,0,ue],pe=[me,re.num_decoder_heads,0,O];for(let X=0;X{var k;D.r(ye),D.d(ye,{apis:()=>O,env:()=>E});var I=D("?569f"),de=D("?3f59"),he=D("?154a");const ve="3.0.2",xe=typeof self<"u",j=xe&&self.constructor.name==="DedicatedWorkerGlobalScope",P=xe&&"caches"in self,L=typeof navigator<"u"&&"gpu"in navigator,B=typeof navigator<"u"&&"ml"in navigator,q=typeof process<"u",re=q&&((k=process==null?void 0:process.release)==null?void 0:k.name)==="node",me=!N(I),ue=!N(de),O=Object.freeze({IS_BROWSER_ENV:xe,IS_WEBWORKER_ENV:j,IS_WEB_CACHE_AVAILABLE:P,IS_WEBGPU_AVAILABLE:L,IS_WEBNN_AVAILABLE:B,IS_PROCESS_AVAILABLE:q,IS_NODE_ENV:re,IS_FS_AVAILABLE:me,IS_PATH_AVAILABLE:ue}),J=me&&ue;let pe="./";if(J){const le=Object(import.meta).url;le?pe=de.dirname(de.dirname(he.fileURLToPath(le))):typeof __dirname<"u"&&(pe=de.dirname(__dirname))}const X=J?de.join(pe,"/.cache/"):null,K="/models/",V=J?de.join(pe,K):K,E={version:ve,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!xe,localModelPath:V,useFS:me,useBrowserCache:P,useFSCache:me,cacheDir:X,useCustomCache:!1,customCache:null};function N(le){return Object.keys(le).length===0}},"./src/generation/configuration_utils.js":(At,ye,D)=>{D.r(ye),D.d(ye,{GenerationConfig:()=>de});var I=D("./src/utils/core.js");class de{constructor(ve){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,I.pick)(ve,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(At,ye,D)=>{D.r(ye),D.d(ye,{ClassifierFreeGuidanceLogitsProcessor:()=>J,ForcedBOSTokenLogitsProcessor:()=>j,ForcedEOSTokenLogitsProcessor:()=>P,LogitsProcessor:()=>he,LogitsProcessorList:()=>xe,LogitsWarper:()=>ve,MinLengthLogitsProcessor:()=>me,MinNewTokensLengthLogitsProcessor:()=>ue,NoBadWordsLogitsProcessor:()=>O,NoRepeatNGramLogitsProcessor:()=>q,RepetitionPenaltyLogitsProcessor:()=>re,SuppressTokensAtBeginLogitsProcessor:()=>L,TemperatureLogitsWarper:()=>pe,TopKLogitsWarper:()=>K,TopPLogitsWarper:()=>X,WhisperTimeStampLogitsProcessor:()=>B});var I=D("./src/utils/generic.js");D("./src/utils/tensor.js");var de=D("./src/utils/maths.js");class he extends I.Callable{_call(E,N){throw Error("`_call` should be implemented in a subclass")}}class ve extends I.Callable{_call(E,N){throw Error("`_call` should be implemented in a subclass")}}class xe extends I.Callable{constructor(){super(),this.processors=[]}push(E){this.processors.push(E)}extend(E){this.processors.push(...E)}_call(E,N){let k=N;for(const le of this.processors)k=le(E,k);return k}[Symbol.iterator](){return this.processors.values()}}class j extends he{constructor(E){super(),this.bos_token_id=E}_call(E,N){for(let k=0;k=1&&be[be.length-1]>=this.timestamp_begin,De=be.length<2||be[be.length-2]>=this.timestamp_begin;if($e&&(De?le.subarray(this.timestamp_begin).fill(-1/0):le.subarray(0,this.eos_token_id).fill(-1/0)),E[k].length===this.begin_index&&this.max_initial_timestamp_index!==null){const lt=this.timestamp_begin+this.max_initial_timestamp_index;le.subarray(lt+1).fill(-1/0)}const ze=(0,de.log_softmax)(le),it=Math.log(ze.subarray(this.timestamp_begin).map(Math.exp).reduce((lt,_e)=>lt+_e)),rt=(0,de.max)(ze.subarray(0,this.timestamp_begin))[0];it>rt&&le.subarray(0,this.timestamp_begin).fill(-1/0)}return N}}class q extends he{constructor(E){super(),this.no_repeat_ngram_size=E}getNgrams(E){const N=E.length,k=[];for(let be=0;be1 to use the classifier free guidance processor, got guidance scale ${E}.`);this.guidance_scale=E}_call(E,N){if(N.dims[0]!==2*E.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${N.dims[0]} for the logits and ${E.length} for the input ids.`);const k=E.length,le=N.slice([0,k],null),be=N.slice([k,N.dims[0]],null);for(let $e=0;$e1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${E}`);if(!Number.isInteger(k)||k<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${k}`);this.top_p=E,this.filter_value=N,this.min_tokens_to_keep=k}}class K extends ve{constructor(E,{filter_value:N=-1/0,min_tokens_to_keep:k=1}={}){if(super(),!Number.isInteger(E)||E<0)throw new Error(`\`top_k\` must be a positive integer, but is ${E}`);this.top_k=Math.max(E,k),this.filter_value=N}}},"./src/generation/logits_sampler.js":(At,ye,D)=>{D.r(ye),D.d(ye,{LogitsSampler:()=>ve});var I=D("./src/utils/generic.js"),de=D("./src/utils/tensor.js"),he=D("./src/utils/maths.js");D("./src/generation/configuration_utils.js");class ve extends I.Callable{constructor(B){super(),this.generation_config=B}async _call(B){return this.sample(B)}async sample(B){throw Error("sample should be implemented in subclasses.")}getLogits(B,q){let re=B.dims.at(-1),me=B.data;if(q===-1)me=me.slice(-re);else{let ue=q*re;me=me.slice(ue,ue+re)}return me}randomSelect(B){let q=0;for(let me=0;me1)return new P(B);if(B.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${B.num_return_sequences}.`);return new xe(B)}}class xe extends ve{async sample(B){const q=(0,he.max)(B.data)[1];return[[BigInt(q),0]]}}class j extends ve{async sample(B){let q=B.dims.at(-1);this.generation_config.top_k>0&&(q=Math.min(this.generation_config.top_k,q));const[re,me]=await(0,de.topk)(B,q),ue=(0,he.softmax)(re.data);return Array.from({length:this.generation_config.num_beams},()=>{const O=this.randomSelect(ue);return[me.data[O],Math.log(ue[O])]})}}class P extends ve{async sample(B){let q=B.dims.at(-1);this.generation_config.top_k>0&&(q=Math.min(this.generation_config.top_k,q));const[re,me]=await(0,de.topk)(B,q),ue=(0,he.softmax)(re.data);return Array.from({length:this.generation_config.num_beams},(O,J)=>[me.data[J],Math.log(ue[J])])}}},"./src/generation/stopping_criteria.js":(At,ye,D)=>{D.r(ye),D.d(ye,{EosTokenCriteria:()=>xe,InterruptableStoppingCriteria:()=>j,MaxLengthCriteria:()=>ve,StoppingCriteria:()=>de,StoppingCriteriaList:()=>he});var I=D("./src/utils/generic.js");class de extends I.Callable{_call(L,B){throw Error("StoppingCriteria needs to be subclassed")}}class he extends I.Callable{constructor(){super(),this.criteria=[]}push(L){this.criteria.push(L)}extend(L){L instanceof he?L=L.criteria:L instanceof de&&(L=[L]),this.criteria.push(...L)}_call(L,B){const q=new Array(L.length).fill(!1);for(const re of this.criteria){const me=re(L,B);for(let ue=0;ueB.length>=this.max_length)}}class xe extends de{constructor(L){super(),Array.isArray(L)||(L=[L]),this.eos_token_id=L}_call(L,B){return L.map(q=>{const re=q.at(-1);return this.eos_token_id.some(me=>re==me)})}}class j extends de{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(L,B){return new Array(L.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(At,ye,D)=>{D.r(ye),D.d(ye,{BaseStreamer:()=>ve,TextStreamer:()=>j,WhisperTextStreamer:()=>P});var I=D("./src/utils/core.js"),de=D("./src/tokenizers.js"),he=D("./src/env.js");class ve{put(B){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const xe=he.apis.IS_PROCESS_AVAILABLE?L=>process.stdout.write(L):L=>console.log(L);class j extends ve{constructor(B,{skip_prompt:q=!1,callback_function:re=null,token_callback_function:me=null,decode_kwargs:ue={},...O}={}){super(),this.tokenizer=B,this.skip_prompt=q,this.callback_function=re??xe,this.token_callback_function=me,this.decode_kwargs={...ue,...O},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(B){var ue;if(B.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const q=B[0];(ue=this.token_callback_function)==null||ue.call(this,q),this.token_cache=(0,I.mergeArrays)(this.token_cache,q);const re=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let me;re.endsWith(` `)?(me=re.slice(this.print_len),this.token_cache=[],this.print_len=0):re.length>0&&(0,de.is_chinese_char)(re.charCodeAt(re.length-1))?(me=re.slice(this.print_len),this.print_len+=me.length):(me=re.slice(this.print_len,re.lastIndexOf(" ")+1),this.print_len+=me.length),this.on_finalized_text(me,!1)}end(){let B;this.token_cache.length>0?(B=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):B="",this.next_tokens_are_prompt=!0,this.on_finalized_text(B,!0)}on_finalized_text(B,q){var re,me;B.length>0&&((re=this.callback_function)==null||re.call(this,B)),q&&this.callback_function===xe&&he.apis.IS_PROCESS_AVAILABLE&&((me=this.callback_function)==null||me.call(this,` `))}}class P extends j{constructor(B,{skip_prompt:q=!1,callback_function:re=null,token_callback_function:me=null,on_chunk_start:ue=null,on_chunk_end:O=null,on_finalize:J=null,time_precision:pe=.02,skip_special_tokens:X=!0,decode_kwargs:K={}}={}){super(B,{skip_prompt:q,callback_function:re,token_callback_function:me,decode_kwargs:{skip_special_tokens:X,...K}}),this.timestamp_begin=B.timestamp_begin,this.on_chunk_start=ue,this.on_chunk_end=O,this.on_finalize=J,this.time_precision=pe,this.waiting_for_timestamp=!1}put(B){var re,me;if(B.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const q=B[0];if(q.length===1){const ue=Number(q[0])-this.timestamp_begin;if(ue>=0){const O=ue*this.time_precision;this.waiting_for_timestamp?(re=this.on_chunk_end)==null||re.call(this,O):(me=this.on_chunk_start)==null||me.call(this,O),this.waiting_for_timestamp=!this.waiting_for_timestamp,B=[[]]}}return super.put(B)}end(){var B;super.end(),(B=this.on_finalize)==null||B.call(this)}}},"./src/models.js":(At,ye,D)=>{D.r(ye),D.d(ye,{ASTForAudioClassification:()=>Js,ASTModel:()=>Wt,ASTPreTrainedModel:()=>Nn,AlbertForMaskedLM:()=>Yt,AlbertForQuestionAnswering:()=>ms,AlbertForSequenceClassification:()=>fs,AlbertModel:()=>hs,AlbertPreTrainedModel:()=>Dn,AutoModel:()=>Ga,AutoModelForAudioClassification:()=>cd,AutoModelForAudioFrameClassification:()=>Qa,AutoModelForCTC:()=>Xa,AutoModelForCausalLM:()=>id,AutoModelForDepthEstimation:()=>Za,AutoModelForDocumentQuestionAnswering:()=>Ya,AutoModelForImageClassification:()=>ud,AutoModelForImageFeatureExtraction:()=>_d,AutoModelForImageMatting:()=>hd,AutoModelForImageSegmentation:()=>dd,AutoModelForImageToImage:()=>fd,AutoModelForMaskGeneration:()=>Ka,AutoModelForMaskedLM:()=>ad,AutoModelForNormalEstimation:()=>md,AutoModelForObjectDetection:()=>qa,AutoModelForQuestionAnswering:()=>od,AutoModelForSemanticSegmentation:()=>rc,AutoModelForSeq2SeqLM:()=>tc,AutoModelForSequenceClassification:()=>ed,AutoModelForSpeechSeq2Seq:()=>rd,AutoModelForTextToSpectrogram:()=>nd,AutoModelForTextToWaveform:()=>sd,AutoModelForTokenClassification:()=>td,AutoModelForUniversalSegmentation:()=>Ws,AutoModelForVision2Seq:()=>ld,AutoModelForXVector:()=>pd,AutoModelForZeroShotObjectDetection:()=>Ha,BartForConditionalGeneration:()=>Q,BartForSequenceClassification:()=>oe,BartModel:()=>F,BartPretrainedModel:()=>_,BaseModelOutput:()=>dt,BeitForImageClassification:()=>gl,BeitModel:()=>_l,BeitPreTrainedModel:()=>Zi,BertForMaskedLM:()=>Mt,BertForQuestionAnswering:()=>Ae,BertForSequenceClassification:()=>Xe,BertForTokenClassification:()=>Z,BertModel:()=>ht,BertPreTrainedModel:()=>Re,BlenderbotForConditionalGeneration:()=>Sr,BlenderbotModel:()=>er,BlenderbotPreTrainedModel:()=>zt,BlenderbotSmallForConditionalGeneration:()=>en,BlenderbotSmallModel:()=>Wr,BlenderbotSmallPreTrainedModel:()=>lr,BloomForCausalLM:()=>qo,BloomModel:()=>Go,BloomPreTrainedModel:()=>ri,CLIPModel:()=>lo,CLIPPreTrainedModel:()=>ss,CLIPSegForImageSegmentation:()=>go,CLIPSegModel:()=>_o,CLIPSegPreTrainedModel:()=>xi,CLIPTextModel:()=>Ed,CLIPTextModelWithProjection:()=>xn,CLIPVisionModel:()=>Sd,CLIPVisionModelWithProjection:()=>uo,CamembertForMaskedLM:()=>Yr,CamembertForQuestionAnswering:()=>yn,CamembertForSequenceClassification:()=>Rr,CamembertForTokenClassification:()=>Jr,CamembertModel:()=>Cr,CamembertPreTrainedModel:()=>dr,CausalLMOutput:()=>is,CausalLMOutputWithPast:()=>nc,ChineseCLIPModel:()=>mo,ChineseCLIPPreTrainedModel:()=>fo,ClapAudioModelWithProjection:()=>xu,ClapModel:()=>vu,ClapPreTrainedModel:()=>pi,ClapTextModelWithProjection:()=>ka,CodeGenForCausalLM:()=>$o,CodeGenModel:()=>Co,CodeGenPreTrainedModel:()=>$n,CohereForCausalLM:()=>zo,CohereModel:()=>Oo,CoherePreTrainedModel:()=>zi,ConvBertForMaskedLM:()=>$,ConvBertForQuestionAnswering:()=>nt,ConvBertForSequenceClassification:()=>Y,ConvBertForTokenClassification:()=>fe,ConvBertModel:()=>H,ConvBertPreTrainedModel:()=>v,ConvNextForImageClassification:()=>Ul,ConvNextModel:()=>Vl,ConvNextPreTrainedModel:()=>da,ConvNextV2ForImageClassification:()=>Wl,ConvNextV2Model:()=>ca,ConvNextV2PreTrainedModel:()=>Ls,DPTForDepthEstimation:()=>Id,DPTModel:()=>Dl,DPTPreTrainedModel:()=>aa,DebertaForMaskedLM:()=>we,DebertaForQuestionAnswering:()=>Ne,DebertaForSequenceClassification:()=>Ie,DebertaForTokenClassification:()=>Se,DebertaModel:()=>G,DebertaPreTrainedModel:()=>at,DebertaV2ForMaskedLM:()=>mt,DebertaV2ForQuestionAnswering:()=>Lt,DebertaV2ForSequenceClassification:()=>Ct,DebertaV2ForTokenClassification:()=>ft,DebertaV2Model:()=>wt,DebertaV2PreTrainedModel:()=>tt,DecisionTransformerModel:()=>Du,DecisionTransformerPreTrainedModel:()=>zu,DeiTForImageClassification:()=>$l,DeiTModel:()=>Cl,DeiTPreTrainedModel:()=>na,DepthAnythingForDepthEstimation:()=>Bl,DepthAnythingPreTrainedModel:()=>Ll,DepthProForDepthEstimation:()=>Yn,DepthProPreTrainedModel:()=>Fd,DetrForObjectDetection:()=>yl,DetrForSegmentation:()=>ii,DetrModel:()=>wl,DetrObjectDetectionOutput:()=>Ji,DetrPreTrainedModel:()=>si,DetrSegmentationOutput:()=>ea,Dinov2ForImageClassification:()=>pa,Dinov2Model:()=>Gl,Dinov2PreTrainedModel:()=>Bs,DistilBertForMaskedLM:()=>Ut,DistilBertForQuestionAnswering:()=>ct,DistilBertForSequenceClassification:()=>Fe,DistilBertForTokenClassification:()=>Oe,DistilBertModel:()=>Ot,DistilBertPreTrainedModel:()=>jt,DonutSwinModel:()=>ua,DonutSwinPreTrainedModel:()=>li,EfficientNetForImageClassification:()=>Wd,EfficientNetModel:()=>ku,EfficientNetPreTrainedModel:()=>Ia,ElectraForMaskedLM:()=>yt,ElectraForQuestionAnswering:()=>Pt,ElectraForSequenceClassification:()=>bt,ElectraForTokenClassification:()=>Dt,ElectraModel:()=>Nt,ElectraPreTrainedModel:()=>Je,EsmForMaskedLM:()=>Nr,EsmForSequenceClassification:()=>mr,EsmForTokenClassification:()=>Er,EsmModel:()=>br,EsmPreTrainedModel:()=>sr,FalconForCausalLM:()=>Mu,FalconModel:()=>bu,FalconPreTrainedModel:()=>ci,FastViTForImageClassification:()=>ol,FastViTModel:()=>al,FastViTPreTrainedModel:()=>Hi,Florence2ForConditionalGeneration:()=>vi,Florence2PreTrainedModel:()=>oo,GLPNForDepthEstimation:()=>la,GLPNModel:()=>hn,GLPNPreTrainedModel:()=>Un,GPT2LMHeadModel:()=>An,GPT2Model:()=>wo,GPT2PreTrainedModel:()=>Ti,GPTBigCodeForCausalLM:()=>Pi,GPTBigCodeModel:()=>ei,GPTBigCodePreTrainedModel:()=>Si,GPTJForCausalLM:()=>In,GPTJModel:()=>Pd,GPTJPreTrainedModel:()=>Ei,GPTNeoForCausalLM:()=>vo,GPTNeoModel:()=>Mo,GPTNeoPreTrainedModel:()=>$i,GPTNeoXForCausalLM:()=>To,GPTNeoXModel:()=>xo,GPTNeoXPreTrainedModel:()=>ki,Gemma2ForCausalLM:()=>Ri,Gemma2Model:()=>Bi,Gemma2PreTrainedModel:()=>Li,GemmaForCausalLM:()=>Lo,GemmaModel:()=>Do,GemmaPreTrainedModel:()=>Di,GraniteForCausalLM:()=>Fo,GraniteModel:()=>Io,GranitePreTrainedModel:()=>Oi,GroupViTModel:()=>il,GroupViTPreTrainedModel:()=>sl,HieraForImageClassification:()=>Sl,HieraModel:()=>El,HieraPreTrainedModel:()=>kl,HubertForCTC:()=>ou,HubertForSequenceClassification:()=>Ta,HubertModel:()=>au,HubertPreTrainedModel:()=>Rd,ImageMattingOutput:()=>yd,JAISLMHeadModel:()=>bo,JAISModel:()=>yo,JAISPreTrainedModel:()=>Ci,LlamaForCausalLM:()=>Eo,LlamaModel:()=>ko,LlamaPreTrainedModel:()=>Ai,LlavaForConditionalGeneration:()=>gs,LlavaPreTrainedModel:()=>ao,LongT5ForConditionalGeneration:()=>Os,LongT5Model:()=>Fs,LongT5PreTrainedModel:()=>_s,M2M100ForConditionalGeneration:()=>zd,M2M100Model:()=>Ql,M2M100PreTrainedModel:()=>_a,MBartForCausalLM:()=>Tt,MBartForConditionalGeneration:()=>gt,MBartForSequenceClassification:()=>$t,MBartModel:()=>Ge,MBartPreTrainedModel:()=>ge,MPNetForMaskedLM:()=>ks,MPNetForQuestionAnswering:()=>Ps,MPNetForSequenceClassification:()=>Es,MPNetForTokenClassification:()=>Ss,MPNetModel:()=>$s,MPNetPreTrainedModel:()=>Kn,MT5ForConditionalGeneration:()=>ae,MT5Model:()=>zs,MT5PreTrainedModel:()=>rs,MarianMTModel:()=>Xl,MarianModel:()=>ma,MarianPreTrainedModel:()=>fa,MaskFormerForInstanceSegmentation:()=>oa,MaskFormerModel:()=>Zn,MaskFormerPreTrainedModel:()=>Vn,MaskedLMOutput:()=>ln,MistralForCausalLM:()=>wu,MistralModel:()=>gu,MistralPreTrainedModel:()=>$a,MobileBertForMaskedLM:()=>Ur,MobileBertForQuestionAnswering:()=>Cs,MobileBertForSequenceClassification:()=>cs,MobileBertModel:()=>Cn,MobileBertPreTrainedModel:()=>wr,MobileLLMForCausalLM:()=>Po,MobileLLMModel:()=>So,MobileLLMPreTrainedModel:()=>Ii,MobileNetV1ForImageClassification:()=>Pu,MobileNetV1Model:()=>Su,MobileNetV1PreTrainedModel:()=>Eu,MobileNetV2ForImageClassification:()=>Hd,MobileNetV2Model:()=>Au,MobileNetV2PreTrainedModel:()=>za,MobileNetV3ForImageClassification:()=>Fu,MobileNetV3Model:()=>Iu,MobileNetV3PreTrainedModel:()=>Da,MobileNetV4ForImageClassification:()=>Ou,MobileNetV4Model:()=>Kd,MobileNetV4PreTrainedModel:()=>La,MobileViTForImageClassification:()=>ul,MobileViTModel:()=>ni,MobileViTPreTrainedModel:()=>Ki,MobileViTV2ForImageClassification:()=>cl,MobileViTV2Model:()=>dl,MobileViTV2PreTrainedModel:()=>Xi,ModelOutput:()=>Ze,Moondream1ForConditionalGeneration:()=>pr,MptForCausalLM:()=>Ad,MptModel:()=>Ho,MptPreTrainedModel:()=>Ui,MusicgenForCausalLM:()=>qd,MusicgenForConditionalGeneration:()=>Oa,MusicgenModel:()=>Gd,MusicgenPreTrainedModel:()=>Fa,NomicBertModel:()=>et,NomicBertPreTrainedModel:()=>Ke,OPTForCausalLM:()=>Xo,OPTModel:()=>Ko,OPTPreTrainedModel:()=>Wi,OlmoForCausalLM:()=>Fn,OlmoModel:()=>Ao,OlmoPreTrainedModel:()=>Fi,OpenELMForCausalLM:()=>ji,OpenELMModel:()=>Bo,OpenELMPreTrainedModel:()=>Ni,OwlViTForObjectDetection:()=>hl,OwlViTModel:()=>pl,OwlViTPreTrainedModel:()=>Qi,Owlv2ForObjectDetection:()=>ml,Owlv2Model:()=>fl,Owlv2PreTrainedModel:()=>Yi,Phi3ForCausalLM:()=>Wo,Phi3Model:()=>Uo,Phi3PreTrainedModel:()=>ws,PhiForCausalLM:()=>Vo,PhiModel:()=>jo,PhiPreTrainedModel:()=>Vi,PreTrainedModel:()=>ne,PretrainedMixin:()=>zr,PvtForImageClassification:()=>Jo,PvtModel:()=>Zo,PvtPreTrainedModel:()=>Gi,PyAnnoteForAudioFrameClassification:()=>eu,PyAnnoteModel:()=>Jl,PyAnnotePreTrainedModel:()=>wa,QuestionAnsweringModelOutput:()=>_n,Qwen2ForCausalLM:()=>ti,Qwen2Model:()=>No,Qwen2PreTrainedModel:()=>Ro,RTDetrForObjectDetection:()=>Ml,RTDetrModel:()=>bl,RTDetrObjectDetectionOutput:()=>vl,RTDetrPreTrainedModel:()=>ai,ResNetForImageClassification:()=>Al,ResNetModel:()=>Pl,ResNetPreTrainedModel:()=>kn,RoFormerForMaskedLM:()=>ut,RoFormerForQuestionAnswering:()=>xt,RoFormerForSequenceClassification:()=>_t,RoFormerForTokenClassification:()=>St,RoFormerModel:()=>Ve,RoFormerPreTrainedModel:()=>je,RobertaForMaskedLM:()=>mn,RobertaForQuestionAnswering:()=>tn,RobertaForSequenceClassification:()=>bn,RobertaForTokenClassification:()=>ke,RobertaModel:()=>Pr,RobertaPreTrainedModel:()=>or,SamImageSegmentationOutput:()=>Ns,SamModel:()=>ha,SamPreTrainedModel:()=>Kl,SapiensForDepthEstimation:()=>Nl,SapiensForNormalEstimation:()=>jl,SapiensForSemanticSegmentation:()=>Rl,SapiensPreTrainedModel:()=>oi,SegformerForImageClassification:()=>Pa,SegformerForSemanticSegmentation:()=>Cu,SegformerModel:()=>Vd,SegformerPreTrainedModel:()=>Sa,Seq2SeqLMOutput:()=>gd,SequenceClassifierOutput:()=>cr,SiglipModel:()=>co,SiglipPreTrainedModel:()=>jn,SiglipTextModel:()=>po,SiglipVisionModel:()=>ho,SpeechT5ForSpeechToText:()=>hu,SpeechT5ForTextToSpeech:()=>fu,SpeechT5HifiGan:()=>jd,SpeechT5Model:()=>Nd,SpeechT5PreTrainedModel:()=>Ca,SqueezeBertForMaskedLM:()=>Sn,SqueezeBertForQuestionAnswering:()=>ps,SqueezeBertForSequenceClassification:()=>Bn,SqueezeBertModel:()=>Xn,SqueezeBertPreTrainedModel:()=>es,StableLmForCausalLM:()=>Ud,StableLmModel:()=>$u,StableLmPreTrainedModel:()=>Aa,Starcoder2ForCausalLM:()=>Vs,Starcoder2Model:()=>di,Starcoder2PreTrainedModel:()=>yu,Swin2SRForImageSuperResolution:()=>zl,Swin2SRModel:()=>Ol,Swin2SRPreTrainedModel:()=>ia,SwinForImageClassification:()=>Fl,SwinModel:()=>Il,SwinPreTrainedModel:()=>sa,T5ForConditionalGeneration:()=>Is,T5Model:()=>As,T5PreTrainedModel:()=>ts,TableTransformerForObjectDetection:()=>Tl,TableTransformerModel:()=>xl,TableTransformerObjectDetectionOutput:()=>ra,TableTransformerPreTrainedModel:()=>ta,TokenClassifierOutput:()=>sn,TrOCRForCausalLM:()=>_u,TrOCRPreTrainedModel:()=>mu,UniSpeechForCTC:()=>ba,UniSpeechForSequenceClassification:()=>ru,UniSpeechModel:()=>ya,UniSpeechPreTrainedModel:()=>ys,UniSpeechSatForAudioFrameClassification:()=>su,UniSpeechSatForCTC:()=>Ld,UniSpeechSatForSequenceClassification:()=>nu,UniSpeechSatModel:()=>Ma,UniSpeechSatPreTrainedModel:()=>js,ViTForImageClassification:()=>vr,ViTMAEModel:()=>tl,ViTMAEPreTrainedModel:()=>el,ViTMSNForImageClassification:()=>nl,ViTMSNModel:()=>rl,ViTMSNPreTrainedModel:()=>qi,ViTModel:()=>Yo,ViTPreTrainedModel:()=>Qo,VisionEncoderDecoderModel:()=>Mi,VitMatteForImageMatting:()=>Ds,VitMattePreTrainedModel:()=>ll,VitsModel:()=>Ea,VitsModelOutput:()=>bd,VitsPreTrainedModel:()=>Tu,Wav2Vec2BertForCTC:()=>xa,Wav2Vec2BertForSequenceClassification:()=>Bd,Wav2Vec2BertModel:()=>iu,Wav2Vec2BertPreTrainedModel:()=>va,Wav2Vec2ForAudioFrameClassification:()=>Zl,Wav2Vec2ForCTC:()=>Dd,Wav2Vec2ForSequenceClassification:()=>ga,Wav2Vec2Model:()=>Yl,Wav2Vec2PreTrainedModel:()=>Jn,WavLMForAudioFrameClassification:()=>pu,WavLMForCTC:()=>uu,WavLMForSequenceClassification:()=>du,WavLMForXVector:()=>cu,WavLMModel:()=>lu,WavLMPreTrainedModel:()=>bs,WeSpeakerResNetModel:()=>tu,WeSpeakerResNetPreTrainedModel:()=>ui,WhisperForConditionalGeneration:()=>bi,WhisperModel:()=>qt,WhisperPreTrainedModel:()=>Qe,XLMForQuestionAnswering:()=>Kr,XLMForSequenceClassification:()=>Kt,XLMForTokenClassification:()=>pn,XLMModel:()=>Pn,XLMPreTrainedModel:()=>on,XLMRobertaForMaskedLM:()=>kt,XLMRobertaForQuestionAnswering:()=>Qn,XLMRobertaForSequenceClassification:()=>_r,XLMRobertaForTokenClassification:()=>ns,XLMRobertaModel:()=>Or,XLMRobertaPreTrainedModel:()=>fr,XLMWithLMHeadModel:()=>Rn,XVectorOutput:()=>wd,YolosForObjectDetection:()=>Hl,YolosModel:()=>ql,YolosObjectDetectionOutput:()=>Od,YolosPreTrainedModel:()=>Rs});var I=D("./src/configs.js"),de=D("./src/backends/onnx.js"),he=D("./src/utils/dtypes.js"),ve=D("./src/utils/generic.js"),xe=D("./src/utils/core.js"),j=D("./src/utils/hub.js"),P=D("./src/utils/constants.js"),L=D("./src/generation/logits_process.js"),B=D("./src/generation/configuration_utils.js"),q=D("./src/utils/tensor.js"),re=D("./src/utils/maths.js"),me=D("./src/generation/stopping_criteria.js"),ue=D("./src/generation/logits_sampler.js"),O=D("./src/env.js"),J=D("./src/models/whisper/generation_whisper.js"),pe=D("./src/models/whisper/common_whisper.js");const X={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},K=new Map,V=new Map,E=new Map;async function N(f,b,R){var un;const Te=((un=R.config)==null?void 0:un["transformers.js_config"])??{};let Ue=R.device??Te.device;Ue&&typeof Ue!="string"&&(Ue.hasOwnProperty(b)?Ue=Ue[b]:(console.warn(`device not specified for "${b}". Using the default device.`),Ue=null));const Le=Ue??(O.apis.IS_NODE_ENV?"cpu":"wasm"),pt=(0,de.deviceToExecutionProviders)(Le);let Et=R.dtype??Te.dtype;typeof Et!="string"&&(Et&&Et.hasOwnProperty(b)?Et=Et[b]:(Et=he.DEFAULT_DEVICE_DTYPE_MAPPING[Le]??he.DATA_TYPES.fp32,console.warn(`dtype not specified for "${b}". Using the default dtype (${Et}) for this device (${Le}).`)));const Vt=Et;if(he.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Vt)){if(Vt===he.DATA_TYPES.fp16&&Le==="webgpu"&&!await(0,he.isWebGpuFp16Supported)())throw new Error(`The device (${Le}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Vt}. Should be one of: ${Object.keys(he.DATA_TYPES).join(", ")}`);const tr=Te.kv_cache_dtype?typeof Te.kv_cache_dtype=="string"?Te.kv_cache_dtype:Te.kv_cache_dtype[Vt]??"float32":void 0;if(tr&&!["float32","float16"].includes(tr))throw new Error(`Invalid kv_cache_dtype: ${tr}. Should be one of: float32, float16`);const Ar={dtype:Vt,kv_cache_dtype:tr},Dr=he.DEFAULT_DTYPE_SUFFIX_MAPPING[Vt],yr=`${R.subfolder??""}/${b}${Dr}.onnx`,ir={...R.session_options};ir.executionProviders??(ir.executionProviders=pt);const Ir=Te.free_dimension_overrides;Ir?ir.freeDimensionOverrides??(ir.freeDimensionOverrides=Ir):Le.startsWith("webnn")&&!ir.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const $r=(0,j.getModelFile)(f,yr,!0,R),gr=R.use_external_data_format??Te.use_external_data_format;let Lr=[];if(gr&&(gr===!0||typeof gr=="object"&&gr.hasOwnProperty(b)&&gr[b]===!0)){if(O.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const Gr=`${b}${Dr}.onnx_data`,Xr=`${R.subfolder??""}/${Gr}`;Lr.push(new Promise(async(Qr,gn)=>{const as=await(0,j.getModelFile)(f,Xr,!0,R);Qr({path:Gr,data:as})}))}else ir.externalData!==void 0&&(Lr=ir.externalData.map(async Gr=>{if(typeof Gr.data=="string"){const Xr=await(0,j.getModelFile)(f,Gr.data,!0,R);return{...Gr,data:Xr}}return Gr}));if(Lr.length>0&&(ir.externalData=await Promise.all(Lr)),Le==="webgpu"){const Gr=(0,I.getKeyValueShapes)(R.config,{prefix:"present"});if(Object.keys(Gr).length>0&&!(0,de.isONNXProxy)()){const Xr={};for(const Qr in Gr)Xr[Qr]="gpu-buffer";ir.preferredOutputLocation=Xr}}return{buffer:await $r,session_options:ir,session_config:Ar}}async function k(f,b,R){return Object.fromEntries(await Promise.all(Object.keys(b).map(async Te=>{const{buffer:Ue,session_options:Le,session_config:pt}=await N(f,b[Te],R),Et=await(0,de.createInferenceSession)(Ue,Le,pt);return[Te,Et]})))}async function le(f,b,R){return Object.fromEntries(await Promise.all(Object.keys(b).map(async Te=>{const Ue=await(0,j.getModelJSON)(f,b[Te],!1,R);return[Te,Ue]})))}function be(f,b){const R=Object.create(null),Te=[];for(const pt of f.inputNames){const Et=b[pt];if(!(Et instanceof q.Tensor)){Te.push(pt);continue}R[pt]=(0,de.isONNXProxy)()?Et.clone():Et}if(Te.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Te.join(", ")}.`);const Ue=Object.keys(b).length,Le=f.inputNames.length;if(Ue>Le){let pt=Object.keys(b).filter(Et=>!f.inputNames.includes(Et));console.warn(`WARNING: Too many inputs were provided (${Ue} > ${Le}). The following inputs will be ignored: "${pt.join(", ")}".`)}return R}async function $e(f,b){const R=be(f,b);try{const Te=Object.fromEntries(Object.entries(R).map(([Le,pt])=>[Le,pt.ort_tensor]));let Ue=await f.run(Te);return Ue=De(Ue),Ue}catch(Te){throw console.error(`An error occurred during model execution: "${Te}".`),console.error("Inputs given to model:",R),Te}}function De(f){for(let b in f)(0,de.isONNXTensor)(f[b])?f[b]=new q.Tensor(f[b]):typeof f[b]=="object"&&De(f[b]);return f}function ze(f){if(f instanceof q.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(b=>b.length!==f[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new q.Tensor("int64",BigInt64Array.from(f.flat().map(b=>BigInt(b))),[f.length,f[0].length])}else return new q.Tensor("int64",BigInt64Array.from(f.map(b=>BigInt(b))),[1,f.length])}function it(f){return new q.Tensor("bool",[f],[1])}async function rt(f,b){let{encoder_outputs:R,input_ids:Te,decoder_input_ids:Ue,...Le}=b;if(!R){const Et=(0,xe.pick)(b,f.sessions.model.inputNames);R=(await lt(f,Et)).last_hidden_state}return Le.input_ids=Ue,Le.encoder_hidden_states=R,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Le.encoder_attention_mask=b.attention_mask),await _e(f,Le,!0)}async function lt(f,b){const R=f.sessions.model,Te=(0,xe.pick)(b,R.inputNames);if(R.inputNames.includes("inputs_embeds")&&!Te.inputs_embeds){if(!b.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Te.inputs_embeds=await f.encode_text({input_ids:b.input_ids})}return R.inputNames.includes("token_type_ids")&&!Te.token_type_ids&&(Te.token_type_ids=new q.Tensor("int64",new BigInt64Array(Te.input_ids.data.length),Te.input_ids.dims)),await $e(R,Te)}async function _e(f,b,R=!1){const Te=f.sessions[R?"decoder_model_merged":"model"],{past_key_values:Ue,...Le}=b;Te.inputNames.includes("use_cache_branch")&&(Le.use_cache_branch=it(!!Ue)),Te.inputNames.includes("position_ids")&&Le.attention_mask&&!Le.position_ids&&(Le.position_ids=ce(Le,Ue)),f.addPastKeyValues(Le,Ue);const pt=(0,xe.pick)(Le,Te.inputNames);return await $e(Te,pt)}async function W(f,{input_ids:b=null,attention_mask:R=null,pixel_values:Te=null,position_ids:Ue=null,inputs_embeds:Le=null,past_key_values:pt=null,generation_config:Et=null,logits_processor:Vt=null,...tr}){if(!Le){if(Le=await f.encode_text({input_ids:b}),Te&&b.dims[1]!==1){const Dr=await f.encode_image({pixel_values:Te});({inputs_embeds:Le,attention_mask:R}=f._merge_input_ids_with_image_features({image_features:Dr,inputs_embeds:Le,input_ids:b,attention_mask:R}))}else if(pt&&Te&&b.dims[1]===1){const Dr=b.dims[1],yr=Object.values(pt)[0].dims.at(-2);R=(0,q.cat)([(0,q.ones)([b.dims[0],yr]),R.slice(null,[R.dims[1]-Dr,R.dims[1]])],1)}}return await _e(f,{inputs_embeds:Le,past_key_values:pt,attention_mask:R,position_ids:Ue,generation_config:Et,logits_processor:Vt},!0)}function ce(f,b=null){const{input_ids:R,inputs_embeds:Te,attention_mask:Ue}=f,[Le,pt]=Ue.dims,Et=new BigInt64Array(Ue.data.length);for(let tr=0;trLe.dims[1])){if(UeEt==f.config.image_token_index)){const Et=f.config.num_image_tokens;if(!Et)throw new Error("`num_image_tokens` is missing in the model configuration.");const Vt=Le.dims[1]-(Ue-Et);R.input_ids=Le.slice(null,[-Vt,null]),R.attention_mask=(0,q.ones)([1,Ue+Vt])}}}return R}function We(f,b,R,Te){return R.past_key_values&&(b=b.map(Ue=>[Ue.at(-1)])),{...R,decoder_input_ids:ze(b)}}function ot(f,...b){return f.config.is_encoder_decoder?We(f,...b):Ce(f,...b)}class ne extends ve.Callable{constructor(R,Te,Ue){super();Me(this,"main_input_name","input_ids");Me(this,"forward_params",["input_ids","attention_mask"]);this.config=R,this.sessions=Te,this.configs=Ue;const Le=E.get(this.constructor),pt=K.get(Le);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,pt){case X.DecoderOnly:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=Ce;break;case X.Seq2Seq:case X.Vision2Seq:case X.Musicgen:this.can_generate=!0,this._forward=rt,this._prepare_inputs_for_generation=We;break;case X.EncoderDecoder:this._forward=rt;break;case X.ImageTextToText:this.can_generate=!0,this._forward=W,this._prepare_inputs_for_generation=ot;break;default:this._forward=lt;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var Te;const R=[];for(const Ue of Object.values(this.sessions))(Te=Ue==null?void 0:Ue.handler)!=null&&Te.dispose&&R.push(Ue.handler.dispose());return await Promise.all(R)}static async from_pretrained(R,{progress_callback:Te=null,config:Ue=null,cache_dir:Le=null,local_files_only:pt=!1,revision:Et="main",model_file_name:Vt=null,subfolder:tr="onnx",device:Ar=null,dtype:Dr=null,use_external_data_format:yr=null,session_options:ir={}}={}){let Ir={progress_callback:Te,config:Ue,cache_dir:Le,local_files_only:pt,revision:Et,model_file_name:Vt,subfolder:tr,device:Ar,dtype:Dr,use_external_data_format:yr,session_options:ir};const $r=E.get(this),gr=K.get($r);Ue=Ir.config=await I.AutoConfig.from_pretrained(R,Ir);let Lr;if(gr===X.DecoderOnly)Lr=await Promise.all([k(R,{model:Ir.model_file_name??"model"},Ir),le(R,{generation_config:"generation_config.json"},Ir)]);else if(gr===X.Seq2Seq||gr===X.Vision2Seq)Lr=await Promise.all([k(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Ir),le(R,{generation_config:"generation_config.json"},Ir)]);else if(gr===X.MaskGeneration)Lr=await Promise.all([k(R,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Ir)]);else if(gr===X.EncoderDecoder)Lr=await Promise.all([k(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Ir)]);else if(gr===X.ImageTextToText){const Tn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ue.is_encoder_decoder&&(Tn.model="encoder_model"),Lr=await Promise.all([k(R,Tn,Ir),le(R,{generation_config:"generation_config.json"},Ir)])}else gr===X.Musicgen?Lr=await Promise.all([k(R,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Ir),le(R,{generation_config:"generation_config.json"},Ir)]):(gr!==X.EncoderOnly&&console.warn(`Model type for '${$r??(Ue==null?void 0:Ue.model_type)}' not found, assuming encoder-only architecture. Please report this at ${P.GITHUB_ISSUE_URL}.`),Lr=await Promise.all([k(R,{model:Ir.model_file_name??"model"},Ir)]));return new this(Ue,...Lr)}async _call(R){return await this.forward(R)}async forward(R){return await this._forward(this,R)}get generation_config(){var R;return((R=this.configs)==null?void 0:R.generation_config)??null}_get_logits_warper(R){const Te=new L.LogitsProcessorList;return R.temperature!==null&&R.temperature!==1&&Te.push(new L.TemperatureLogitsWarper(R.temperature)),R.top_k!==null&&R.top_k!==0&&Te.push(new L.TopKLogitsWarper(R.top_k)),R.top_p!==null&&R.top_p<1&&Te.push(new L.TopPLogitsWarper(R.top_p)),Te}_get_logits_processor(R,Te,Ue=null){const Le=new L.LogitsProcessorList;if(R.repetition_penalty!==null&&R.repetition_penalty!==1&&Le.push(new L.RepetitionPenaltyLogitsProcessor(R.repetition_penalty)),R.no_repeat_ngram_size!==null&&R.no_repeat_ngram_size>0&&Le.push(new L.NoRepeatNGramLogitsProcessor(R.no_repeat_ngram_size)),R.bad_words_ids!==null&&Le.push(new L.NoBadWordsLogitsProcessor(R.bad_words_ids,R.eos_token_id)),R.min_length!==null&&R.eos_token_id!==null&&R.min_length>0&&Le.push(new L.MinLengthLogitsProcessor(R.min_length,R.eos_token_id)),R.min_new_tokens!==null&&R.eos_token_id!==null&&R.min_new_tokens>0&&Le.push(new L.MinNewTokensLengthLogitsProcessor(Te,R.min_new_tokens,R.eos_token_id)),R.forced_bos_token_id!==null&&Le.push(new L.ForcedBOSTokenLogitsProcessor(R.forced_bos_token_id)),R.forced_eos_token_id!==null&&Le.push(new L.ForcedEOSTokenLogitsProcessor(R.max_length,R.forced_eos_token_id)),R.begin_suppress_tokens!==null){const pt=Te>1||R.forced_bos_token_id===null?Te:Te+1;Le.push(new L.SuppressTokensAtBeginLogitsProcessor(R.begin_suppress_tokens,pt))}return R.guidance_scale!==null&&R.guidance_scale>1&&Le.push(new L.ClassifierFreeGuidanceLogitsProcessor(R.guidance_scale)),Ue!==null&&Le.extend(Ue),Le}_prepare_generation_config(R,Te,Ue=B.GenerationConfig){const Le={...this.config};for(const Et of["decoder","generator","text_config"])Et in Le&&Object.assign(Le,Le[Et]);const pt=new Ue(Le);return Object.assign(pt,this.generation_config??{}),R&&Object.assign(pt,R),Te&&Object.assign(pt,(0,xe.pick)(Te,Object.getOwnPropertyNames(pt))),pt}_get_stopping_criteria(R,Te=null){const Ue=new me.StoppingCriteriaList;return R.max_length!==null&&Ue.push(new me.MaxLengthCriteria(R.max_length,this.config.max_position_embeddings??null)),R.eos_token_id!==null&&Ue.push(new me.EosTokenCriteria(R.eos_token_id)),Te&&Ue.extend(Te),Ue}_validate_model_class(){if(!this.can_generate){const R=[ja,Va,Na,Ba],Te=E.get(this.constructor),Ue=new Set,Le=this.config.model_type;for(const Et of R){const Vt=Et.get(Le);Vt&&Ue.add(Vt[0])}let pt=`The current model class (${Te}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ue.size>0&&(pt+=` Please use the following class instead: ${[...Ue].join(", ")}`),Error(pt)}}prepare_inputs_for_generation(...R){return this._prepare_inputs_for_generation(this,...R)}_update_model_kwargs_for_generation({generated_input_ids:R,outputs:Te,model_inputs:Ue,is_encoder_decoder:Le}){return Ue.past_key_values=this.getPastKeyValues(Te,Ue.past_key_values),Ue.input_ids=new q.Tensor("int64",R.flat(),[R.length,1]),Le||(Ue.attention_mask=(0,q.cat)([Ue.attention_mask,(0,q.ones)([Ue.attention_mask.dims[0],1])],1)),Ue.position_ids=null,Ue}_prepare_model_inputs({inputs:R,bos_token_id:Te,model_kwargs:Ue}){const Le=(0,xe.pick)(Ue,this.forward_params),pt=this.main_input_name;if(pt in Le){if(R)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Le[pt]=R;return{inputs_tensor:Le[pt],model_inputs:Le,model_input_name:pt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:R,model_inputs:Te,model_input_name:Ue,generation_config:Le}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Te.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Et,pixel_values:Vt,attention_mask:tr,...Ar}=Te,Dr=await this._prepare_inputs_embeds(Te);Te={...Ar,...(0,xe.pick)(Dr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:pt}=await lt(this,Te);if(Le.guidance_scale!==null&&Le.guidance_scale>1)pt=(0,q.cat)([pt,(0,q.full_like)(pt,0)],0),"attention_mask"in Te&&(Te.attention_mask=(0,q.cat)([Te.attention_mask,(0,q.zeros_like)(Te.attention_mask)],0));else if(Te.decoder_input_ids){const Et=ze(Te.decoder_input_ids).dims[0];if(Et!==pt.dims[0]){if(pt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${pt.dims[0]}) than the decoder inputs (${Et}).`);pt=(0,q.cat)(Array.from({length:Et},()=>pt),0)}}return Te.encoder_outputs=pt,Te}_prepare_decoder_input_ids_for_generation({batch_size:R,model_input_name:Te,model_kwargs:Ue,decoder_start_token_id:Le,bos_token_id:pt,generation_config:Et}){let{decoder_input_ids:Vt,...tr}=Ue;if(!(Vt instanceof q.Tensor)){if(Vt)Array.isArray(Vt[0])||(Vt=Array.from({length:R},()=>Vt));else if(Le??(Le=pt),this.config.model_type==="musicgen")Vt=Array.from({length:R*this.config.decoder.num_codebooks},()=>[Le]);else if(Array.isArray(Le)){if(Le.length!==R)throw new Error(`\`decoder_start_token_id\` expcted to have length ${R} but got ${Le.length}`);Vt=Le}else Vt=Array.from({length:R},()=>[Le]);Vt=ze(Vt)}return Ue.decoder_attention_mask=(0,q.ones_like)(Vt),{input_ids:Vt,model_inputs:tr}}async generate({inputs:R=null,generation_config:Te=null,logits_processor:Ue=null,stopping_criteria:Le=null,streamer:pt=null,...Et}){this._validate_model_class(),Te=this._prepare_generation_config(Te,Et);let{inputs_tensor:Vt,model_inputs:tr,model_input_name:Ar}=this._prepare_model_inputs({inputs:R,model_kwargs:Et});const Dr=this.config.is_encoder_decoder;Dr&&("encoder_outputs"in tr||(tr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Vt,model_inputs:tr,model_input_name:Ar,generation_config:Te})));let yr;Dr?{input_ids:yr,model_inputs:tr}=this._prepare_decoder_input_ids_for_generation({batch_size:tr[Ar].dims.at(0),model_input_name:Ar,model_kwargs:tr,decoder_start_token_id:Te.decoder_start_token_id,bos_token_id:Te.bos_token_id,generation_config:Te}):yr=tr[Ar];let ir=yr.dims.at(-1);Te.max_new_tokens!==null&&(Te.max_length=ir+Te.max_new_tokens);const Ir=this._get_logits_processor(Te,ir,Ue),$r=this._get_stopping_criteria(Te,Le),gr=tr[Ar].dims.at(0),Lr=ue.LogitsSampler.getSampler(Te),Tn=new Array(gr).fill(0),un=yr.tolist();pt&&pt.put(un);let Gr,Xr={};for(;;){if(tr=this.prepare_inputs_for_generation(un,tr,Te),Gr=await this.forward(tr),Te.output_attentions&&Te.return_dict_in_generate){const Wn=this.getAttentions(Gr);for(const Ms in Wn)Ms in Xr||(Xr[Ms]=[]),Xr[Ms].push(Wn[Ms])}const as=Gr.logits.slice(null,-1,null),hi=Ir(un,as),Ja=[];for(let Wn=0;WnWn))break;tr=this._update_model_kwargs_for_generation({generated_input_ids:Ja,outputs:Gr,model_inputs:tr,is_encoder_decoder:Dr})}pt&&pt.end();const Qr=this.getPastKeyValues(Gr,tr.past_key_values,!0),gn=new q.Tensor("int64",un.flat(),[un.length,un[0].length]);if(Te.return_dict_in_generate)return{sequences:gn,past_key_values:Qr,...Xr};for(const as of Object.values(Gr))as.location==="gpu-buffer"&&as.dispose();return gn}getPastKeyValues(R,Te,Ue=!1){const Le=Object.create(null);for(const pt in R)if(pt.startsWith("present")){const Et=pt.replace("present","past_key_values"),Vt=pt.includes("encoder");if(Vt&&Te?Le[Et]=Te[Et]:Le[Et]=R[pt],Te&&(!Vt||Ue)){const tr=Te[Et];tr.location==="gpu-buffer"&&tr.dispose()}}return Le}getAttentions(R){const Te={};for(const Ue of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Le in R)Le.startsWith(Ue)&&(Ue in Te||(Te[Ue]=[]),Te[Ue].push(R[Le]));return Te}addPastKeyValues(R,Te){var Ue;if(Te)Object.assign(R,Te);else{const Le=this.sessions.decoder_model_merged??this.sessions.model,pt=((Ue=Le==null?void 0:Le.config)==null?void 0:Ue.kv_cache_dtype)??"float32",Et=pt==="float16"?new Uint16Array:[],Vt=(0,I.getKeyValueShapes)(this.config);for(const tr in Vt)R[tr]=new q.Tensor(pt,Et,Vt[tr])}}async encode_image({pixel_values:R}){const Te=(await $e(this.sessions.vision_encoder,{pixel_values:R})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${Te.dims[1]}).`),this.config.num_image_tokens=Te.dims[1]),Te}async encode_text({input_ids:R}){return(await $e(this.sessions.embed_tokens,{input_ids:R})).inputs_embeds}}class Ze{}class dt extends Ze{constructor({last_hidden_state:b,hidden_states:R=null,attentions:Te=null}){super(),this.last_hidden_state=b,this.hidden_states=R,this.attentions=Te}}class Re extends ne{}class ht extends Re{}class Mt extends Re{async _call(b){return new ln(await super._call(b))}}class Xe extends Re{async _call(b){return new cr(await super._call(b))}}class Z extends Re{async _call(b){return new sn(await super._call(b))}}class Ae extends Re{async _call(b){return new _n(await super._call(b))}}class Ke extends ne{}class et extends Ke{}class je extends ne{}class Ve extends je{}class ut extends je{async _call(b){return new ln(await super._call(b))}}class _t extends je{async _call(b){return new cr(await super._call(b))}}class St extends je{async _call(b){return new sn(await super._call(b))}}class xt extends je{async _call(b){return new _n(await super._call(b))}}class v extends ne{}class H extends v{}class $ extends v{async _call(b){return new ln(await super._call(b))}}class Y extends v{async _call(b){return new cr(await super._call(b))}}class fe extends v{async _call(b){return new sn(await super._call(b))}}class nt extends v{async _call(b){return new _n(await super._call(b))}}class Je extends ne{}class Nt extends Je{}class yt extends Je{async _call(b){return new ln(await super._call(b))}}class bt extends Je{async _call(b){return new cr(await super._call(b))}}class Dt extends Je{async _call(b){return new sn(await super._call(b))}}class Pt extends Je{async _call(b){return new _n(await super._call(b))}}class dr extends ne{}class Cr extends dr{}class Yr extends dr{async _call(b){return new ln(await super._call(b))}}class Rr extends dr{async _call(b){return new cr(await super._call(b))}}class Jr extends dr{async _call(b){return new sn(await super._call(b))}}class yn extends dr{async _call(b){return new _n(await super._call(b))}}class at extends ne{}class G extends at{}class we extends at{async _call(b){return new ln(await super._call(b))}}class Ie extends at{async _call(b){return new cr(await super._call(b))}}class Se extends at{async _call(b){return new sn(await super._call(b))}}class Ne extends at{async _call(b){return new _n(await super._call(b))}}class tt extends ne{}class wt extends tt{}class mt extends tt{async _call(b){return new ln(await super._call(b))}}class Ct extends tt{async _call(b){return new cr(await super._call(b))}}class ft extends tt{async _call(b){return new sn(await super._call(b))}}class Lt extends tt{async _call(b){return new _n(await super._call(b))}}class jt extends ne{}class Ot extends jt{}class Fe extends jt{async _call(b){return new cr(await super._call(b))}}class Oe extends jt{async _call(b){return new sn(await super._call(b))}}class ct extends jt{async _call(b){return new _n(await super._call(b))}}class Ut extends jt{async _call(b){return new ln(await super._call(b))}}class sr extends ne{}class br extends sr{}class Nr extends sr{async _call(b){return new ln(await super._call(b))}}class mr extends sr{async _call(b){return new cr(await super._call(b))}}class Er extends sr{async _call(b){return new sn(await super._call(b))}}class wr extends ne{}class Cn extends wr{}class Ur extends wr{async _call(b){return new ln(await super._call(b))}}class cs extends wr{async _call(b){return new cr(await super._call(b))}}class Cs extends wr{async _call(b){return new _n(await super._call(b))}}class Kn extends ne{}class $s extends Kn{}class ks extends Kn{async _call(b){return new ln(await super._call(b))}}class Es extends Kn{async _call(b){return new cr(await super._call(b))}}class Ss extends Kn{async _call(b){return new sn(await super._call(b))}}class Ps extends Kn{async _call(b){return new _n(await super._call(b))}}class es extends ne{}class Xn extends es{}class Sn extends es{async _call(b){return new ln(await super._call(b))}}class Bn extends es{async _call(b){return new cr(await super._call(b))}}class ps extends es{async _call(b){return new _n(await super._call(b))}}class Dn extends ne{}class hs extends Dn{}class fs extends Dn{async _call(b){return new cr(await super._call(b))}}class ms extends Dn{async _call(b){return new _n(await super._call(b))}}class Yt extends Dn{async _call(b){return new ln(await super._call(b))}}class ts extends ne{constructor(){super(...arguments);Me(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class As extends ts{}class Is extends ts{}class _s extends ne{}class Fs extends _s{}class Os extends _s{}class rs extends ne{}class zs extends rs{}class ae extends rs{}class _ extends ne{}class F extends _{}class Q extends _{}class oe extends _{async _call(b){return new cr(await super._call(b))}}class ge extends ne{}class Ge extends ge{}class gt extends ge{}class $t extends ge{async _call(b){return new cr(await super._call(b))}}class Tt extends ge{}class zt extends ne{}class er extends zt{}class Sr extends zt{}class lr extends ne{}class Wr extends lr{}class en extends lr{}class or extends ne{}class Pr extends or{}class mn extends or{async _call(b){return new ln(await super._call(b))}}class bn extends or{async _call(b){return new cr(await super._call(b))}}class ke extends or{async _call(b){return new sn(await super._call(b))}}class tn extends or{async _call(b){return new _n(await super._call(b))}}class on extends ne{}class Pn extends on{}class Rn extends on{async _call(b){return new ln(await super._call(b))}}class Kt extends on{async _call(b){return new cr(await super._call(b))}}class pn extends on{async _call(b){return new sn(await super._call(b))}}class Kr extends on{async _call(b){return new _n(await super._call(b))}}class fr extends ne{}class Or extends fr{}class kt extends fr{async _call(b){return new ln(await super._call(b))}}class _r extends fr{async _call(b){return new cr(await super._call(b))}}class ns extends fr{async _call(b){return new sn(await super._call(b))}}class Qn extends fr{async _call(b){return new _n(await super._call(b))}}class Nn extends ne{}class Wt extends Nn{}class Js extends Nn{}class Qe extends ne{constructor(){super(...arguments);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"])}}class qt extends Qe{}class bi extends Qe{_prepare_generation_config(b,R){return super._prepare_generation_config(b,R,J.WhisperGenerationConfig)}_retrieve_init_tokens(b){const R=[b.decoder_start_token_id];let Te=b.language;const Ue=b.task;if(b.is_multilingual){Te||(console.warn("No language specified - defaulting to English (en)."),Te="en");const pt=`<|${(0,pe.whisper_language_to_code)(Te)}|>`;R.push(b.lang_to_id[pt]),R.push(b.task_to_id[Ue??"transcribe"])}else if(Te||Ue)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!b.return_timestamps&&b.no_timestamps_token_id&&R.at(-1)!==b.no_timestamps_token_id?R.push(b.no_timestamps_token_id):b.return_timestamps&&R.at(-1)===b.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),R.pop()),R.filter(Le=>Le!=null)}async generate({inputs:b=null,generation_config:R=null,logits_processor:Te=null,stopping_criteria:Ue=null,...Le}){R=this._prepare_generation_config(R,Le);const pt=Le.decoder_input_ids??this._retrieve_init_tokens(R);if(R.return_timestamps&&(Te??(Te=new L.LogitsProcessorList),Te.push(new L.WhisperTimeStampLogitsProcessor(R,pt))),R.begin_suppress_tokens&&(Te??(Te=new L.LogitsProcessorList),Te.push(new L.SuppressTokensAtBeginLogitsProcessor(R.begin_suppress_tokens,pt.length))),R.return_token_timestamps){if(!R.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");R.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),R.output_attentions=!0,R.return_dict_in_generate=!0}const Et=await super.generate({inputs:b,generation_config:R,logits_processor:Te,decoder_input_ids:pt,...Le});return R.return_token_timestamps&&(Et.token_timestamps=this._extract_token_timestamps(Et,R.alignment_heads,R.num_frames)),Et}_extract_token_timestamps(b,R,Te=null,Ue=.02){if(!b.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");Te==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let Le=this.config.median_filter_width;Le===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Le=7);const pt=b.cross_attentions,Et=Array.from({length:this.config.decoder_layers},($r,gr)=>(0,q.cat)(pt.map(Lr=>Lr[gr]),2)),Vt=(0,q.stack)(R.map(([$r,gr])=>{if($r>=Et.length)throw new Error(`Layer index ${$r} is out of bounds for cross attentions (length ${Et.length}).`);return Te?Et[$r].slice(null,gr,null,[0,Te]):Et[$r].slice(null,gr)})).transpose(1,0,2,3),[tr,Ar]=(0,q.std_mean)(Vt,-2,0,!0),Dr=Vt.clone();for(let $r=0;$rLr[gn+1]-Lr[gn]),Gr=(0,xe.mergeArrays)([1],un).map(Qr=>!!Qr),Xr=[];for(let Qr=0;Qryr.findIndex(ir=>ir==Le)),Vt=Et.every(yr=>yr===-1),tr=Et.every(yr=>yr!==-1);if(!Vt&&!tr)throw new Error("Every input should contain either 0 or 1 image token.");if(Vt)return{inputs_embeds:b,attention_mask:Ue};const Ar=[],Dr=[];for(let yr=0;yrLe*pt,1);b.input_labels=new q.Tensor("int64",new BigInt64Array(Ue).fill(1n),Te)}const R={image_embeddings:b.image_embeddings,image_positional_embeddings:b.image_positional_embeddings};return b.input_points&&(R.input_points=b.input_points),b.input_labels&&(R.input_labels=b.input_labels),b.input_boxes&&(R.input_boxes=b.input_boxes),await $e(this.sessions.prompt_encoder_mask_decoder,R)}async _call(b){return new Ns(await super._call(b))}}class Ns extends Ze{constructor({iou_scores:b,pred_masks:R}){super(),this.iou_scores=b,this.pred_masks=R}}class fa extends ne{}class ma extends fa{}class Xl extends fa{}class _a extends ne{}class Ql extends _a{}class zd extends _a{}class Jn extends ne{}class Yl extends Jn{}class Dd extends Jn{async _call(b){return new is(await super._call(b))}}class ga extends Jn{async _call(b){return new cr(await super._call(b))}}class Zl extends Jn{async _call(b){return new sn(await super._call(b))}}class wa extends ne{}class Jl extends wa{}class eu extends wa{async _call(b){return new sn(await super._call(b))}}class ui extends ne{}class tu extends ui{}class ys extends ne{}class ya extends ys{}class ba extends ys{async _call(b){return new is(await super._call(b))}}class ru extends ys{async _call(b){return new cr(await super._call(b))}}class js extends ne{}class Ma extends js{}class Ld extends js{async _call(b){return new is(await super._call(b))}}class nu extends js{async _call(b){return new cr(await super._call(b))}}class su extends js{async _call(b){return new sn(await super._call(b))}}class va extends ne{}class iu extends va{}class xa extends va{async _call(b){return new is(await super._call(b))}}class Bd extends va{async _call(b){return new cr(await super._call(b))}}class Rd extends ne{}class au extends Jn{}class ou extends Jn{async _call(b){return new is(await super._call(b))}}class Ta extends Jn{async _call(b){return new cr(await super._call(b))}}class bs extends ne{}class lu extends bs{}class uu extends bs{async _call(b){return new is(await super._call(b))}}class du extends bs{async _call(b){return new cr(await super._call(b))}}class cu extends bs{async _call(b){return new wd(await super._call(b))}}class pu extends bs{async _call(b){return new sn(await super._call(b))}}class Ca extends ne{}class Nd extends Ca{}class hu extends Ca{}class fu extends Ca{async generate_speech(b,R,{threshold:Te=.5,minlenratio:Ue=0,maxlenratio:Le=20,vocoder:pt=null}={}){const Et={input_ids:b},{encoder_outputs:Vt,encoder_attention_mask:tr}=await lt(this,Et),Ar=Vt.dims[1]/this.config.reduction_factor,Dr=Math.floor(Ar*Le),yr=Math.floor(Ar*Ue),ir=this.config.num_mel_bins;let Ir=[],$r=null,gr=null,Lr=0;for(;;){++Lr;const Gr=it(!!gr);let Xr;gr?Xr=gr.output_sequence_out:Xr=new q.Tensor("float32",new Float32Array(ir),[1,1,ir]);let Qr={use_cache_branch:Gr,output_sequence:Xr,encoder_attention_mask:tr,speaker_embeddings:R,encoder_hidden_states:Vt};this.addPastKeyValues(Qr,$r),gr=await $e(this.sessions.decoder_model_merged,Qr),$r=this.getPastKeyValues(gr,$r);const{prob:gn,spectrum:as}=gr;if(Ir.push(as),Lr>=yr&&(Array.from(gn.data).filter(hi=>hi>=Te).length>0||Lr>=Dr))break}const Tn=(0,q.cat)(Ir),{waveform:un}=await $e(pt.sessions.model,{spectrogram:Tn});return{spectrogram:Tn,waveform:un}}}class jd extends ne{constructor(){super(...arguments);Me(this,"main_input_name","spectrogram")}}class mu extends ne{}class _u extends mu{}class $a extends ne{}class gu extends $a{}class wu extends $a{}class yu extends ne{}class di extends yu{}class Vs extends yu{}class ci extends ne{}class bu extends ci{}class Mu extends ci{}class pi extends ne{}class vu extends pi{}class ka extends pi{static async from_pretrained(b,R={}){return R.model_file_name??(R.model_file_name="text_model"),super.from_pretrained(b,R)}}class xu extends pi{static async from_pretrained(b,R={}){return R.model_file_name??(R.model_file_name="audio_model"),super.from_pretrained(b,R)}}class Tu extends ne{}class Ea extends Tu{async _call(b){return new bd(await super._call(b))}}class Sa extends ne{}class Vd extends Sa{}class Pa extends Sa{}class Cu extends Sa{}class Aa extends ne{}class $u extends Aa{}class Ud extends Aa{}class Ia extends ne{}class ku extends Ia{}class Wd extends Ia{async _call(b){return new cr(await super._call(b))}}class Fa extends ne{}class Gd extends Fa{}class qd extends Fa{}class Oa extends ne{constructor(){super(...arguments);Me(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(R){const[Te,Ue]=R.dims,Le=this.config.decoder.num_codebooks,pt=Ue-Le;let Et=0;for(let Ar=0;Ar0&&ir<=pt&&(R.data[Et++]=R.data[Ar])}const Vt=Math.floor(Te/Le),tr=Et/(Vt*Le);return new q.Tensor(R.type,R.data.slice(0,Et),[Vt,Le,tr])}prepare_inputs_for_generation(R,Te,Ue){let Le=structuredClone(R);for(let Et=0;Et=Vt&&(Le[Et][Vt]=BigInt(this.config.decoder.pad_token_id));return Ue.guidance_scale!==null&&Ue.guidance_scale>1&&(Le=Le.concat(Le)),super.prepare_inputs_for_generation(Le,Te,Ue)}async generate(R){const Te=await super.generate(R),Ue=this._apply_and_filter_by_delay_pattern_mask(Te).unsqueeze_(0),{audio_values:Le}=await $e(this.sessions.encodec_decode,{audio_codes:Ue});return Le}}class Eu extends ne{}class Su extends Eu{}class Pu extends Eu{async _call(b){return new cr(await super._call(b))}}class za extends ne{}class Au extends za{}class Hd extends za{async _call(b){return new cr(await super._call(b))}}class Da extends ne{}class Iu extends Da{}class Fu extends Da{async _call(b){return new cr(await super._call(b))}}class La extends ne{}class Kd extends La{}class Ou extends La{async _call(b){return new cr(await super._call(b))}}class zu extends ne{}class Du extends zu{}class zr{static async from_pretrained(b,{progress_callback:R=null,config:Te=null,cache_dir:Ue=null,local_files_only:Le=!1,revision:pt="main",model_file_name:Et=null,subfolder:Vt="onnx",device:tr=null,dtype:Ar=null,use_external_data_format:Dr=null,session_options:yr={}}={}){const ir={progress_callback:R,config:Te,cache_dir:Ue,local_files_only:Le,revision:pt,model_file_name:Et,subfolder:Vt,device:tr,dtype:Ar,use_external_data_format:Dr,session_options:yr};if(ir.config=await I.AutoConfig.from_pretrained(b,ir),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const Ir of this.MODEL_CLASS_MAPPINGS){const $r=Ir.get(ir.config.model_type);if($r)return await $r[1].from_pretrained(b,ir)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${ir.config.model_type}", attempting to construct from base class.`),await ne.from_pretrained(b,ir);throw Error(`Unsupported model type: ${ir.config.model_type}`)}}Me(zr,"MODEL_CLASS_MAPPINGS",null),Me(zr,"BASE_IF_FAIL",!1);const Cc=new Map([["bert",["BertModel",ht]],["nomic_bert",["NomicBertModel",et]],["roformer",["RoFormerModel",Ve]],["electra",["ElectraModel",Nt]],["esm",["EsmModel",br]],["convbert",["ConvBertModel",H]],["camembert",["CamembertModel",Cr]],["deberta",["DebertaModel",G]],["deberta-v2",["DebertaV2Model",wt]],["mpnet",["MPNetModel",$s]],["albert",["AlbertModel",hs]],["distilbert",["DistilBertModel",Ot]],["roberta",["RobertaModel",Pr]],["xlm",["XLMModel",Pn]],["xlm-roberta",["XLMRobertaModel",Or]],["clap",["ClapModel",vu]],["clip",["CLIPModel",lo]],["clipseg",["CLIPSegModel",_o]],["chinese_clip",["ChineseCLIPModel",mo]],["siglip",["SiglipModel",co]],["mobilebert",["MobileBertModel",Cn]],["squeezebert",["SqueezeBertModel",Xn]],["wav2vec2",["Wav2Vec2Model",Yl]],["wav2vec2-bert",["Wav2Vec2BertModel",iu]],["unispeech",["UniSpeechModel",ya]],["unispeech-sat",["UniSpeechSatModel",Ma]],["hubert",["HubertModel",au]],["wavlm",["WavLMModel",lu]],["audio-spectrogram-transformer",["ASTModel",Wt]],["vits",["VitsModel",Ea]],["pyannote",["PyAnnoteModel",Jl]],["wespeaker-resnet",["WeSpeakerResNetModel",tu]],["detr",["DetrModel",wl]],["rt_detr",["RTDetrModel",bl]],["table-transformer",["TableTransformerModel",xl]],["vit",["ViTModel",Yo]],["pvt",["PvtModel",Zo]],["vit_msn",["ViTMSNModel",rl]],["vit_mae",["ViTMAEModel",tl]],["groupvit",["GroupViTModel",il]],["fastvit",["FastViTModel",al]],["mobilevit",["MobileViTModel",ni]],["mobilevitv2",["MobileViTV2Model",dl]],["owlvit",["OwlViTModel",pl]],["owlv2",["Owlv2Model",fl]],["beit",["BeitModel",_l]],["deit",["DeiTModel",Cl]],["hiera",["HieraModel",El]],["convnext",["ConvNextModel",Vl]],["convnextv2",["ConvNextV2Model",ca]],["dinov2",["Dinov2Model",Gl]],["resnet",["ResNetModel",Pl]],["swin",["SwinModel",Il]],["swin2sr",["Swin2SRModel",Ol]],["donut-swin",["DonutSwinModel",ua]],["yolos",["YolosModel",ql]],["dpt",["DPTModel",Dl]],["glpn",["GLPNModel",hn]],["hifigan",["SpeechT5HifiGan",jd]],["efficientnet",["EfficientNetModel",ku]],["decision_transformer",["DecisionTransformerModel",Du]],["mobilenet_v1",["MobileNetV1Model",Su]],["mobilenet_v2",["MobileNetV2Model",Au]],["mobilenet_v3",["MobileNetV3Model",Iu]],["mobilenet_v4",["MobileNetV4Model",Kd]],["maskformer",["MaskFormerModel",Zn]]]),Mn=new Map([["t5",["T5Model",As]],["longt5",["LongT5Model",Fs]],["mt5",["MT5Model",zs]],["bart",["BartModel",F]],["mbart",["MBartModel",Ge]],["marian",["MarianModel",ma]],["whisper",["WhisperModel",qt]],["m2m_100",["M2M100Model",Ql]],["blenderbot",["BlenderbotModel",er]],["blenderbot-small",["BlenderbotSmallModel",Wr]]]),Xd=new Map([["bloom",["BloomModel",Go]],["jais",["JAISModel",yo]],["gpt2",["GPT2Model",wo]],["gptj",["GPTJModel",Pd]],["gpt_bigcode",["GPTBigCodeModel",ei]],["gpt_neo",["GPTNeoModel",Mo]],["gpt_neox",["GPTNeoXModel",xo]],["codegen",["CodeGenModel",Co]],["llama",["LlamaModel",ko]],["olmo",["OlmoModel",Ao]],["mobilellm",["MobileLLMModel",So]],["granite",["GraniteModel",Io]],["cohere",["CohereModel",Oo]],["gemma",["GemmaModel",Do]],["gemma2",["Gemma2Model",Bi]],["openelm",["OpenELMModel",Bo]],["qwen2",["Qwen2Model",No]],["phi",["PhiModel",jo]],["phi3",["Phi3Model",Uo]],["mpt",["MptModel",Ho]],["opt",["OPTModel",Ko]],["mistral",["MistralModel",gu]],["starcoder2",["Starcoder2Model",di]],["falcon",["FalconModel",bu]],["stablelm",["StableLmModel",$u]]]),Ba=new Map([["speecht5",["SpeechT5ForSpeechToText",hu]],["whisper",["WhisperForConditionalGeneration",bi]]]),Ra=new Map([["speecht5",["SpeechT5ForTextToSpeech",fu]]]),Lu=new Map([["vits",["VitsModel",Ea]],["musicgen",["MusicgenForConditionalGeneration",Oa]]]),Us=new Map([["bert",["BertForSequenceClassification",Xe]],["roformer",["RoFormerForSequenceClassification",_t]],["electra",["ElectraForSequenceClassification",bt]],["esm",["EsmForSequenceClassification",mr]],["convbert",["ConvBertForSequenceClassification",Y]],["camembert",["CamembertForSequenceClassification",Rr]],["deberta",["DebertaForSequenceClassification",Ie]],["deberta-v2",["DebertaV2ForSequenceClassification",Ct]],["mpnet",["MPNetForSequenceClassification",Es]],["albert",["AlbertForSequenceClassification",fs]],["distilbert",["DistilBertForSequenceClassification",Fe]],["roberta",["RobertaForSequenceClassification",bn]],["xlm",["XLMForSequenceClassification",Kt]],["xlm-roberta",["XLMRobertaForSequenceClassification",_r]],["bart",["BartForSequenceClassification",oe]],["mbart",["MBartForSequenceClassification",$t]],["mobilebert",["MobileBertForSequenceClassification",cs]],["squeezebert",["SqueezeBertForSequenceClassification",Bn]]]),Bu=new Map([["bert",["BertForTokenClassification",Z]],["roformer",["RoFormerForTokenClassification",St]],["electra",["ElectraForTokenClassification",Dt]],["esm",["EsmForTokenClassification",Er]],["convbert",["ConvBertForTokenClassification",fe]],["camembert",["CamembertForTokenClassification",Jr]],["deberta",["DebertaForTokenClassification",Se]],["deberta-v2",["DebertaV2ForTokenClassification",ft]],["mpnet",["MPNetForTokenClassification",Ss]],["distilbert",["DistilBertForTokenClassification",Oe]],["roberta",["RobertaForTokenClassification",ke]],["xlm",["XLMForTokenClassification",pn]],["xlm-roberta",["XLMRobertaForTokenClassification",ns]]]),Na=new Map([["t5",["T5ForConditionalGeneration",Is]],["longt5",["LongT5ForConditionalGeneration",Os]],["mt5",["MT5ForConditionalGeneration",ae]],["bart",["BartForConditionalGeneration",Q]],["mbart",["MBartForConditionalGeneration",gt]],["marian",["MarianMTModel",Xl]],["m2m_100",["M2M100ForConditionalGeneration",zd]],["blenderbot",["BlenderbotForConditionalGeneration",Sr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",en]]]),ja=new Map([["bloom",["BloomForCausalLM",qo]],["gpt2",["GPT2LMHeadModel",An]],["jais",["JAISLMHeadModel",bo]],["gptj",["GPTJForCausalLM",In]],["gpt_bigcode",["GPTBigCodeForCausalLM",Pi]],["gpt_neo",["GPTNeoForCausalLM",vo]],["gpt_neox",["GPTNeoXForCausalLM",To]],["codegen",["CodeGenForCausalLM",$o]],["llama",["LlamaForCausalLM",Eo]],["olmo",["OlmoForCausalLM",Fn]],["mobilellm",["MobileLLMForCausalLM",Po]],["granite",["GraniteForCausalLM",Fo]],["cohere",["CohereForCausalLM",zo]],["gemma",["GemmaForCausalLM",Lo]],["gemma2",["Gemma2ForCausalLM",Ri]],["openelm",["OpenELMForCausalLM",ji]],["qwen2",["Qwen2ForCausalLM",ti]],["phi",["PhiForCausalLM",Vo]],["phi3",["Phi3ForCausalLM",Wo]],["mpt",["MptForCausalLM",Ad]],["opt",["OPTForCausalLM",Xo]],["mbart",["MBartForCausalLM",Tt]],["mistral",["MistralForCausalLM",wu]],["starcoder2",["Starcoder2ForCausalLM",Vs]],["falcon",["FalconForCausalLM",Mu]],["trocr",["TrOCRForCausalLM",_u]],["stablelm",["StableLmForCausalLM",Ud]]]),Ru=new Map([["bert",["BertForMaskedLM",Mt]],["roformer",["RoFormerForMaskedLM",ut]],["electra",["ElectraForMaskedLM",yt]],["esm",["EsmForMaskedLM",Nr]],["convbert",["ConvBertForMaskedLM",$]],["camembert",["CamembertForMaskedLM",Yr]],["deberta",["DebertaForMaskedLM",we]],["deberta-v2",["DebertaV2ForMaskedLM",mt]],["mpnet",["MPNetForMaskedLM",ks]],["albert",["AlbertForMaskedLM",Yt]],["distilbert",["DistilBertForMaskedLM",Ut]],["roberta",["RobertaForMaskedLM",mn]],["xlm",["XLMWithLMHeadModel",Rn]],["xlm-roberta",["XLMRobertaForMaskedLM",kt]],["mobilebert",["MobileBertForMaskedLM",Ur]],["squeezebert",["SqueezeBertForMaskedLM",Sn]]]),Nu=new Map([["bert",["BertForQuestionAnswering",Ae]],["roformer",["RoFormerForQuestionAnswering",xt]],["electra",["ElectraForQuestionAnswering",Pt]],["convbert",["ConvBertForQuestionAnswering",nt]],["camembert",["CamembertForQuestionAnswering",yn]],["deberta",["DebertaForQuestionAnswering",Ne]],["deberta-v2",["DebertaV2ForQuestionAnswering",Lt]],["mpnet",["MPNetForQuestionAnswering",Ps]],["albert",["AlbertForQuestionAnswering",ms]],["distilbert",["DistilBertForQuestionAnswering",ct]],["roberta",["RobertaForQuestionAnswering",tn]],["xlm",["XLMForQuestionAnswering",Kr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Qn]],["mobilebert",["MobileBertForQuestionAnswering",Cs]],["squeezebert",["SqueezeBertForQuestionAnswering",ps]]]),Va=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Mi]]]),ju=new Map([["llava",["LlavaForConditionalGeneration",gs]],["moondream1",["Moondream1ForConditionalGeneration",pr]],["florence2",["Florence2ForConditionalGeneration",vi]]]),Qd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Mi]]]),Vu=new Map([["vit",["ViTForImageClassification",vr]],["pvt",["PvtForImageClassification",Jo]],["vit_msn",["ViTMSNForImageClassification",nl]],["fastvit",["FastViTForImageClassification",ol]],["mobilevit",["MobileViTForImageClassification",ul]],["mobilevitv2",["MobileViTV2ForImageClassification",cl]],["beit",["BeitForImageClassification",gl]],["deit",["DeiTForImageClassification",$l]],["hiera",["HieraForImageClassification",Sl]],["convnext",["ConvNextForImageClassification",Ul]],["convnextv2",["ConvNextV2ForImageClassification",Wl]],["dinov2",["Dinov2ForImageClassification",pa]],["resnet",["ResNetForImageClassification",Al]],["swin",["SwinForImageClassification",Fl]],["segformer",["SegformerForImageClassification",Pa]],["efficientnet",["EfficientNetForImageClassification",Wd]],["mobilenet_v1",["MobileNetV1ForImageClassification",Pu]],["mobilenet_v2",["MobileNetV2ForImageClassification",Hd]],["mobilenet_v3",["MobileNetV3ForImageClassification",Fu]],["mobilenet_v4",["MobileNetV4ForImageClassification",Ou]]]),Uu=new Map([["detr",["DetrForObjectDetection",yl]],["rt_detr",["RTDetrForObjectDetection",Ml]],["table-transformer",["TableTransformerForObjectDetection",Tl]],["yolos",["YolosForObjectDetection",Hl]]]),Wu=new Map([["owlvit",["OwlViTForObjectDetection",hl]],["owlv2",["Owlv2ForObjectDetection",ml]]]),Gu=new Map([["detr",["DetrForSegmentation",ii]],["clipseg",["CLIPSegForImageSegmentation",go]]]),Ua=new Map([["segformer",["SegformerForSemanticSegmentation",Cu]],["sapiens",["SapiensForSemanticSegmentation",Rl]]]),qu=new Map([["detr",["DetrForSegmentation",ii]],["maskformer",["MaskFormerForInstanceSegmentation",oa]]]),Yd=new Map([["sam",["SamModel",ha]]]),Wa=new Map([["wav2vec2",["Wav2Vec2ForCTC",Dd]],["wav2vec2-bert",["Wav2Vec2BertForCTC",xa]],["unispeech",["UniSpeechForCTC",ba]],["unispeech-sat",["UniSpeechSatForCTC",Ld]],["wavlm",["WavLMForCTC",uu]],["hubert",["HubertForCTC",ou]]]),Hu=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",ga]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Bd]],["unispeech",["UniSpeechForSequenceClassification",ru]],["unispeech-sat",["UniSpeechSatForSequenceClassification",nu]],["wavlm",["WavLMForSequenceClassification",du]],["hubert",["HubertForSequenceClassification",Ta]],["audio-spectrogram-transformer",["ASTForAudioClassification",Js]]]),Ku=new Map([["wavlm",["WavLMForXVector",cu]]]),Xu=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",su]],["wavlm",["WavLMForAudioFrameClassification",pu]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Zl]],["pyannote",["PyAnnoteForAudioFrameClassification",eu]]]),Zd=new Map([["vitmatte",["VitMatteForImageMatting",Ds]]]),Qu=new Map([["swin2sr",["Swin2SRForImageSuperResolution",zl]]]),Yu=new Map([["dpt",["DPTForDepthEstimation",Id]],["depth_anything",["DepthAnythingForDepthEstimation",Bl]],["glpn",["GLPNForDepthEstimation",la]],["sapiens",["SapiensForDepthEstimation",Nl]],["depth_pro",["DepthProForDepthEstimation",Yn]]]),Zu=new Map([["sapiens",["SapiensForNormalEstimation",jl]]]),Jd=new Map([["clip",["CLIPVisionModelWithProjection",uo]],["siglip",["SiglipVisionModel",ho]]]),Ju=[[Cc,X.EncoderOnly],[Mn,X.EncoderDecoder],[Xd,X.DecoderOnly],[Us,X.EncoderOnly],[Bu,X.EncoderOnly],[Na,X.Seq2Seq],[Ba,X.Seq2Seq],[ja,X.DecoderOnly],[Ru,X.EncoderOnly],[Nu,X.EncoderOnly],[Va,X.Vision2Seq],[ju,X.ImageTextToText],[Vu,X.EncoderOnly],[Gu,X.EncoderOnly],[qu,X.EncoderOnly],[Ua,X.EncoderOnly],[Zd,X.EncoderOnly],[Qu,X.EncoderOnly],[Yu,X.EncoderOnly],[Zu,X.EncoderOnly],[Uu,X.EncoderOnly],[Wu,X.EncoderOnly],[Yd,X.MaskGeneration],[Wa,X.EncoderOnly],[Hu,X.EncoderOnly],[Ra,X.Seq2Seq],[Lu,X.EncoderOnly],[Ku,X.EncoderOnly],[Xu,X.EncoderOnly],[Jd,X.EncoderOnly]];for(const[f,b]of Ju)for(const[R,Te]of f.values())K.set(R,b),E.set(Te,R),V.set(R,Te);const ec=[["MusicgenForConditionalGeneration",Oa,X.Musicgen],["CLIPTextModelWithProjection",xn,X.EncoderOnly],["SiglipTextModel",po,X.EncoderOnly],["ClapTextModelWithProjection",ka,X.EncoderOnly],["ClapAudioModelWithProjection",xu,X.EncoderOnly]];for(const[f,b,R]of ec)K.set(f,R),E.set(b,f),V.set(f,b);class Ga extends zr{}Me(Ga,"MODEL_CLASS_MAPPINGS",Ju.map(b=>b[0])),Me(Ga,"BASE_IF_FAIL",!0);class ed extends zr{}Me(ed,"MODEL_CLASS_MAPPINGS",[Us]);class td extends zr{}Me(td,"MODEL_CLASS_MAPPINGS",[Bu]);class tc extends zr{}Me(tc,"MODEL_CLASS_MAPPINGS",[Na]);class rd extends zr{}Me(rd,"MODEL_CLASS_MAPPINGS",[Ba]);class nd extends zr{}Me(nd,"MODEL_CLASS_MAPPINGS",[Ra]);class sd extends zr{}Me(sd,"MODEL_CLASS_MAPPINGS",[Lu]);class id extends zr{}Me(id,"MODEL_CLASS_MAPPINGS",[ja]);class ad extends zr{}Me(ad,"MODEL_CLASS_MAPPINGS",[Ru]);class od extends zr{}Me(od,"MODEL_CLASS_MAPPINGS",[Nu]);class ld extends zr{}Me(ld,"MODEL_CLASS_MAPPINGS",[Va]);class ud extends zr{}Me(ud,"MODEL_CLASS_MAPPINGS",[Vu]);class dd extends zr{}Me(dd,"MODEL_CLASS_MAPPINGS",[Gu]);class rc extends zr{}Me(rc,"MODEL_CLASS_MAPPINGS",[Ua]);class Ws extends zr{}Me(Ws,"MODEL_CLASS_MAPPINGS",[qu]);class qa extends zr{}Me(qa,"MODEL_CLASS_MAPPINGS",[Uu]);class Ha extends zr{}Me(Ha,"MODEL_CLASS_MAPPINGS",[Wu]);class Ka extends zr{}Me(Ka,"MODEL_CLASS_MAPPINGS",[Yd]);class Xa extends zr{}Me(Xa,"MODEL_CLASS_MAPPINGS",[Wa]);class cd extends zr{}Me(cd,"MODEL_CLASS_MAPPINGS",[Hu]);class pd extends zr{}Me(pd,"MODEL_CLASS_MAPPINGS",[Ku]);class Qa extends zr{}Me(Qa,"MODEL_CLASS_MAPPINGS",[Xu]);class Ya extends zr{}Me(Ya,"MODEL_CLASS_MAPPINGS",[Qd]);class hd extends zr{}Me(hd,"MODEL_CLASS_MAPPINGS",[Zd]);class fd extends zr{}Me(fd,"MODEL_CLASS_MAPPINGS",[Qu]);class Za extends zr{}Me(Za,"MODEL_CLASS_MAPPINGS",[Yu]);class md extends zr{}Me(md,"MODEL_CLASS_MAPPINGS",[Zu]);class _d extends zr{}Me(_d,"MODEL_CLASS_MAPPINGS",[Jd]);class gd extends Ze{constructor({logits:b,past_key_values:R,encoder_outputs:Te,decoder_attentions:Ue=null,cross_attentions:Le=null}){super(),this.logits=b,this.past_key_values=R,this.encoder_outputs=Te,this.decoder_attentions=Ue,this.cross_attentions=Le}}class cr extends Ze{constructor({logits:b}){super(),this.logits=b}}class wd extends Ze{constructor({logits:b,embeddings:R}){super(),this.logits=b,this.embeddings=R}}class sn extends Ze{constructor({logits:b}){super(),this.logits=b}}class ln extends Ze{constructor({logits:b}){super(),this.logits=b}}class _n extends Ze{constructor({start_logits:b,end_logits:R}){super(),this.start_logits=b,this.end_logits=R}}class is extends Ze{constructor({logits:b}){super(),this.logits=b}}class nc extends Ze{constructor({logits:b,past_key_values:R}){super(),this.logits=b,this.past_key_values=R}}class yd extends Ze{constructor({alphas:b}){super(),this.alphas=b}}class bd extends Ze{constructor({waveform:b,spectrogram:R}){super(),this.waveform=b,this.spectrogram=R}}},"./src/models/whisper/common_whisper.js":(At,ye,D)=>{D.r(ye),D.d(ye,{WHISPER_LANGUAGE_MAPPING:()=>de,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>he,whisper_language_to_code:()=>ve});const I=[["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"]],de=new Map(I),he=new Map([...I.map(([xe,j])=>[j,xe]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function ve(xe){xe=xe.toLowerCase();let j=he.get(xe);if(j===void 0)if(de.has(xe))j=xe;else{const L=xe.length===2?de.keys():de.values();throw new Error(`Language "${xe}" is not supported. Must be one of: ${JSON.stringify(L)}`)}return j}},"./src/models/whisper/generation_whisper.js":(At,ye,D)=>{D.r(ye),D.d(ye,{WhisperGenerationConfig:()=>de});var I=D("./src/generation/configuration_utils.js");class de extends I.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":(At,ye,D)=>{D.r(ye),D.d(ye,{TensorOpRegistry:()=>ve});var I=D("./src/backends/onnx.js"),de=D("./src/utils/tensor.js");const he=async(xe,j,P)=>{const L=await(0,I.createInferenceSession)(new Uint8Array(xe),j);return async B=>{const q=Object.fromEntries(Object.entries(B).map(([me,ue])=>[me,ue.ort_tensor])),re=await L.run(q);return Array.isArray(P)?P.map(me=>new de.Tensor(re[me])):new de.Tensor(re[P])}};class ve{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=he([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=he([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=he([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=he([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=he([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=he([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(ve,"session_options",{})},"./src/pipelines.js":(At,ye,D)=>{D.r(ye),D.d(ye,{AudioClassificationPipeline:()=>De,AutomaticSpeechRecognitionPipeline:()=>it,DepthEstimationPipeline:()=>Ze,DocumentQuestionAnsweringPipeline:()=>We,FeatureExtractionPipeline:()=>be,FillMaskPipeline:()=>X,ImageClassificationPipeline:()=>lt,ImageFeatureExtractionPipeline:()=>$e,ImageSegmentationPipeline:()=>_e,ImageToImagePipeline:()=>ne,ImageToTextPipeline:()=>rt,ObjectDetectionPipeline:()=>ce,Pipeline:()=>ue,QuestionAnsweringPipeline:()=>pe,SummarizationPipeline:()=>V,Text2TextGenerationPipeline:()=>K,TextClassificationPipeline:()=>O,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>ot,TokenClassificationPipeline:()=>J,TranslationPipeline:()=>E,ZeroShotAudioClassificationPipeline:()=>ze,ZeroShotClassificationPipeline:()=>le,ZeroShotImageClassificationPipeline:()=>W,ZeroShotObjectDetectionPipeline:()=>Ce,pipeline:()=>ht});var I=D("./src/tokenizers.js"),de=D("./src/models.js"),he=D("./src/processors.js"),ve=D("./src/utils/generic.js"),xe=D("./src/utils/core.js"),j=D("./src/utils/maths.js"),P=D("./src/utils/audio.js"),L=D("./src/utils/tensor.js"),B=D("./src/utils/image.js");async function q(Xe){return Array.isArray(Xe)||(Xe=[Xe]),await Promise.all(Xe.map(Z=>B.RawImage.read(Z)))}async function re(Xe,Z){return Array.isArray(Xe)||(Xe=[Xe]),await Promise.all(Xe.map(Ae=>typeof Ae=="string"||Ae instanceof URL?(0,P.read_audio)(Ae,Z):Ae instanceof Float64Array?new Float32Array(Ae):Ae))}function me(Xe,Z){Z&&(Xe=Xe.map(Ve=>Ve|0));const[Ae,Ke,et,je]=Xe;return{xmin:Ae,ymin:Ke,xmax:et,ymax:je}}class ue extends ve.Callable{constructor({task:Z,model:Ae,tokenizer:Ke=null,processor:et=null}){super(),this.task=Z,this.model=Ae,this.tokenizer=Ke,this.processor=et}async dispose(){await this.model.dispose()}}class O extends ue{constructor(Z){super(Z)}async _call(Z,{top_k:Ae=1}={}){const Ke=this.tokenizer(Z,{padding:!0,truncation:!0}),et=await this.model(Ke),je=this.model.config.problem_type==="multi_label_classification"?_t=>_t.sigmoid():_t=>new L.Tensor("float32",(0,j.softmax)(_t.data),_t.dims),Ve=this.model.config.id2label,ut=[];for(const _t of et.logits){const St=je(_t),xt=await(0,L.topk)(St,Ae),v=xt[0].tolist(),$=xt[1].tolist().map((Y,fe)=>({label:Ve?Ve[Y]:`LABEL_${Y}`,score:v[fe]}));Ae===1?ut.push(...$):ut.push($)}return Array.isArray(Z)||Ae===1?ut:ut[0]}}class J extends ue{constructor(Z){super(Z)}async _call(Z,{ignore_labels:Ae=["O"]}={}){const Ke=Array.isArray(Z),et=this.tokenizer(Ke?Z:[Z],{padding:!0,truncation:!0}),Ve=(await this.model(et)).logits,ut=this.model.config.id2label,_t=[];for(let St=0;Styt==this.tokenizer.sep_token_id);_t[v].map((yt,bt)=>yt==1&&(bt===0||bt>$&&St.findIndex(Dt=>Dt==H[bt])===-1));const Y=je[v].tolist(),fe=Ve[v].tolist();for(let yt=1;ytbt==H[yt])!==-1)&&(Y[yt]=-1/0,fe[yt]=-1/0);const nt=(0,j.softmax)(Y).map((yt,bt)=>[yt,bt]),Je=(0,j.softmax)(fe).map((yt,bt)=>[yt,bt]);nt[0][0]=0,Je[0][0]=0;const Nt=(0,xe.product)(nt,Je).filter(yt=>yt[0][1]<=yt[1][1]).map(yt=>[yt[0][1],yt[1][1],yt[0][0]*yt[1][0]]).sort((yt,bt)=>bt[2]-yt[2]);for(let yt=0;ytY==this.tokenizer.mask_token_id);if(St===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const xt=et[ut][St],v=await(0,L.topk)(new L.Tensor("float32",(0,j.softmax)(xt.data),xt.dims),Ae),H=v[0].tolist(),$=v[1].tolist();je.push($.map((Y,fe)=>{const nt=_t.slice();return nt[St]=Y,{score:H[fe],token:Number(Y),token_str:this.tokenizer.model.vocab[Y],sequence:this.tokenizer.decode(nt,{skip_special_tokens:!0})}}))}return Array.isArray(Z)?je:je[0]}}class K extends ue{constructor(Ae){super(Ae);Me(this,"_key","generated_text")}async _call(Ae,Ke={}){Array.isArray(Ae)||(Ae=[Ae]),this.model.config.prefix&&(Ae=Ae.map(St=>this.model.config.prefix+St));const et=this.model.config.task_specific_params;et&&et[this.task]&&et[this.task].prefix&&(Ae=Ae.map(St=>et[this.task].prefix+St));const je=this.tokenizer,Ve={padding:!0,truncation:!0};let ut;this instanceof E&&"_build_translation_inputs"in je?ut=je._build_translation_inputs(Ae,Ve,Ke):ut=je(Ae,Ve);const _t=await this.model.generate({...ut,...Ke});return je.batch_decode(_t,{skip_special_tokens:!0}).map(St=>({[this._key]:St}))}}class V extends K{constructor(Ae){super(Ae);Me(this,"_key","summary_text")}}class E extends K{constructor(Ae){super(Ae);Me(this,"_key","translation_text")}}function N(Xe){return Array.isArray(Xe)&&Xe.every(Z=>"role"in Z&&"content"in Z)}class k extends ue{constructor(Z){super(Z)}async _call(Z,Ae={}){let Ke=!1,et=!1,je;if(typeof Z=="string")je=Z=[Z];else if(Array.isArray(Z)&&Z.every($=>typeof $=="string"))Ke=!0,je=Z;else{if(N(Z))Z=[Z];else if(Array.isArray(Z)&&Z.every(N))Ke=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");et=!0,je=Z.map($=>this.tokenizer.apply_chat_template($,{tokenize:!1,add_generation_prompt:!0}))}const Ve=Ae.add_special_tokens??!1,ut=et?!1:Ae.return_full_text??!0;this.tokenizer.padding_side="left";const _t=this.tokenizer(je,{add_special_tokens:Ve,padding:!0,truncation:!0}),St=await this.model.generate({..._t,...Ae}),xt=this.tokenizer.batch_decode(St,{skip_special_tokens:!0});let v;!ut&&_t.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(_t.input_ids,{skip_special_tokens:!0}).map($=>$.length));const H=Array.from({length:Z.length},$=>[]);for(let $=0;$[Ae.toLowerCase(),Ke])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(Z,Ae,{hypothesis_template:Ke="This example is {}.",multi_label:et=!1}={}){const je=Array.isArray(Z);je||(Z=[Z]),Array.isArray(Ae)||(Ae=[Ae]);const Ve=Ae.map(St=>Ke.replace("{}",St)),ut=et||Ae.length===1,_t=[];for(const St of Z){const xt=[];for(const $ of Ve){const Y=this.tokenizer(St,{text_pair:$,padding:!0,truncation:!0}),fe=await this.model(Y);ut?xt.push([fe.logits.data[this.contradiction_id],fe.logits.data[this.entailment_id]]):xt.push(fe.logits.data[this.entailment_id])}const H=(ut?xt.map($=>(0,j.softmax)($)[1]):(0,j.softmax)(xt)).map(($,Y)=>[$,Y]).sort(($,Y)=>Y[0]-$[0]);_t.push({sequence:St,labels:H.map($=>Ae[$[1]]),scores:H.map($=>$[0])})}return je?_t:_t[0]}}class be extends ue{constructor(Z){super(Z)}async _call(Z,{pooling:Ae="none",normalize:Ke=!1,quantize:et=!1,precision:je="binary"}={}){const Ve=this.tokenizer(Z,{padding:!0,truncation:!0}),ut=await this.model(Ve);let _t=ut.last_hidden_state??ut.logits??ut.token_embeddings;if(Ae!=="none")if(Ae==="mean")_t=(0,L.mean_pooling)(_t,Ve.attention_mask);else if(Ae==="cls")_t=_t.slice(null,0);else throw Error(`Pooling method '${Ae}' not supported.`);return Ke&&(_t=_t.normalize(2,-1)),et&&(_t=(0,L.quantize_embeddings)(_t,je)),_t}}class $e extends ue{constructor(Z){super(Z)}async _call(Z,{pool:Ae=null}={}){const Ke=await q(Z),{pixel_values:et}=await this.processor(Ke),je=await this.model({pixel_values:et});let Ve;if(Ae){if(!("pooler_output"in je))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ve=je.pooler_output}else Ve=je.last_hidden_state??je.logits??je.image_embeds;return Ve}}class De extends ue{constructor(Z){super(Z)}async _call(Z,{top_k:Ae=5}={}){const Ke=this.processor.feature_extractor.config.sampling_rate,et=await re(Z,Ke),je=this.model.config.id2label,Ve=[];for(const ut of et){const _t=await this.processor(ut),xt=(await this.model(_t)).logits[0],v=await(0,L.topk)(new L.Tensor("float32",(0,j.softmax)(xt.data),xt.dims),Ae),H=v[0].tolist(),Y=v[1].tolist().map((fe,nt)=>({label:je?je[fe]:`LABEL_${fe}`,score:H[nt]}));Ve.push(Y)}return Array.isArray(Z)?Ve:Ve[0]}}class ze extends ue{constructor(Z){super(Z)}async _call(Z,Ae,{hypothesis_template:Ke="This is a sound of {}."}={}){const et=!Array.isArray(Z);et&&(Z=[Z]);const je=Ae.map(xt=>Ke.replace("{}",xt)),Ve=this.tokenizer(je,{padding:!0,truncation:!0}),ut=this.processor.feature_extractor.config.sampling_rate,_t=await re(Z,ut),St=[];for(const xt of _t){const v=await this.processor(xt),H=await this.model({...Ve,...v}),$=(0,j.softmax)(H.logits_per_audio.data);St.push([...$].map((Y,fe)=>({score:Y,label:Ae[fe]})))}return et?St[0]:St}}class it extends ue{constructor(Z){super(Z)}async _call(Z,Ae={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(Z,Ae);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(Z,Ae);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Z,Ae){Ae.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Ae.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ke=!Array.isArray(Z);Ke&&(Z=[Z]);const et=this.processor.feature_extractor.config.sampling_rate,je=await re(Z,et),Ve=[];for(const ut of je){const _t=await this.processor(ut),xt=(await this.model(_t)).logits[0],v=[];for(const $ of xt)v.push((0,j.max)($.data)[1]);const H=this.tokenizer.decode(v);Ve.push({text:H})}return Ke?Ve[0]:Ve}async _call_whisper(Z,Ae){const Ke=Ae.return_timestamps??!1,et=Ae.chunk_length_s??0,je=Ae.force_full_sequences??!1;let Ve=Ae.stride_length_s??null;const ut={...Ae};Ke==="word"&&(ut.return_token_timestamps=!0,ut.return_timestamps=!1);const _t=!Array.isArray(Z);_t&&(Z=[Z]);const St=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,xt=this.processor.feature_extractor.config.hop_length,v=this.processor.feature_extractor.config.sampling_rate,H=await re(Z,v),$=[];for(const Y of H){let fe=[];if(et>0){if(Ve===null)Ve=et/6;else if(et<=Ve)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Nt=v*et,yt=v*Ve,bt=Nt-2*yt;let Dt=0;for(;;){const Pt=Dt+Nt,dr=Y.subarray(Dt,Pt),Cr=await this.processor(dr),Yr=Dt===0,Rr=Pt>=Y.length;if(fe.push({stride:[dr.length,Yr?0:yt,Rr?0:yt],input_features:Cr.input_features,is_last:Rr}),Rr)break;Dt+=bt}}else fe=[{stride:[Y.length,0,0],input_features:(await this.processor(Y)).input_features,is_last:!0}];for(const Nt of fe){ut.num_frames=Math.floor(Nt.stride[0]/xt);const yt=await this.model.generate({inputs:Nt.input_features,...ut});Ke==="word"?(Nt.tokens=yt.sequences.tolist()[0],Nt.token_timestamps=yt.token_timestamps.tolist()[0].map(bt=>(0,j.round)(bt,2))):Nt.tokens=yt[0].tolist(),Nt.stride=Nt.stride.map(bt=>bt/v)}const[nt,Je]=this.tokenizer._decode_asr(fe,{time_precision:St,return_timestamps:Ke,force_full_sequences:je});$.push({text:nt,...Je})}return _t?$[0]:$}}class rt extends ue{constructor(Z){super(Z)}async _call(Z,Ae={}){const Ke=Array.isArray(Z),et=await q(Z),{pixel_values:je}=await this.processor(et),Ve=[];for(const ut of je){ut.dims=[1,...ut.dims];const _t=await this.model.generate({inputs:ut,...Ae}),St=this.tokenizer.batch_decode(_t,{skip_special_tokens:!0}).map(xt=>({generated_text:xt.trim()}));Ve.push(St)}return Ke?Ve:Ve[0]}}class lt extends ue{constructor(Z){super(Z)}async _call(Z,{top_k:Ae=5}={}){const Ke=await q(Z),{pixel_values:et}=await this.processor(Ke),je=await this.model({pixel_values:et}),Ve=this.model.config.id2label,ut=[];for(const _t of je.logits){const St=await(0,L.topk)(new L.Tensor("float32",(0,j.softmax)(_t.data),_t.dims),Ae),xt=St[0].tolist(),H=St[1].tolist().map(($,Y)=>({label:Ve?Ve[$]:`LABEL_${$}`,score:xt[Y]}));ut.push(H)}return Array.isArray(Z)?ut:ut[0]}}class _e extends ue{constructor(Z){super(Z),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Z,{threshold:Ae=.5,mask_threshold:Ke=.5,overlap_mask_area_threshold:et=.8,label_ids_to_fuse:je=null,target_sizes:Ve=null,subtask:ut=null}={}){if(Array.isArray(Z)&&Z.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const St=await q(Z),xt=St.map(Je=>[Je.height,Je.width]),{pixel_values:v,pixel_mask:H}=await this.processor(St),$=await this.model({pixel_values:v,pixel_mask:H});let Y=null;if(ut!==null)Y=this.subtasks_mapping[ut];else for(let[Je,Nt]of Object.entries(this.subtasks_mapping))if(Nt in this.processor.feature_extractor){Y=this.processor.feature_extractor[Nt].bind(this.processor.feature_extractor),ut=Je;break}const fe=this.model.config.id2label,nt=[];if(ut==="panoptic"||ut==="instance"){const Je=Y($,Ae,Ke,et,je,Ve??xt)[0],Nt=Je.segmentation;for(const yt of Je.segments_info){const bt=new Uint8ClampedArray(Nt.data.length);for(let Pt=0;PtKe.replace("{}",H)),ut=this.tokenizer(Ve,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:_t}=await this.processor(je),St=await this.model({...ut,pixel_values:_t}),xt=this.model.config.model_type==="siglip"?H=>H.sigmoid().data:H=>(0,j.softmax)(H.data),v=[];for(const H of St.logits_per_image){const Y=[...xt(H)].map((fe,nt)=>({score:fe,label:Ae[nt]}));Y.sort((fe,nt)=>nt.score-fe.score),v.push(Y)}return et?v:v[0]}}class ce extends ue{constructor(Z){super(Z)}async _call(Z,{threshold:Ae=.9,percentage:Ke=!1}={}){const et=Array.isArray(Z);if(et&&Z.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const je=await q(Z),Ve=Ke?null:je.map($=>[$.height,$.width]),{pixel_values:ut,pixel_mask:_t}=await this.processor(je),St=await this.model({pixel_values:ut,pixel_mask:_t}),xt=this.processor.feature_extractor.post_process_object_detection(St,Ae,Ve),v=this.model.config.id2label,H=xt.map($=>$.boxes.map((Y,fe)=>({score:$.scores[fe],label:v[$.classes[fe]],box:me(Y,!Ke)})));return et?H:H[0]}}class Ce extends ue{constructor(Z){super(Z)}async _call(Z,Ae,{threshold:Ke=.1,top_k:et=null,percentage:je=!1}={}){const Ve=Array.isArray(Z),ut=await q(Z),_t=this.tokenizer(Ae,{padding:!0,truncation:!0}),St=await this.processor(ut),xt=[];for(let v=0;v({score:nt.scores[yt],label:Ae[nt.classes[yt]],box:me(Nt,!je)})).sort((Nt,yt)=>yt.score-Nt.score);et!==null&&(Je=Je.slice(0,et)),xt.push(Je)}return Ve?xt:xt[0]}}class We extends ue{constructor(Z){super(Z)}async _call(Z,Ae,Ke={}){const et=(await q(Z))[0],{pixel_values:je}=await this.processor(et),Ve=`${Ae}`,ut=this.tokenizer(Ve,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,_t=await this.model.generate({inputs:je,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:ut,...Ke}),xt=this.tokenizer.batch_decode(_t)[0].match(/(.*?)<\/s_answer>/);let v=null;return xt&&xt.length>=2&&(v=xt[1].trim()),[{answer:v}]}}class ot extends ue{constructor(Ae){super(Ae);Me(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Ae.vocoder??null}async _call(Ae,{speaker_embeddings:Ke=null}={}){return this.processor?this._call_text_to_spectrogram(Ae,{speaker_embeddings:Ke}):this._call_text_to_waveform(Ae)}async _call_text_to_waveform(Ae){const Ke=this.tokenizer(Ae,{padding:!0,truncation:!0}),{waveform:et}=await this.model(Ke),je=this.model.config.sampling_rate;return{audio:et.data,sampling_rate:je}}async _call_text_to_spectrogram(Ae,{speaker_embeddings:Ke}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await de.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ke=="string"||Ke instanceof URL)&&(Ke=new Float32Array(await(await fetch(Ke)).arrayBuffer())),Ke instanceof Float32Array)Ke=new L.Tensor("float32",Ke,[1,Ke.length]);else if(!(Ke instanceof L.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:et}=this.tokenizer(Ae,{padding:!0,truncation:!0}),{waveform:je}=await this.model.generate_speech(et,Ke,{vocoder:this.vocoder}),Ve=this.processor.feature_extractor.config.sampling_rate;return{audio:je.data,sampling_rate:Ve}}}class ne extends ue{constructor(Z){super(Z)}async _call(Z){const Ae=await q(Z),Ke=await this.processor(Ae),et=await this.model(Ke),je=[];for(const Ve of et.reconstruction){const ut=Ve.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");je.push(B.RawImage.fromTensor(ut))}return je.length>1?je:je[0]}}class Ze extends ue{constructor(Z){super(Z)}async _call(Z){const Ae=await q(Z),Ke=await this.processor(Ae),{predicted_depth:et}=await this.model(Ke),je=[];for(let Ve=0;Ve1?je:je[0]}}const dt=Object.freeze({"text-classification":{tokenizer:I.AutoTokenizer,pipeline:O,model:de.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:I.AutoTokenizer,pipeline:J,model:de.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:I.AutoTokenizer,pipeline:pe,model:de.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:I.AutoTokenizer,pipeline:X,model:de.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:I.AutoTokenizer,pipeline:V,model:de.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:I.AutoTokenizer,pipeline:E,model:de.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:I.AutoTokenizer,pipeline:K,model:de.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:I.AutoTokenizer,pipeline:k,model:de.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:I.AutoTokenizer,pipeline:le,model:de.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:De,model:de.AutoModelForAudioClassification,processor:he.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:I.AutoTokenizer,pipeline:ze,model:de.AutoModel,processor:he.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:I.AutoTokenizer,pipeline:it,model:[de.AutoModelForSpeechSeq2Seq,de.AutoModelForCTC],processor:he.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:I.AutoTokenizer,pipeline:ot,model:[de.AutoModelForTextToWaveform,de.AutoModelForTextToSpectrogram],processor:[he.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:I.AutoTokenizer,pipeline:rt,model:de.AutoModelForVision2Seq,processor:he.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:lt,model:de.AutoModelForImageClassification,processor:he.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:_e,model:[de.AutoModelForImageSegmentation,de.AutoModelForSemanticSegmentation,de.AutoModelForUniversalSegmentation],processor:he.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:I.AutoTokenizer,pipeline:W,model:de.AutoModel,processor:he.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ce,model:de.AutoModelForObjectDetection,processor:he.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:I.AutoTokenizer,pipeline:Ce,model:de.AutoModelForZeroShotObjectDetection,processor:he.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:I.AutoTokenizer,pipeline:We,model:de.AutoModelForDocumentQuestionAnswering,processor:he.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ne,model:de.AutoModelForImageToImage,processor:he.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ze,model:de.AutoModelForDepthEstimation,processor:he.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:I.AutoTokenizer,pipeline:be,model:de.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:he.AutoProcessor,pipeline:$e,model:[de.AutoModelForImageFeatureExtraction,de.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Re=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ht(Xe,Z=null,{progress_callback:Ae=null,config:Ke=null,cache_dir:et=null,local_files_only:je=!1,revision:Ve="main",device:ut=null,dtype:_t=null,model_file_name:St=null,session_options:xt={}}={}){Xe=Re[Xe]??Xe;const v=dt[Xe.split("_",1)[0]];if(!v)throw Error(`Unsupported pipeline: ${Xe}. Must be one of [${Object.keys(dt)}]`);Z||(Z=v.default.model,console.log(`No model specified. Using default model: "${Z}".`));const H={progress_callback:Ae,config:Ke,cache_dir:et,local_files_only:je,revision:Ve,device:ut,dtype:_t,model_file_name:St,session_options:xt},$=new Map([["tokenizer",v.tokenizer],["model",v.model],["processor",v.processor]]),Y=await Mt($,Z,H);Y.task=Xe,(0,xe.dispatchCallback)(Ae,{status:"ready",task:Xe,model:Z});const fe=v.pipeline;return new fe(Y)}async function Mt(Xe,Z,Ae){const Ke=Object.create(null),et=[];for(const[je,Ve]of Xe.entries()){if(!Ve)continue;let ut;Array.isArray(Ve)?ut=new Promise(async(_t,St)=>{var v,H;let xt;for(const $ of Ve){if($===null){_t(null);return}try{_t(await $.from_pretrained(Z,Ae));return}catch(Y){if((v=Y.message)!=null&&v.includes("Unsupported model type"))xt=Y;else if((H=Y.message)!=null&&H.includes("Could not locate file"))xt=Y;else{St(Y);return}}}St(xt)}):ut=Ve.from_pretrained(Z,Ae),Ke[je]=ut,et.push(ut)}await Promise.all(et);for(const[je,Ve]of Object.entries(Ke))Ke[je]=await Ve;return Ke}},"./src/processors.js":(At,ye,D)=>{D.r(ye),D.d(ye,{ASTFeatureExtractor:()=>fe,AutoProcessor:()=>yn,BeitFeatureExtractor:()=>Ae,BitImageProcessor:()=>be,CLIPFeatureExtractor:()=>De,CLIPImageProcessor:()=>ze,ChineseCLIPFeatureExtractor:()=>it,ClapFeatureExtractor:()=>nt,ConvNextFeatureExtractor:()=>lt,ConvNextImageProcessor:()=>_e,DPTFeatureExtractor:()=>k,DPTImageProcessor:()=>le,DeiTFeatureExtractor:()=>Z,DetrFeatureExtractor:()=>Ve,DonutFeatureExtractor:()=>Ke,DonutImageProcessor:()=>et,EfficientNetImageProcessor:()=>Ce,FeatureExtractor:()=>X,Florence2Processor:()=>Jr,GLPNFeatureExtractor:()=>$e,ImageFeatureExtractor:()=>K,MaskFormerFeatureExtractor:()=>ut,MobileNetV1FeatureExtractor:()=>We,MobileNetV2FeatureExtractor:()=>ot,MobileNetV3FeatureExtractor:()=>ne,MobileNetV4FeatureExtractor:()=>Ze,MobileViTFeatureExtractor:()=>dt,MobileViTImageProcessor:()=>Re,NougatImageProcessor:()=>je,OwlViTFeatureExtractor:()=>ht,OwlViTProcessor:()=>Rr,Owlv2ImageProcessor:()=>Mt,Processor:()=>bt,PvtImageProcessor:()=>N,PyAnnoteFeatureExtractor:()=>Je,PyAnnoteProcessor:()=>Cr,RTDetrImageProcessor:()=>Xe,SamImageProcessor:()=>St,SamProcessor:()=>Dt,SapiensFeatureExtractor:()=>V,SeamlessM4TFeatureExtractor:()=>Y,SegformerFeatureExtractor:()=>E,SiglipImageProcessor:()=>rt,SpeechT5FeatureExtractor:()=>yt,SpeechT5Processor:()=>Yr,Swin2SRImageProcessor:()=>xt,ViTFeatureExtractor:()=>W,ViTImageProcessor:()=>ce,VitMatteImageProcessor:()=>v,Wav2Vec2FeatureExtractor:()=>$,Wav2Vec2ProcessorWithLM:()=>dr,WeSpeakerFeatureExtractor:()=>Nt,WhisperFeatureExtractor:()=>H,WhisperProcessor:()=>Pt,YolosFeatureExtractor:()=>_t});var I=D("./src/utils/generic.js"),de=D("./src/utils/core.js"),he=D("./src/utils/hub.js"),ve=D("./src/utils/maths.js"),xe=D("./src/utils/tensor.js");D("./src/utils/image.js");var j=D("./src/utils/audio.js");function P([at,G,we,Ie]){return[at-we/2,G-Ie/2,at+we/2,G+Ie/2]}function L(at,G=.5,we=null,Ie=!1){const Se=at.logits,Ne=at.pred_boxes,[tt,wt,mt]=Se.dims;if(we!==null&&we.length!==tt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Ct=[];for(let ft=0;ftG&&Ut.push(br)}else{let br=(0,ve.max)(ct.data)[1];if(br===mt-1||(sr=(0,ve.softmax)(ct.data),sr[br]mr*Lt[(Er+1)%2])),jt.boxes.push(Nr),jt.classes.push(br),jt.scores.push(sr[br])}}Ct.push(jt)}return Ct}function B(at,G=null){const we=at.logits,Ie=we.dims[0];if(G!==null&&G.length!==Ie)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Se=[];for(let Ne=0;NeLt[Ut]&&(Lt[Ut]=ct[Ut],jt[Ut]=Oe)}const Ot=new Array(wt.dims[0]);for(let Oe=0;OeOe!==void 0);Se.push({segmentation:ft,labels:Fe})}return Se}function q(at,G,we,Ie){const Se=[],Ne=[],tt=[];for(let wt=0;wtwe&&(Se.push(Ct),Ne.push(jt),tt.push(ft))}return[Se,Ne,tt]}function re(at,G,we,Ie=.5,Se=.8){const Ne=[];let tt=0,wt=0;const mt=G[we].data;for(let ft=0;ft=Ie&&++wt;let Ct=tt>0&&wt>0;return Ct&&(Ct=tt/wt>Se),[Ct,Ne]}function me(at,G,we,Ie,Se,Ne=null,tt=null){const[wt,mt]=tt??at[0].dims,Ct=new xe.Tensor("int32",new Int32Array(wt*mt),[wt,mt]),ft=[];if(tt!==null)for(let Oe=0;Oejt[sr]&&(Lt[sr]=Oe,jt[sr]=Ut[sr])}let Ot=0;const Fe=Ct.data;for(let Oe=0;OeIe&&(Ne=Math.floor(Se)*G),NeNe?Ct=Math.floor(Ne*mt/Se):Ne>Se&&(mt=Math.floor(Se*Ct/Ne)),await G.resize(Ct,mt,{resample:Ie}))}async crop_margin(G,we=200){const Ie=G.clone().grayscale(),Se=(0,ve.min)(Ie.data)[0],tt=(0,ve.max)(Ie.data)[0]-Se;if(tt===0)return G;const wt=we/255;let mt=Ie.width,Ct=Ie.height,ft=0,Lt=0;const jt=Ie.data;for(let Ot=0;Otthis.preprocess(Ne)));return{pixel_values:(0,xe.stack)(Ie.map(Ne=>Ne.pixel_values),0),original_sizes:Ie.map(Ne=>Ne.original_size),reshaped_input_sizes:Ie.map(Ne=>Ne.reshaped_input_size)}}}class V extends K{post_process_semantic_segmentation(...G){return B(...G)}}class E extends K{post_process_semantic_segmentation(...G){return B(...G)}}class N extends K{}class k extends K{}class le extends k{}class be extends K{}class $e extends K{}class De extends K{}class ze extends De{}class it extends K{}class rt extends K{}class lt extends K{constructor(G){super(G),this.crop_pct=this.config.crop_pct??.875}async resize(G){var Ie;const we=(Ie=this.size)==null?void 0:Ie.shortest_edge;if(we===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(we<384){const Se=Math.floor(we/this.crop_pct),[Ne,tt]=this.get_resize_output_image_size(G,{shortest_edge:Se});G=await G.resize(Ne,tt,{resample:this.resample}),G=await G.center_crop(we,we)}else G=await G.resize(we,we,{resample:this.resample});return G}}class _e extends lt{}class W extends K{}class ce extends K{}class Ce extends K{constructor(G){super(G),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(we=>we*we))}}class We extends K{}class ot extends K{}class ne extends K{}class Ze extends K{}class dt extends K{}class Re extends dt{}class ht extends K{post_process_object_detection(...G){return L(...G)}}class Mt extends ht{}class Xe extends K{post_process_object_detection(...G){return L(...G)}}class Z extends K{}class Ae extends K{}class Ke extends K{pad_image(G,we,Ie,Se={}){const[Ne,tt,wt]=we;let mt=this.image_mean;Array.isArray(this.image_mean)||(mt=new Array(wt).fill(mt));let Ct=this.image_std;Array.isArray(Ct)||(Ct=new Array(wt).fill(mt));const ft=mt.map((Lt,jt)=>-Lt/Ct[jt]);return super.pad_image(G,we,Ie,{center:!0,constant_values:ft,...Se})}}class et extends Ke{}class je extends Ke{}class Ve extends K{async _call(G){const we=await super._call(G),Ie=[we.pixel_values.dims[0],64,64],Se=(0,xe.full)(Ie,1n);return{...we,pixel_mask:Se}}post_process_object_detection(...G){return L(...G)}post_process_panoptic_segmentation(...G){return ue(...G)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class ut extends K{post_process_panoptic_segmentation(...G){return ue(...G)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class _t extends K{post_process_object_detection(...G){return L(...G)}}class St extends K{reshape_input_points(G,we,Ie,Se=!1){G=structuredClone(G);let Ne=(0,de.calculateDimensions)(G);if(Ne.length===3)Se||(Ne=[1,...Ne]),G=[G];else if(Ne.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let tt=0;ttSe!==we.dims[Ne]))throw Error(`The first ${Ie.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new xe.Tensor("int64",G.flat(1/0).map(BigInt),Ie)}async _call(G,{input_points:we=null,input_labels:Ie=null,input_boxes:Se=null}={}){const Ne=await super._call(G);if(we&&(Ne.input_points=this.reshape_input_points(we,Ne.original_sizes,Ne.reshaped_input_sizes)),Ie){if(!Ne.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Ne.input_labels=this.add_input_labels(Ie,Ne.input_points)}return Se&&(Ne.input_boxes=this.reshape_input_points(Se,Ne.original_sizes,Ne.reshaped_input_sizes,!0)),Ne}async post_process_masks(G,we,Ie,{mask_threshold:Se=0,binarize:Ne=!0,pad_size:tt=null}={}){const wt=[];tt=tt??this.pad_size;const mt=[tt.height,tt.width];for(let Ct=0;CtSe&&(Fe[Oe]=1);jt=new xe.Tensor("bool",Fe,jt.dims)}wt.push(jt)}return wt}generate_crop_boxes(G,we,{crop_n_layers:Ie=0,overlap_ratio:Se=.3413333333333333,points_per_crop:Ne=32,crop_n_points_downscale_factor:tt=1}={}){}}class xt extends K{pad_image(G,we,Ie,Se={}){const[Ne,tt,wt]=we;return super.pad_image(G,we,{width:tt+(Ie-tt%Ie)%Ie,height:Ne+(Ie-Ne%Ie)%Ie},{mode:"symmetric",center:!1,constant_values:-1,...Se})}}class v extends K{async _call(G,we){Array.isArray(G)||(G=[G]),Array.isArray(we)||(we=[we]);const Ie=await Promise.all(G.map(tt=>this.preprocess(tt))),Se=await Promise.all(we.map(tt=>this.preprocess(tt,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,xe.stack)(Ie.map((tt,wt)=>(0,xe.cat)([tt.pixel_values,Se[wt].pixel_values],0)),0),original_sizes:Ie.map(tt=>tt.original_size),reshaped_input_sizes:Ie.map(tt=>tt.reshaped_input_size)}}}class H extends X{constructor(G){var we;super(G),(we=this.config).mel_filters??(we.mel_filters=(0,j.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,j.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(G){const we=await(0,j.spectrogram)(G,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),Ie=we.data,Se=(0,ve.max)(Ie)[0];for(let Ne=0;Nethis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),we=G.slice(0,this.config.n_samples)):(we=new Float32Array(this.config.n_samples),we.set(G)),{input_features:(await this._extract_fbank_features(we)).unsqueeze_(0)}}}class $ extends X{_zero_mean_unit_var_norm(G){const Ie=G.reduce((Ne,tt)=>Ne+tt,0)/G.length,Se=G.reduce((Ne,tt)=>Ne+(tt-Ie)**2,0)/G.length;return G.map(Ne=>(Ne-Ie)/Math.sqrt(Se+1e-7))}async _call(G){O(G,"Wav2Vec2FeatureExtractor"),G instanceof Float64Array&&(G=new Float32Array(G));let we=G;this.config.do_normalize&&(we=this._zero_mean_unit_var_norm(we));const Ie=[1,we.length];return{input_values:new xe.Tensor("float32",we,Ie),attention_mask:new xe.Tensor("int64",new BigInt64Array(we.length).fill(1n),Ie)}}}class Y extends X{constructor(G){super(G);const we=this.config.sampling_rate,Ie=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(we/2),we,null,"kaldi",!0);for(let Se=0;SeIe*32768),(0,j.spectrogram)(G,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:we,transpose:!0})}async _call(G,{padding:we=!0,pad_to_multiple_of:Ie=2,do_normalize_per_mel_bins:Se=!0,return_attention_mask:Ne=!0}={}){O(G,"SeamlessM4TFeatureExtractor");let tt=await this._extract_fbank_features(G,this.config.max_length);if(Se){const[Fe,Oe]=tt.dims,ct=tt.data;for(let Ut=0;Ut0){const sr=new Float32Array(Oe*(Fe+Ut));sr.set(ct),sr.fill(this.config.padding_value,ct.length);const br=Fe+Ut;tt=new xe.Tensor(tt.type,sr,[br,Oe]),Ne&&(wt=new xe.Tensor("int64",new BigInt64Array(br),[1,br]),wt.data.fill(1n,0,Fe))}}const[mt,Ct]=tt.dims,ft=this.config.stride;if(mt%ft!==0)throw new Error(`The number of frames (${mt}) must be a multiple of the stride (${ft}).`);const jt=tt.view(1,Math.floor(mt/ft),Ct*ft),Ot={input_features:jt};if(Ne){const Fe=jt.dims[1],Oe=new BigInt64Array(Fe);if(wt){const ct=wt.data;for(let Ut=1,sr=0;Ut0)if(Ie==="rand_trunc"){const wt=Math.floor(Math.random()*(tt+1));G=G.subarray(wt,wt+we),Ne=await this._extract_fbank_features(G,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Ie}" not implemented`);else{if(tt<0){let wt=new Float64Array(we);if(wt.set(G),Se==="repeat")for(let mt=G.length;mt({id:mt,start:Ct*Ie,end:ft*Ie,confidence:Lt/(ft-Ct)})))}return Se}}class Nt extends X{constructor(G){super(G);const we=this.config.sampling_rate,Ie=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(we/2),we,null,"kaldi",!0);for(let Se=0;Sewe*32768),(0,j.spectrogram)(G,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(G){O(G,"WeSpeakerFeatureExtractor");const we=(await this._extract_fbank_features(G)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Ie=we.mean(1).data,Se=we.data,[Ne,tt,wt]=we.dims;for(let mt=0;mt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(G){typeof G=="string"&&(G=[G]);const we=[];for(const Ie of G)if(this.task_prompts_without_inputs.has(Ie))we.push(this.task_prompts_without_inputs.get(Ie));else{for(const[Se,Ne]of this.task_prompts_with_input)if(Ie.includes(Se)){we.push(Ne.replaceAll("{input}",Ie).replaceAll(Se,""));break}we.length!==G.length&&we.push(Ie)}return we}post_process_generation(G,we,Ie){const Se=this.tasks_answer_post_processing_type.get(we)??"pure_text";G=G.replaceAll("","").replaceAll("","");let Ne;switch(Se){case"pure_text":Ne=G;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const tt=Se==="ocr"?"quad_boxes":"bboxes",wt=G.matchAll(this.regexes[tt]),mt=[],Ct=[];for(const[ft,Lt,...jt]of wt)mt.push(Lt?Lt.trim():mt.at(-1)??""),Ct.push(jt.map((Ot,Fe)=>(Number(Ot)+.5)/this.size_per_bin*Ie[Fe%2]));Ne={labels:mt,[tt]:Ct};break;default:throw new Error(`Task "${we}" (of type "${Se}") not yet implemented.`)}return{[we]:Ne}}}class yn{static async from_pretrained(G,{progress_callback:we=null,config:Ie=null,cache_dir:Se=null,local_files_only:Ne=!1,revision:tt="main"}={}){let wt=Ie??await(0,he.getModelJSON)(G,"preprocessor_config.json",!0,{progress_callback:we,config:Ie,cache_dir:Se,local_files_only:Ne,revision:tt}),mt=wt.feature_extractor_type??wt.image_processor_type,Ct=this.FEATURE_EXTRACTOR_CLASS_MAPPING[mt];if(!Ct)if(wt.size!==void 0)console.warn(`Feature extractor type "${mt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Ct=K;else throw new Error(`Unknown Feature Extractor type: ${mt}`);let ft=this.PROCESSOR_CLASS_MAPPING[wt.processor_class]??bt,Lt=new Ct(wt);return new ft(Lt)}}Me(yn,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:K,WhisperFeatureExtractor:H,ViTFeatureExtractor:W,MobileViTFeatureExtractor:dt,MobileViTImageProcessor:Re,MobileNetV1FeatureExtractor:We,MobileNetV2FeatureExtractor:ot,MobileNetV3FeatureExtractor:ne,MobileNetV4FeatureExtractor:Ze,OwlViTFeatureExtractor:ht,Owlv2ImageProcessor:Mt,CLIPFeatureExtractor:De,CLIPImageProcessor:ze,Florence2Processor:Jr,ChineseCLIPFeatureExtractor:it,SiglipImageProcessor:rt,ConvNextFeatureExtractor:lt,ConvNextImageProcessor:_e,SegformerFeatureExtractor:E,SapiensFeatureExtractor:V,BitImageProcessor:be,DPTImageProcessor:le,DPTFeatureExtractor:k,PvtImageProcessor:N,GLPNFeatureExtractor:$e,BeitFeatureExtractor:Ae,DeiTFeatureExtractor:Z,DetrFeatureExtractor:Ve,RTDetrImageProcessor:Xe,MaskFormerFeatureExtractor:ut,YolosFeatureExtractor:_t,DonutFeatureExtractor:Ke,DonutImageProcessor:et,NougatImageProcessor:je,EfficientNetImageProcessor:Ce,ViTImageProcessor:ce,VitMatteImageProcessor:v,SamImageProcessor:St,Swin2SRImageProcessor:xt,Wav2Vec2FeatureExtractor:$,SeamlessM4TFeatureExtractor:Y,SpeechT5FeatureExtractor:yt,ASTFeatureExtractor:fe,ClapFeatureExtractor:nt,PyAnnoteFeatureExtractor:Je,WeSpeakerFeatureExtractor:Nt}),Me(yn,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:Pt,Wav2Vec2ProcessorWithLM:dr,PyAnnoteProcessor:Cr,SamProcessor:Dt,SpeechT5Processor:Yr,OwlViTProcessor:Rr,Florence2Processor:Jr})},"./src/tokenizers.js":(At,ye,D)=>{D.r(ye),D.d(ye,{AlbertTokenizer:()=>tt,AutoTokenizer:()=>zs,BartTokenizer:()=>Nr,BertTokenizer:()=>Ne,BlenderbotSmallTokenizer:()=>Is,BlenderbotTokenizer:()=>As,BloomTokenizer:()=>Cn,CLIPTokenizer:()=>fs,CamembertTokenizer:()=>Oe,CodeGenTokenizer:()=>hs,CodeLlamaTokenizer:()=>Cs,CohereTokenizer:()=>rs,ConvBertTokenizer:()=>jt,DebertaTokenizer:()=>Ct,DebertaV2Tokenizer:()=>ft,DistilBertTokenizer:()=>Fe,ElectraTokenizer:()=>Ut,EsmTokenizer:()=>Ss,FalconTokenizer:()=>ks,GPT2Tokenizer:()=>br,GPTNeoXTokenizer:()=>Es,GemmaTokenizer:()=>es,Grok1Tokenizer:()=>Xn,HerbertTokenizer:()=>Lt,LlamaTokenizer:()=>cs,M2M100Tokenizer:()=>ps,MBart50Tokenizer:()=>Er,MBartTokenizer:()=>mr,MPNetTokenizer:()=>$s,MarianTokenizer:()=>Yt,MobileBertTokenizer:()=>wt,NllbTokenizer:()=>Bn,NougatTokenizer:()=>Fs,PreTrainedTokenizer:()=>Se,Qwen2Tokenizer:()=>Ps,RoFormerTokenizer:()=>Ot,RobertaTokenizer:()=>wr,SiglipTokenizer:()=>ms,SpeechT5Tokenizer:()=>_s,SqueezeBertTokenizer:()=>mt,T5Tokenizer:()=>sr,TokenizerModel:()=>$e,VitsTokenizer:()=>Os,Wav2Vec2CTCTokenizer:()=>ts,WhisperTokenizer:()=>Dn,XLMRobertaTokenizer:()=>Kn,XLMTokenizer:()=>ct,is_chinese_char:()=>X});var I=D("./src/utils/generic.js"),de=D("./src/utils/core.js"),he=D("./src/utils/hub.js"),ve=D("./src/utils/maths.js"),xe=D("./src/utils/tensor.js"),j=D("./src/utils/data-structures.js"),P=D("./node_modules/@huggingface/jinja/dist/index.js"),L=D("./src/models/whisper/common_whisper.js");D("./src/utils/constants.js");async function B(ae,_){const F=await Promise.all([(0,he.getModelJSON)(ae,"tokenizer.json",!0,_),(0,he.getModelJSON)(ae,"tokenizer_config.json",!0,_)]);return _.legacy!==null&&(F[1].legacy=_.legacy),F}function q(ae,_){const F=[];let Q=0;for(const oe of ae.matchAll(_)){const ge=oe[0];Q0&&F.push(ge),Q=oe.index+ge.length}return Q=19968&&ae<=40959||ae>=13312&&ae<=19903||ae>=131072&&ae<=173791||ae>=173824&&ae<=177983||ae>=177984&&ae<=178207||ae>=178208&&ae<=183983||ae>=63744&&ae<=64255||ae>=194560&&ae<=195103}function K(ae,_,F){const Q=[];let oe=0;for(;oethis.tokens_to_ids.get(F)??this.unk_token_id)}convert_ids_to_tokens(_){return _.map(F=>this.vocab[F]??this.unk_token)}}class De extends $e{constructor(_){super(_),this.tokens_to_ids=me(_.vocab),this.unk_token_id=this.tokens_to_ids.get(_.unk_token),this.unk_token=_.unk_token,this.max_input_chars_per_word=_.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[F,Q]of this.tokens_to_ids)this.vocab[Q]=F}encode(_){const F=[];for(const Q of _){const oe=[...Q];if(oe.length>this.max_input_chars_per_word){F.push(this.unk_token);continue}let ge=!1,Ge=0;const gt=[];for(;Ge0&&(zt=this.config.continuing_subword_prefix+zt),this.tokens_to_ids.has(zt)){Tt=zt;break}--$t}if(Tt===null){ge=!0;break}gt.push(Tt),Ge=$t}ge?F.push(this.unk_token):F.push(...gt)}return F}}class ze extends $e{constructor(_,F){super(_);const Q=_.vocab.length;this.vocab=new Array(Q),this.scores=new Array(Q);for(let oe=0;oe[oe,ge])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=F.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,ve.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new j.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(_){const F=_.chars,Q=1;let oe=0;for(;oe{const ae=[...Array.from({length:94},(oe,ge)=>ge+33),...Array.from({length:12},(oe,ge)=>ge+161),...Array.from({length:82},(oe,ge)=>ge+174)],_=ae.slice();let F=0;for(let oe=0;oe<256;++oe)ae.includes(oe)||(ae.push(oe),_.push(256+F),F+=1);const Q=_.map(oe=>String.fromCharCode(oe));return Object.fromEntries(ae.map((oe,ge)=>[oe,Q[ge]]))})(),rt=(0,de.reverseDictionary)(it);class lt extends $e{constructor(_){super(_),this.tokens_to_ids=me(_.vocab),this.unk_token_id=this.tokens_to_ids.get(_.unk_token),this.unk_token=_.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,oe]of this.tokens_to_ids)this.vocab[oe]=Q;const F=Array.isArray(_.merges[0]);this.merges=F?_.merges:_.merges.map(Q=>Q.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Q,oe)=>[JSON.stringify(Q),oe])),this.end_of_word_suffix=_.end_of_word_suffix,this.continuing_subword_suffix=_.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(_){if(_.length===0)return[];const F=this.cache.get(_);if(F!==void 0)return F;const Q=Array.from(_);this.end_of_word_suffix&&(Q[Q.length-1]+=this.end_of_word_suffix);let oe=[];if(Q.length>1){const ge=new j.PriorityQueue(($t,Tt)=>$t.score`<0x${gt.toString(16).toUpperCase().padStart(2,"0")}>`);Ge.every(gt=>this.tokens_to_ids.has(gt))?F.push(...Ge):F.push(this.unk_token)}else F.push(this.unk_token)}return F}}class _e extends $e{constructor(_,F){super(_),this.tokens_to_ids=me(F.target_lang?_.vocab[F.target_lang]:_.vocab),this.bos_token=F.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=F.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=F.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=F.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,oe]of this.tokens_to_ids)this.vocab[oe]=Q}encode(_){return _}}class W extends I.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"BertNormalizer":return new Mt(_);case"Precompiled":return new Yr(_);case"Sequence":return new ht(_);case"Replace":return new ce(_);case"NFC":return new Ce(_);case"NFKC":return new We(_);case"NFKD":return new ot(_);case"Strip":return new ne(_);case"StripAccents":return new Ze(_);case"Lowercase":return new dt(_);case"Prepend":return new Re(_);default:throw new Error(`Unknown Normalizer type: ${_.type}`)}}normalize(_){throw Error("normalize should be implemented in subclass.")}_call(_){return this.normalize(_)}}class ce extends W{normalize(_){const F=re(this.config.pattern);return F===null?_:_.replaceAll(F,this.config.content)}}class Ce extends W{normalize(_){return _=_.normalize("NFC"),_}}class We extends W{normalize(_){return _=_.normalize("NFKC"),_}}class ot extends W{normalize(_){return _=_.normalize("NFKD"),_}}class ne extends W{normalize(_){return this.config.strip_left&&this.config.strip_right?_=_.trim():(this.config.strip_left&&(_=_.trimStart()),this.config.strip_right&&(_=_.trimEnd())),_}}class Ze extends W{normalize(_){return _=J(_),_}}class dt extends W{normalize(_){return _=_.toLowerCase(),_}}class Re extends W{normalize(_){return _=this.config.prepend+_,_}}class ht extends W{constructor(_){super(_),this.normalizers=_.normalizers.map(F=>W.fromConfig(F))}normalize(_){return this.normalizers.reduce((F,Q)=>Q.normalize(F),_)}}class Mt extends W{_tokenize_chinese_chars(_){const F=[];for(let Q=0;Q<_.length;++Q){const oe=_[Q],ge=oe.charCodeAt(0);X(ge)?(F.push(" "),F.push(oe),F.push(" ")):F.push(oe)}return F.join("")}stripAccents(_){return _.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control(_){switch(_){case" ":case` `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(_)}}_clean_text(_){const F=[];for(const Q of _){const oe=Q.charCodeAt(0);oe===0||oe===65533||this._is_control(Q)||(/^\s$/.test(Q)?F.push(" "):F.push(Q))}return F.join("")}normalize(_){return this.config.clean_text&&(_=this._clean_text(_)),this.config.handle_chinese_chars&&(_=this._tokenize_chinese_chars(_)),this.config.lowercase?(_=_.toLowerCase(),this.config.strip_accents!==!1&&(_=this.stripAccents(_))):this.config.strip_accents&&(_=this.stripAccents(_)),_}}class Xe extends I.Callable{static fromConfig(_){if(_===null)return null;switch(_.type){case"BertPreTokenizer":return new Z(_);case"Sequence":return new Rr(_);case"Whitespace":return new Jr(_);case"WhitespaceSplit":return new yn(_);case"Metaspace":return new dr(_);case"ByteLevel":return new Ae(_);case"Split":return new Ke(_);case"Punctuation":return new et(_);case"Digits":return new je(_);case"Replace":return new at(_);default:throw new Error(`Unknown PreTokenizer type: ${_.type}`)}}pre_tokenize_text(_,F){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(_,F){return(Array.isArray(_)?_.map(Q=>this.pre_tokenize_text(Q,F)):this.pre_tokenize_text(_,F)).flat()}_call(_,F){return this.pre_tokenize(_,F)}}class Z extends Xe{constructor(_){super(),this.pattern=new RegExp(`[^\\s${E}]+|[${E}]`,"gu")}pre_tokenize_text(_,F){return _.trim().match(this.pattern)||[]}}class Ae extends Xe{constructor(_){super(),this.config=_,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=it,this.text_encoder=new TextEncoder}pre_tokenize_text(_,F){return this.add_prefix_space&&!_.startsWith(" ")&&(_=" "+_),(this.use_regex?_.match(this.pattern)||[]:[_]).map(oe=>Array.from(this.text_encoder.encode(oe),ge=>this.byte_encoder[ge]).join(""))}}class Ke extends Xe{constructor(_){super(),this.config=_,this.pattern=re(this.config.pattern,this.config.invert)}pre_tokenize_text(_,F){return this.pattern===null?[]:this.config.invert?_.match(this.pattern)||[]:q(_,this.pattern)}}class et extends Xe{constructor(_){super(),this.config=_,this.pattern=new RegExp(`[^${E}]+|[${E}]+`,"gu")}pre_tokenize_text(_,F){return _.match(this.pattern)||[]}}class je extends Xe{constructor(_){super(),this.config=_;const F=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(F,"gu")}pre_tokenize_text(_,F){return _.match(this.pattern)||[]}}class Ve extends I.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"TemplateProcessing":return new St(_);case"ByteLevel":return new xt(_);case"RobertaProcessing":return new _t(_);case"BertProcessing":return new ut(_);case"Sequence":return new v(_);default:throw new Error(`Unknown PostProcessor type: ${_.type}`)}}post_process(_,...F){throw Error("post_process should be implemented in subclass.")}_call(_,...F){return this.post_process(_,...F)}}class ut extends Ve{constructor(_){super(_),this.cls=_.cls[0],this.sep=_.sep[0]}post_process(_,F=null,{add_special_tokens:Q=!0}={}){Q&&(_=(0,de.mergeArrays)([this.cls],_,[this.sep]));let oe=new Array(_.length).fill(0);if(F!==null){const ge=Q&&this instanceof _t?[this.sep]:[],Ge=Q?[this.sep]:[];_=(0,de.mergeArrays)(_,ge,F,Ge),oe=(0,de.mergeArrays)(oe,new Array(F.length+ge.length+Ge.length).fill(1))}return{tokens:_,token_type_ids:oe}}}class _t extends ut{}class St extends Ve{constructor(_){super(_),this.single=_.single,this.pair=_.pair}post_process(_,F=null,{add_special_tokens:Q=!0}={}){const oe=F===null?this.single:this.pair;let ge=[],Ge=[];for(const gt of oe)"SpecialToken"in gt?Q&&(ge.push(gt.SpecialToken.id),Ge.push(gt.SpecialToken.type_id)):"Sequence"in gt&&(gt.Sequence.id==="A"?(ge=(0,de.mergeArrays)(ge,_),Ge=(0,de.mergeArrays)(Ge,new Array(_.length).fill(gt.Sequence.type_id))):gt.Sequence.id==="B"&&(ge=(0,de.mergeArrays)(ge,F),Ge=(0,de.mergeArrays)(Ge,new Array(F.length).fill(gt.Sequence.type_id))));return{tokens:ge,token_type_ids:Ge}}}class xt extends Ve{post_process(_,F=null){return F&&(_=(0,de.mergeArrays)(_,F)),{tokens:_}}}class v extends Ve{constructor(_){super(_),this.processors=_.processors.map(F=>Ve.fromConfig(F))}post_process(_,F=null,Q={}){let oe;for(const ge of this.processors)if(ge instanceof xt)_=ge.post_process(_).tokens,F&&(F=ge.post_process(F).tokens);else{const Ge=ge.post_process(_,F,Q);_=Ge.tokens,oe=Ge.token_type_ids}return{tokens:_,token_type_ids:oe}}}class H extends I.Callable{constructor(_){super(),this.config=_,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=_.trim_offsets}static fromConfig(_){if(_===null)return null;switch(_.type){case"WordPiece":return new Je(_);case"Metaspace":return new Cr(_);case"ByteLevel":return new Nt(_);case"Replace":return new $(_);case"ByteFallback":return new Y(_);case"Fuse":return new fe(_);case"Strip":return new nt(_);case"Sequence":return new bt(_);case"CTC":return new yt(_);case"BPEDecoder":return new Dt(_);default:throw new Error(`Unknown Decoder type: ${_.type}`)}}_call(_){return this.decode(_)}decode(_){return this.decode_chain(_).join("")}decode_chain(_){throw Error("`decode_chain` should be implemented in subclass.")}}class $ extends H{decode_chain(_){const F=re(this.config.pattern);return F===null?_:_.map(Q=>Q.replaceAll(F,this.config.content))}}class Y extends H{constructor(_){super(_),this.text_decoder=new TextDecoder}decode_chain(_){const F=[];let Q=[];for(const oe of _){let ge=null;if(oe.length===6&&oe.startsWith("<0x")&&oe.endsWith(">")){const Ge=parseInt(oe.slice(3,5),16);isNaN(Ge)||(ge=Ge)}if(ge!==null)Q.push(ge);else{if(Q.length>0){const Ge=this.text_decoder.decode(Uint8Array.from(Q));F.push(Ge),Q=[]}F.push(oe)}}if(Q.length>0){const oe=this.text_decoder.decode(Uint8Array.from(Q));F.push(oe),Q=[]}return F}}class fe extends H{decode_chain(_){return[_.join("")]}}class nt extends H{constructor(_){super(_),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(_){return _.map(F=>{let Q=0;for(let ge=0;ge(Q!==0&&(F.startsWith(this.config.prefix)?F=F.replace(this.config.prefix,""):F=" "+F),this.cleanup&&(F=O(F)),F))}}class Nt extends H{constructor(_){super(_),this.byte_decoder=rt,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(_){const F=_.join(""),Q=new Uint8Array([...F].map(ge=>this.byte_decoder[ge]));return this.text_decoder.decode(Q)}decode_chain(_){const F=[];let Q=[];for(const oe of _)this.added_tokens.find(ge=>ge.content===oe)!==void 0?(Q.length>0&&(F.push(this.convert_tokens_to_string(Q)),Q=[]),F.push(oe)):Q.push(oe);return Q.length>0&&F.push(this.convert_tokens_to_string(Q)),F}}class yt extends H{constructor(_){super(_),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(_){if(_.length===0)return"";const F=[_[0]];for(let ge=1;ge<_.length;++ge)_[ge]!==F.at(-1)&&F.push(_[ge]);let oe=F.filter(ge=>ge!==this.pad_token).join("");return this.cleanup&&(oe=O(oe).replaceAll(this.word_delimiter_token," ").trim()),oe}decode_chain(_){return[this.convert_tokens_to_string(_)]}}class bt extends H{constructor(_){super(_),this.decoders=_.decoders.map(F=>H.fromConfig(F))}decode_chain(_){return this.decoders.reduce((F,Q)=>Q.decode_chain(F),_)}}class Dt extends H{constructor(_){super(_),this.suffix=this.config.suffix}decode_chain(_){return _.map((F,Q)=>F.replaceAll(this.suffix,Q===_.length-1?"":" "))}}class Pt extends H{decode_chain(_){let F="";for(let Q=1;Q<_.length;Q+=2)F+=_[Q];return[F]}}class dr extends Xe{constructor(_){super(),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement,this.strRep=_.str_rep||this.replacement,this.prepend_scheme=_.prepend_scheme??"always"}pre_tokenize_text(_,{section_index:F=void 0}={}){let Q=_.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Q.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&F===0)&&(Q=this.strRep+Q),[Q]}}class Cr extends H{constructor(_){super(_),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement}decode_chain(_){const F=[];for(let Q=0;Q<_.length;++Q){let oe=_[Q].replaceAll(this.replacement," ");this.addPrefixSpace&&Q==0&&oe.startsWith(" ")&&(oe=oe.substring(1)),F.push(oe)}return F}}class Yr extends W{constructor(_){super(_),this.charsmap=_.precompiled_charsmap}normalize(_){return _=_.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),_=_.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),_.includes("~")?_=_.split("~").map(Q=>Q.normalize("NFKC")).join("~"):_=_.normalize("NFKC"),_}}class Rr extends Xe{constructor(_){super(),this.tokenizers=_.pretokenizers.map(F=>Xe.fromConfig(F))}pre_tokenize_text(_,F){return this.tokenizers.reduce((Q,oe)=>oe.pre_tokenize(Q,F),[_])}}class Jr extends Xe{constructor(_){super()}pre_tokenize_text(_,F){return _.match(/\w+|[^\w\s]+/g)||[]}}class yn extends Xe{constructor(_){super()}pre_tokenize_text(_,F){return V(_)}}class at extends Xe{constructor(_){super(),this.config=_,this.pattern=re(this.config.pattern),this.content=this.config.content}pre_tokenize_text(_,F){return this.pattern===null?[_]:[_.replaceAll(this.pattern,this.config.content)]}}const G=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function we(ae,_,F,Q){for(const oe of Object.keys(ae)){const ge=_-ae[oe].length,Ge=F(oe),gt=new Array(ge).fill(Ge);ae[oe]=Q==="right"?(0,de.mergeArrays)(ae[oe],gt):(0,de.mergeArrays)(gt,ae[oe])}}function Ie(ae,_){for(const F of Object.keys(ae))ae[F].length=_}class Se extends I.Callable{constructor(F,Q){super();Me(this,"return_token_type_ids",!1);Me(this,"padding_side","right");this._tokenizer_config=Q,this.normalizer=W.fromConfig(F.normalizer),this.pre_tokenizer=Xe.fromConfig(F.pre_tokenizer),this.model=$e.fromConfig(F.model,Q),this.post_processor=Ve.fromConfig(F.post_processor),this.decoder=H.fromConfig(F.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const oe of F.added_tokens){const ge=new be(oe);this.added_tokens.push(ge),this.model.tokens_to_ids.set(ge.content,ge.id),this.model.vocab[ge.id]=ge.content,ge.special&&(this.special_tokens.push(ge.content),this.all_special_ids.push(ge.id))}if(this.additional_special_tokens=Q.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((oe,ge)=>ge.content.length-oe.content.length).map(oe=>`${oe.lstrip?"\\s*":""}(${(0,de.escapeRegExp)(oe.content)})${oe.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=Q.model_max_length,this.remove_space=Q.remove_space,this.clean_up_tokenization_spaces=Q.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Q.do_lowercase_and_remove_accent??!1,Q.padding_side&&(this.padding_side=Q.padding_side),this.legacy=!1,this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){const oe=Object.create(null);for(const{name:ge,template:Ge}of this.chat_template){if(typeof ge!="string"||typeof Ge!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');oe[ge]=Ge}this.chat_template=oe}this._compiled_template_cache=new Map}getToken(...F){for(const Q of F){const oe=this._tokenizer_config[Q];if(oe)if(typeof oe=="object"){if(oe.__type==="AddedToken")return oe.content;throw Error(`Unknown token: ${oe}`)}else return oe}return null}static async from_pretrained(F,{progress_callback:Q=null,config:oe=null,cache_dir:ge=null,local_files_only:Ge=!1,revision:gt="main",legacy:$t=null}={}){const Tt=await B(F,{progress_callback:Q,config:oe,cache_dir:ge,local_files_only:Ge,revision:gt,legacy:$t});return new this(...Tt)}_call(F,{text_pair:Q=null,add_special_tokens:oe=!0,padding:ge=!1,truncation:Ge=null,max_length:gt=null,return_tensor:$t=!0,return_token_type_ids:Tt=null}={}){const zt=Array.isArray(F);let er;if(zt){if(F.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(F.length!==Q.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");er=F.map((lr,Wr)=>this._encode_plus(lr,{text_pair:Q[Wr],add_special_tokens:oe,return_token_type_ids:Tt}))}else er=F.map(lr=>this._encode_plus(lr,{add_special_tokens:oe,return_token_type_ids:Tt}))}else{if(F==null)throw Error("text may not be null or undefined");if(Array.isArray(Q))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");er=[this._encode_plus(F,{text_pair:Q,add_special_tokens:oe,return_token_type_ids:Tt})]}if(gt===null?ge==="max_length"?gt=this.model_max_length:gt=(0,ve.max)(er.map(lr=>lr.input_ids.length))[0]:Ge||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),gt=Math.min(gt,this.model_max_length??1/0),ge||Ge)for(let lr=0;lrgt?Ge&&Ie(er[lr],gt):ge&&we(er[lr],gt,Wr=>Wr==="input_ids"?this.pad_token_id:0,this.padding_side));const Sr={};if($t){if(!(ge&&Ge)&&er.some(Wr=>{var en;for(const or of Object.keys(Wr))if(Wr[or].length!==((en=er[0][or])==null?void 0:en.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const lr=[er.length,er[0].input_ids.length];for(const Wr of Object.keys(er[0]))Sr[Wr]=new xe.Tensor("int64",BigInt64Array.from(er.flatMap(en=>en[Wr]).map(BigInt)),lr)}else{for(const lr of Object.keys(er[0]))Sr[lr]=er.map(Wr=>Wr[lr]);if(!zt)for(const lr of Object.keys(Sr))Sr[lr]=Sr[lr][0]}return Sr}_encode_text(F){return F===null?null:(this.added_tokens_regex?F.split(this.added_tokens_regex).filter(ge=>ge):[F]).map((ge,Ge)=>{if(this.added_tokens.find($t=>$t.content===ge)!==void 0)return ge;{if(this.remove_space===!0&&(ge=ge.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ge=pe(ge)),this.normalizer!==null&&(ge=this.normalizer(ge)),ge.length===0)return[];const $t=this.pre_tokenizer!==null?this.pre_tokenizer(ge,{section_index:Ge}):[ge];return this.model($t)}}).flat()}_encode_plus(F,{text_pair:Q=null,add_special_tokens:oe=!0,return_token_type_ids:ge=null}={}){const{tokens:Ge,token_type_ids:gt}=this._tokenize_helper(F,{pair:Q,add_special_tokens:oe}),$t=this.model.convert_tokens_to_ids(Ge),Tt={input_ids:$t,attention_mask:new Array($t.length).fill(1)};return(ge??this.return_token_type_ids)&>&&(Tt.token_type_ids=gt),Tt}_tokenize_helper(F,{pair:Q=null,add_special_tokens:oe=!1}={}){const ge=this._encode_text(F),Ge=this._encode_text(Q);return this.post_processor?this.post_processor(ge,Ge,{add_special_tokens:oe}):{tokens:(0,de.mergeArrays)(ge??[],Ge??[])}}tokenize(F,{pair:Q=null,add_special_tokens:oe=!1}={}){return this._tokenize_helper(F,{pair:Q,add_special_tokens:oe}).tokens}encode(F,{text_pair:Q=null,add_special_tokens:oe=!0,return_token_type_ids:ge=null}={}){return this._encode_plus(F,{text_pair:Q,add_special_tokens:oe,return_token_type_ids:ge}).input_ids}batch_decode(F,Q={}){return F instanceof xe.Tensor&&(F=F.tolist()),F.map(oe=>this.decode(oe,Q))}decode(F,Q={}){if(F instanceof xe.Tensor&&(F=ue(F)),!Array.isArray(F)||F.length===0||!(0,de.isIntegralNumber)(F[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(F,Q)}decode_single(F,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:oe=null}){let ge=this.model.convert_ids_to_tokens(F);Q&&(ge=ge.filter(gt=>!this.special_tokens.includes(gt)));let Ge=this.decoder?this.decoder(ge):ge.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ge=Ge.replaceAll(this.decoder.end_of_word_suffix," "),Q&&(Ge=Ge.trim())),(oe??this.clean_up_tokenization_spaces)&&(Ge=O(Ge)),Ge}get_chat_template({chat_template:F=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const oe=this.chat_template;if(F!==null&&Object.hasOwn(oe,F))F=oe[F];else if(F===null)if(Q!==null&&"tool_use"in oe)F=oe.tool_use;else if("default"in oe)F=oe.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(oe).sort()}.`)}else if(F===null)if(this.chat_template)F=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return F}apply_chat_template(F,{tools:Q=null,documents:oe=null,chat_template:ge=null,add_generation_prompt:Ge=!1,tokenize:gt=!0,padding:$t=!1,truncation:Tt=!1,max_length:zt=null,return_tensor:er=!0,return_dict:Sr=!1,tokenizer_kwargs:lr={},...Wr}={}){if(ge=this.get_chat_template({chat_template:ge,tools:Q}),typeof ge!="string")throw Error(`chat_template must be a string, but got ${typeof ge}`);let en=this._compiled_template_cache.get(ge);en===void 0&&(en=new P.Template(ge),this._compiled_template_cache.set(ge,en));const or=Object.create(null);for(const mn of G){const bn=this.getToken(mn);bn&&(or[mn]=bn)}const Pr=en.render({messages:F,add_generation_prompt:Ge,tools:Q,documents:oe,...or,...Wr});if(gt){const mn=this._call(Pr,{add_special_tokens:!1,padding:$t,truncation:Tt,max_length:zt,return_tensor:er,...lr});return Sr?mn:mn.input_ids}return Pr}}class Ne extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class tt extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class wt extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class mt extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class Ct extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class ft extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class Lt extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class jt extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class Ot extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class Fe extends Se{}class Oe extends Se{}class ct extends Se{constructor(F,Q){super(F,Q);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 Ut extends Se{constructor(){super(...arguments);Me(this,"return_token_type_ids",!0)}}class sr extends Se{}class br extends Se{}class Nr extends Se{}class mr extends Se{constructor(_,F){super(_,F),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(_,F,Q){return Sn(this,_,F,Q)}}class Er extends mr{}class wr extends Se{}class Cn extends Se{}const Ur="▁";class cs extends Se{constructor(F,Q){super(F,Q);Me(this,"padding_side","left");this.legacy=Q.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new dr({replacement:Ur,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(F){if(F===null)return null;if(this.legacy||F.length===0)return super._encode_text(F);let Q=super._encode_text(Ur+F.replaceAll(Ur," "));return Q.length>1&&Q[0]===Ur&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class Cs extends Se{}class Kn extends Se{}class $s extends Se{}class ks extends Se{}class Es extends Se{}class Ss extends Se{}class Ps extends Se{}class es extends Se{}class Xn extends Se{}function Sn(ae,_,F,Q){if(!("language_codes"in ae)||!Array.isArray(ae.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ae)||!(ae.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ae)||typeof ae.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const oe=Q.src_lang,ge=Q.tgt_lang;if(!ae.language_codes.includes(ge))throw new Error(`Target language code "${ge}" is not valid. Must be one of: {${ae.language_codes.join(", ")}}`);if(oe!==void 0){if(!ae.language_codes.includes(oe))throw new Error(`Source language code "${oe}" is not valid. Must be one of: {${ae.language_codes.join(", ")}}`);for(const Ge of ae.post_processor.config.single)if("SpecialToken"in Ge&&ae.languageRegex.test(Ge.SpecialToken.id)){Ge.SpecialToken.id=ae.lang_to_token(oe);break}}return Q.forced_bos_token_id=ae.model.convert_tokens_to_ids([ae.lang_to_token(ge)])[0],ae._call(_,F)}class Bn extends Se{constructor(_,F){super(_,F),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(_,F,Q){return Sn(this,_,F,Q)}}class ps extends Se{constructor(_,F){super(_,F),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)).map(Q=>Q.slice(2,-2)),this.lang_to_token=Q=>`__${Q}__`}_build_translation_inputs(_,F,Q){return Sn(this,_,F,Q)}}class Dn extends Se{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(_,{return_timestamps:F=!1,return_language:Q=!1,time_precision:oe=null,force_full_sequences:ge=!0}={}){if(oe===null)throw Error("Must specify time_precision");let Ge=null;const gt=F==="word";function $t(){return{language:Ge,timestamp:[null,null],text:""}}const Tt=[];let zt=$t(),er=0;const Sr=this.timestamp_begin;let lr=[],Wr=[],en=!1,or=null;const Pr=new Set(this.all_special_ids);for(const ke of _){const tn=ke.tokens,on=gt?ke.token_timestamps:null;let Pn=null,Rn=Sr;if("stride"in ke){const[Kr,fr,Or]=ke.stride;if(er-=fr,or=Kr-Or,fr&&(Rn=fr/oe+Sr),Or)for(let kt=tn.length-1;kt>=0;--kt){const _r=Number(tn[kt]);if(_r>=Sr){if(Pn!==null&&(_r-Sr)*oe=Sr){const Or=(fr-Sr)*oe+er,kt=(0,ve.round)(Or,2);if(Pn!==null&&fr>=Pn)en=!0;else if(en||lr.length>0&&fr0?(lr.push(Kt),gt&&Wr.push(pn)):lr.every(Kr=>Kr.length===0)&&(zt=$t(),lr=[],Kt=[],Wr=[],pn=[])}if(lr.length>0){if(ge&&F)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[ke,tn]=this.findLongestCommonSequence(lr,Wr),on=this.decode(ke);zt.text=on,gt&&(zt.words=this.collateWordTimestamps(ke,tn,Ge)),Tt.push(zt)}let mn=Object.create(null);const bn=Tt.map(ke=>ke.text).join("");if(F||Q){for(let ke=0;ke0;let gt=Ge?[]:null,$t=Ge?F[0]:null;for(let Tt=1;Tt<_.length;++Tt){const zt=_[Tt];let er=0,Sr=[oe,oe,0,0];const lr=zt.length;for(let ke=1;kekt===pn[_r]&&$t[tn+_r]<=F[Tt][Rn+_r]).length:Kr=Pn.filter((kt,_r)=>kt===pn[_r]).length;const fr=ke/1e4,Or=Kr/ke+fr;Kr>1&&Or>er&&(er=Or,Sr=[tn,on,Rn,Kt])}const[Wr,en,or,Pr]=Sr,mn=Math.floor((en+Wr)/2),bn=Math.floor((Pr+or)/2);ge.push(...Q.slice(0,mn)),Q=zt.slice(bn),oe=Q.length,Ge&&(gt.push(...$t.slice(0,mn)),$t=F[Tt].slice(bn))}return ge.push(...Q),Ge?(gt.push(...$t),[ge,gt]):[ge,[]]}collateWordTimestamps(_,F,Q){const[oe,ge,Ge]=this.combineTokensIntoWords(_,Q),gt=[];for(let $t=0;$t=oe){const gt=((Ge-oe)*Q).toFixed(2);ge.push(`<|${gt}|>`),ge.push([])}else ge[ge.length-1].push(Ge);return ge=ge.map(Ge=>typeof Ge=="string"?Ge:super.decode(Ge,F)),ge.join("")}splitTokensOnUnicode(_){const F=this.decode(_,{decode_with_timestamps:!0}),Q="�",oe=[],ge=[],Ge=[];let gt=[],$t=[],Tt=0;for(let zt=0;zt<_.length;++zt){const er=_[zt];gt.push(er),$t.push(zt);const Sr=this.decode(gt,{decode_with_timestamps:!0});(!Sr.includes(Q)||F[Tt+Sr.indexOf(Q)]===Q)&&(oe.push(Sr),ge.push(gt),Ge.push($t),gt=[],$t=[],Tt+=Sr.length)}return[oe,ge,Ge]}splitTokensOnSpaces(_){const[F,Q,oe]=this.splitTokensOnUnicode(_),ge=[],Ge=[],gt=[],$t=new RegExp(`^[${E}]$`,"gu");for(let Tt=0;Tt=this.model.tokens_to_ids.get("<|endoftext|>"),Wr=zt.startsWith(" "),en=zt.trim(),or=$t.test(en);if(lr||Wr||or||ge.length===0)ge.push(zt),Ge.push(er),gt.push(Sr);else{const Pr=ge.length-1;ge[Pr]+=zt,Ge[Pr].push(...er),gt[Pr].push(...Sr)}}return[ge,Ge,gt]}mergePunctuations(_,F,Q,oe,ge){const Ge=structuredClone(_),gt=structuredClone(F),$t=structuredClone(Q);let Tt=Ge.length-2,zt=Ge.length-1;for(;Tt>=0;)Ge[Tt].startsWith(" ")&&oe.includes(Ge[Tt].trim())?(Ge[zt]=Ge[Tt]+Ge[zt],gt[zt]=(0,de.mergeArrays)(gt[Tt],gt[zt]),$t[zt]=(0,de.mergeArrays)($t[Tt],$t[zt]),Ge[Tt]="",gt[Tt]=[],$t[Tt]=[]):zt=Tt,--Tt;for(Tt=0,zt=1;zter),gt.filter(er=>er.length>0),$t.filter(er=>er.length>0)]}}class hs extends Se{}class fs extends Se{}class ms extends Se{}class Yt extends Se{constructor(_,F){super(_,F),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Q=>this.languageRegex.test(Q)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(_){if(_===null)return null;const[F,...Q]=_.trim().split(this.languageRegex);if(Q.length===0)return super._encode_text(F);if(Q.length===2){const[oe,ge]=Q;return this.supported_language_codes.includes(oe)||console.warn(`Unsupported language code "${oe}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,de.mergeArrays)([oe],super._encode_text(ge))}}}class ts extends Se{}class As extends Se{}class Is extends Se{}class _s extends Se{}class Fs extends Se{}class Os extends Se{constructor(_,F){super(_,F),this.decoder=new Pt({})}}class rs extends Se{}class zs{static async from_pretrained(_,{progress_callback:F=null,config:Q=null,cache_dir:oe=null,local_files_only:ge=!1,revision:Ge="main",legacy:gt=null}={}){var Sr;const[$t,Tt]=await B(_,{progress_callback:F,config:Q,cache_dir:oe,local_files_only:ge,revision:Ge,legacy:gt}),zt=((Sr=Tt.tokenizer_class)==null?void 0:Sr.replace(/Fast$/,""))??"PreTrainedTokenizer";let er=this.TOKENIZER_CLASS_MAPPING[zt];return er||(console.warn(`Unknown tokenizer class "${zt}", attempting to construct from base class.`),er=Se),new er($t,Tt)}}Me(zs,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:sr,DistilBertTokenizer:Fe,CamembertTokenizer:Oe,DebertaTokenizer:Ct,DebertaV2Tokenizer:ft,BertTokenizer:Ne,HerbertTokenizer:Lt,ConvBertTokenizer:jt,RoFormerTokenizer:Ot,XLMTokenizer:ct,ElectraTokenizer:Ut,MobileBertTokenizer:wt,SqueezeBertTokenizer:mt,AlbertTokenizer:tt,GPT2Tokenizer:br,BartTokenizer:Nr,MBartTokenizer:mr,MBart50Tokenizer:Er,RobertaTokenizer:wr,WhisperTokenizer:Dn,CodeGenTokenizer:hs,CLIPTokenizer:fs,SiglipTokenizer:ms,MarianTokenizer:Yt,BloomTokenizer:Cn,NllbTokenizer:Bn,M2M100Tokenizer:ps,LlamaTokenizer:cs,CodeLlamaTokenizer:Cs,XLMRobertaTokenizer:Kn,MPNetTokenizer:$s,FalconTokenizer:ks,GPTNeoXTokenizer:Es,EsmTokenizer:Ss,Wav2Vec2CTCTokenizer:ts,BlenderbotTokenizer:As,BlenderbotSmallTokenizer:Is,SpeechT5Tokenizer:_s,NougatTokenizer:Fs,VitsTokenizer:Os,Qwen2Tokenizer:Ps,GemmaTokenizer:es,Grok1Tokenizer:Xn,CohereTokenizer:rs,PreTrainedTokenizer:Se})},"./src/utils/audio.js":(At,ye,D)=>{D.r(ye),D.d(ye,{hamming:()=>L,hanning:()=>P,mel_filter_bank:()=>J,read_audio:()=>xe,spectrogram:()=>E,window_function:()=>N});var I=D("./src/utils/hub.js"),de=D("./src/utils/maths.js"),he=D("./src/utils/core.js"),ve=D("./src/utils/tensor.js");async function xe(k,le){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const be=await(await(0,I.getFile)(k)).arrayBuffer(),$e=new AudioContext({sampleRate:le});typeof le>"u"&&console.warn(`No sampling rate provided, using default of ${$e.sampleRate}Hz.`);const De=await $e.decodeAudioData(be);let ze;if(De.numberOfChannels===2){const it=Math.sqrt(2),rt=De.getChannelData(0),lt=De.getChannelData(1);ze=new Float32Array(rt.length);for(let _e=0;_e2595*Math.log10(1+k/700),kaldi:k=>1127*Math.log(1+k/700),slaney:(k,le=1e3,be=15,$e=27/Math.log(6.4))=>k>=le?be+Math.log(k/le)*$e:3*k/200};function q(k,le="htk"){const be=B[le];if(!be)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?be(k):k.map($e=>be($e))}const re={htk:k=>700*(10**(k/2595)-1),kaldi:k=>700*(Math.exp(k/1127)-1),slaney:(k,le=1e3,be=15,$e=Math.log(6.4)/27)=>k>=be?le*Math.exp($e*(k-be)):200*k/3};function me(k,le="htk"){const be=re[le];if(!be)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?be(k):k.map($e=>be($e))}function ue(k,le){const be=Float64Array.from({length:le.length-1},(it,rt)=>le[rt+1]-le[rt]),$e=Array.from({length:k.length},()=>new Array(le.length));for(let it=0;itnew Array(k.length));for(let it=0;itk+$e*ze)}function J(k,le,be,$e,De,ze=null,it="htk",rt=!1){if(ze!==null&&ze!=="slaney")throw new Error('norm must be one of null or "slaney"');const lt=q(be,it),_e=q($e,it),W=O(lt,_e,le+2);let ce=me(W,it),Ce;if(rt){const ot=De/(k*2);Ce=q(Float64Array.from({length:k},(ne,Ze)=>Ze*ot),it),ce=W}else Ce=O(0,Math.floor(De/2),k);const We=ue(Ce,ce);if(ze!==null&&ze==="slaney")for(let ot=0;otDe)throw Error(`frame_length (${be}) may not be larger than fft_length (${De})`);if(Xe!==be)throw new Error(`Length of the window (${Xe}) must equal frame_length (${be})`);if($e<=0)throw new Error("hop_length must be greater than zero");if(ze===null&&W!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(it){if(rt!=="reflect")throw new Error(`pad_mode="${rt}" not implemented yet.`);const H=Math.floor((De-1)/2)+1;k=pe(k,H,H)}let Z=Math.floor(1+Math.floor((k.length-be)/$e));dt!==null&&ZZ?ht&&(et=Re):et=Ke=Re);const je=new de.FFT(De),Ve=new Float64Array(De),ut=new Float64Array(je.outputBufferSize),_t=new Float32Array(Ae*et);for(let H=0;H=1;--fe)Ve[fe]-=_e*Ve[fe-1];Ve[0]*=1-_e}for(let fe=0;feMath.pow(rt,.85));break;default:throw new Error(`Unknown window type ${le}.`)}if(be&&(it=it.subarray(0,k)),$e===null)return it;if(k>$e)throw new Error(`Length of the window (${k}) may not be larger than frame_length (${$e})`);return it}},"./src/utils/constants.js":(At,ye,D)=>{D.r(ye),D.d(ye,{GITHUB_ISSUE_URL:()=>I});const I="https://github.com/huggingface/transformers.js/issues/new/choose"},"./src/utils/core.js":(At,ye,D)=>{D.r(ye),D.d(ye,{calculateDimensions:()=>j,calculateReflectOffset:()=>q,dispatchCallback:()=>I,escapeRegExp:()=>he,isIntegralNumber:()=>xe,isTypedArray:()=>ve,len:()=>me,mergeArrays:()=>L,pick:()=>re,pop:()=>P,product:()=>B,reverseDictionary:()=>de});function I(ue,O){ue&&ue(O)}function de(ue){return Object.fromEntries(Object.entries(ue).map(([O,J])=>[J,O]))}function he(ue){return ue.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ve(ue){var O,J,pe;return((pe=(J=(O=ue==null?void 0:ue.prototype)==null?void 0:O.__proto__)==null?void 0:J.constructor)==null?void 0:pe.name)==="TypedArray"}function xe(ue){return Number.isInteger(ue)||typeof ue=="bigint"}function j(ue){const O=[];let J=ue;for(;Array.isArray(J);)O.push(J.length),J=J[0];return O}function P(ue,O,J=void 0){const pe=ue[O];if(pe!==void 0)return delete ue[O],pe;if(J===void 0)throw Error(`Key ${O} does not exist in object.`);return J}function L(...ue){return Array.prototype.concat.apply([],ue)}function B(...ue){return ue.reduce((O,J)=>O.flatMap(pe=>J.map(X=>[pe,X])))}function q(ue,O){return Math.abs((ue+O)%(2*O)-O)}function re(ue,O){return Object.assign({},...O.map(J=>{if(ue[J]!==void 0)return{[J]:ue[J]}}))}function me(ue){let O=0;for(const J of ue)++O;return O}},"./src/utils/data-structures.js":(At,ye,D)=>{D.r(ye),D.d(ye,{CharTrie:()=>de,PriorityQueue:()=>I,TokenLattice:()=>ve});class I{constructor(P=(B,q)=>B>q,L=1/0){this._heap=[],this._comparator=P,this._maxSize=L}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...P){return this.extend(P)}extend(P){for(const L of P)if(this.size0&&this._swap(0,L),this._heap.pop(),this._siftDown(),P}replace(P){const L=this.peek();return this._heap[0]=P,this._siftDown(),L}_parent(P){return(P+1>>>1)-1}_left(P){return(P<<1)+1}_right(P){return P+1<<1}_greater(P,L){return this._comparator(this._heap[P],this._heap[L])}_swap(P,L){const B=this._heap[P];this._heap[P]=this._heap[L],this._heap[L]=B}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(P){for(;P>0&&this._greater(P,this._parent(P));)this._swap(P,this._parent(P)),P=this._parent(P)}_siftDown(){let P=0;for(;this._left(P)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const q=new xe(this.bosTokenId,0,0,0,0),re=new xe(this.eosTokenId,1,this.len,0,0);this.nodes.push(q.clone()),this.nodes.push(re.clone()),this.beginNodes[this.len].push(re),this.endNodes[0].push(q)}insert(P,L,B,q){const re=this.nodes.length,me=new xe(q,re,P,L,B);this.beginNodes[P].push(me),this.endNodes[P+L].push(me),this.nodes.push(me)}viterbi(){const P=this.len;let L=0;for(;L<=P;){if(this.beginNodes[L].length==0)return[];for(let ue of this.beginNodes[L]){ue.prev=null;let O=0,J=null;for(let pe of this.endNodes[L]){const X=pe.backtraceScore+ue.score;(J===null||X>O)&&(J=pe.clone(),O=X)}if(J!==null)ue.prev=J,ue.backtraceScore=O;else return[]}++L}const B=[],re=this.beginNodes[P][0].prev;if(re===null)return[];let me=re.clone();for(;me.prev!==null;)B.push(me.clone()),me=me.clone().prev.clone();return B.reverse(),B}piece(P){return this.chars.slice(P.pos,P.pos+P.length).join("")}tokens(){return this.viterbi().map(L=>this.piece(L))}tokenIds(){return this.viterbi().map(L=>L.tokenId)}}class xe{constructor(P,L,B,q,re){this.tokenId=P,this.nodeId=L,this.pos=B,this.length=q,this.score=re,this.prev=null,this.backtraceScore=0}clone(){const P=new xe(this.tokenId,this.nodeId,this.pos,this.length,this.score);return P.prev=this.prev,P.backtraceScore=this.backtraceScore,P}}},"./src/utils/devices.js":(At,ye,D)=>{D.r(ye),D.d(ye,{DEVICE_TYPES:()=>I});const I=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":(At,ye,D)=>{D.r(ye),D.d(ye,{DATA_TYPES:()=>ve,DEFAULT_DEVICE_DTYPE_MAPPING:()=>xe,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>j,isWebGpuFp16Supported:()=>he});var I=D("./src/env.js"),de=D("./src/utils/devices.js");const he=function(){let P;return async function(){if(P===void 0)if(!I.apis.IS_WEBGPU_AVAILABLE)P=!1;else try{P=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{P=!1}return P}}(),ve=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),xe=Object.freeze({[de.DEVICE_TYPES.wasm]:ve.q8}),j=Object.freeze({[ve.fp32]:"",[ve.fp16]:"_fp16",[ve.int8]:"_int8",[ve.uint8]:"_uint8",[ve.q8]:"_quantized",[ve.q4]:"_q4",[ve.q4f16]:"_q4f16",[ve.bnb4]:"_bnb4"})},"./src/utils/generic.js":(At,ye,D)=>{D.r(ye),D.d(ye,{Callable:()=>I});const I=class{constructor(){let de=function(...he){return de._call(...he)};return Object.setPrototypeOf(de,new.target.prototype)}_call(...de){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(At,ye,D)=>{D.r(ye),D.d(ye,{getFile:()=>L,getModelFile:()=>ue,getModelJSON:()=>O});var I=D("?7a2c"),de=D("?a42a"),he=D("./src/env.js"),ve=D("./src/utils/core.js");const xe={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class j{constructor(K){if(this.filePath=K,this.headers=new Headers,this.exists=I.existsSync(K),this.exists){this.status=200,this.statusText="OK";let V=I.statSync(K);this.headers.set("content-length",V.size.toString()),this.updateContentType();let E=this;this.body=new ReadableStream({start(N){E.arrayBuffer().then(k=>{N.enqueue(new Uint8Array(k)),N.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const K=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",xe[K]??"application/octet-stream")}clone(){let K=new j(this.filePath);return K.exists=this.exists,K.status=this.status,K.statusText=this.statusText,K.headers=new Headers(this.headers),K}async arrayBuffer(){return(await I.promises.readFile(this.filePath)).buffer}async blob(){const K=await I.promises.readFile(this.filePath);return new Blob([K],{type:this.headers.get("content-type")})}async text(){return await I.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function P(X,K=null,V=null){let E;try{E=new URL(X)}catch{return!1}return!(K&&!K.includes(E.protocol)||V&&!V.includes(E.hostname))}async function L(X){var K;if(he.env.useFS&&!P(X,["http:","https:","blob:"]))return new j(X);if(typeof process<"u"&&((K=process==null?void 0:process.release)==null?void 0:K.name)==="node"){const V=!!(Ts!=null&&Ts.TESTING_REMOTELY),E=he.env.version,N=new Headers;if(N.set("User-Agent",`transformers.js/${E}; is_ci/${V};`),P(X,["http:","https:"],["huggingface.co","hf.co"])){const le=(Ts==null?void 0:Ts.HF_TOKEN)??(Ts==null?void 0:Ts.HF_ACCESS_TOKEN);le&&N.set("Authorization",`Bearer ${le}`)}return fetch(X,{headers:N})}else return fetch(X)}const B={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function q(X,K,V){if(!V)return null;const E=B[X]??`Error (${X}) occurred while trying to load file`;throw Error(`${E}: "${K}".`)}class re{constructor(K){this.path=K}async match(K){let V=de.join(this.path,K),E=new j(V);if(E.exists)return E}async put(K,V){const E=Buffer.from(await V.arrayBuffer());let N=de.join(this.path,K);try{await I.promises.mkdir(de.dirname(N),{recursive:!0}),await I.promises.writeFile(N,E)}catch(k){console.warn("An error occurred while writing the file to cache:",k)}}}async function me(X,...K){for(let V of K)try{let E=await X.match(V);if(E)return E}catch{continue}}async function ue(X,K,V=!0,E={}){if(!he.env.allowLocalModels){if(E.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(!he.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,ve.dispatchCallback)(E.progress_callback,{status:"initiate",name:X,file:K});let N;if(!N&&he.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{N=await caches.open("transformers-cache")}catch(Ce){console.warn("An error occurred while opening the browser cache:",Ce)}}if(!N&&he.env.useFSCache&&(N=new re(E.cache_dir??he.env.cacheDir)),!N&&he.env.useCustomCache){if(!he.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!he.env.customCache.match||!he.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");N=he.env.customCache}const k=E.revision??"main";let le=pe(X,K),be=pe(he.env.localModelPath,le),$e=pe(he.env.remoteHost,he.env.remotePathTemplate.replaceAll("{model}",X).replaceAll("{revision}",encodeURIComponent(k)),K),De=k==="main"?le:pe(X,k,K),ze,it=N instanceof re?De:$e,rt=!1,lt;N&&(lt=await me(N,be,it));const _e=lt!==void 0;if(lt===void 0){if(he.env.allowLocalModels)if(P(le,["http:","https:"])){if(E.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${le}.`);if(!he.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${le}.`)}else try{lt=await L(be),ze=be}catch(We){console.warn(`Unable to load from local path "${be}": "${We}"`)}if(lt===void 0||lt.status===404){if(E.local_files_only||!he.env.allowRemoteModels){if(V)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${be}".`);return null}if(lt=await L($e),lt.status!==200)return q(lt.status,$e,V);ze=it}rt=N&&typeof Response<"u"&< instanceof Response&<.status===200}(0,ve.dispatchCallback)(E.progress_callback,{status:"download",name:X,file:K});const W={status:"progress",name:X,file:K};let ce;return E.progress_callback?_e&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ce=new Uint8Array(await lt.arrayBuffer()),(0,ve.dispatchCallback)(E.progress_callback,{...W,progress:100,loaded:ce.length,total:ce.length})):ce=await J(lt,Ce=>{(0,ve.dispatchCallback)(E.progress_callback,{...W,...Ce})}):ce=new Uint8Array(await lt.arrayBuffer()),rt&&ze&&await N.match(ze)===void 0&&await N.put(ze,new Response(ce,{headers:lt.headers})).catch(Ce=>{console.warn(`Unable to add response to browser cache: ${Ce}.`)}),(0,ve.dispatchCallback)(E.progress_callback,{status:"done",name:X,file:K}),ce}async function O(X,K,V=!0,E={}){let N=await ue(X,K,V,E);if(N===null)return{};let le=new TextDecoder("utf-8").decode(N);return JSON.parse(le)}async function J(X,K){const V=X.headers.get("Content-Length");V===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let E=parseInt(V??"0"),N=new Uint8Array(E),k=0;const le=X.body.getReader();async function be(){const{done:$e,value:De}=await le.read();if($e)return;let ze=k+De.length;if(ze>E){E=ze;let rt=new Uint8Array(E);rt.set(N),N=rt}N.set(De,k),k=ze;const it=k/E*100;return K({progress:it,loaded:k,total:E}),be()}return await be(),N}function pe(...X){return X=X.map((K,V)=>(V&&(K=K.replace(new RegExp("^/"),"")),V!==X.length-1&&(K=K.replace(new RegExp("/$"),"")),K)),X.join("/")}},"./src/utils/image.js":(At,ye,D)=>{D.r(ye),D.d(ye,{RawImage:()=>me});var I=D("./src/utils/hub.js"),de=D("./src/env.js"),he=D("./src/utils/tensor.js"),ve=D("?2b25");const xe=typeof self<"u",j=xe&&self.constructor.name==="DedicatedWorkerGlobalScope";let P,L,B;if(xe)P=(ue,O)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ue,O)},B=self.createImageBitmap,L=self.ImageData;else if(ve)B=async ue=>{const J=(await ue.metadata()).channels,{data:pe,info:X}=await ue.rotate().raw().toBuffer({resolveWithObject:!0}),K=new me(new Uint8ClampedArray(pe),X.width,X.height,X.channels);return J!==void 0&&J!==X.channels&&K.convert(J),K};else throw new Error("Unable to load image processing library.");const q={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},re=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class me{constructor(O,J,pe,X){this.data=O,this.width=J,this.height=pe,this.channels=X}get size(){return[this.width,this.height]}static async read(O){if(O instanceof me)return O;if(typeof O=="string"||O instanceof URL)return await this.fromURL(O);throw new Error(`Unsupported input type: ${typeof O}`)}static fromCanvas(O){if(!xe)throw new Error("fromCanvas() is only supported in browser environments.");const pe=O.getContext("2d").getImageData(0,0,O.width,O.height).data;return new me(pe,O.width,O.height,4)}static async fromURL(O){const J=await(0,I.getFile)(O);if(J.status!==200)throw new Error(`Unable to read image from "${O}" (${J.status} ${J.statusText})`);const pe=await J.blob();return this.fromBlob(pe)}static async fromBlob(O){if(xe){const J=await B(O),pe=P(J.width,J.height).getContext("2d");return pe.drawImage(J,0,0),new this(pe.getImageData(0,0,J.width,J.height).data,J.width,J.height,4)}else{const J=ve(await O.arrayBuffer());return await B(J)}}static fromTensor(O,J="CHW"){if(O.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${O.dims.length} dimensions.`);if(J==="CHW")O=O.transpose(1,2,0);else if(J!=="HWC")throw new Error(`Unsupported channel format: ${J}`);if(!(O.data instanceof Uint8ClampedArray||O.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${O.type}`);switch(O.dims[2]){case 1:case 2:case 3:case 4:return new me(O.data,O.dims[1],O.dims[0],O.dims[2]);default:throw new Error(`Unsupported number of channels: ${O.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const O=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let J=0,pe=0;J=0?N=pe:le=-pe,X>=0?k=X:be=-X,E.drawImage(V,N,k,O,J,le,be,O,J),new me(E.getImageData(0,0,O,J).data,O,J,4).convert(K)}else{let K=this.toSharp();if(pe>=0&&X>=0)K=K.extract({left:Math.floor(pe),top:Math.floor(X),width:O,height:J});else if(pe<=0&&X<=0){const V=Math.floor(-X),E=Math.floor(-pe);K=K.extend({top:V,left:E,right:O-this.width-E,bottom:J-this.height-V})}else{let V=[0,0],E=0;X<0?(V[0]=Math.floor(-X),V[1]=J-this.height-V[0]):E=Math.floor(X);let N=[0,0],k=0;pe<0?(N[0]=Math.floor(-pe),N[1]=O-this.width-N[0]):k=Math.floor(pe),K=K.extend({top:V[0],bottom:V[1],left:N[0],right:N[1]}).extract({left:k,top:E,width:O,height:J})}return await B(K)}}async toBlob(O="image/png",J=1){if(!xe)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:O,quality:J})}toTensor(O="CHW"){let J=new he.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(O!=="HWC")if(O==="CHW")J=J.permute(2,0,1);else throw new Error(`Unsupported channel format: ${O}`);return J}toCanvas(){if(!xe)throw new Error("toCanvas() is only supported in browser environments.");const O=this.clone().rgba(),J=P(O.width,O.height),pe=new L(O.data,O.width,O.height);return J.getContext("2d").putImageData(pe,0,0),J}_update(O,J,pe,X=null){return this.data=O,this.width=J,this.height=pe,X!==null&&(this.channels=X),this}clone(){return new me(this.data.slice(),this.width,this.height,this.channels)}convert(O){if(this.channels===O)return this;switch(O){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(O){if(xe){if(j)throw new Error("Unable to save an image from a Web Worker.");const J=O.split(".").pop().toLowerCase(),pe=re.get(J)??"image/png",X=await this.toBlob(pe),K=URL.createObjectURL(X),V=document.createElement("a");V.href=K,V.download=O,V.click(),V.remove()}else{if(de.env.useFS)return await this.toSharp().toFile(O);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(xe)throw new Error("toSharp() is only supported in server-side environments.");return ve(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(At,ye,D)=>{D.r(ye),D.d(ye,{FFT:()=>ue,bankers_round:()=>pe,cos_sim:()=>j,dot:()=>xe,dynamic_time_warping:()=>X,interpolate_data:()=>I,log_softmax:()=>ve,magnitude:()=>P,max:()=>B,medianFilter:()=>O,min:()=>L,permute_data:()=>de,round:()=>J,softmax:()=>he});function I(K,[V,E,N],[k,le],be="bilinear",$e=!1){const De=le/N,ze=k/E,it=new K.constructor(k*le*V),rt=E*N,lt=k*le;for(let _e=0;_e=0;--$e)k[$e]=De,N[$e]=V[E[$e]],De*=N[$e];const le=E.map(($e,De)=>k[E.indexOf(De)]),be=new K.constructor(K.length);for(let $e=0;$e=0;--ze)De+=it%V[ze]*le[ze],it=Math.floor(it/V[ze]);be[De]=K[$e]}return[be,N]}function he(K){const V=B(K)[0],E=K.map(le=>Math.exp(le-V)),N=E.reduce((le,be)=>le+be,0);return E.map(le=>le/N)}function ve(K){const V=B(K)[0];let E=0;for(let le=0;lele-V-N)}function xe(K,V){let E=0;for(let N=0;NV+E*E,0))}function L(K){if(K.length===0)throw Error("Array must not be empty");let V=K[0],E=0;for(let N=1;NV&&(V=K[N],E=N);return[Number(V),E]}function q(K){return K>0&&(K&K-1)===0}class re{constructor(V){if(this.size=V|0,this.size<=1||!q(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=V<<1,this.table=new Float64Array(this.size*2);for(let N=0;NN;N<<=1)++E;this._width=E%2===0?E-1:E,this._bitrev=new Int32Array(1<>>k&3)<>>1);for(let k=0;k>>1]=V[k];return N}toComplexArray(V,E){const N=E||this.createComplexArray();for(let k=0;k>>1],N[k+1]=0;return N}transform(V,E){if(V===E)throw new Error("Input and output buffers must be different");this._transform4(V,E,1)}realTransform(V,E){if(V===E)throw new Error("Input and output buffers must be different");this._realTransform4(V,E,1)}inverseTransform(V,E){if(V===E)throw new Error("Input and output buffers must be different");this._transform4(V,E,-1);for(let N=0;N>=2;be>=2;be>>=2){$e=k/be<<1;const lt=$e>>>2;for(De=0;De>>1,be>>>1)}else for(De=0,ze=0;De>>1,be>>>1,N)}const rt=this.table;for(be>>=2;be>=2;be>>=2){$e=k/be<<1;const _e=$e>>>1,W=_e>>>1,ce=W>>>1;for(De=0;De>>1;for(let _e=2;_e>1;++it){const rt=(it+1-V)**2/2,lt=Math.sqrt(De**2+ze**2)**rt,_e=rt*Math.atan2(ze,De),W=2*it;le[W]=lt*Math.cos(_e),le[W+1]=lt*Math.sin(_e),be[W]=le[W],be[W+1]=-le[W+1]}this._slicedChirpBuffer=le.subarray(E,N),this._f=new re(k>>1),this._f.transform(this._chirpBuffer,be)}_transform(V,E,N){const k=this._buffer1,le=this._buffer2,be=this._outBuffer1,$e=this._outBuffer2,De=this._chirpBuffer,ze=this._slicedChirpBuffer,it=this._a;if(N)for(let rt=0;rt>1,W=E[_e];k[rt]=W*ze[rt],k[lt]=W*ze[lt]}else for(let rt=0;rt=K.length&&(De=2*(K.length-1)-De),N[be++]=K[De]}N.sort(),E[le]=N[k]}return E}function J(K,V){const E=Math.pow(10,V);return Math.round(K*E)/E}function pe(K){const V=Math.round(K);return Math.abs(K)%1===.5?V%2===0?V:V-1:V}function X(K){const V=K.length,E=K[0].length,N=[V+1,E+1],k=Array.from({length:N[0]},()=>Array(N[1]).fill(1/0));k[0][0]=0;const le=Array.from({length:N[0]},()=>Array(N[1]).fill(-1));for(let it=1;it0||$e>0;)switch(De.push(be-1),ze.push($e-1),le[be][$e]){case 0:--be,--$e;break;case 1:--be;break;case 2:--$e;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${be}, ${$e}]. Please file a bug report.`)}return De.reverse(),ze.reverse(),[De,ze]}},"./src/utils/tensor.js":(At,ye,D)=>{D.r(ye),D.d(ye,{Tensor:()=>xe,cat:()=>K,full:()=>be,full_like:()=>$e,interpolate:()=>L,interpolate_4d:()=>B,layer_norm:()=>O,matmul:()=>q,mean:()=>N,mean_pooling:()=>ue,ones:()=>De,ones_like:()=>ze,permute:()=>P,quantize_embeddings:()=>lt,rfft:()=>re,stack:()=>V,std_mean:()=>E,topk:()=>me,zeros:()=>it,zeros_like:()=>rt});var I=D("./src/utils/maths.js"),de=D("./src/backends/onnx.js"),he=D("./src/ops/registry.js");const ve=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 xe{constructor(...W){Me(this,"ort_tensor");return(0,de.isONNXTensor)(W[0])?this.ort_tensor=W[0]:this.ort_tensor=new de.Tensor(W[0],W[1],W[2]),new Proxy(this,{get:(ce,Ce)=>{if(typeof Ce=="string"){let We=Number(Ce);if(Number.isInteger(We))return ce._getitem(We)}return ce[Ce]},set:(ce,Ce,We)=>ce[Ce]=We})}get dims(){return this.ort_tensor.dims}set dims(W){this.ort_tensor.dims=W}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[W,...ce]=this.dims;if(ce.length>0){const Ce=ce.reduce((We,ot)=>We*ot);for(let We=0;We0){const We=Ce.reduce((ot,ne)=>ot*ne);return this._subarray(W,We,Ce)}else return new xe(this.type,[this.data[W]],Ce)}indexOf(W){const ce=this.data;for(let Ce=0;CeXe)throw new Error(`Invalid slice: ${ht}`);const Z=[Math.max(Mt,0),Math.min(Xe,this.dims[Re])];Ce.push(Z),ce.push(Z[1]-Z[0])}else throw new Error(`Invalid slice: ${ht}`)}const We=Ce.map(([Re,ht])=>ht-Re),ot=We.reduce((Re,ht)=>Re*ht),ne=this.data,Ze=new ne.constructor(ot),dt=this.stride();for(let Re=0;Re=0;--Mt){const Z=We[Mt];ht+=(Xe%Z+Ce[Mt][0])*dt[Mt],Xe=Math.floor(Xe/Z)}Ze[Re]=ne[ht]}return new xe(this.type,Ze,ce)}permute(...W){return P(this,W)}transpose(...W){return this.permute(...W)}sum(W=null,ce=!1){return this.norm(1,W,ce)}norm(W="fro",ce=null,Ce=!1){if(W==="fro")W=2;else if(typeof W=="string")throw Error(`Unsupported norm: ${W}`);const We=this.data;if(ce===null){let Ze=We.reduce((dt,Re)=>dt+Re**W,0)**(1/W);return new xe(this.type,[Ze],[])}ce=X(ce,this.dims.length);const ot=this.dims.slice();ot[ce]=1;const ne=new We.constructor(We.length/this.dims[ce]);for(let Ze=0;Ze=0;--Re){const Xe=this.dims[Re];if(Re!==ce){const Z=ht%Xe;dt+=Z*Mt,Mt*=ot[Re]}ht=Math.floor(ht/Xe)}ne[dt]+=We[Ze]**W}if(W!==1)for(let Ze=0;Ze=0;--dt){const Mt=this.dims[dt];if(dt!==ce){const Xe=Re%Mt;Ze+=Xe*ht,ht*=this.dims[dt]}Re=Math.floor(Re/Mt)}We[ne]/=ot[Ze]}return this}normalize(W=2,ce=1){return this.clone().normalize_(W,ce)}stride(){return k(this.dims)}squeeze(W=null){return new xe(this.type,this.data,J(this.dims,W))}squeeze_(W=null){return this.dims=J(this.dims,W),this}unsqueeze(W=null){return new xe(this.type,this.data,pe(this.dims,W))}unsqueeze_(W=null){return this.dims=pe(this.dims,W),this}flatten_(W=0,ce=-1){ce=(ce+this.dims.length)%this.dims.length;let Ce=this.dims.slice(0,W),We=this.dims.slice(W,ce+1),ot=this.dims.slice(ce+1);return this.dims=[...Ce,We.reduce((ne,Ze)=>ne*Ze,1),...ot],this}flatten(W=0,ce=-1){return this.clone().flatten_(W,ce)}view(...W){let ce=-1;for(let We=0;WeZe!==ce?ot*ne:ot,1);W[ce]=Ce.length/We}return new xe(this.type,Ce,W)}neg_(){const W=this.data;for(let ce=0;ceot*ne);if(ce!==Ce)throw Error(`cannot reshape array of size ${ce} into shape (${W})`);let We=_e;for(let ot=W.length-1;ot>=0;ot--)We=We.reduce((ne,Ze)=>{let dt=ne[ne.length-1];return dt.lengthce!==1):typeof W=="number"?_e[W]===1&&_e.splice(W,1):Array.isArray(W)&&(_e=_e.filter((ce,Ce)=>ce!==1||!W.includes(Ce))),_e}function pe(_e,W){return W=X(W,_e.length+1),_e=_e.slice(),_e.splice(W,0,1),_e}function X(_e,W,ce=null,Ce=!0){if(Ce&&(_e<-W||_e>=W))throw new Error(`IndexError: index ${_e} is out of bounds for dimension${ce===null?"":" "+ce} with size ${W}`);return _e<0&&(_e=(_e%W+W)%W),_e}function K(_e,W=0){W=X(W,_e[0].dims.length);const ce=_e[0].dims.slice();ce[W]=_e.reduce((ne,Ze)=>ne+Ze.dims[W],0);const Ce=ce.reduce((ne,Ze)=>ne*Ze,1),We=new _e[0].data.constructor(Ce),ot=_e[0].type;if(W===0){let ne=0;for(const Ze of _e){const dt=Ze.data;We.set(dt,ne),ne+=dt.length}}else{let ne=0;for(let Ze=0;Ze<_e.length;++Ze){const{data:dt,dims:Re}=_e[Ze];for(let ht=0;ht=0;--Xe){const Ke=Re[Xe];let et=Z%Ke;Xe===W&&(et+=ne),Mt+=et*Ae,Ae*=ce[Xe],Z=Math.floor(Z/Ke)}We[Mt]=dt[ht]}ne+=Re[W]}}return new xe(ot,We,ce)}function V(_e,W=0){return K(_e.map(ce=>ce.unsqueeze(W)),W)}function E(_e,W=null,ce=1,Ce=!1){const We=_e.data,ot=_e.dims;if(W===null){const Xe=We.reduce((et,je)=>et+je,0)/We.length,Z=Math.sqrt(We.reduce((et,je)=>et+(je-Xe)**2,0)/(We.length-ce)),Ae=new xe(_e.type,[Xe],[]);return[new xe(_e.type,[Z],[]),Ae]}W=X(W,ot.length);const ne=N(_e,W,Ce),Ze=ne.data,dt=ot.slice();dt[W]=1;const Re=new We.constructor(We.length/ot[W]);for(let Mt=0;Mt=0;--Z){const et=ot[Z];if(Z!==W){const je=Ae%et;Xe+=je*Ke,Ke*=dt[Z]}Ae=Math.floor(Ae/et)}Re[Xe]+=(We[Mt]-Ze[Xe])**2}for(let Mt=0;Mtdt+Re,0);return new xe(_e.type,[Ze/Ce.length],[])}const We=_e.dims;W=X(W,We.length);const ot=We.slice();ot[W]=1;const ne=new Ce.constructor(Ce.length/We[W]);for(let Ze=0;Ze=0;--Re){const Xe=We[Re];if(Re!==W){const Z=ht%Xe;dt+=Z*Mt,Mt*=ot[Re]}ht=Math.floor(ht/Xe)}ne[dt]+=Ce[Ze]}if(We[W]!==1)for(let Ze=0;Ze=0;--ce)W[ce]=Ce,Ce*=_e[ce];return W}function le(_e,W,ce,Ce){const We=_e.reduce((ot,ne)=>ot*ne,1);return new xe(ce,new Ce(We).fill(W),_e)}function be(_e,W){let ce,Ce;if(typeof W=="number")ce="float32",Ce=Float32Array;else if(typeof W=="bigint")ce="int64",Ce=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof W}`);return le(_e,W,ce,Ce)}function $e(_e,W){return be(_e.dims,W)}function De(_e){return le(_e,1n,"int64",BigInt64Array)}function ze(_e){return De(_e.dims)}function it(_e){return le(_e,0n,"int64",BigInt64Array)}function rt(_e){return it(_e.dims)}function lt(_e,W){if(_e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(_e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(W))throw new Error("The precision must be either 'binary' or 'ubinary'");const ce=W==="binary",Ce=ce?"int8":"uint8",We=ce?Int8Array:Uint8Array,ot=_e.data,ne=new We(ot.length/8);for(let Ze=0;Ze0?1:0,Re=Math.floor(Ze/8),ht=Ze%8;ne[Re]|=dt<<7-ht,ce&&ht===0&&(ne[Re]-=128)}return new xe(Ce,ne,[_e.dims[0],_e.dims[1]/8])}}},kf={};function Hr(At){var ye=kf[At];if(ye!==void 0)return ye.exports;var D=kf[At]={exports:{}};return Ef[At](D,D.exports,Hr),D.exports}Hr.m=Ef;(()=>{var At=Object.getPrototypeOf?D=>Object.getPrototypeOf(D):D=>D.__proto__,ye;Hr.t=function(D,I){if(I&1&&(D=this(D)),I&8||typeof D=="object"&&D&&(I&4&&D.__esModule||I&16&&typeof D.then=="function"))return D;var de=Object.create(null);Hr.r(de);var he={};ye=ye||[null,At({}),At([]),At(At)];for(var ve=I&2&&D;typeof ve=="object"&&!~ye.indexOf(ve);ve=At(ve))Object.getOwnPropertyNames(ve).forEach(xe=>he[xe]=()=>D[xe]);return he.default=()=>D,Hr.d(de,he),de}})();Hr.d=(At,ye)=>{for(var D in ye)Hr.o(ye,D)&&!Hr.o(At,D)&&Object.defineProperty(At,D,{enumerable:!0,get:ye[D]})};Hr.o=(At,ye)=>Object.prototype.hasOwnProperty.call(At,ye);Hr.r=At=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(At,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(At,"__esModule",{value:!0})};(()=>{var At;if(typeof import.meta.url=="string"&&(At=import.meta.url),!At)throw new Error("Automatic publicPath is not supported in this browser");At=At.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Hr.p=At})();Hr.b=new URL("./",import.meta.url);var p={};/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/Hr.r(p);Hr.d(p,{ASTFeatureExtractor:()=>Jt.ASTFeatureExtractor,ASTForAudioClassification:()=>y.ASTForAudioClassification,ASTModel:()=>y.ASTModel,ASTPreTrainedModel:()=>y.ASTPreTrainedModel,AlbertForMaskedLM:()=>y.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>y.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>y.AlbertForSequenceClassification,AlbertModel:()=>y.AlbertModel,AlbertPreTrainedModel:()=>y.AlbertPreTrainedModel,AlbertTokenizer:()=>ur.AlbertTokenizer,AudioClassificationPipeline:()=>qr.AudioClassificationPipeline,AutoConfig:()=>mp.AutoConfig,AutoModel:()=>y.AutoModel,AutoModelForAudioClassification:()=>y.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>y.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>y.AutoModelForCTC,AutoModelForCausalLM:()=>y.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>y.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>y.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>y.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>y.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>y.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>y.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>y.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>y.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>y.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>y.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>y.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>y.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>y.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>y.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>y.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>y.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>y.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>y.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>y.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>y.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>y.AutoModelForVision2Seq,AutoModelForXVector:()=>y.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>y.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Jt.AutoProcessor,AutoTokenizer:()=>ur.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>qr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>y.BartForConditionalGeneration,BartForSequenceClassification:()=>y.BartForSequenceClassification,BartModel:()=>y.BartModel,BartPretrainedModel:()=>y.BartPretrainedModel,BartTokenizer:()=>ur.BartTokenizer,BaseModelOutput:()=>y.BaseModelOutput,BaseStreamer:()=>_p.BaseStreamer,BeitFeatureExtractor:()=>Jt.BeitFeatureExtractor,BeitForImageClassification:()=>y.BeitForImageClassification,BeitModel:()=>y.BeitModel,BeitPreTrainedModel:()=>y.BeitPreTrainedModel,BertForMaskedLM:()=>y.BertForMaskedLM,BertForQuestionAnswering:()=>y.BertForQuestionAnswering,BertForSequenceClassification:()=>y.BertForSequenceClassification,BertForTokenClassification:()=>y.BertForTokenClassification,BertModel:()=>y.BertModel,BertPreTrainedModel:()=>y.BertPreTrainedModel,BertTokenizer:()=>ur.BertTokenizer,BitImageProcessor:()=>Jt.BitImageProcessor,BlenderbotForConditionalGeneration:()=>y.BlenderbotForConditionalGeneration,BlenderbotModel:()=>y.BlenderbotModel,BlenderbotPreTrainedModel:()=>y.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>y.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>y.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>y.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>ur.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>ur.BlenderbotTokenizer,BloomForCausalLM:()=>y.BloomForCausalLM,BloomModel:()=>y.BloomModel,BloomPreTrainedModel:()=>y.BloomPreTrainedModel,BloomTokenizer:()=>ur.BloomTokenizer,CLIPFeatureExtractor:()=>Jt.CLIPFeatureExtractor,CLIPImageProcessor:()=>Jt.CLIPImageProcessor,CLIPModel:()=>y.CLIPModel,CLIPPreTrainedModel:()=>y.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>y.CLIPSegForImageSegmentation,CLIPSegModel:()=>y.CLIPSegModel,CLIPSegPreTrainedModel:()=>y.CLIPSegPreTrainedModel,CLIPTextModel:()=>y.CLIPTextModel,CLIPTextModelWithProjection:()=>y.CLIPTextModelWithProjection,CLIPTokenizer:()=>ur.CLIPTokenizer,CLIPVisionModel:()=>y.CLIPVisionModel,CLIPVisionModelWithProjection:()=>y.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>y.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>y.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>y.CamembertForSequenceClassification,CamembertForTokenClassification:()=>y.CamembertForTokenClassification,CamembertModel:()=>y.CamembertModel,CamembertPreTrainedModel:()=>y.CamembertPreTrainedModel,CamembertTokenizer:()=>ur.CamembertTokenizer,CausalLMOutput:()=>y.CausalLMOutput,CausalLMOutputWithPast:()=>y.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Jt.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>y.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>y.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>y.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Jt.ClapFeatureExtractor,ClapModel:()=>y.ClapModel,ClapPreTrainedModel:()=>y.ClapPreTrainedModel,ClapTextModelWithProjection:()=>y.ClapTextModelWithProjection,CodeGenForCausalLM:()=>y.CodeGenForCausalLM,CodeGenModel:()=>y.CodeGenModel,CodeGenPreTrainedModel:()=>y.CodeGenPreTrainedModel,CodeGenTokenizer:()=>ur.CodeGenTokenizer,CodeLlamaTokenizer:()=>ur.CodeLlamaTokenizer,CohereForCausalLM:()=>y.CohereForCausalLM,CohereModel:()=>y.CohereModel,CoherePreTrainedModel:()=>y.CoherePreTrainedModel,CohereTokenizer:()=>ur.CohereTokenizer,ConvBertForMaskedLM:()=>y.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>y.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>y.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>y.ConvBertForTokenClassification,ConvBertModel:()=>y.ConvBertModel,ConvBertPreTrainedModel:()=>y.ConvBertPreTrainedModel,ConvBertTokenizer:()=>ur.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Jt.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>y.ConvNextForImageClassification,ConvNextImageProcessor:()=>Jt.ConvNextImageProcessor,ConvNextModel:()=>y.ConvNextModel,ConvNextPreTrainedModel:()=>y.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>y.ConvNextV2ForImageClassification,ConvNextV2Model:()=>y.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>y.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Jt.DPTFeatureExtractor,DPTForDepthEstimation:()=>y.DPTForDepthEstimation,DPTImageProcessor:()=>Jt.DPTImageProcessor,DPTModel:()=>y.DPTModel,DPTPreTrainedModel:()=>y.DPTPreTrainedModel,DebertaForMaskedLM:()=>y.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>y.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>y.DebertaForSequenceClassification,DebertaForTokenClassification:()=>y.DebertaForTokenClassification,DebertaModel:()=>y.DebertaModel,DebertaPreTrainedModel:()=>y.DebertaPreTrainedModel,DebertaTokenizer:()=>ur.DebertaTokenizer,DebertaV2ForMaskedLM:()=>y.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>y.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>y.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>y.DebertaV2ForTokenClassification,DebertaV2Model:()=>y.DebertaV2Model,DebertaV2PreTrainedModel:()=>y.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>ur.DebertaV2Tokenizer,DecisionTransformerModel:()=>y.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>y.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>Jt.DeiTFeatureExtractor,DeiTForImageClassification:()=>y.DeiTForImageClassification,DeiTModel:()=>y.DeiTModel,DeiTPreTrainedModel:()=>y.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>y.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>y.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>qr.DepthEstimationPipeline,DepthProForDepthEstimation:()=>y.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>y.DepthProPreTrainedModel,DetrFeatureExtractor:()=>Jt.DetrFeatureExtractor,DetrForObjectDetection:()=>y.DetrForObjectDetection,DetrForSegmentation:()=>y.DetrForSegmentation,DetrModel:()=>y.DetrModel,DetrObjectDetectionOutput:()=>y.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>y.DetrPreTrainedModel,DetrSegmentationOutput:()=>y.DetrSegmentationOutput,Dinov2ForImageClassification:()=>y.Dinov2ForImageClassification,Dinov2Model:()=>y.Dinov2Model,Dinov2PreTrainedModel:()=>y.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>y.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>y.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>y.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>y.DistilBertForTokenClassification,DistilBertModel:()=>y.DistilBertModel,DistilBertPreTrainedModel:()=>y.DistilBertPreTrainedModel,DistilBertTokenizer:()=>ur.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>qr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Jt.DonutFeatureExtractor,DonutImageProcessor:()=>Jt.DonutImageProcessor,DonutSwinModel:()=>y.DonutSwinModel,DonutSwinPreTrainedModel:()=>y.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>y.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Jt.EfficientNetImageProcessor,EfficientNetModel:()=>y.EfficientNetModel,EfficientNetPreTrainedModel:()=>y.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>y.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>y.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>y.ElectraForSequenceClassification,ElectraForTokenClassification:()=>y.ElectraForTokenClassification,ElectraModel:()=>y.ElectraModel,ElectraPreTrainedModel:()=>y.ElectraPreTrainedModel,ElectraTokenizer:()=>ur.ElectraTokenizer,EosTokenCriteria:()=>$d.EosTokenCriteria,EsmForMaskedLM:()=>y.EsmForMaskedLM,EsmForSequenceClassification:()=>y.EsmForSequenceClassification,EsmForTokenClassification:()=>y.EsmForTokenClassification,EsmModel:()=>y.EsmModel,EsmPreTrainedModel:()=>y.EsmPreTrainedModel,EsmTokenizer:()=>ur.EsmTokenizer,FFT:()=>zn.FFT,FalconForCausalLM:()=>y.FalconForCausalLM,FalconModel:()=>y.FalconModel,FalconPreTrainedModel:()=>y.FalconPreTrainedModel,FalconTokenizer:()=>ur.FalconTokenizer,FastViTForImageClassification:()=>y.FastViTForImageClassification,FastViTModel:()=>y.FastViTModel,FastViTPreTrainedModel:()=>y.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>qr.FeatureExtractionPipeline,FeatureExtractor:()=>Jt.FeatureExtractor,FillMaskPipeline:()=>qr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>y.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>y.Florence2PreTrainedModel,Florence2Processor:()=>Jt.Florence2Processor,GLPNFeatureExtractor:()=>Jt.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>y.GLPNForDepthEstimation,GLPNModel:()=>y.GLPNModel,GLPNPreTrainedModel:()=>y.GLPNPreTrainedModel,GPT2LMHeadModel:()=>y.GPT2LMHeadModel,GPT2Model:()=>y.GPT2Model,GPT2PreTrainedModel:()=>y.GPT2PreTrainedModel,GPT2Tokenizer:()=>ur.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>y.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>y.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>y.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>y.GPTJForCausalLM,GPTJModel:()=>y.GPTJModel,GPTJPreTrainedModel:()=>y.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>y.GPTNeoForCausalLM,GPTNeoModel:()=>y.GPTNeoModel,GPTNeoPreTrainedModel:()=>y.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>y.GPTNeoXForCausalLM,GPTNeoXModel:()=>y.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>y.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>ur.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>y.Gemma2ForCausalLM,Gemma2Model:()=>y.Gemma2Model,Gemma2PreTrainedModel:()=>y.Gemma2PreTrainedModel,GemmaForCausalLM:()=>y.GemmaForCausalLM,GemmaModel:()=>y.GemmaModel,GemmaPreTrainedModel:()=>y.GemmaPreTrainedModel,GemmaTokenizer:()=>ur.GemmaTokenizer,GraniteForCausalLM:()=>y.GraniteForCausalLM,GraniteModel:()=>y.GraniteModel,GranitePreTrainedModel:()=>y.GranitePreTrainedModel,Grok1Tokenizer:()=>ur.Grok1Tokenizer,GroupViTModel:()=>y.GroupViTModel,GroupViTPreTrainedModel:()=>y.GroupViTPreTrainedModel,HerbertTokenizer:()=>ur.HerbertTokenizer,HieraForImageClassification:()=>y.HieraForImageClassification,HieraModel:()=>y.HieraModel,HieraPreTrainedModel:()=>y.HieraPreTrainedModel,HubertForCTC:()=>y.HubertForCTC,HubertForSequenceClassification:()=>y.HubertForSequenceClassification,HubertModel:()=>y.HubertModel,HubertPreTrainedModel:()=>y.HubertPreTrainedModel,ImageClassificationPipeline:()=>qr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>qr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Jt.ImageFeatureExtractor,ImageMattingOutput:()=>y.ImageMattingOutput,ImageSegmentationPipeline:()=>qr.ImageSegmentationPipeline,ImageToImagePipeline:()=>qr.ImageToImagePipeline,ImageToTextPipeline:()=>qr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>$d.InterruptableStoppingCriteria,JAISLMHeadModel:()=>y.JAISLMHeadModel,JAISModel:()=>y.JAISModel,JAISPreTrainedModel:()=>y.JAISPreTrainedModel,LlamaForCausalLM:()=>y.LlamaForCausalLM,LlamaModel:()=>y.LlamaModel,LlamaPreTrainedModel:()=>y.LlamaPreTrainedModel,LlamaTokenizer:()=>ur.LlamaTokenizer,LlavaForConditionalGeneration:()=>y.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>y.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>y.LongT5ForConditionalGeneration,LongT5Model:()=>y.LongT5Model,LongT5PreTrainedModel:()=>y.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>y.M2M100ForConditionalGeneration,M2M100Model:()=>y.M2M100Model,M2M100PreTrainedModel:()=>y.M2M100PreTrainedModel,M2M100Tokenizer:()=>ur.M2M100Tokenizer,MBart50Tokenizer:()=>ur.MBart50Tokenizer,MBartForCausalLM:()=>y.MBartForCausalLM,MBartForConditionalGeneration:()=>y.MBartForConditionalGeneration,MBartForSequenceClassification:()=>y.MBartForSequenceClassification,MBartModel:()=>y.MBartModel,MBartPreTrainedModel:()=>y.MBartPreTrainedModel,MBartTokenizer:()=>ur.MBartTokenizer,MPNetForMaskedLM:()=>y.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>y.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>y.MPNetForSequenceClassification,MPNetForTokenClassification:()=>y.MPNetForTokenClassification,MPNetModel:()=>y.MPNetModel,MPNetPreTrainedModel:()=>y.MPNetPreTrainedModel,MPNetTokenizer:()=>ur.MPNetTokenizer,MT5ForConditionalGeneration:()=>y.MT5ForConditionalGeneration,MT5Model:()=>y.MT5Model,MT5PreTrainedModel:()=>y.MT5PreTrainedModel,MarianMTModel:()=>y.MarianMTModel,MarianModel:()=>y.MarianModel,MarianPreTrainedModel:()=>y.MarianPreTrainedModel,MarianTokenizer:()=>ur.MarianTokenizer,MaskFormerFeatureExtractor:()=>Jt.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>y.MaskFormerForInstanceSegmentation,MaskFormerModel:()=>y.MaskFormerModel,MaskFormerPreTrainedModel:()=>y.MaskFormerPreTrainedModel,MaskedLMOutput:()=>y.MaskedLMOutput,MaxLengthCriteria:()=>$d.MaxLengthCriteria,MistralForCausalLM:()=>y.MistralForCausalLM,MistralModel:()=>y.MistralModel,MistralPreTrainedModel:()=>y.MistralPreTrainedModel,MobileBertForMaskedLM:()=>y.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>y.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>y.MobileBertForSequenceClassification,MobileBertModel:()=>y.MobileBertModel,MobileBertPreTrainedModel:()=>y.MobileBertPreTrainedModel,MobileBertTokenizer:()=>ur.MobileBertTokenizer,MobileLLMForCausalLM:()=>y.MobileLLMForCausalLM,MobileLLMModel:()=>y.MobileLLMModel,MobileLLMPreTrainedModel:()=>y.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>Jt.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>y.MobileNetV1ForImageClassification,MobileNetV1Model:()=>y.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>y.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Jt.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>y.MobileNetV2ForImageClassification,MobileNetV2Model:()=>y.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>y.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Jt.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>y.MobileNetV3ForImageClassification,MobileNetV3Model:()=>y.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>y.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Jt.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>y.MobileNetV4ForImageClassification,MobileNetV4Model:()=>y.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>y.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Jt.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>y.MobileViTForImageClassification,MobileViTImageProcessor:()=>Jt.MobileViTImageProcessor,MobileViTModel:()=>y.MobileViTModel,MobileViTPreTrainedModel:()=>y.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>y.MobileViTV2ForImageClassification,MobileViTV2Model:()=>y.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>y.MobileViTV2PreTrainedModel,ModelOutput:()=>y.ModelOutput,Moondream1ForConditionalGeneration:()=>y.Moondream1ForConditionalGeneration,MptForCausalLM:()=>y.MptForCausalLM,MptModel:()=>y.MptModel,MptPreTrainedModel:()=>y.MptPreTrainedModel,MusicgenForCausalLM:()=>y.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>y.MusicgenForConditionalGeneration,MusicgenModel:()=>y.MusicgenModel,MusicgenPreTrainedModel:()=>y.MusicgenPreTrainedModel,NllbTokenizer:()=>ur.NllbTokenizer,NomicBertModel:()=>y.NomicBertModel,NomicBertPreTrainedModel:()=>y.NomicBertPreTrainedModel,NougatImageProcessor:()=>Jt.NougatImageProcessor,NougatTokenizer:()=>ur.NougatTokenizer,OPTForCausalLM:()=>y.OPTForCausalLM,OPTModel:()=>y.OPTModel,OPTPreTrainedModel:()=>y.OPTPreTrainedModel,ObjectDetectionPipeline:()=>qr.ObjectDetectionPipeline,OlmoForCausalLM:()=>y.OlmoForCausalLM,OlmoModel:()=>y.OlmoModel,OlmoPreTrainedModel:()=>y.OlmoPreTrainedModel,OpenELMForCausalLM:()=>y.OpenELMForCausalLM,OpenELMModel:()=>y.OpenELMModel,OpenELMPreTrainedModel:()=>y.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Jt.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>y.OwlViTForObjectDetection,OwlViTModel:()=>y.OwlViTModel,OwlViTPreTrainedModel:()=>y.OwlViTPreTrainedModel,OwlViTProcessor:()=>Jt.OwlViTProcessor,Owlv2ForObjectDetection:()=>y.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Jt.Owlv2ImageProcessor,Owlv2Model:()=>y.Owlv2Model,Owlv2PreTrainedModel:()=>y.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>y.Phi3ForCausalLM,Phi3Model:()=>y.Phi3Model,Phi3PreTrainedModel:()=>y.Phi3PreTrainedModel,PhiForCausalLM:()=>y.PhiForCausalLM,PhiModel:()=>y.PhiModel,PhiPreTrainedModel:()=>y.PhiPreTrainedModel,Pipeline:()=>qr.Pipeline,PreTrainedModel:()=>y.PreTrainedModel,PreTrainedTokenizer:()=>ur.PreTrainedTokenizer,PretrainedConfig:()=>mp.PretrainedConfig,PretrainedMixin:()=>y.PretrainedMixin,Processor:()=>Jt.Processor,PvtForImageClassification:()=>y.PvtForImageClassification,PvtImageProcessor:()=>Jt.PvtImageProcessor,PvtModel:()=>y.PvtModel,PvtPreTrainedModel:()=>y.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>Jt.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>y.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>y.PyAnnoteModel,PyAnnotePreTrainedModel:()=>y.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Jt.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>y.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>qr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>y.Qwen2ForCausalLM,Qwen2Model:()=>y.Qwen2Model,Qwen2PreTrainedModel:()=>y.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>ur.Qwen2Tokenizer,RTDetrForObjectDetection:()=>y.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Jt.RTDetrImageProcessor,RTDetrModel:()=>y.RTDetrModel,RTDetrObjectDetectionOutput:()=>y.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>y.RTDetrPreTrainedModel,RawImage:()=>p_.RawImage,ResNetForImageClassification:()=>y.ResNetForImageClassification,ResNetModel:()=>y.ResNetModel,ResNetPreTrainedModel:()=>y.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>y.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>y.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>y.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>y.RoFormerForTokenClassification,RoFormerModel:()=>y.RoFormerModel,RoFormerPreTrainedModel:()=>y.RoFormerPreTrainedModel,RoFormerTokenizer:()=>ur.RoFormerTokenizer,RobertaForMaskedLM:()=>y.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>y.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>y.RobertaForSequenceClassification,RobertaForTokenClassification:()=>y.RobertaForTokenClassification,RobertaModel:()=>y.RobertaModel,RobertaPreTrainedModel:()=>y.RobertaPreTrainedModel,RobertaTokenizer:()=>ur.RobertaTokenizer,SamImageProcessor:()=>Jt.SamImageProcessor,SamImageSegmentationOutput:()=>y.SamImageSegmentationOutput,SamModel:()=>y.SamModel,SamPreTrainedModel:()=>y.SamPreTrainedModel,SamProcessor:()=>Jt.SamProcessor,SapiensFeatureExtractor:()=>Jt.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>y.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>y.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>y.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>y.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Jt.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Jt.SegformerFeatureExtractor,SegformerForImageClassification:()=>y.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>y.SegformerForSemanticSegmentation,SegformerModel:()=>y.SegformerModel,SegformerPreTrainedModel:()=>y.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>y.Seq2SeqLMOutput,SequenceClassifierOutput:()=>y.SequenceClassifierOutput,SiglipImageProcessor:()=>Jt.SiglipImageProcessor,SiglipModel:()=>y.SiglipModel,SiglipPreTrainedModel:()=>y.SiglipPreTrainedModel,SiglipTextModel:()=>y.SiglipTextModel,SiglipTokenizer:()=>ur.SiglipTokenizer,SiglipVisionModel:()=>y.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Jt.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>y.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>y.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>y.SpeechT5HifiGan,SpeechT5Model:()=>y.SpeechT5Model,SpeechT5PreTrainedModel:()=>y.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Jt.SpeechT5Processor,SpeechT5Tokenizer:()=>ur.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>y.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>y.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>y.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>y.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>y.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>ur.SqueezeBertTokenizer,StableLmForCausalLM:()=>y.StableLmForCausalLM,StableLmModel:()=>y.StableLmModel,StableLmPreTrainedModel:()=>y.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>y.Starcoder2ForCausalLM,Starcoder2Model:()=>y.Starcoder2Model,Starcoder2PreTrainedModel:()=>y.Starcoder2PreTrainedModel,StoppingCriteria:()=>$d.StoppingCriteria,StoppingCriteriaList:()=>$d.StoppingCriteriaList,SummarizationPipeline:()=>qr.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>y.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Jt.Swin2SRImageProcessor,Swin2SRModel:()=>y.Swin2SRModel,Swin2SRPreTrainedModel:()=>y.Swin2SRPreTrainedModel,SwinForImageClassification:()=>y.SwinForImageClassification,SwinModel:()=>y.SwinModel,SwinPreTrainedModel:()=>y.SwinPreTrainedModel,T5ForConditionalGeneration:()=>y.T5ForConditionalGeneration,T5Model:()=>y.T5Model,T5PreTrainedModel:()=>y.T5PreTrainedModel,T5Tokenizer:()=>ur.T5Tokenizer,TableTransformerForObjectDetection:()=>y.TableTransformerForObjectDetection,TableTransformerModel:()=>y.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>y.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>y.TableTransformerPreTrainedModel,Tensor:()=>cn.Tensor,Text2TextGenerationPipeline:()=>qr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>qr.TextClassificationPipeline,TextGenerationPipeline:()=>qr.TextGenerationPipeline,TextStreamer:()=>_p.TextStreamer,TextToAudioPipeline:()=>qr.TextToAudioPipeline,TokenClassificationPipeline:()=>qr.TokenClassificationPipeline,TokenClassifierOutput:()=>y.TokenClassifierOutput,TokenizerModel:()=>ur.TokenizerModel,TrOCRForCausalLM:()=>y.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>y.TrOCRPreTrainedModel,TranslationPipeline:()=>qr.TranslationPipeline,UniSpeechForCTC:()=>y.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>y.UniSpeechForSequenceClassification,UniSpeechModel:()=>y.UniSpeechModel,UniSpeechPreTrainedModel:()=>y.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>y.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>y.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>y.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>y.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>y.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>Jt.ViTFeatureExtractor,ViTForImageClassification:()=>y.ViTForImageClassification,ViTImageProcessor:()=>Jt.ViTImageProcessor,ViTMAEModel:()=>y.ViTMAEModel,ViTMAEPreTrainedModel:()=>y.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>y.ViTMSNForImageClassification,ViTMSNModel:()=>y.ViTMSNModel,ViTMSNPreTrainedModel:()=>y.ViTMSNPreTrainedModel,ViTModel:()=>y.ViTModel,ViTPreTrainedModel:()=>y.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>y.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>y.VitMatteForImageMatting,VitMatteImageProcessor:()=>Jt.VitMatteImageProcessor,VitMattePreTrainedModel:()=>y.VitMattePreTrainedModel,VitsModel:()=>y.VitsModel,VitsModelOutput:()=>y.VitsModelOutput,VitsPreTrainedModel:()=>y.VitsPreTrainedModel,VitsTokenizer:()=>ur.VitsTokenizer,Wav2Vec2BertForCTC:()=>y.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>y.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>y.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>y.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>ur.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Jt.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>y.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>y.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>y.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>y.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>y.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Jt.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>y.WavLMForAudioFrameClassification,WavLMForCTC:()=>y.WavLMForCTC,WavLMForSequenceClassification:()=>y.WavLMForSequenceClassification,WavLMForXVector:()=>y.WavLMForXVector,WavLMModel:()=>y.WavLMModel,WavLMPreTrainedModel:()=>y.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Jt.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>y.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>y.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Jt.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>y.WhisperForConditionalGeneration,WhisperModel:()=>y.WhisperModel,WhisperPreTrainedModel:()=>y.WhisperPreTrainedModel,WhisperProcessor:()=>Jt.WhisperProcessor,WhisperTextStreamer:()=>_p.WhisperTextStreamer,WhisperTokenizer:()=>ur.WhisperTokenizer,XLMForQuestionAnswering:()=>y.XLMForQuestionAnswering,XLMForSequenceClassification:()=>y.XLMForSequenceClassification,XLMForTokenClassification:()=>y.XLMForTokenClassification,XLMModel:()=>y.XLMModel,XLMPreTrainedModel:()=>y.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>y.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>y.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>y.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>y.XLMRobertaForTokenClassification,XLMRobertaModel:()=>y.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>y.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>ur.XLMRobertaTokenizer,XLMTokenizer:()=>ur.XLMTokenizer,XLMWithLMHeadModel:()=>y.XLMWithLMHeadModel,XVectorOutput:()=>y.XVectorOutput,YolosFeatureExtractor:()=>Jt.YolosFeatureExtractor,YolosForObjectDetection:()=>y.YolosForObjectDetection,YolosModel:()=>y.YolosModel,YolosObjectDetectionOutput:()=>y.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>y.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>qr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>qr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>qr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>qr.ZeroShotObjectDetectionPipeline,bankers_round:()=>zn.bankers_round,cat:()=>cn.cat,cos_sim:()=>zn.cos_sim,dot:()=>zn.dot,dynamic_time_warping:()=>zn.dynamic_time_warping,env:()=>c_.env,full:()=>cn.full,full_like:()=>cn.full_like,getKeyValueShapes:()=>mp.getKeyValueShapes,hamming:()=>io.hamming,hanning:()=>io.hanning,interpolate:()=>cn.interpolate,interpolate_4d:()=>cn.interpolate_4d,interpolate_data:()=>zn.interpolate_data,is_chinese_char:()=>ur.is_chinese_char,layer_norm:()=>cn.layer_norm,log_softmax:()=>zn.log_softmax,magnitude:()=>zn.magnitude,matmul:()=>cn.matmul,max:()=>zn.max,mean:()=>cn.mean,mean_pooling:()=>cn.mean_pooling,medianFilter:()=>zn.medianFilter,mel_filter_bank:()=>io.mel_filter_bank,min:()=>zn.min,ones:()=>cn.ones,ones_like:()=>cn.ones_like,permute:()=>cn.permute,permute_data:()=>zn.permute_data,pipeline:()=>qr.pipeline,quantize_embeddings:()=>cn.quantize_embeddings,read_audio:()=>io.read_audio,rfft:()=>cn.rfft,round:()=>zn.round,softmax:()=>zn.softmax,spectrogram:()=>io.spectrogram,stack:()=>cn.stack,std_mean:()=>cn.std_mean,topk:()=>cn.topk,window_function:()=>io.window_function,zeros:()=>cn.zeros,zeros_like:()=>cn.zeros_like});var c_=Hr("./src/env.js"),qr=Hr("./src/pipelines.js"),y=Hr("./src/models.js"),ur=Hr("./src/tokenizers.js"),Jt=Hr("./src/processors.js"),mp=Hr("./src/configs.js"),io=Hr("./src/utils/audio.js"),p_=Hr("./src/utils/image.js"),cn=Hr("./src/utils/tensor.js"),zn=Hr("./src/utils/maths.js"),_p=Hr("./src/generation/streamers.js"),$d=Hr("./src/generation/stopping_criteria.js");p.ASTFeatureExtractor;p.ASTForAudioClassification;p.ASTModel;p.ASTPreTrainedModel;p.AlbertForMaskedLM;p.AlbertForQuestionAnswering;p.AlbertForSequenceClassification;p.AlbertModel;p.AlbertPreTrainedModel;p.AlbertTokenizer;p.AudioClassificationPipeline;p.AutoConfig;p.AutoModel;p.AutoModelForAudioClassification;p.AutoModelForAudioFrameClassification;p.AutoModelForCTC;p.AutoModelForCausalLM;p.AutoModelForDepthEstimation;p.AutoModelForDocumentQuestionAnswering;p.AutoModelForImageClassification;p.AutoModelForImageFeatureExtraction;p.AutoModelForImageMatting;p.AutoModelForImageSegmentation;p.AutoModelForImageToImage;p.AutoModelForMaskGeneration;p.AutoModelForMaskedLM;p.AutoModelForNormalEstimation;p.AutoModelForObjectDetection;p.AutoModelForQuestionAnswering;p.AutoModelForSemanticSegmentation;p.AutoModelForSeq2SeqLM;p.AutoModelForSequenceClassification;p.AutoModelForSpeechSeq2Seq;p.AutoModelForTextToSpectrogram;p.AutoModelForTextToWaveform;p.AutoModelForTokenClassification;p.AutoModelForUniversalSegmentation;p.AutoModelForVision2Seq;p.AutoModelForXVector;p.AutoModelForZeroShotObjectDetection;p.AutoProcessor;p.AutoTokenizer;p.AutomaticSpeechRecognitionPipeline;p.BartForConditionalGeneration;p.BartForSequenceClassification;p.BartModel;p.BartPretrainedModel;p.BartTokenizer;p.BaseModelOutput;p.BaseStreamer;p.BeitFeatureExtractor;p.BeitForImageClassification;p.BeitModel;p.BeitPreTrainedModel;p.BertForMaskedLM;p.BertForQuestionAnswering;p.BertForSequenceClassification;p.BertForTokenClassification;p.BertModel;p.BertPreTrainedModel;p.BertTokenizer;p.BitImageProcessor;p.BlenderbotForConditionalGeneration;p.BlenderbotModel;p.BlenderbotPreTrainedModel;p.BlenderbotSmallForConditionalGeneration;p.BlenderbotSmallModel;p.BlenderbotSmallPreTrainedModel;p.BlenderbotSmallTokenizer;p.BlenderbotTokenizer;p.BloomForCausalLM;p.BloomModel;p.BloomPreTrainedModel;p.BloomTokenizer;p.CLIPFeatureExtractor;p.CLIPImageProcessor;p.CLIPModel;p.CLIPPreTrainedModel;p.CLIPSegForImageSegmentation;p.CLIPSegModel;p.CLIPSegPreTrainedModel;p.CLIPTextModel;p.CLIPTextModelWithProjection;p.CLIPTokenizer;p.CLIPVisionModel;p.CLIPVisionModelWithProjection;p.CamembertForMaskedLM;p.CamembertForQuestionAnswering;p.CamembertForSequenceClassification;p.CamembertForTokenClassification;p.CamembertModel;p.CamembertPreTrainedModel;p.CamembertTokenizer;p.CausalLMOutput;p.CausalLMOutputWithPast;p.ChineseCLIPFeatureExtractor;p.ChineseCLIPModel;p.ChineseCLIPPreTrainedModel;p.ClapAudioModelWithProjection;p.ClapFeatureExtractor;p.ClapModel;p.ClapPreTrainedModel;p.ClapTextModelWithProjection;p.CodeGenForCausalLM;p.CodeGenModel;p.CodeGenPreTrainedModel;p.CodeGenTokenizer;p.CodeLlamaTokenizer;p.CohereForCausalLM;p.CohereModel;p.CoherePreTrainedModel;p.CohereTokenizer;p.ConvBertForMaskedLM;p.ConvBertForQuestionAnswering;p.ConvBertForSequenceClassification;p.ConvBertForTokenClassification;p.ConvBertModel;p.ConvBertPreTrainedModel;p.ConvBertTokenizer;p.ConvNextFeatureExtractor;p.ConvNextForImageClassification;p.ConvNextImageProcessor;p.ConvNextModel;p.ConvNextPreTrainedModel;p.ConvNextV2ForImageClassification;p.ConvNextV2Model;p.ConvNextV2PreTrainedModel;p.DPTFeatureExtractor;p.DPTForDepthEstimation;p.DPTImageProcessor;p.DPTModel;p.DPTPreTrainedModel;p.DebertaForMaskedLM;p.DebertaForQuestionAnswering;p.DebertaForSequenceClassification;p.DebertaForTokenClassification;p.DebertaModel;p.DebertaPreTrainedModel;p.DebertaTokenizer;p.DebertaV2ForMaskedLM;p.DebertaV2ForQuestionAnswering;p.DebertaV2ForSequenceClassification;p.DebertaV2ForTokenClassification;p.DebertaV2Model;p.DebertaV2PreTrainedModel;p.DebertaV2Tokenizer;p.DecisionTransformerModel;p.DecisionTransformerPreTrainedModel;p.DeiTFeatureExtractor;p.DeiTForImageClassification;p.DeiTModel;p.DeiTPreTrainedModel;p.DepthAnythingForDepthEstimation;p.DepthAnythingPreTrainedModel;p.DepthEstimationPipeline;p.DepthProForDepthEstimation;p.DepthProPreTrainedModel;p.DetrFeatureExtractor;p.DetrForObjectDetection;p.DetrForSegmentation;p.DetrModel;p.DetrObjectDetectionOutput;p.DetrPreTrainedModel;p.DetrSegmentationOutput;p.Dinov2ForImageClassification;p.Dinov2Model;p.Dinov2PreTrainedModel;p.DistilBertForMaskedLM;p.DistilBertForQuestionAnswering;p.DistilBertForSequenceClassification;p.DistilBertForTokenClassification;p.DistilBertModel;p.DistilBertPreTrainedModel;p.DistilBertTokenizer;p.DocumentQuestionAnsweringPipeline;p.DonutFeatureExtractor;p.DonutImageProcessor;p.DonutSwinModel;p.DonutSwinPreTrainedModel;p.EfficientNetForImageClassification;p.EfficientNetImageProcessor;p.EfficientNetModel;p.EfficientNetPreTrainedModel;p.ElectraForMaskedLM;p.ElectraForQuestionAnswering;p.ElectraForSequenceClassification;p.ElectraForTokenClassification;p.ElectraModel;p.ElectraPreTrainedModel;p.ElectraTokenizer;p.EosTokenCriteria;p.EsmForMaskedLM;p.EsmForSequenceClassification;p.EsmForTokenClassification;p.EsmModel;p.EsmPreTrainedModel;p.EsmTokenizer;p.FFT;p.FalconForCausalLM;p.FalconModel;p.FalconPreTrainedModel;p.FalconTokenizer;p.FastViTForImageClassification;p.FastViTModel;p.FastViTPreTrainedModel;p.FeatureExtractionPipeline;p.FeatureExtractor;p.FillMaskPipeline;p.Florence2ForConditionalGeneration;p.Florence2PreTrainedModel;p.Florence2Processor;p.GLPNFeatureExtractor;p.GLPNForDepthEstimation;p.GLPNModel;p.GLPNPreTrainedModel;p.GPT2LMHeadModel;p.GPT2Model;p.GPT2PreTrainedModel;p.GPT2Tokenizer;p.GPTBigCodeForCausalLM;p.GPTBigCodeModel;p.GPTBigCodePreTrainedModel;p.GPTJForCausalLM;p.GPTJModel;p.GPTJPreTrainedModel;p.GPTNeoForCausalLM;p.GPTNeoModel;p.GPTNeoPreTrainedModel;p.GPTNeoXForCausalLM;p.GPTNeoXModel;p.GPTNeoXPreTrainedModel;p.GPTNeoXTokenizer;p.Gemma2ForCausalLM;p.Gemma2Model;p.Gemma2PreTrainedModel;p.GemmaForCausalLM;p.GemmaModel;p.GemmaPreTrainedModel;p.GemmaTokenizer;p.GraniteForCausalLM;p.GraniteModel;p.GranitePreTrainedModel;p.Grok1Tokenizer;p.GroupViTModel;p.GroupViTPreTrainedModel;p.HerbertTokenizer;p.HieraForImageClassification;p.HieraModel;p.HieraPreTrainedModel;p.HubertForCTC;p.HubertForSequenceClassification;p.HubertModel;p.HubertPreTrainedModel;p.ImageClassificationPipeline;p.ImageFeatureExtractionPipeline;p.ImageFeatureExtractor;p.ImageMattingOutput;p.ImageSegmentationPipeline;p.ImageToImagePipeline;p.ImageToTextPipeline;p.InterruptableStoppingCriteria;p.JAISLMHeadModel;p.JAISModel;p.JAISPreTrainedModel;p.LlamaForCausalLM;p.LlamaModel;p.LlamaPreTrainedModel;p.LlamaTokenizer;p.LlavaForConditionalGeneration;p.LlavaPreTrainedModel;p.LongT5ForConditionalGeneration;p.LongT5Model;p.LongT5PreTrainedModel;p.M2M100ForConditionalGeneration;p.M2M100Model;p.M2M100PreTrainedModel;p.M2M100Tokenizer;p.MBart50Tokenizer;p.MBartForCausalLM;p.MBartForConditionalGeneration;p.MBartForSequenceClassification;p.MBartModel;p.MBartPreTrainedModel;p.MBartTokenizer;p.MPNetForMaskedLM;p.MPNetForQuestionAnswering;p.MPNetForSequenceClassification;p.MPNetForTokenClassification;p.MPNetModel;p.MPNetPreTrainedModel;p.MPNetTokenizer;p.MT5ForConditionalGeneration;p.MT5Model;p.MT5PreTrainedModel;p.MarianMTModel;p.MarianModel;p.MarianPreTrainedModel;p.MarianTokenizer;p.MaskFormerFeatureExtractor;p.MaskFormerForInstanceSegmentation;p.MaskFormerModel;p.MaskFormerPreTrainedModel;p.MaskedLMOutput;p.MaxLengthCriteria;p.MistralForCausalLM;p.MistralModel;p.MistralPreTrainedModel;p.MobileBertForMaskedLM;p.MobileBertForQuestionAnswering;p.MobileBertForSequenceClassification;p.MobileBertModel;p.MobileBertPreTrainedModel;p.MobileBertTokenizer;p.MobileLLMForCausalLM;p.MobileLLMModel;p.MobileLLMPreTrainedModel;p.MobileNetV1FeatureExtractor;p.MobileNetV1ForImageClassification;p.MobileNetV1Model;p.MobileNetV1PreTrainedModel;p.MobileNetV2FeatureExtractor;p.MobileNetV2ForImageClassification;p.MobileNetV2Model;p.MobileNetV2PreTrainedModel;p.MobileNetV3FeatureExtractor;p.MobileNetV3ForImageClassification;p.MobileNetV3Model;p.MobileNetV3PreTrainedModel;p.MobileNetV4FeatureExtractor;p.MobileNetV4ForImageClassification;p.MobileNetV4Model;p.MobileNetV4PreTrainedModel;p.MobileViTFeatureExtractor;p.MobileViTForImageClassification;p.MobileViTImageProcessor;p.MobileViTModel;p.MobileViTPreTrainedModel;p.MobileViTV2ForImageClassification;p.MobileViTV2Model;p.MobileViTV2PreTrainedModel;p.ModelOutput;p.Moondream1ForConditionalGeneration;p.MptForCausalLM;p.MptModel;p.MptPreTrainedModel;p.MusicgenForCausalLM;p.MusicgenForConditionalGeneration;p.MusicgenModel;p.MusicgenPreTrainedModel;p.NllbTokenizer;p.NomicBertModel;p.NomicBertPreTrainedModel;p.NougatImageProcessor;p.NougatTokenizer;p.OPTForCausalLM;p.OPTModel;p.OPTPreTrainedModel;p.ObjectDetectionPipeline;p.OlmoForCausalLM;p.OlmoModel;p.OlmoPreTrainedModel;p.OpenELMForCausalLM;p.OpenELMModel;p.OpenELMPreTrainedModel;p.OwlViTFeatureExtractor;p.OwlViTForObjectDetection;p.OwlViTModel;p.OwlViTPreTrainedModel;p.OwlViTProcessor;p.Owlv2ForObjectDetection;p.Owlv2ImageProcessor;p.Owlv2Model;p.Owlv2PreTrainedModel;p.Phi3ForCausalLM;p.Phi3Model;p.Phi3PreTrainedModel;p.PhiForCausalLM;p.PhiModel;p.PhiPreTrainedModel;p.Pipeline;p.PreTrainedModel;p.PreTrainedTokenizer;p.PretrainedConfig;p.PretrainedMixin;p.Processor;p.PvtForImageClassification;p.PvtImageProcessor;p.PvtModel;p.PvtPreTrainedModel;p.PyAnnoteFeatureExtractor;p.PyAnnoteForAudioFrameClassification;p.PyAnnoteModel;p.PyAnnotePreTrainedModel;p.PyAnnoteProcessor;p.QuestionAnsweringModelOutput;p.QuestionAnsweringPipeline;p.Qwen2ForCausalLM;p.Qwen2Model;p.Qwen2PreTrainedModel;p.Qwen2Tokenizer;p.RTDetrForObjectDetection;p.RTDetrImageProcessor;p.RTDetrModel;p.RTDetrObjectDetectionOutput;p.RTDetrPreTrainedModel;p.RawImage;p.ResNetForImageClassification;p.ResNetModel;p.ResNetPreTrainedModel;p.RoFormerForMaskedLM;p.RoFormerForQuestionAnswering;p.RoFormerForSequenceClassification;p.RoFormerForTokenClassification;p.RoFormerModel;p.RoFormerPreTrainedModel;p.RoFormerTokenizer;p.RobertaForMaskedLM;p.RobertaForQuestionAnswering;p.RobertaForSequenceClassification;p.RobertaForTokenClassification;p.RobertaModel;p.RobertaPreTrainedModel;p.RobertaTokenizer;p.SamImageProcessor;p.SamImageSegmentationOutput;p.SamModel;p.SamPreTrainedModel;p.SamProcessor;p.SapiensFeatureExtractor;p.SapiensForDepthEstimation;p.SapiensForNormalEstimation;p.SapiensForSemanticSegmentation;p.SapiensPreTrainedModel;p.SeamlessM4TFeatureExtractor;p.SegformerFeatureExtractor;p.SegformerForImageClassification;p.SegformerForSemanticSegmentation;p.SegformerModel;p.SegformerPreTrainedModel;p.Seq2SeqLMOutput;p.SequenceClassifierOutput;p.SiglipImageProcessor;p.SiglipModel;p.SiglipPreTrainedModel;p.SiglipTextModel;p.SiglipTokenizer;p.SiglipVisionModel;p.SpeechT5FeatureExtractor;p.SpeechT5ForSpeechToText;p.SpeechT5ForTextToSpeech;p.SpeechT5HifiGan;p.SpeechT5Model;p.SpeechT5PreTrainedModel;p.SpeechT5Processor;p.SpeechT5Tokenizer;p.SqueezeBertForMaskedLM;p.SqueezeBertForQuestionAnswering;p.SqueezeBertForSequenceClassification;p.SqueezeBertModel;p.SqueezeBertPreTrainedModel;p.SqueezeBertTokenizer;p.StableLmForCausalLM;p.StableLmModel;p.StableLmPreTrainedModel;p.Starcoder2ForCausalLM;p.Starcoder2Model;p.Starcoder2PreTrainedModel;p.StoppingCriteria;p.StoppingCriteriaList;p.SummarizationPipeline;p.Swin2SRForImageSuperResolution;p.Swin2SRImageProcessor;p.Swin2SRModel;p.Swin2SRPreTrainedModel;p.SwinForImageClassification;p.SwinModel;p.SwinPreTrainedModel;p.T5ForConditionalGeneration;p.T5Model;p.T5PreTrainedModel;p.T5Tokenizer;p.TableTransformerForObjectDetection;p.TableTransformerModel;p.TableTransformerObjectDetectionOutput;p.TableTransformerPreTrainedModel;p.Tensor;p.Text2TextGenerationPipeline;p.TextClassificationPipeline;p.TextGenerationPipeline;p.TextStreamer;p.TextToAudioPipeline;p.TokenClassificationPipeline;p.TokenClassifierOutput;p.TokenizerModel;p.TrOCRForCausalLM;p.TrOCRPreTrainedModel;p.TranslationPipeline;p.UniSpeechForCTC;p.UniSpeechForSequenceClassification;p.UniSpeechModel;p.UniSpeechPreTrainedModel;p.UniSpeechSatForAudioFrameClassification;p.UniSpeechSatForCTC;p.UniSpeechSatForSequenceClassification;p.UniSpeechSatModel;p.UniSpeechSatPreTrainedModel;p.ViTFeatureExtractor;p.ViTForImageClassification;p.ViTImageProcessor;p.ViTMAEModel;p.ViTMAEPreTrainedModel;p.ViTMSNForImageClassification;p.ViTMSNModel;p.ViTMSNPreTrainedModel;p.ViTModel;p.ViTPreTrainedModel;p.VisionEncoderDecoderModel;p.VitMatteForImageMatting;p.VitMatteImageProcessor;p.VitMattePreTrainedModel;p.VitsModel;p.VitsModelOutput;p.VitsPreTrainedModel;p.VitsTokenizer;p.Wav2Vec2BertForCTC;p.Wav2Vec2BertForSequenceClassification;p.Wav2Vec2BertModel;p.Wav2Vec2BertPreTrainedModel;p.Wav2Vec2CTCTokenizer;p.Wav2Vec2FeatureExtractor;p.Wav2Vec2ForAudioFrameClassification;p.Wav2Vec2ForCTC;p.Wav2Vec2ForSequenceClassification;p.Wav2Vec2Model;p.Wav2Vec2PreTrainedModel;p.Wav2Vec2ProcessorWithLM;p.WavLMForAudioFrameClassification;p.WavLMForCTC;p.WavLMForSequenceClassification;p.WavLMForXVector;p.WavLMModel;p.WavLMPreTrainedModel;p.WeSpeakerFeatureExtractor;p.WeSpeakerResNetModel;p.WeSpeakerResNetPreTrainedModel;p.WhisperFeatureExtractor;p.WhisperForConditionalGeneration;p.WhisperModel;p.WhisperPreTrainedModel;p.WhisperProcessor;p.WhisperTextStreamer;p.WhisperTokenizer;p.XLMForQuestionAnswering;p.XLMForSequenceClassification;p.XLMForTokenClassification;p.XLMModel;p.XLMPreTrainedModel;p.XLMRobertaForMaskedLM;p.XLMRobertaForQuestionAnswering;p.XLMRobertaForSequenceClassification;p.XLMRobertaForTokenClassification;p.XLMRobertaModel;p.XLMRobertaPreTrainedModel;p.XLMRobertaTokenizer;p.XLMTokenizer;p.XLMWithLMHeadModel;p.XVectorOutput;p.YolosFeatureExtractor;p.YolosForObjectDetection;p.YolosModel;p.YolosObjectDetectionOutput;p.YolosPreTrainedModel;p.ZeroShotAudioClassificationPipeline;p.ZeroShotClassificationPipeline;p.ZeroShotImageClassificationPipeline;p.ZeroShotObjectDetectionPipeline;p.bankers_round;p.cat;p.cos_sim;p.dot;p.dynamic_time_warping;var h_=p.env;p.full;p.full_like;p.getKeyValueShapes;p.hamming;p.hanning;p.interpolate;p.interpolate_4d;p.interpolate_data;p.is_chinese_char;p.layer_norm;p.log_softmax;p.magnitude;p.matmul;p.max;p.mean;p.mean_pooling;p.medianFilter;p.mel_filter_bank;p.min;p.ones;p.ones_like;p.permute;p.permute_data;var f_=p.pipeline;p.quantize_embeddings;p.read_audio;p.rfft;p.round;p.softmax;p.spectrogram;p.stack;p.std_mean;p.topk;p.window_function;p.zeros;p.zeros_like;h_.allowLocalModels=!1;class Ln{static async tryLoadPipeline(ye,D,I,de){try{return await f_("fill-mask",ye,{progress_callback:he=>{if(he&&he.status==="progress"&&he.total>0){const ve=Math.min(Math.round(he.loaded/he.total*100),100),xe=(he.loaded/(1024*1024)).toFixed(1),j=(he.total/(1024*1024)).toFixed(1);postMessage({status:"progress",message:`Downloading model: ${ve}% (${xe}MB / ${j}MB)`})}},quantized:I!=="fp32",dtype:I,device:D})}catch(he){return console.warn(`Failed to load with ${I}:`,he.message),null}}static async warmupInference(ye){postMessage({status:"progress",message:"Warming up model..."});try{const D=`This is a ${ye.tokenizer.mask_token} sentence.`;await ye(D,{topk:1})}catch(D){console.warn("Warmup inference failed:",D)}}static async getInstance(ye,D,I,de=null){if(!this.pipeline){if(this.pipeline=await this.tryLoadPipeline(ye,D,I,de),!this.pipeline){const he=D==="webgpu"?"fp32":"q8";I!==he&&(postMessage({status:"warning",message:`Falling back to ${he} for ${D}`,duration:3e3}),this.pipeline=await this.tryLoadPipeline(ye,D,he,de))}if(!this.pipeline)throw new Error("Failed to load model. Please try a different model or device.");if(this.tokenizer=this.pipeline.tokenizer,this.tokenizer.mask_token)this.maskToken=this.tokenizer.mask_token,console.log(`Found mask token in tokenizer: ${this.maskToken}`),await this.warmupInference(this.pipeline);else return console.warn("Could not detect mask token automatically"),postMessage({status:"warning",message:"Could not detect mask token automatically. Please check model documentation.",duration:5e3}),null}return this.pipeline}}Me(Ln,"pipeline",null),Me(Ln,"tokenizer",null),Me(Ln,"maskToken",null);self.onmessage=async At=>{try{const{type:ye,text:D,model:I,device:de,quantization:he}=At.data;if(ye==="load_model"){postMessage({status:"loading",message:"Starting model download..."});const ve=performance.now();try{if(!await Ln.getInstance(I,de,he))throw new Error("Failed to initialize model pipeline");const j=performance.now()-ve;postMessage({status:"model_loaded",loadTime:j.toFixed(0),maskToken:Ln.maskToken})}catch(xe){if(de==="webgpu"&&xe.message.includes("WebGPU"))postMessage({status:"error",predictions:["WebGPU is not available. Please try using WASM backend instead."]});else throw xe}return}if(ye==="predict"){const ve=await Ln.getInstance();if(!Ln.maskToken)throw new Error("Mask token not available. Please check model documentation.");const xe=D.replace(/\.\./g,Ln.maskToken).replace(//g,Ln.maskToken).replace(/\[MASK\]/g,Ln.maskToken);if(!xe.includes(Ln.maskToken)){postMessage({status:"error",predictions:[`Text must contain or .. (model uses ${Ln.maskToken} internally)`]});return}const j=performance.now(),P=await ve(xe,{topk:5}),L=performance.now()-j,B=P.map(q=>`${Ln.tokenizer.decode([q.token],{skip_special_tokens:!0,clean_up_tokenization_spaces:!0}).trim()} (${(q.score*100).toFixed(2)}%)`);postMessage({status:"complete",predictions:B,inferenceTime:L.toFixed(0)})}}catch(ye){console.error("Error in worker:",ye),postMessage({status:"error",predictions:[`Error: ${ye.message}`]})}};