var Dm=Object.defineProperty;var Bm=(_n,ts,Ls)=>ts in _n?Dm(_n,ts,{enumerable:!0,configurable:!0,writable:!0,value:Ls}):_n[ts]=Ls;var Te=(_n,ts,Ls)=>Bm(_n,typeof ts!="symbol"?ts+"":ts,Ls);(function(){"use strict";var _n={},ts={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(bt,fe,l)=>{bt.exports=l.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{Environment:()=>qe,Interpreter:()=>lt,Template:()=>Mt,parse:()=>ke,tokenize:()=>P});var M=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"}),K=Object.freeze({set:M.Set,for:M.For,in:M.In,is:M.Is,if:M.If,else:M.Else,endif:M.EndIf,elif:M.ElseIf,endfor:M.EndFor,and:M.And,or:M.Or,not:M.Not,"not in":M.NotIn,macro:M.Macro,endmacro:M.EndMacro,true:M.BooleanLiteral,false:M.BooleanLiteral,True:M.BooleanLiteral,False:M.BooleanLiteral}),ge=class{constructor(v,W){this.value=v,this.type=W}};function Me(v){return/\w/.test(v)}function xe(v){return/[0-9]/.test(v)}var D=[["{%",M.OpenStatement],["%}",M.CloseStatement],["{{",M.OpenExpression],["}}",M.CloseExpression],["(",M.OpenParen],[")",M.CloseParen],["{",M.OpenCurlyBracket],["}",M.CloseCurlyBracket],["[",M.OpenSquareBracket],["]",M.CloseSquareBracket],[",",M.Comma],[".",M.Dot],[":",M.Colon],["|",M.Pipe],["<=",M.ComparisonBinaryOperator],[">=",M.ComparisonBinaryOperator],["==",M.ComparisonBinaryOperator],["!=",M.ComparisonBinaryOperator],["<",M.ComparisonBinaryOperator],[">",M.ComparisonBinaryOperator],["+",M.AdditiveBinaryOperator],["-",M.AdditiveBinaryOperator],["*",M.MultiplicativeBinaryOperator],["/",M.MultiplicativeBinaryOperator],["%",M.MultiplicativeBinaryOperator],["=",M.Equals]],x=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function V(v,W={}){return v.endsWith(` `)&&(v=v.slice(0,-1)),v=v.replace(/{#.*?#}/gs,"{##}"),W.lstrip_blocks&&(v=v.replace(/^[ \t]*({[#%])/gm,"$1")),W.trim_blocks&&(v=v.replace(/([#%]})\n/g,"$1")),v.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function P(v,W={}){var Je,Pt,mt;const S=[],Q=V(v,W);let he=0;const Ye=Ee=>{let k="";for(;Ee(Q[he]);){if(Q[he]==="\\"){if(++he,he>=Q.length)throw new SyntaxError("Unexpected end of input");const H=Q[he++],be=x.get(H);if(be===void 0)throw new SyntaxError(`Unexpected escaped character: ${H}`);k+=be;continue}if(k+=Q[he++],he>=Q.length)throw new SyntaxError("Unexpected end of input")}return k};e:for(;he0){S.push(new ge(H,M.Text));continue}}Ye(H=>/\s/.test(H));const k=Q[he];if(k==="-"||k==="+"){const H=(Pt=S.at(-1))==null?void 0:Pt.type;if(H===M.Text||H===void 0)throw new SyntaxError(`Unexpected character: ${k}`);switch(H){case M.Identifier:case M.NumericLiteral:case M.BooleanLiteral:case M.StringLiteral:case M.CloseParen:case M.CloseSquareBracket:break;default:{++he;const be=Ye(xe);S.push(new ge(`${k}${be}`,be.length>0?M.NumericLiteral:M.UnaryOperator));continue}}}for(const[H,be]of D)if(Q.slice(he,he+H.length)===H){S.push(new ge(H,be)),he+=H.length;continue e}if(k==="'"||k==='"'){++he;const H=Ye(be=>be!==k);S.push(new ge(H,M.StringLiteral)),++he;continue}if(xe(k)){const H=Ye(xe);S.push(new ge(H,M.NumericLiteral));continue}if(Me(k)){const H=Ye(Me),be=Object.hasOwn(K,H)?K[H]:M.Identifier;be===M.In&&((mt=S.at(-1))==null?void 0:mt.type)===M.Not?(S.pop(),S.push(new ge("not in",M.NotIn))):S.push(new ge(H,be));continue}throw new SyntaxError(`Unexpected character: ${k}`)}return S}var J=class{constructor(){Te(this,"type","Statement")}},te=class extends J{constructor(W){super();Te(this,"type","Program");this.body=W}},ne=class extends J{constructor(W,S,Q){super();Te(this,"type","If");this.test=W,this.body=S,this.alternate=Q}},ie=class extends J{constructor(W,S,Q,he){super();Te(this,"type","For");this.loopvar=W,this.iterable=S,this.body=Q,this.defaultBlock=he}},R=class extends J{constructor(W,S){super();Te(this,"type","Set");this.assignee=W,this.value=S}},Z=class extends J{constructor(W,S,Q){super();Te(this,"type","Macro");this.name=W,this.args=S,this.body=Q}},se=class extends J{constructor(){super(...arguments);Te(this,"type","Expression")}},ue=class extends se{constructor(W,S,Q){super();Te(this,"type","MemberExpression");this.object=W,this.property=S,this.computed=Q}},ae=class extends se{constructor(W,S){super();Te(this,"type","CallExpression");this.callee=W,this.args=S}},N=class extends se{constructor(W){super();Te(this,"type","Identifier");this.value=W}},F=class extends se{constructor(W){super();Te(this,"type","Literal");this.value=W}},B=class extends F{constructor(){super(...arguments);Te(this,"type","NumericLiteral")}},A=class extends F{constructor(){super(...arguments);Te(this,"type","StringLiteral")}},_e=class extends F{constructor(){super(...arguments);Te(this,"type","BooleanLiteral")}},ye=class extends F{constructor(){super(...arguments);Te(this,"type","ArrayLiteral")}},$e=class extends F{constructor(){super(...arguments);Te(this,"type","TupleLiteral")}},Se=class extends F{constructor(){super(...arguments);Te(this,"type","ObjectLiteral")}},Fe=class extends se{constructor(W,S,Q){super();Te(this,"type","BinaryExpression");this.operator=W,this.left=S,this.right=Q}},et=class extends se{constructor(W,S){super();Te(this,"type","FilterExpression");this.operand=W,this.filter=S}},Xe=class extends se{constructor(W,S){super();Te(this,"type","SelectExpression");this.iterable=W,this.test=S}},ct=class extends se{constructor(W,S,Q){super();Te(this,"type","TestExpression");this.operand=W,this.negate=S,this.test=Q}},we=class extends se{constructor(W,S){super();Te(this,"type","UnaryExpression");this.operator=W,this.argument=S}},U=class extends se{constructor(W=void 0,S=void 0,Q=void 0){super();Te(this,"type","SliceExpression");this.start=W,this.stop=S,this.step=Q}},pe=class extends se{constructor(W,S){super();Te(this,"type","KeywordArgumentExpression");this.key=W,this.value=S}};function ke(v){const W=new te([]);let S=0;function Q(Ze,Ct){const Dt=v[S++];if(!Dt||Dt.type!==Ze)throw new Error(`Parser Error: ${Ct}. ${Dt.type} !== ${Ze}.`);return Dt}function he(){switch(v[S].type){case M.Text:return Pt();case M.OpenStatement:return mt();case M.OpenExpression:return Ee();default:throw new SyntaxError(`Unexpected token type: ${v[S].type}`)}}function Ye(...Ze){return S+Ze.length<=v.length&&Ze.some((Ct,Dt)=>Ct!==v[S+Dt].type)}function Je(...Ze){return S+Ze.length<=v.length&&Ze.every((Ct,Dt)=>Ct===v[S+Dt].type)}function Pt(){return new A(Q(M.Text,"Expected text token").value)}function mt(){Q(M.OpenStatement,"Expected opening statement token");let Ze;switch(v[S].type){case M.Set:++S,Ze=k(),Q(M.CloseStatement,"Expected closing statement token");break;case M.If:++S,Ze=H(),Q(M.OpenStatement,"Expected {% token"),Q(M.EndIf,"Expected endif token"),Q(M.CloseStatement,"Expected %} token");break;case M.Macro:++S,Ze=be(),Q(M.OpenStatement,"Expected {% token"),Q(M.EndMacro,"Expected endmacro token"),Q(M.CloseStatement,"Expected %} token");break;case M.For:++S,Ze=Ie(),Q(M.OpenStatement,"Expected {% token"),Q(M.EndFor,"Expected endfor token"),Q(M.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${v[S].type}`)}return Ze}function Ee(){Q(M.OpenExpression,"Expected opening expression token");const Ze=Re();return Q(M.CloseExpression,"Expected closing expression token"),Ze}function k(){const Ze=Re();if(Je(M.Equals)){++S;const Ct=k();return new R(Ze,Ct)}return Ze}function H(){var Ur,Vn,An,Or,Xr,Dr,kn,Er;const Ze=Re();Q(M.CloseStatement,"Expected closing statement token");const Ct=[],Dt=[];for(;!(((Ur=v[S])==null?void 0:Ur.type)===M.OpenStatement&&(((Vn=v[S+1])==null?void 0:Vn.type)===M.ElseIf||((An=v[S+1])==null?void 0:An.type)===M.Else||((Or=v[S+1])==null?void 0:Or.type)===M.EndIf));)Ct.push(he());if(((Xr=v[S])==null?void 0:Xr.type)===M.OpenStatement&&((Dr=v[S+1])==null?void 0:Dr.type)!==M.EndIf)if(++S,Je(M.ElseIf))Q(M.ElseIf,"Expected elseif token"),Dt.push(H());else for(Q(M.Else,"Expected else token"),Q(M.CloseStatement,"Expected closing statement token");!(((kn=v[S])==null?void 0:kn.type)===M.OpenStatement&&((Er=v[S+1])==null?void 0:Er.type)===M.EndIf);)Dt.push(he());return new ne(Ze,Ct,Dt)}function be(){const Ze=Tr();if(Ze.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Ct=Rt();Q(M.CloseStatement,"Expected closing statement token");const Dt=[];for(;Ye(M.OpenStatement,M.EndMacro);)Dt.push(he());return new Z(Ze,Ct,Dt)}function Be(Ze=!1){const Ct=Ze?Tr:Re,Dt=[Ct()],Ur=Je(M.Comma);for(;Ur&&(++S,Dt.push(Ct()),!!Je(M.Comma)););return Ur?new $e(Dt):Dt[0]}function Ie(){const Ze=Be(!0);if(!(Ze instanceof N||Ze instanceof $e))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Ze.type} instead`);Q(M.In,"Expected `in` keyword following loop variable");const Ct=Re();Q(M.CloseStatement,"Expected closing statement token");const Dt=[];for(;Ye(M.OpenStatement,M.EndFor)&&Ye(M.OpenStatement,M.Else);)Dt.push(he());const Ur=[];if(Je(M.OpenStatement,M.Else))for(++S,++S,Q(M.CloseStatement,"Expected closing statement token");Ye(M.OpenStatement,M.EndFor);)Ur.push(he());return new ie(Ze,Ct,Dt,Ur)}function Re(){return ut()}function ut(){const Ze=nt();if(Je(M.If)){++S;const Ct=nt();if(Je(M.Else)){++S;const Dt=nt();return new ne(Ct,[Ze],[Dt])}else return new Xe(Ze,Ct)}return Ze}function nt(){let Ze=vt();for(;Je(M.Or);){const Ct=v[S];++S;const Dt=vt();Ze=new Fe(Ct,Ze,Dt)}return Ze}function vt(){let Ze=pt();for(;Je(M.And);){const Ct=v[S];++S;const Dt=pt();Ze=new Fe(Ct,Ze,Dt)}return Ze}function pt(){let Ze;for(;Je(M.Not);){const Ct=v[S];++S;const Dt=pt();Ze=new we(Ct,Dt)}return Ze??Tt()}function Tt(){let Ze=Lt();for(;Je(M.ComparisonBinaryOperator)||Je(M.In)||Je(M.NotIn);){const Ct=v[S];++S;const Dt=Lt();Ze=new Fe(Ct,Ze,Dt)}return Ze}function Lt(){let Ze=Wt();for(;Je(M.AdditiveBinaryOperator);){const Ct=v[S];++S;const Dt=Wt();Ze=new Fe(Ct,Ze,Dt)}return Ze}function He(){const Ze=Yt();return Je(M.OpenParen)?Nt(Ze):Ze}function Nt(Ze){let Ct=new ae(Ze,Rt());return Je(M.OpenParen)&&(Ct=Nt(Ct)),Ct}function Rt(){Q(M.OpenParen,"Expected opening parenthesis for arguments list");const Ze=qt();return Q(M.CloseParen,"Expected closing parenthesis for arguments list"),Ze}function qt(){const Ze=[];for(;!Je(M.CloseParen);){let Ct=Re();if(Je(M.Equals)){if(++S,!(Ct instanceof N))throw new SyntaxError("Expected identifier for keyword argument");const Dt=Re();Ct=new pe(Ct,Dt)}Ze.push(Ct),Je(M.Comma)&&++S}return Ze}function Ht(){const Ze=[];let Ct=!1;for(;!Je(M.CloseSquareBracket);)Je(M.Colon)?(Ze.push(void 0),++S,Ct=!0):(Ze.push(Re()),Je(M.Colon)&&(++S,Ct=!0));if(Ze.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Ct){if(Ze.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new U(...Ze)}return Ze[0]}function Yt(){let Ze=Tr();for(;Je(M.Dot)||Je(M.OpenSquareBracket);){const Ct=v[S];++S;let Dt;const Ur=Ct.type!==M.Dot;if(Ur)Dt=Ht(),Q(M.CloseSquareBracket,"Expected closing square bracket");else if(Dt=Tr(),Dt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Ze=new ue(Ze,Dt,Ur)}return Ze}function Wt(){let Ze=xr();for(;Je(M.MultiplicativeBinaryOperator);){const Ct=v[S];++S;const Dt=xr();Ze=new Fe(Ct,Ze,Dt)}return Ze}function xr(){let Ze=Vr();for(;Je(M.Is);){++S;const Ct=Je(M.Not);Ct&&++S;let Dt=Tr();if(Dt instanceof _e&&(Dt=new N(Dt.value.toString())),!(Dt instanceof N))throw new SyntaxError("Expected identifier for the test");Ze=new ct(Ze,Ct,Dt)}return Ze}function Vr(){let Ze=He();for(;Je(M.Pipe);){++S;let Ct=Tr();if(!(Ct instanceof N))throw new SyntaxError("Expected identifier for the filter");Je(M.OpenParen)&&(Ct=Nt(Ct)),Ze=new et(Ze,Ct)}return Ze}function Tr(){const Ze=v[S];switch(Ze.type){case M.NumericLiteral:return++S,new B(Number(Ze.value));case M.StringLiteral:return++S,new A(Ze.value);case M.BooleanLiteral:return++S,new _e(Ze.value.toLowerCase()==="true");case M.Identifier:return++S,new N(Ze.value);case M.OpenParen:{++S;const Ct=Be();if(v[S].type!==M.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${v[S].type} instead`);return++S,Ct}case M.OpenSquareBracket:{++S;const Ct=[];for(;!Je(M.CloseSquareBracket);)Ct.push(Re()),Je(M.Comma)&&++S;return++S,new ye(Ct)}case M.OpenCurlyBracket:{++S;const Ct=new Map;for(;!Je(M.CloseCurlyBracket);){const Dt=Re();Q(M.Colon,"Expected colon between key and value in object literal");const Ur=Re();Ct.set(Dt,Ur),Je(M.Comma)&&++S}return++S,new Se(Ct)}default:throw new SyntaxError(`Unexpected token: ${Ze.type}`)}}for(;S=0?(W=(W??(W=0))<0?Math.max(v.length+W,0):Math.min(W,v.length),S=(S??(S=v.length))<0?Math.max(v.length+S,0):Math.min(S,v.length)):(W=(W??(W=v.length-1))<0?Math.max(v.length+W,-1):Math.min(W,v.length-1),S=(S??(S=-1))<-1?Math.max(v.length+S,-1):Math.min(S,v.length-1));const Ye=[];for(let Je=W;he*JeW.toUpperCase())}var tt=class{constructor(v=void 0){Te(this,"type","RuntimeValue");Te(this,"value");Te(this,"builtins",new Map);this.value=v}__bool__(){return new st(!!this.value)}},ot=class extends tt{constructor(){super(...arguments);Te(this,"type","NumericValue")}},Le=class extends tt{constructor(){super(...arguments);Te(this,"type","StringValue");Te(this,"builtins",new Map([["upper",new Ve(()=>new Le(this.value.toUpperCase()))],["lower",new Ve(()=>new Le(this.value.toLowerCase()))],["strip",new Ve(()=>new Le(this.value.trim()))],["title",new Ve(()=>new Le(dt(this.value)))],["length",new ot(this.value.length)]]))}},st=class extends tt{constructor(){super(...arguments);Te(this,"type","BooleanValue")}},xt=class extends tt{constructor(){super(...arguments);Te(this,"type","ObjectValue");Te(this,"builtins",new Map([["get",new Ve(([W,S])=>{if(!(W instanceof Le))throw new Error(`Object key must be a string: got ${W.type}`);return this.value.get(W.value)??S??new Ue})],["items",new Ve(()=>new re(Array.from(this.value.entries()).map(([W,S])=>new re([new Le(W),S]))))]]))}__bool__(){return new st(this.value.size>0)}},ze=class extends xt{constructor(){super(...arguments);Te(this,"type","KeywordArgumentsValue")}},re=class extends tt{constructor(){super(...arguments);Te(this,"type","ArrayValue");Te(this,"builtins",new Map([["length",new ot(this.value.length)]]))}__bool__(){return new st(this.value.length>0)}},Ce=class extends re{constructor(){super(...arguments);Te(this,"type","TupleValue")}},Ve=class extends tt{constructor(){super(...arguments);Te(this,"type","FunctionValue")}},Ue=class extends tt{constructor(){super(...arguments);Te(this,"type","NullValue")}},je=class extends tt{constructor(){super(...arguments);Te(this,"type","UndefinedValue")}},qe=class{constructor(v){Te(this,"variables",new Map([["namespace",new Ve(v=>{if(v.length===0)return new xt(new Map);if(v.length!==1||!(v[0]instanceof xt))throw new Error("`namespace` expects either zero arguments or a single object argument");return v[0]})]]));Te(this,"tests",new Map([["boolean",v=>v.type==="BooleanValue"],["callable",v=>v instanceof Ve],["odd",v=>{if(v.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${v.type}`);return v.value%2!==0}],["even",v=>{if(v.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${v.type}`);return v.value%2===0}],["false",v=>v.type==="BooleanValue"&&!v.value],["true",v=>v.type==="BooleanValue"&&v.value],["string",v=>v.type==="StringValue"],["number",v=>v.type==="NumericValue"],["integer",v=>v.type==="NumericValue"&&Number.isInteger(v.value)],["iterable",v=>v instanceof re||v instanceof Le],["lower",v=>{const W=v.value;return v.type==="StringValue"&&W===W.toLowerCase()}],["upper",v=>{const W=v.value;return v.type==="StringValue"&&W===W.toUpperCase()}],["none",v=>v.type==="NullValue"],["defined",v=>v.type!=="UndefinedValue"],["undefined",v=>v.type==="UndefinedValue"],["equalto",(v,W)=>v.value===W.value],["eq",(v,W)=>v.value===W.value]]));this.parent=v}set(v,W){return this.declareVariable(v,ft(W))}declareVariable(v,W){if(this.variables.has(v))throw new SyntaxError(`Variable already declared: ${v}`);return this.variables.set(v,W),W}setVariable(v,W){return this.variables.set(v,W),W}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}}},lt=class{constructor(v){Te(this,"global");this.global=v??new qe}run(v){return this.evaluate(v,this.global)}evaluateBinaryExpression(v,W){const S=this.evaluate(v.left,W);switch(v.operator.value){case"and":return S.__bool__().value?this.evaluate(v.right,W):S;case"or":return S.__bool__().value?S:this.evaluate(v.right,W)}const Q=this.evaluate(v.right,W);switch(v.operator.value){case"==":return new st(S.value==Q.value);case"!=":return new st(S.value!=Q.value)}if(S instanceof je||Q instanceof je)throw new Error("Cannot perform operation on undefined values");if(S instanceof Ue||Q instanceof Ue)throw new Error("Cannot perform operation on null values");if(S instanceof ot&&Q instanceof ot)switch(v.operator.value){case"+":return new ot(S.value+Q.value);case"-":return new ot(S.value-Q.value);case"*":return new ot(S.value*Q.value);case"/":return new ot(S.value/Q.value);case"%":return new ot(S.value%Q.value);case"<":return new st(S.value":return new st(S.value>Q.value);case">=":return new st(S.value>=Q.value);case"<=":return new st(S.value<=Q.value)}else if(S instanceof re&&Q instanceof re)switch(v.operator.value){case"+":return new re(S.value.concat(Q.value))}else if(Q instanceof re){const he=Q.value.find(Ye=>Ye.value===S.value)!==void 0;switch(v.operator.value){case"in":return new st(he);case"not in":return new st(!he)}}if(S instanceof Le||Q instanceof Le)switch(v.operator.value){case"+":return new Le(S.value.toString()+Q.value.toString())}if(S instanceof Le&&Q instanceof Le)switch(v.operator.value){case"in":return new st(Q.value.includes(S.value));case"not in":return new st(!Q.value.includes(S.value))}if(S instanceof Le&&Q instanceof xt)switch(v.operator.value){case"in":return new st(Q.value.has(S.value));case"not in":return new st(!Q.value.has(S.value))}throw new SyntaxError(`Unknown operator "${v.operator.value}" between ${S.type} and ${Q.type}`)}evaluateArguments(v,W){const S=[],Q=new Map;for(const he of v)if(he.type==="KeywordArgumentExpression"){const Ye=he;Q.set(Ye.key.value,this.evaluate(Ye.value,W))}else{if(Q.size>0)throw new Error("Positional arguments must come before keyword arguments");S.push(this.evaluate(he,W))}return[S,Q]}evaluateFilterExpression(v,W){const S=this.evaluate(v.operand,W);if(v.filter.type==="Identifier"){const Q=v.filter;if(Q.value==="tojson")return new Le(gt(S));if(S instanceof re)switch(Q.value){case"list":return S;case"first":return S.value[0];case"last":return S.value[S.value.length-1];case"length":return new ot(S.value.length);case"reverse":return new re(S.value.reverse());case"sort":return new re(S.value.sort((he,Ye)=>{if(he.type!==Ye.type)throw new Error(`Cannot compare different types: ${he.type} and ${Ye.type}`);switch(he.type){case"NumericValue":return he.value-Ye.value;case"StringValue":return he.value.localeCompare(Ye.value);default:throw new Error(`Cannot compare type: ${he.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Q.value}`)}else if(S instanceof Le)switch(Q.value){case"length":return new ot(S.value.length);case"upper":return new Le(S.value.toUpperCase());case"lower":return new Le(S.value.toLowerCase());case"title":return new Le(dt(S.value));case"capitalize":return new Le(S.value.charAt(0).toUpperCase()+S.value.slice(1));case"trim":return new Le(S.value.trim());case"indent":return new Le(S.value.split(` `).map((he,Ye)=>Ye===0||he.length===0?he:" "+he).join(` `));case"string":return S;default:throw new Error(`Unknown StringValue filter: ${Q.value}`)}else if(S instanceof ot)switch(Q.value){case"abs":return new ot(Math.abs(S.value));default:throw new Error(`Unknown NumericValue filter: ${Q.value}`)}else if(S instanceof xt)switch(Q.value){case"items":return new re(Array.from(S.value.entries()).map(([he,Ye])=>new re([new Le(he),Ye])));case"length":return new ot(S.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Q.value}`)}throw new Error(`Cannot apply filter "${Q.value}" to type: ${S.type}`)}else if(v.filter.type==="CallExpression"){const Q=v.filter;if(Q.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Q.callee.type}`);const he=Q.callee.value;if(he==="tojson"){const[,Ye]=this.evaluateArguments(Q.args,W),Je=Ye.get("indent")??new Ue;if(!(Je instanceof ot||Je instanceof Ue))throw new Error("If set, indent must be a number");return new Le(gt(S,Je.value))}if(S instanceof re){switch(he){case"selectattr":{if(S.value.some(k=>!(k instanceof xt)))throw new Error("`selectattr` can only be applied to array of objects");if(Q.args.some(k=>k.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Ye,Je,Pt]=Q.args.map(k=>this.evaluate(k,W));let mt;if(Je){const k=W.tests.get(Je.value);if(!k)throw new Error(`Unknown test: ${Je.value}`);mt=k}else mt=(...k)=>k[0].__bool__().value;const Ee=S.value.filter(k=>{const H=k.value.get(Ye.value);return H?mt(H,Pt):!1});return new re(Ee)}case"map":{const[,Ye]=this.evaluateArguments(Q.args,W);if(Ye.has("attribute")){const Je=Ye.get("attribute");if(!(Je instanceof Le))throw new Error("attribute must be a string");const Pt=Ye.get("default"),mt=S.value.map(Ee=>{if(!(Ee instanceof xt))throw new Error("items in map must be an object");return Ee.value.get(Je.value)??Pt??new je});return new re(mt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${he}`)}else if(S instanceof Le){switch(he){case"indent":{const[Ye,Je]=this.evaluateArguments(Q.args,W),Pt=Ye.at(0)??Je.get("width")??new ot(4);if(!(Pt instanceof ot))throw new Error("width must be a number");const mt=Ye.at(1)??Je.get("first")??new st(!1),Ee=Ye.at(2)??Je.get("blank")??new st(!1),k=S.value.split(` `),H=" ".repeat(Pt.value),be=k.map((Be,Ie)=>!mt.value&&Ie===0||!Ee.value&&Be.length===0?Be:H+Be);return new Le(be.join(` `))}}throw new Error(`Unknown StringValue filter: ${he}`)}else throw new Error(`Cannot apply filter "${he}" to type: ${S.type}`)}throw new Error(`Unknown filter: ${v.filter.type}`)}evaluateTestExpression(v,W){const S=this.evaluate(v.operand,W),Q=W.tests.get(v.test.value);if(!Q)throw new Error(`Unknown test: ${v.test.value}`);const he=Q(S);return new st(v.negate?!he:he)}evaluateUnaryExpression(v,W){const S=this.evaluate(v.argument,W);switch(v.operator.value){case"not":return new st(!S.value);default:throw new SyntaxError(`Unknown operator: ${v.operator.value}`)}}evalProgram(v,W){return this.evaluateBlock(v.body,W)}evaluateBlock(v,W){let S="";for(const Q of v){const he=this.evaluate(Q,W);he.type!=="NullValue"&&he.type!=="UndefinedValue"&&(S+=he.value)}return new Le(S)}evaluateIdentifier(v,W){return W.lookupVariable(v.value)}evaluateCallExpression(v,W){const[S,Q]=this.evaluateArguments(v.args,W);Q.size>0&&S.push(new ze(Q));const he=this.evaluate(v.callee,W);if(he.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${he.type}`);return he.value(S,W)}evaluateSliceExpression(v,W,S){if(!(v instanceof re||v instanceof Le))throw new Error("Slice object must be an array or string");const Q=this.evaluate(W.start,S),he=this.evaluate(W.stop,S),Ye=this.evaluate(W.step,S);if(!(Q instanceof ot||Q instanceof je))throw new Error("Slice start must be numeric or undefined");if(!(he instanceof ot||he instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(Ye instanceof ot||Ye instanceof je))throw new Error("Slice step must be numeric or undefined");return v instanceof re?new re(Ge(v.value,Q.value,he.value,Ye.value)):new Le(Ge(Array.from(v.value),Q.value,he.value,Ye.value).join(""))}evaluateMemberExpression(v,W){const S=this.evaluate(v.object,W);let Q;if(v.computed){if(v.property.type==="SliceExpression")return this.evaluateSliceExpression(S,v.property,W);Q=this.evaluate(v.property,W)}else Q=new Le(v.property.value);let he;if(S instanceof xt){if(!(Q instanceof Le))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=S.value.get(Q.value)??S.builtins.get(Q.value)}else if(S instanceof re||S instanceof Le)if(Q instanceof ot)he=S.value.at(Q.value),S instanceof Le&&(he=new Le(S.value.at(Q.value)));else if(Q instanceof Le)he=S.builtins.get(Q.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Q.type}`);else{if(!(Q instanceof Le))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=S.builtins.get(Q.value)}return he instanceof tt?he:new je}evaluateSet(v,W){const S=this.evaluate(v.value,W);if(v.assignee.type==="Identifier"){const Q=v.assignee.value;W.setVariable(Q,S)}else if(v.assignee.type==="MemberExpression"){const Q=v.assignee,he=this.evaluate(Q.object,W);if(!(he instanceof xt))throw new Error("Cannot assign to member of non-object");if(Q.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");he.value.set(Q.property.value,S)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(v.assignee)}`);return new Ue}evaluateIf(v,W){const S=this.evaluate(v.test,W);return this.evaluateBlock(S.__bool__().value?v.body:v.alternate,W)}evaluateFor(v,W){const S=new qe(W);let Q,he;if(v.iterable.type==="SelectExpression"){const Ee=v.iterable;he=this.evaluate(Ee.iterable,S),Q=Ee.test}else he=this.evaluate(v.iterable,S);if(!(he instanceof re))throw new Error(`Expected iterable type in for loop: got ${he.type}`);const Ye=[],Je=[];for(let Ee=0;EeBe.setVariable(v.loopvar.value,H);else if(v.loopvar.type==="TupleLiteral"){const Be=v.loopvar;if(H.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${H.type}`);const Ie=H;if(Be.value.length!==Ie.value.length)throw new Error(`Too ${Be.value.length>Ie.value.length?"few":"many"} items to unpack`);be=Re=>{for(let ut=0;ut0?Ye[Ee-1]:new je],["nextitem",Ee{var Je;const he=new qe(Q);S=S.slice();let Ye;((Je=S.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(Ye=S.pop());for(let Pt=0;Ptthis.evaluate(S,W)));case"TupleLiteral":return new Ce(v.value.map(S=>this.evaluate(S,W)));case"ObjectLiteral":{const S=new Map;for(const[Q,he]of v.value){const Ye=this.evaluate(Q,W);if(!(Ye instanceof Le))throw new Error(`Object keys must be strings: got ${Ye.type}`);S.set(Ye.value,this.evaluate(he,W))}return new xt(S)}case"Identifier":return this.evaluateIdentifier(v,W);case"CallExpression":return this.evaluateCallExpression(v,W);case"MemberExpression":return this.evaluateMemberExpression(v,W);case"UnaryExpression":return this.evaluateUnaryExpression(v,W);case"BinaryExpression":return this.evaluateBinaryExpression(v,W);case"FilterExpression":return this.evaluateFilterExpression(v,W);case"TestExpression":return this.evaluateTestExpression(v,W);default:throw new SyntaxError(`Unknown node type: ${v.type}`)}}};function ft(v){switch(typeof v){case"number":return new ot(v);case"string":return new Le(v);case"boolean":return new st(v);case"undefined":return new je;case"object":return v===null?new Ue:Array.isArray(v)?new re(v.map(ft)):new xt(new Map(Object.entries(v).map(([W,S])=>[W,ft(S)])));case"function":return new Ve((W,S)=>{const Q=v(...W.map(he=>he.value))??null;return ft(Q)});default:throw new Error(`Cannot convert to runtime value: ${v}`)}}function gt(v,W,S){const Q=S??0;switch(v.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(v.value);case"ArrayValue":case"ObjectValue":{const he=W?" ".repeat(W):"",Ye=` `+he.repeat(Q),Je=Ye+he;if(v.type==="ArrayValue"){const Pt=v.value.map(mt=>gt(mt,W,Q+1));return W?`[${Je}${Pt.join(`,${Je}`)}${Ye}]`:`[${Pt.join(", ")}]`}else{const Pt=Array.from(v.value.entries()).map(([mt,Ee])=>{const k=`"${mt}": ${gt(Ee,W,Q+1)}`;return W?`${Je}${k}`:k});return W?`{${Pt.join(",")}${Ye}}`:`{${Pt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${v.type}`)}}var Mt=class{constructor(v){Te(this,"parsed");const W=P(v,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ke(W)}render(v){const W=new qe;W.set("false",!1),W.set("true",!0),W.set("raise_exception",he=>{throw new Error(he)}),W.set("range",ee);for(const[he,Ye]of Object.entries(v))W.set(he,Ye);return new lt(W).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{registerBackend:()=>ge,resolveBackendAndExecutionProviders:()=>xe});const M=new Map,K=[],ge=(D,x,V)=>{if(x&&typeof x.init=="function"&&typeof x.createInferenceSessionHandler=="function"){const P=M.get(D);if(P===void 0)M.set(D,{backend:x,priority:V});else{if(P.priority>V)return;if(P.priority===V&&P.backend!==x)throw new Error(`cannot register backend "${D}" using priority ${V}`)}if(V>=0){const J=K.indexOf(D);J!==-1&&K.splice(J,1);for(let te=0;te{const x=M.get(D);if(!x)return"backend not found.";if(x.initialized)return x.backend;if(x.aborted)return x.error;{const V=!!x.initPromise;try{return V||(x.initPromise=x.backend.init(D)),await x.initPromise,x.initialized=!0,x.backend}catch(P){return V||(x.error=`${P}`,x.aborted=!0),x.error}finally{delete x.initPromise}}},xe=async D=>{const x=D.executionProviders||[],V=x.map(R=>typeof R=="string"?R:R.name),P=V.length===0?K:V;let J;const te=[],ne=new Set;for(const R of P){const Z=await Me(R);typeof Z=="string"?te.push({name:R,err:Z}):(J||(J=Z),J===Z&&ne.add(R))}if(!J)throw new Error(`no available backend found. ERR: ${te.map(R=>`[${R.name}] ${R.err}`).join(", ")}`);for(const{name:R,err:Z}of te)V.includes(R)&&console.warn(`removing requested execution provider "${R}" from session options because it is not available: ${Z}`);const ie=x.filter(R=>ne.has(typeof R=="string"?R:R.name));return[J,new Proxy(D,{get:(R,Z)=>Z==="executionProviders"?ie:Reflect.get(R,Z)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{registerBackend:()=>M.registerBackend});var M=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{env:()=>ge});var M=l("./node_modules/onnxruntime-common/dist/esm/version.js");let K="warning";const ge={wasm:{},webgl:{},webgpu:{},versions:{common:M.version},set logLevel(Me){if(Me!==void 0){if(typeof Me!="string"||["verbose","info","warning","error","fatal"].indexOf(Me)===-1)throw new Error(`Unsupported logging level: ${Me}`);K=Me}},get logLevel(){return K}};Object.defineProperty(ge,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{env:()=>K});var M=l("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const K=M.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{InferenceSession:()=>ge.InferenceSession,TRACE:()=>xe.TRACE,TRACE_FUNC_BEGIN:()=>xe.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>xe.TRACE_FUNC_END,Tensor:()=>Me.Tensor,TrainingSession:()=>D.TrainingSession,env:()=>K.env,registerBackend:()=>M.registerBackend});var M=l("./node_modules/onnxruntime-common/dist/esm/backend.js"),K=l("./node_modules/onnxruntime-common/dist/esm/env.js"),ge=l("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Me=l("./node_modules/onnxruntime-common/dist/esm/tensor.js");l("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),l("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var xe=l("./node_modules/onnxruntime-common/dist/esm/trace.js");l("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),l("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var D=l("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{InferenceSession:()=>Me});var M=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),K=l("./node_modules/onnxruntime-common/dist/esm/tensor.js"),ge=l("./node_modules/onnxruntime-common/dist/esm/trace.js");class Me{constructor(D){this.handler=D}async run(D,x,V){(0,ge.TRACE_FUNC_BEGIN)();const P={};let J={};if(typeof D!="object"||D===null||D instanceof K.Tensor||Array.isArray(D))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let te=!0;if(typeof x=="object"){if(x===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(x instanceof K.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(x)){if(x.length===0)throw new TypeError("'fetches' cannot be an empty array.");te=!1;for(const R of x){if(typeof R!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(R)===-1)throw new RangeError(`'fetches' contains invalid output name: ${R}.`);P[R]=null}if(typeof V=="object"&&V!==null)J=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else{let R=!1;const Z=Object.getOwnPropertyNames(x);for(const se of this.outputNames)if(Z.indexOf(se)!==-1){const ue=x[se];(ue===null||ue instanceof K.Tensor)&&(R=!0,te=!1,P[se]=ue)}if(R){if(typeof V=="object"&&V!==null)J=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else J=x}}else if(typeof x<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const R of this.inputNames)if(typeof D[R]>"u")throw new Error(`input '${R}' is missing in 'feeds'.`);if(te)for(const R of this.outputNames)P[R]=null;const ne=await this.handler.run(D,P,J),ie={};for(const R in ne)if(Object.hasOwnProperty.call(ne,R)){const Z=ne[R];Z instanceof K.Tensor?ie[R]=Z:ie[R]=new K.Tensor(Z.type,Z.data,Z.dims)}return(0,ge.TRACE_FUNC_END)(),ie}async release(){return this.handler.dispose()}static async create(D,x,V,P){(0,ge.TRACE_FUNC_BEGIN)();let J,te={};if(typeof D=="string"){if(J=D,typeof x=="object"&&x!==null)te=x;else if(typeof x<"u")throw new TypeError("'options' must be an object.")}else if(D instanceof Uint8Array){if(J=D,typeof x=="object"&&x!==null)te=x;else if(typeof x<"u")throw new TypeError("'options' must be an object.")}else if(D instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&D instanceof SharedArrayBuffer){const Z=D;let se=0,ue=D.byteLength;if(typeof x=="object"&&x!==null)te=x;else if(typeof x=="number"){if(se=x,!Number.isSafeInteger(se))throw new RangeError("'byteOffset' must be an integer.");if(se<0||se>=Z.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${Z.byteLength}).`);if(ue=D.byteLength-se,typeof V=="number"){if(ue=V,!Number.isSafeInteger(ue))throw new RangeError("'byteLength' must be an integer.");if(ue<=0||se+ue>Z.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${Z.byteLength-se}].`);if(typeof P=="object"&&P!==null)te=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof V<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof x<"u")throw new TypeError("'options' must be an object.");J=new Uint8Array(Z,se,ue)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[ne,ie]=await(0,M.resolveBackendAndExecutionProviders)(te),R=await ne.createInferenceSessionHandler(J,ie);return(0,ge.TRACE_FUNC_END)(),new Me(R)}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":(bt,fe,l)=>{l.r(fe),l.d(fe,{InferenceSession:()=>K});var M=l("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const K=M.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(bt,fe,l)=>{l.r(fe)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(bt,fe,l)=>{l.r(fe)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{tensorToDataURL:()=>M,tensorToImageData:()=>K});const M=(ge,Me)=>{const xe=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);xe.width=ge.dims[3],xe.height=ge.dims[2];const D=xe.getContext("2d");if(D!=null){let x,V;(Me==null?void 0:Me.tensorLayout)!==void 0&&Me.tensorLayout==="NHWC"?(x=ge.dims[2],V=ge.dims[3]):(x=ge.dims[3],V=ge.dims[2]);const P=(Me==null?void 0:Me.format)!==void 0?Me.format:"RGB",J=Me==null?void 0:Me.norm;let te,ne;J===void 0||J.mean===void 0?te=[255,255,255,255]:typeof J.mean=="number"?te=[J.mean,J.mean,J.mean,J.mean]:(te=[J.mean[0],J.mean[1],J.mean[2],0],J.mean[3]!==void 0&&(te[3]=J.mean[3])),J===void 0||J.bias===void 0?ne=[0,0,0,0]:typeof J.bias=="number"?ne=[J.bias,J.bias,J.bias,J.bias]:(ne=[J.bias[0],J.bias[1],J.bias[2],0],J.bias[3]!==void 0&&(ne[3]=J.bias[3]));const ie=V*x;let R=0,Z=ie,se=ie*2,ue=-1;P==="RGBA"?(R=0,Z=ie,se=ie*2,ue=ie*3):P==="RGB"?(R=0,Z=ie,se=ie*2):P==="RBG"&&(R=0,se=ie,Z=ie*2);for(let ae=0;ae{const xe=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let D;if(xe!=null){let x,V,P;(Me==null?void 0:Me.tensorLayout)!==void 0&&Me.tensorLayout==="NHWC"?(x=ge.dims[2],V=ge.dims[1],P=ge.dims[3]):(x=ge.dims[3],V=ge.dims[2],P=ge.dims[1]);const J=Me!==void 0&&Me.format!==void 0?Me.format:"RGB",te=Me==null?void 0:Me.norm;let ne,ie;te===void 0||te.mean===void 0?ne=[255,255,255,255]:typeof te.mean=="number"?ne=[te.mean,te.mean,te.mean,te.mean]:(ne=[te.mean[0],te.mean[1],te.mean[2],255],te.mean[3]!==void 0&&(ne[3]=te.mean[3])),te===void 0||te.bias===void 0?ie=[0,0,0,0]:typeof te.bias=="number"?ie=[te.bias,te.bias,te.bias,te.bias]:(ie=[te.bias[0],te.bias[1],te.bias[2],0],te.bias[3]!==void 0&&(ie[3]=te.bias[3]));const R=V*x;if(Me!==void 0&&(Me.format!==void 0&&P===4&&Me.format!=="RGBA"||P===3&&Me.format!=="RGB"&&Me.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const Z=4;let se=0,ue=1,ae=2,N=3,F=0,B=R,A=R*2,_e=-1;J==="RGBA"?(F=0,B=R,A=R*2,_e=R*3):J==="RGB"?(F=0,B=R,A=R*2):J==="RBG"&&(F=0,A=R,B=R*2),D=xe.createImageData(x,V);for(let ye=0;ye{l.r(fe)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{bufferToTensor:()=>K,tensorFromGpuBuffer:()=>xe,tensorFromImage:()=>ge,tensorFromPinnedBuffer:()=>D,tensorFromTexture:()=>Me});var M=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const K=(x,V)=>{if(x===void 0)throw new Error("Image buffer must be defined");if(V.height===void 0||V.width===void 0)throw new Error("Image height and width must be defined");if(V.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:P,width:J}=V,te=V.norm??{mean:255,bias:0};let ne,ie;typeof te.mean=="number"?ne=[te.mean,te.mean,te.mean,te.mean]:ne=[te.mean[0],te.mean[1],te.mean[2],te.mean[3]??255],typeof te.bias=="number"?ie=[te.bias,te.bias,te.bias,te.bias]:ie=[te.bias[0],te.bias[1],te.bias[2],te.bias[3]??0];const R=V.format!==void 0?V.format:"RGBA",Z=V.tensorFormat!==void 0&&V.tensorFormat!==void 0?V.tensorFormat:"RGB",se=P*J,ue=Z==="RGBA"?new Float32Array(se*4):new Float32Array(se*3);let ae=4,N=0,F=1,B=2,A=3,_e=0,ye=se,$e=se*2,Se=-1;R==="RGB"&&(ae=3,N=0,F=1,B=2,A=-1),Z==="RGBA"?Se=se*3:Z==="RBG"?(_e=0,$e=se,ye=se*2):Z==="BGR"&&($e=0,ye=se,_e=se*2);for(let et=0;et{const P=typeof HTMLImageElement<"u"&&x instanceof HTMLImageElement,J=typeof ImageData<"u"&&x instanceof ImageData,te=typeof ImageBitmap<"u"&&x instanceof ImageBitmap,ne=typeof x=="string";let ie,R=V??{};const Z=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},se=ue=>ue instanceof HTMLCanvasElement||ue instanceof OffscreenCanvas?ue.getContext("2d"):null;if(P){const ue=Z();ue.width=x.width,ue.height=x.height;const ae=se(ue);if(ae!=null){let N=x.height,F=x.width;if(V!==void 0&&V.resizedHeight!==void 0&&V.resizedWidth!==void 0&&(N=V.resizedHeight,F=V.resizedWidth),V!==void 0){if(R=V,V.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");R.tensorFormat="RGBA",R.height=N,R.width=F}else R.tensorFormat="RGBA",R.height=N,R.width=F;ae.drawImage(x,0,0),ie=ae.getImageData(0,0,F,N).data}else throw new Error("Can not access image data")}else if(J){let ue,ae;if(V!==void 0&&V.resizedWidth!==void 0&&V.resizedHeight!==void 0?(ue=V.resizedHeight,ae=V.resizedWidth):(ue=x.height,ae=x.width),V!==void 0&&(R=V),R.format="RGBA",R.height=ue,R.width=ae,V!==void 0){const N=Z();N.width=ae,N.height=ue;const F=se(N);if(F!=null)F.putImageData(x,0,0),ie=F.getImageData(0,0,ae,ue).data;else throw new Error("Can not access image data")}else ie=x.data}else if(te){if(V===void 0)throw new Error("Please provide image config with format for Imagebitmap");const ue=Z();ue.width=x.width,ue.height=x.height;const ae=se(ue);if(ae!=null){const N=x.height,F=x.width;return ae.drawImage(x,0,0,F,N),ie=ae.getImageData(0,0,F,N).data,R.height=N,R.width=F,K(ie,R)}else throw new Error("Can not access image data")}else{if(ne)return new Promise((ue,ae)=>{const N=Z(),F=se(N);if(!x||!F)return ae();const B=new Image;B.crossOrigin="Anonymous",B.src=x,B.onload=()=>{N.width=B.width,N.height=B.height,F.drawImage(B,0,0,N.width,N.height);const A=F.getImageData(0,0,N.width,N.height);R.height=N.height,R.width=N.width,ue(K(A.data,R))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ie!==void 0)return K(ie,R);throw new Error("Input data provided is not supported - aborted tensor creation")},Me=(x,V)=>{const{width:P,height:J,download:te,dispose:ne}=V,ie=[1,J,P,4];return new M.Tensor({location:"texture",type:"float32",texture:x,dims:ie,download:te,dispose:ne})},xe=(x,V)=>{const{dataType:P,dims:J,download:te,dispose:ne}=V;return new M.Tensor({location:"gpu-buffer",type:P??"float32",gpuBuffer:x,dims:J,download:te,dispose:ne})},D=(x,V,P)=>new M.Tensor({location:"cpu-pinned",type:x,data:V,dims:P??[V.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(bt,fe,l)=>{l.r(fe)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>K,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>M,checkTypedArray:()=>Me});const M=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),K=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ge=!1;const Me=()=>{if(!ge){ge=!0;const xe=typeof BigInt64Array<"u"&&BigInt64Array.from,D=typeof BigUint64Array<"u"&&BigUint64Array.from,x=typeof Float16Array<"u"&&Float16Array.from;xe&&(M.set("int64",BigInt64Array),K.set(BigInt64Array,"int64")),D&&(M.set("uint64",BigUint64Array),K.set(BigUint64Array,"uint64")),x?(M.set("float16",Float16Array),K.set(Float16Array,"float16")):M.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{Tensor:()=>xe});var M=l("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),K=l("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),ge=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Me=l("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class xe{constructor(x,V,P){(0,ge.checkTypedArray)();let J,te;if(typeof x=="object"&&"location"in x)switch(this.dataLocation=x.location,J=x.type,te=x.dims,x.location){case"cpu-pinned":{const ie=ge.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(J);if(!ie)throw new TypeError(`unsupported type "${J}" to create tensor from pinned buffer`);if(!(x.data instanceof ie))throw new TypeError(`buffer should be of type ${ie.name}`);this.cpuData=x.data;break}case"texture":{if(J!=="float32")throw new TypeError(`unsupported type "${J}" to create tensor from texture`);this.gpuTextureData=x.texture,this.downloader=x.download,this.disposer=x.dispose;break}case"gpu-buffer":{if(J!=="float32"&&J!=="float16"&&J!=="int32"&&J!=="int64"&&J!=="uint32"&&J!=="uint8"&&J!=="bool")throw new TypeError(`unsupported type "${J}" to create tensor from gpu buffer`);this.gpuBufferData=x.gpuBuffer,this.downloader=x.download,this.disposer=x.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ie,R;if(typeof x=="string")if(J=x,R=P,x==="string"){if(!Array.isArray(V))throw new TypeError("A string tensor's data must be a string array.");ie=V}else{const Z=ge.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(x);if(Z===void 0)throw new TypeError(`Unsupported tensor type: ${x}.`);if(Array.isArray(V)){if(x==="float16"&&Z===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");x==="uint64"||x==="int64"?ie=Z.from(V,BigInt):ie=Z.from(V)}else if(V instanceof Z)ie=V;else throw new TypeError(`A ${J} tensor's data must be type of ${Z}`)}else if(R=V,Array.isArray(x)){if(x.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const Z=typeof x[0];if(Z==="string")J="string",ie=x;else if(Z==="boolean")J="bool",ie=Uint8Array.from(x);else throw new TypeError(`Invalid element type of data array: ${Z}.`)}else{const Z=ge.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(x.constructor);if(Z===void 0)throw new TypeError(`Unsupported type for tensor data: ${x.constructor}.`);J=Z,ie=x}if(R===void 0)R=[ie.length];else if(!Array.isArray(R))throw new TypeError("A tensor's dims must be a number array");te=R,this.cpuData=ie,this.dataLocation="cpu"}const ne=(0,Me.calculateSize)(te);if(this.cpuData&&ne!==this.cpuData.length)throw new Error(`Tensor's size(${ne}) does not match data length(${this.cpuData.length}).`);this.type=J,this.dims=te,this.size=ne}static async fromImage(x,V){return(0,K.tensorFromImage)(x,V)}static fromTexture(x,V){return(0,K.tensorFromTexture)(x,V)}static fromGpuBuffer(x,V){return(0,K.tensorFromGpuBuffer)(x,V)}static fromPinnedBuffer(x,V,P){return(0,K.tensorFromPinnedBuffer)(x,V,P)}toDataURL(x){return(0,M.tensorToDataURL)(this,x)}toImageData(x){return(0,M.tensorToImageData)(this,x)}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(x){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const V=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=V,x&&this.disposer&&(this.disposer(),this.disposer=void 0),V}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(x){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Me.tensorReshape)(this,x)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{calculateSize:()=>K,tensorReshape:()=>ge});var M=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const K=Me=>{let xe=1;for(let D=0;D{switch(Me.location){case"cpu":return new M.Tensor(Me.type,Me.data,xe);case"cpu-pinned":return new M.Tensor({location:"cpu-pinned",data:Me.data,type:Me.type,dims:xe});case"texture":return new M.Tensor({location:"texture",texture:Me.texture,type:Me.type,dims:xe});case"gpu-buffer":return new M.Tensor({location:"gpu-buffer",gpuBuffer:Me.gpuBuffer,type:Me.type,dims:xe});default:throw new Error(`tensorReshape: tensor location ${Me.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{Tensor:()=>K});var M=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const K=M.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{TRACE:()=>K,TRACE_FUNC_BEGIN:()=>Me,TRACE_FUNC_END:()=>xe});var M=l("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const K=(D,x)=>{(typeof M.env.trace>"u"?!M.env.wasm.trace:!M.env.trace)||console.timeStamp(`${D}::ORT::${x}`)},ge=(D,x)=>{var J;const V=((J=new Error().stack)==null?void 0:J.split(/\r\n|\r|\n/g))||[];let P=!1;for(let te=0;te{(typeof M.env.trace>"u"?!M.env.wasm.trace:!M.env.trace)||ge("BEGIN",D)},xe=D=>{(typeof M.env.trace>"u"?!M.env.wasm.trace:!M.env.trace)||ge("END",D)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{TrainingSession:()=>Me});var M=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),K=l("./node_modules/onnxruntime-common/dist/esm/tensor.js");const ge="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Me{constructor(D,x,V){this.handler=D,this.hasOptimizerModel=x,this.hasEvalModel=V}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(D,x){const V=D.evalModel||"",P=D.optimizerModel||"",J=x||{},[te,ne]=await(0,M.resolveBackendAndExecutionProviders)(J);if(te.createTrainingSessionHandler){const ie=await te.createTrainingSessionHandler(D.checkpointState,D.trainModel,V,P,ne);return new Me(ie,!!D.optimizerModel,!!D.evalModel)}else throw new Error(ge)}typeNarrowingForRunStep(D,x,V,P,J){const te={};let ne={};if(typeof V!="object"||V===null||V instanceof K.Tensor||Array.isArray(V))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ie=!0;if(typeof P=="object"){if(P===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(P instanceof K.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.");ie=!1;for(const R of P){if(typeof R!="string")throw new TypeError("'fetches' must be a string array or an object.");if(x.indexOf(R)===-1)throw new RangeError(`'fetches' contains invalid output name: ${R}.`);te[R]=null}if(typeof J=="object"&&J!==null)ne=J;else if(typeof J<"u")throw new TypeError("'options' must be an object.")}else{let R=!1;const Z=Object.getOwnPropertyNames(P);for(const se of x)if(Z.indexOf(se)!==-1){const ue=P[se];(ue===null||ue instanceof K.Tensor)&&(R=!0,ie=!1,te[se]=ue)}if(R){if(typeof J=="object"&&J!==null)ne=J;else if(typeof J<"u")throw new TypeError("'options' must be an object.")}else ne=P}}else if(typeof P<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const R of D)if(typeof V[R]>"u")throw new Error(`input '${R}' is missing in 'feeds'.`);if(ie)for(const R of x)te[R]=null;return[te,ne]}convertHandlerReturnTypeToMapOfTensors(D){const x={};for(const V in D)if(Object.hasOwnProperty.call(D,V)){const P=D[V];P instanceof K.Tensor?x[V]=P:x[V]=new K.Tensor(P.type,P.data,P.dims)}return x}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(D,x,V){const[P,J]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,D,x,V),te=await this.handler.runTrainStep(D,P,J);return this.convertHandlerReturnTypeToMapOfTensors(te)}async runOptimizerStep(D){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(D||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(D,x,V){if(this.hasEvalModel){const[P,J]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,D,x,V),te=await this.handler.runEvalStep(D,P,J);return this.convertHandlerReturnTypeToMapOfTensors(te)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(D=!0){return this.handler.getParametersSize(D)}async loadParametersBuffer(D,x=!0){const V=await this.getParametersSize(x);if(D.length!==4*V)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(D,x)}async getContiguousParameters(D=!0){return this.handler.getContiguousParameters(D)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{TrainingSession:()=>K});var M=l("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const K=M.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{version:()=>M});const M="1.19.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(bt,fe,l)=>{l.r(fe),l.d(fe,{InferenceSession:()=>gt,TRACE:()=>Ce,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>je,Tensor:()=>ze,TrainingSession:()=>Pt,default:()=>yf,env:()=>A,registerBackend:()=>ne});/*! * ONNX Runtime Web v1.20.0-dev.20240821-009209e016 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var M=Object.defineProperty,K=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyNames,Me=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')}),D=(e,t)=>()=>(e&&(t=e(e=0)),t),x=(e,t)=>{for(var r in t)M(e,r,{get:t[r],enumerable:!0})},V=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ge(t))!Me.call(e,s)&&s!==r&&M(e,s,{get:()=>t[s],enumerable:!(n=K(t,s))||n.enumerable});return e},P=e=>V(M({},"__esModule",{value:!0}),e),J,te,ne,ie,R,Z=D(()=>{J=new Map,te=[],ne=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=J.get(e);if(n===void 0)J.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=te.indexOf(e);s!==-1&&te.splice(s,1);for(let a=0;a{let t=J.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}}},R=async e=>{let t=e.executionProviders||[],r=t.map(c=>typeof c=="string"?c:c.name),n=r.length===0?te:r,s,a=[],i=new Set;for(let c of n){let p=await ie(c);typeof p=="string"?a.push({name:c,err:p}):(s||(s=p),s===p&&i.add(c))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(c=>`[${c.name}] ${c.err}`).join(", ")}`);for(let{name:c,err:p}of a)r.includes(c)&&console.warn(`removing requested execution provider "${c}" from session options because it is not available: ${p}`);let d=t.filter(c=>i.has(typeof c=="string"?c:c.name));return[s,new Proxy(e,{get:(c,p)=>p==="executionProviders"?d:Reflect.get(c,p)})]}}),se=D(()=>{Z()}),ue,ae=D(()=>{ue="1.20.0-dev.20240816-b2d603abda"}),N,F,B=D(()=>{ae(),N="warning",F={wasm:{},webgl:{},webgpu:{},versions:{common:ue},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}`);N=e}},get logLevel(){return N}},Object.defineProperty(F,"logLevel",{enumerable:!0})}),A,_e=D(()=>{B(),A=F}),ye,$e,Se=D(()=>{ye=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,c,p;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],0],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?p=[0,0,0,0]:typeof d.bias=="number"?p=[d.bias,d.bias,d.bias,d.bias]:(p=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(p[3]=d.bias[3]));let w=a*s,y=0,u=w,$=w*2,T=-1;i==="RGBA"?(y=0,u=w,$=w*2,T=w*3):i==="RGB"?(y=0,u=w,$=w*2):i==="RBG"&&(y=0,$=w,u=w*2);for(let I=0;I{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",c=t==null?void 0:t.norm,p,w;c===void 0||c.mean===void 0?p=[255,255,255,255]:typeof c.mean=="number"?p=[c.mean,c.mean,c.mean,c.mean]:(p=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(p[3]=c.mean[3])),c===void 0||c.bias===void 0?w=[0,0,0,0]:typeof c.bias=="number"?w=[c.bias,c.bias,c.bias,c.bias]:(w=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(w[3]=c.bias[3]));let y=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,$=0,T=1,I=2,j=3,G=0,L=y,le=y*2,q=-1;d==="RGBA"?(G=0,L=y,le=y*2,q=y*3):d==="RGB"?(G=0,L=y,le=y*2):d==="RBG"&&(G=0,le=y,L=y*2),n=r.createImageData(s,a);for(let oe=0;oe{xt(),Fe=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*n,w=c==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),y=4,u=0,$=1,T=2,I=3,j=0,G=p,L=p*2,le=-1;d==="RGB"&&(y=3,u=0,$=1,T=2,I=-1),c==="RGBA"?le=p*3:c==="RBG"?(j=0,L=p,G=p*2):c==="BGR"&&(L=0,G=p,j=p*2);for(let q=0;q{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,d=t??{},c=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=w=>w instanceof HTMLCanvasElement||w instanceof OffscreenCanvas?w.getContext("2d"):null;if(r){let w=c();w.width=e.width,w.height=e.height;let y=p(w);if(y!=null){let u=e.height,$=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(u=t.resizedHeight,$=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=u,d.width=$}else d.tensorFormat="RGBA",d.height=u,d.width=$;y.drawImage(e,0,0),i=y.getImageData(0,0,$,u).data}else throw new Error("Can not access image data")}else if(n){let w,y;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(w=t.resizedHeight,y=t.resizedWidth):(w=e.height,y=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=w,d.width=y,t!==void 0){let u=c();u.width=y,u.height=w;let $=p(u);if($!=null)$.putImageData(e,0,0),i=$.getImageData(0,0,y,w).data;else throw new Error("Can not access image data")}else i=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let w=c();w.width=e.width,w.height=e.height;let y=p(w);if(y!=null){let u=e.height,$=e.width;return y.drawImage(e,0,0,$,u),i=y.getImageData(0,0,$,u).data,d.height=u,d.width=$,Fe(i,d)}else throw new Error("Can not access image data")}else{if(a)return new Promise((w,y)=>{let u=c(),$=p(u);if(!e||!$)return y();let T=new Image;T.crossOrigin="Anonymous",T.src=e,T.onload=()=>{u.width=T.width,u.height=T.height,$.drawImage(T,0,0,u.width,u.height);let I=$.getImageData(0,0,u.width,u.height);d.height=u.height,d.width=u.width,w(Fe(I.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Fe(i,d);throw new Error("Input data provided is not supported - aborted tensor creation")},Xe=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new st({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},ct=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new st({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},we=(e,t,r)=>new st({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),pe,ke,ee,Ge,dt=D(()=>{pe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ke=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ee=!1,Ge=()=>{if(!ee){ee=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(pe.set("int64",BigInt64Array),ke.set(BigInt64Array,"int64")),t&&(pe.set("uint64",BigUint64Array),ke.set(BigUint64Array,"uint64")),r?(pe.set("float16",Float16Array),ke.set(Float16Array,"float16")):pe.set("float16",Uint16Array)}}}),tt,ot,Le=D(()=>{xt(),tt=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new st(e.type,e.data,t);case"cpu-pinned":return new st({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new st({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new st({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),st,xt=D(()=>{Se(),U(),dt(),Le(),st=class{constructor(e,t,r){Ge();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let i=pe.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,d;if(typeof e=="string")if(n=e,d=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let c=pe.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(t,BigInt):i=c.from(t)}else if(t instanceof c)i=t;else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else{let c=ke.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(d===void 0)d=[i.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");s=d,this.cpuData=i,this.dataLocation="cpu"}let a=tt(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return et(e,t)}static fromTexture(e,t){return Xe(e,t)}static fromGpuBuffer(e,t){return ct(e,t)}static fromPinnedBuffer(e,t,r){return we(e,t,r)}toDataURL(e){return ye(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}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return ot(this,e)}}}),ze,re=D(()=>{xt(),ze=st}),Ce,Ve,Ue,je,qe=D(()=>{B(),Ce=(e,t)=>{(typeof F.trace>"u"?!F.wasm.trace:!F.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ve=(e,t)=>{var s;let r=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof F.trace>"u"?!F.wasm.trace:!F.trace)||Ve("BEGIN",e)},je=e=>{(typeof F.trace>"u"?!F.wasm.trace:!F.trace)||Ve("END",e)}}),lt,ft=D(()=>{Z(),re(),qe(),lt=class Gh{constructor(t){this.handler=t}async run(t,r,n){Ue();let s={},a={};if(typeof t!="object"||t===null||t instanceof ze||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ze)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let p of r){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);s[p]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,w=Object.getOwnPropertyNames(r);for(let y of this.outputNames)if(w.indexOf(y)!==-1){let u=r[y];(u===null||u instanceof ze)&&(p=!0,i=!1,s[y]=u)}if(p){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(i)for(let p of this.outputNames)s[p]=null;let d=await this.handler.run(t,s,a),c={};for(let p in d)if(Object.hasOwnProperty.call(d,p)){let w=d[p];w instanceof ze?c[p]=w:c[p]=new ze(w.type,w.data,w.dims)}return je(),c}async release(){return this.handler.dispose()}static async create(t,r,n,s){Ue();let a,i={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let w=t,y=0,u=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(y=r,!Number.isSafeInteger(y))throw new RangeError("'byteOffset' must be an integer.");if(y<0||y>=w.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${w.byteLength}).`);if(u=t.byteLength-y,typeof n=="number"){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||y+u>w.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${w.byteLength-y}].`);if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(w,y,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,c]=await R(i),p=await d.createInferenceSessionHandler(a,c);return je(),new Gh(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),gt,Mt=D(()=>{ft(),gt=lt}),v=D(()=>{}),W=D(()=>{}),S=D(()=>{}),Q=D(()=>{}),he,Ye,Je=D(()=>{Z(),re(),he="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Ye=class qh{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let n=t.evalModel||"",s=t.optimizerModel||"",a=r||{},[i,d]=await R(a);if(i.createTrainingSessionHandler){let c=await i.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,s,d);return new qh(c,!!t.optimizerModel,!!t.evalModel)}else throw new Error(he)}typeNarrowingForRunStep(t,r,n,s,a){let i={},d={};if(typeof n!="object"||n===null||n instanceof ze||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let c=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof ze)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");c=!1;for(let p of s){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);i[p]=null}if(typeof a=="object"&&a!==null)d=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,w=Object.getOwnPropertyNames(s);for(let y of r)if(w.indexOf(y)!==-1){let u=s[y];(u===null||u instanceof ze)&&(p=!0,c=!1,i[y]=u)}if(p){if(typeof a=="object"&&a!==null)d=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else d=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of t)if(typeof n[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(c)for(let p of r)i[p]=null;return[i,d]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let s=t[n];s instanceof ze?r[n]=s:r[n]=new ze(s.type,s.data,s.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[s,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),i=await this.handler.runTrainStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[s,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),i=await this.handler.runEvalStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),Pt,mt=D(()=>{Je(),Pt=Ye}),Ee={};x(Ee,{InferenceSession:()=>gt,TRACE:()=>Ce,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>je,Tensor:()=>ze,TrainingSession:()=>Pt,env:()=>A,registerBackend:()=>ne});var k=D(()=>{se(),_e(),Mt(),re(),v(),W(),qe(),S(),Q(),mt()}),H=D(()=>{}),be={};x(be,{default:()=>Re});var Be,Ie,Re,ut=D(()=>{var e;fp(),Xr(),Vr(),Be="ort-wasm-proxy-worker",Ie=((e=globalThis.self)==null?void 0:e.name)===Be,Ie&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":An(n.wasm).then(()=>{Id(n).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:a}=n;Fd(a,s).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})});break}case"copy-from":{let{buffer:s}=n,a=ad(s);postMessage({type:r,out:a});break}case"create":{let{model:s,options:a}=n;Od(s,a).then(i=>{postMessage({type:r,out:i})},i=>{postMessage({type:r,err:i})});break}case"release":zd(n),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:a,inputs:i,outputIndices:d,options:c}=n;Bd(s,a,i,d,new Array(d.length).fill(null),c).then(p=>{p.some(w=>w[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:p},Rd([...i,...p]))},p=>{postMessage({type:r,err:p})});break}case"end-profiling":Ld(n),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),Re=Ie?null:t=>new Worker(t??He,{type:"module",name:Be})}),nt={};x(nt,{default:()=>Tt});var vt,pt,Tt,Lt=D(()=>{var e;pt=(vt=self.location.href,async function(t={}){function r(){return Mr.buffer!=Jt.buffer&&un(),Jt}function n(){return Mr.buffer!=Jt.buffer&&un(),Zt}function s(){return Mr.buffer!=Jt.buffer&&un(),Qe}function a(){return Mr.buffer!=Jt.buffer&&un(),Ft}function i(){return Mr.buffer!=Jt.buffer&&un(),rr}function d(){return Mr.buffer!=Jt.buffer&&un(),Rr}function c(){return Mr.buffer!=Jt.buffer&&un(),qr}function p(){return Mr.buffer!=Jt.buffer&&un(),ud}var w,y,u=t,$=new Promise((o,f)=>{w=o,y=f}),T=typeof window=="object",I=typeof importScripts=="function",j=I&&self.name=="em-pthread";u.mountExternalData=(o,f)=>{o.startsWith("./")&&(o=o.substring(2)),(u.Ab||(u.Ab=new Map)).set(o,f)},u.unmountExternalData=()=>{delete u.Ab};var G=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let L=()=>{let o=(b,E,z)=>(...me)=>{let We=Jn,at=E==null?void 0:E();me=b(...me);let Et=E==null?void 0:E();return at!==Et&&(b=Et,z(at),E=z=null),Jn!=We?new Promise((Bt,ar)=>{rc={resolve:Bt,reject:ar}}):me},f=b=>async(...E)=>{var z;try{if(u.zb)throw Error("Session already started");let me=u.zb={Ub:E[0],errors:[]},We=await b(...E);if(u.zb!==me)throw Error("Session mismatch");(z=u.Eb)==null||z.flush();let at=me.errors;if(0Bt),0u._OrtCreateSession,b=>u._OrtCreateSession=b),u._OrtRun=f(o(u._OrtRun,()=>u._OrtRun,b=>u._OrtRun=b)),u._OrtRunWithBinding=f(o(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,b=>u._OrtRunWithBinding=b)),u._OrtBindInput=o(u._OrtBindInput,()=>u._OrtBindInput,b=>u._OrtBindInput=b),L=void 0};u.jsepInit=(o,f)=>{if(L==null||L(),o==="webgpu"){[u.Eb,u.Lb,u.Pb,u.Fb,u.Ob,u.hb,u.Qb,u.Sb,u.Mb,u.Nb,u.Rb]=f;let b=u.Eb;u.jsepRegisterBuffer=(E,z,me,We)=>b.registerBuffer(E,z,me,We),u.jsepGetBuffer=E=>b.getBuffer(E),u.jsepCreateDownloader=(E,z,me)=>b.createDownloader(E,z,me),u.jsepOnReleaseSession=E=>{b.onReleaseSession(E)},u.jsepOnRunStart=E=>b.onRunStart(E)}};var le,q,oe=Object.assign({},u),Ke="./this.program",Ae=(o,f)=>{throw f},ht="";(T||I)&&(I?ht=self.location.href:typeof document<"u"&&document.currentScript&&(ht=document.currentScript.src),vt&&(ht=vt),ht=ht.startsWith("blob:")?"":ht.substr(0,ht.replace(/[?#].*/,"").lastIndexOf("/")+1),I&&(q=o=>{var f=new XMLHttpRequest;return f.open("GET",o,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),le=o=>Ap(o)?new Promise((f,b)=>{var E=new XMLHttpRequest;E.open("GET",o,!0),E.responseType="arraybuffer",E.onload=()=>{(E.status==200||E.status==0&&E.response)&&b(E.response),f(E.status)},E.onerror=f,E.send(null)}):fetch(o,{credentials:"same-origin"}).then(f=>f.ok?f.arrayBuffer():Promise.reject(Error(f.status+" : "+f.url))));var It,zt=console.log.bind(console),cr=console.error.bind(console),ir=zt,tr=cr;if(Object.assign(u,oe),oe=null,j){let o=function(f){try{var b=f.data,E=b.cmd;if(E==="load"){let z=[];self.onmessage=me=>z.push(me),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let me of z)o(me);self.onmessage=o};for(let me of b.handlers)u[me]&&!u[me].proxy||(u[me]=(...We)=>{postMessage({Db:"callHandler",Yb:me,args:We})},me=="print"&&(ir=u[me]),me=="printErr"&&(tr=u[me]));Mr=b.wasmMemory,un(),mr(b.wasmModule)}else if(E==="run"){ac(b.pthread_ptr,0,0,1,0,0),Jd(b.pthread_ptr),Mf(),Rp(),Lr||(Oh(),Lr=!0);try{xf(b.start_routine,b.arg)}catch(z){if(z!="unwind")throw z}}else E==="cancel"?ka()&&vd(-1):b.target!=="setimmediate"&&(E==="checkMailbox"?Lr&&pd():E&&(tr(`worker: received unknown command ${E}`),tr(b)))}catch(z){throw zh(),z}};var mr,Lr=!1;tr=function(...f){f=f.join(" "),console.error(f)},self.alert=function(...f){postMessage({Db:"alert",text:f.join(" "),$b:ka()})},u.instantiateWasm=(f,b)=>new Promise(E=>{mr=z=>{z=new WebAssembly.Instance(z,Op()),b(z),E()}}),self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=o}u.wasmBinary&&(It=u.wasmBinary);var Mr,zr,At,Jt,Zt,Qe,Ft,rr,Rr,qr,rn,Mn,ud,Pn=!1;function un(){var o=Mr.buffer;u.HEAP8=Jt=new Int8Array(o),u.HEAP16=Qe=new Int16Array(o),u.HEAPU8=Zt=new Uint8Array(o),u.HEAPU16=Ft=new Uint16Array(o),u.HEAP32=rr=new Int32Array(o),u.HEAPU32=Rr=new Uint32Array(o),u.HEAPF32=qr=new Float32Array(o),u.HEAPF64=ud=new Float64Array(o),u.HEAP64=rn=new BigInt64Array(o),u.HEAPU64=Mn=new BigUint64Array(o)}if(!j){if(!((Mr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof G))throw tr("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");un()}var Eu=[],dn=[],xn=[],Ln=0,Fs=null;function dd(){if(--Ln==0&&Fs){var o=Fs;Fs=null,o()}}function Ta(o){throw tr(o="Aborted("+o+")"),Pn=!0,At=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),y(o),o}var jd,Pp=o=>o.startsWith("data:application/octet-stream;base64,"),Ap=o=>o.startsWith("file://");function Ip(o){if(o==jd&&It)return new Uint8Array(It);if(q)return q(o);throw"both async and sync fetching of the wasm failed"}function Fp(o,f,b){return function(E){return It?Promise.resolve().then(()=>Ip(E)):le(E).then(z=>new Uint8Array(z),()=>Ip(E))}(o).then(E=>WebAssembly.instantiate(E,f)).then(b,E=>{tr(`failed to asynchronously prepare wasm: ${E}`),Ta(E)})}function Op(){return{a:{L:vf,xa:bf,b:$f,Z:Up,y:qp,na:Hp,V:Xp,X:Qp,oa:Yp,la:Zp,ea:Jp,ka:eh,I:th,W:rh,T:nh,ma:sh,U:ih,sa:kf,B:Cf,O:Ef,N:Pf,A:If,r:Ff,p:Of,C:zf,x:jf,P:Uf,ra:Wf,ha:Gf,R:qf,_:Hf,E:Kf,ga:Jd,qa:Xf,t:Qf,D:Jf,o:em,m:rm,c:Yd,n:nm,k:am,ya:om,q:lm,g:um,u:dm,l:cm,f:pm,i:hm,j:fm,h:mm,e:_m,ba:gm,ca:wm,da:ym,$:bh,aa:vh,ua:bm,d:vm,M:Mm,F:xm,J:Tm,v:$m,pa:km,S:Cm,s:xh,w:Em,K:Sm,Q:Pm,wa:Am,va:Im,ia:kh,ja:Ch,Y:Hd,z:Eh,H:Sh,fa:Ph,G:Ah,a:Mr,ta:qd}}}var Ud={858772:(o,f,b,E)=>{if(u===void 0||!u.Ab)return 1;if((o=mn(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=u.Ab.get(o)))return 2;if(E>>>=0,(f>>>=0)+(b>>>=0)>o.byteLength)return 3;try{return n().set(o.subarray(f,f+b),E>>>0),0}catch{return 4}},859273:()=>{u.Mb()},859304:()=>{u.Nb()},859333:()=>{u.Rb()},859358:o=>u.Lb(o),859391:o=>u.Pb(o),859423:(o,f,b)=>{u.Fb(o,f,b,!0)},859462:(o,f,b)=>{u.Fb(o,f,b)},859495:()=>typeof wasmOffsetConverter<"u",859552:o=>{u.hb("Abs",o,void 0)},859603:o=>{u.hb("Neg",o,void 0)},859654:o=>{u.hb("Floor",o,void 0)},859707:o=>{u.hb("Ceil",o,void 0)},859759:o=>{u.hb("Reciprocal",o,void 0)},859817:o=>{u.hb("Sqrt",o,void 0)},859869:o=>{u.hb("Exp",o,void 0)},859920:o=>{u.hb("Erf",o,void 0)},859971:o=>{u.hb("Sigmoid",o,void 0)},860026:(o,f,b)=>{u.hb("HardSigmoid",o,{alpha:f,beta:b})},860105:o=>{u.hb("Log",o,void 0)},860156:o=>{u.hb("Sin",o,void 0)},860207:o=>{u.hb("Cos",o,void 0)},860258:o=>{u.hb("Tan",o,void 0)},860309:o=>{u.hb("Asin",o,void 0)},860361:o=>{u.hb("Acos",o,void 0)},860413:o=>{u.hb("Atan",o,void 0)},860465:o=>{u.hb("Sinh",o,void 0)},860517:o=>{u.hb("Cosh",o,void 0)},860569:o=>{u.hb("Asinh",o,void 0)},860622:o=>{u.hb("Acosh",o,void 0)},860675:o=>{u.hb("Atanh",o,void 0)},860728:o=>{u.hb("Tanh",o,void 0)},860780:o=>{u.hb("Not",o,void 0)},860831:(o,f,b)=>{u.hb("Clip",o,{min:f,max:b})},860900:o=>{u.hb("Clip",o,void 0)},860952:(o,f)=>{u.hb("Elu",o,{alpha:f})},861010:o=>{u.hb("Gelu",o,void 0)},861062:o=>{u.hb("Relu",o,void 0)},861114:(o,f)=>{u.hb("LeakyRelu",o,{alpha:f})},861178:(o,f)=>{u.hb("ThresholdedRelu",o,{alpha:f})},861248:(o,f)=>{u.hb("Cast",o,{to:f})},861306:o=>{u.hb("Add",o,void 0)},861357:o=>{u.hb("Sub",o,void 0)},861408:o=>{u.hb("Mul",o,void 0)},861459:o=>{u.hb("Div",o,void 0)},861510:o=>{u.hb("Pow",o,void 0)},861561:o=>{u.hb("Equal",o,void 0)},861614:o=>{u.hb("Greater",o,void 0)},861669:o=>{u.hb("GreaterOrEqual",o,void 0)},861731:o=>{u.hb("Less",o,void 0)},861783:o=>{u.hb("LessOrEqual",o,void 0)},861842:(o,f,b,E,z)=>{u.hb("ReduceMean",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},862001:(o,f,b,E,z)=>{u.hb("ReduceMax",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},862159:(o,f,b,E,z)=>{u.hb("ReduceMin",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},862317:(o,f,b,E,z)=>{u.hb("ReduceProd",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},862476:(o,f,b,E,z)=>{u.hb("ReduceSum",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},862634:(o,f,b,E,z)=>{u.hb("ReduceL1",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},862791:(o,f,b,E,z)=>{u.hb("ReduceL2",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},862948:(o,f,b,E,z)=>{u.hb("ReduceLogSum",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},863109:(o,f,b,E,z)=>{u.hb("ReduceSumSquare",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},863273:(o,f,b,E,z)=>{u.hb("ReduceLogSumExp",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},863437:o=>{u.hb("Where",o,void 0)},863490:(o,f,b)=>{u.hb("Transpose",o,{perm:f?Array.from(i().subarray(f>>>0,b>>>0)):[]})},863598:(o,f,b,E)=>{u.hb("DepthToSpace",o,{blocksize:f,mode:mn(b),format:E?"NHWC":"NCHW"})},863731:(o,f,b,E)=>{u.hb("DepthToSpace",o,{blocksize:f,mode:mn(b),format:E?"NHWC":"NCHW"})},863864:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn,Ca)=>{u.hb("ConvTranspose",o,{format:Et?"NHWC":"NCHW",autoPad:f,dilations:[b],group:E,kernelShape:[z],pads:[me,We],strides:[at],wIsConst:()=>!!r()[Bt>>>0],outputPadding:ar?Array.from(i().subarray(ar>>>0,Cr>>>0)):[],outputShape:Ir?Array.from(i().subarray(Ir>>>0,cn>>>0)):[],activation:mn(Ca)})},864265:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn)=>{u.hb("ConvTranspose",o,{format:at?"NHWC":"NCHW",autoPad:f,dilations:Array.from(i().subarray(b>>>0,2+(b>>>0)>>>0)),group:E,kernelShape:Array.from(i().subarray(z>>>0,2+(z>>>0)>>>0)),pads:Array.from(i().subarray(me>>>0,4+(me>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[Et>>>0],outputPadding:Bt?Array.from(i().subarray(Bt>>>0,ar>>>0)):[],outputShape:Cr?Array.from(i().subarray(Cr>>>0,Ir>>>0)):[],activation:mn(cn)})},864830:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn,Ca)=>{u.hb("ConvTranspose",o,{format:Et?"NHWC":"NCHW",autoPad:f,dilations:[b],group:E,kernelShape:[z],pads:[me,We],strides:[at],wIsConst:()=>!!r()[Bt>>>0],outputPadding:ar?Array.from(i().subarray(ar>>>0,Cr>>>0)):[],outputShape:Ir?Array.from(i().subarray(Ir>>>0,cn>>>0)):[],activation:mn(Ca)})},865231:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn)=>{u.hb("ConvTranspose",o,{format:at?"NHWC":"NCHW",autoPad:f,dilations:Array.from(i().subarray(b>>>0,2+(b>>>0)>>>0)),group:E,kernelShape:Array.from(i().subarray(z>>>0,2+(z>>>0)>>>0)),pads:Array.from(i().subarray(me>>>0,4+(me>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[Et>>>0],outputPadding:Bt?Array.from(i().subarray(Bt>>>0,ar>>>0)):[],outputShape:Cr?Array.from(i().subarray(Cr>>>0,Ir>>>0)):[],activation:mn(cn)})},865796:(o,f)=>{u.hb("GlobalAveragePool",o,{format:f?"NHWC":"NCHW"})},865887:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn)=>{u.hb("AveragePool",o,{format:cn?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:E,storage_order:z,dilations:me?Array.from(i().subarray(me>>>0,We>>>0)):[],kernel_shape:at?Array.from(i().subarray(at>>>0,Et>>>0)):[],pads:Bt?Array.from(i().subarray(Bt>>>0,ar>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Ir>>>0)):[]})},866302:(o,f)=>{u.hb("GlobalAveragePool",o,{format:f?"NHWC":"NCHW"})},866393:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn)=>{u.hb("AveragePool",o,{format:cn?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:E,storage_order:z,dilations:me?Array.from(i().subarray(me>>>0,We>>>0)):[],kernel_shape:at?Array.from(i().subarray(at>>>0,Et>>>0)):[],pads:Bt?Array.from(i().subarray(Bt>>>0,ar>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Ir>>>0)):[]})},866808:(o,f)=>{u.hb("GlobalMaxPool",o,{format:f?"NHWC":"NCHW"})},866895:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn)=>{u.hb("MaxPool",o,{format:cn?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:E,storage_order:z,dilations:me?Array.from(i().subarray(me>>>0,We>>>0)):[],kernel_shape:at?Array.from(i().subarray(at>>>0,Et>>>0)):[],pads:Bt?Array.from(i().subarray(Bt>>>0,ar>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Ir>>>0)):[]})},867306:(o,f)=>{u.hb("GlobalMaxPool",o,{format:f?"NHWC":"NCHW"})},867393:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn)=>{u.hb("MaxPool",o,{format:cn?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:E,storage_order:z,dilations:me?Array.from(i().subarray(me>>>0,We>>>0)):[],kernel_shape:at?Array.from(i().subarray(at>>>0,Et>>>0)):[],pads:Bt?Array.from(i().subarray(Bt>>>0,ar>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Ir>>>0)):[]})},867804:(o,f,b,E,z)=>{u.hb("Gemm",o,{alpha:f,beta:b,transA:E,transB:z})},867908:o=>{u.hb("MatMul",o,void 0)},867962:(o,f,b,E)=>{u.hb("ArgMax",o,{keepDims:!!f,selectLastIndex:!!b,axis:E})},868070:(o,f,b,E)=>{u.hb("ArgMin",o,{keepDims:!!f,selectLastIndex:!!b,axis:E})},868178:(o,f)=>{u.hb("Softmax",o,{axis:f})},868241:(o,f)=>{u.hb("Concat",o,{axis:f})},868301:(o,f,b,E,z)=>{u.hb("Split",o,{axis:f,numOutputs:b,splitSizes:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},868441:o=>{u.hb("Expand",o,void 0)},868495:(o,f)=>{u.hb("Gather",o,{axis:Number(f)})},868566:(o,f)=>{u.hb("GatherElements",o,{axis:Number(f)})},868645:(o,f,b,E,z,me,We,at,Et,Bt,ar)=>{u.hb("Resize",o,{antialias:f,axes:b?Array.from(i().subarray(b>>>0,E>>>0)):[],coordinateTransformMode:mn(z),cubicCoeffA:me,excludeOutside:We,extrapolationValue:at,keepAspectRatioPolicy:mn(Et),mode:mn(Bt),nearestMode:mn(ar)})},868991:(o,f,b,E,z,me,We)=>{u.hb("Slice",o,{starts:f?Array.from(i().subarray(f>>>0,b>>>0)):[],ends:E?Array.from(i().subarray(E>>>0,z>>>0)):[],axes:me?Array.from(i().subarray(me>>>0,We>>>0)):[]})},869207:o=>{u.hb("Tile",o,void 0)},869259:(o,f,b)=>{u.hb("InstanceNormalization",o,{epsilon:f,format:b?"NHWC":"NCHW"})},869373:(o,f,b)=>{u.hb("InstanceNormalization",o,{epsilon:f,format:b?"NHWC":"NCHW"})},869487:o=>{u.hb("Range",o,void 0)},869540:(o,f)=>{u.hb("Einsum",o,{equation:mn(f)})},869621:(o,f,b,E,z)=>{u.hb("Pad",o,{mode:f,value:b,pads:E?Array.from(i().subarray(E>>>0,z>>>0)):[]})},869748:(o,f,b,E,z,me)=>{u.hb("BatchNormalization",o,{epsilon:f,momentum:b,spatial:!!z,trainingMode:!!E,format:me?"NHWC":"NCHW"})},869917:(o,f,b,E,z,me)=>{u.hb("BatchNormalization",o,{epsilon:f,momentum:b,spatial:!!z,trainingMode:!!E,format:me?"NHWC":"NCHW"})},870086:(o,f,b)=>{u.hb("CumSum",o,{exclusive:Number(f),reverse:Number(b)})},870183:(o,f,b)=>{u.hb("DequantizeLinear",o,{axis:f,blockSize:b})},870273:(o,f,b,E,z,me,We,at,Et)=>{u.hb("Attention",o,{numHeads:f,isUnidirectional:b,maskFilterValue:E,scale:z,doRotary:me,qkvHiddenSizes:We?Array.from(i().subarray(Number(at)>>>0,Number(at)+We>>>0)):[],pastPresentShareBuffer:!!Et})},870545:o=>{u.hb("BiasAdd",o,void 0)},870600:o=>{u.hb("BiasSplitGelu",o,void 0)},870661:o=>{u.hb("FastGelu",o,void 0)},870717:(o,f,b,E,z,me,We,at,Et,Bt,ar,Cr,Ir,cn,Ca,zm)=>{u.hb("Conv",o,{format:Cr?"NHWC":"NCHW",auto_pad:f,dilations:b?Array.from(i().subarray(b>>>0,E>>>0)):[],group:z,kernel_shape:me?Array.from(i().subarray(me>>>0,We>>>0)):[],pads:at?Array.from(i().subarray(at>>>0,Et>>>0)):[],strides:Bt?Array.from(i().subarray(Bt>>>0,ar>>>0)):[],w_is_const:()=>!!r()[Ir>>>0],activation:mn(cn),activation_params:Ca?Array.from(c().subarray(Ca>>>0,zm>>>0)):[]})},871213:o=>{u.hb("Gelu",o,void 0)},871265:(o,f,b,E)=>{u.hb("GroupQueryAttention",o,{numHeads:f,kvNumHeads:b,scale:E})},871378:(o,f,b,E)=>{u.hb("LayerNormalization",o,{axis:f,epsilon:b,simplified:!!E})},871489:(o,f,b,E)=>{u.hb("LayerNormalization",o,{axis:f,epsilon:b,simplified:!!E})},871600:(o,f,b,E,z,me)=>{u.hb("MatMulNBits",o,{k:f,n:b,accuracyLevel:E,bits:z,blockSize:me})},871727:(o,f,b,E,z,me)=>{u.hb("MultiHeadAttention",o,{numHeads:f,isUnidirectional:b,maskFilterValue:E,scale:z,doRotary:me})},871886:(o,f)=>{u.hb("QuickGelu",o,{alpha:f})},871950:(o,f,b,E,z)=>{u.hb("RotaryEmbedding",o,{interleaved:!!f,numHeads:b,rotaryEmbeddingDim:E,scale:z})},872089:(o,f,b)=>{u.hb("SkipLayerNormalization",o,{epsilon:f,simplified:!!b})},872191:o=>{u.Qb(o)},872225:(o,f)=>u.Sb(o,f,u.zb.Ub,u.zb.errors),872337:(o,f,b)=>{u.hb("SkipLayerNormalization",o,{epsilon:f,simplified:!!b})}};function bf(o,f,b){return fh(async()=>{await u.Ob(o,f,b)})}function vf(){return typeof wasmOffsetConverter<"u"}function Wd(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var Gd=o=>{o.terminate(),o.onmessage=()=>{}},zp=o=>{Os.length==0&&(Vp(),Np(Os[0]));var f=Os.pop();if(!f)return 6;ui.push(f),Yn[o.sb]=f,f.sb=o.sb;var b={cmd:"run",start_routine:o.Vb,arg:o.Hb,pthread_ptr:o.sb};return f.postMessage(b,o.Wb),0},li=0,jr=(o,f,...b)=>{for(var E=2*b.length,z=uc(),me=lc(8*E),We=me>>>3,at=0;at>>0]=Et)}return o=Dh(o,0,E,me,f),Md(z),o};function qd(o){if(j)return jr(0,1,o);if(At=o,!(0{if(At=o,j)throw Dp(o),"unwind";qd(o)},Os=[],ui=[],Bp=[],Yn={},Lp=o=>{var f=o.sb;delete Yn[f],Os.push(o),ui.splice(ui.indexOf(o),1),o.sb=0,oc(f)};function Rp(){Bp.forEach(o=>o())}var Np=o=>new Promise(f=>{o.onmessage=z=>{var me=(z=z.data).cmd;if(z.targetThread&&z.targetThread!=ka()){var We=Yn[z.targetThread];We?We.postMessage(z,z.transferList):tr(`Internal error! Worker sent a message "${me}" to target pthread ${z.targetThread}, but that thread no longer exists!`)}else me==="checkMailbox"?pd():me==="spawnThread"?zp(z):me==="cleanupThread"?Lp(Yn[z.thread]):me==="killThread"?(z=z.thread,me=Yn[z],delete Yn[z],Gd(me),oc(z),ui.splice(ui.indexOf(me),1),me.sb=0):me==="cancelThread"?Yn[z.thread].postMessage({cmd:"cancel"}):me==="loaded"?(o.loaded=!0,f(o)):me==="alert"?alert(`Thread ${z.threadId}: ${z.text}`):z.target==="setimmediate"?o.postMessage(z):me==="callHandler"?u[z.handler](...z.args):me&&tr(`worker sent an unknown command ${me}`)},o.onerror=z=>{throw tr(`worker sent an error! ${z.filename}:${z.lineno}: ${z.message}`),z};var b,E=[];for(b of[])u.propertyIsEnumerable(b)&&E.push(b);o.postMessage({cmd:"load",handlers:E,wasmMemory:Mr,wasmModule:zr})});function Vp(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Os.push(o)}var cd=o=>{for(;0{var o=ka(),f=d()[o+52>>>2>>>0];o=d()[o+56>>>2>>>0],Lh(f,f-o),Md(f)},xf=(o,f)=>{li=0,o=Rh(o,f),0>>=0);throw f>>>=0,b>>>=0,d()[E.Bb+16>>>2>>>0]=0,d()[E.Bb+4>>>2>>>0]=f,d()[E.Bb+8>>>2>>>0]=b,o}function jp(o,f,b,E){return j?jr(2,1,o,f,b,E):Up(o,f,b,E)}function Up(o,f,b,E){if(o>>>=0,f>>>=0,b>>>=0,E>>>=0,G===void 0)return tr("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var z=[];return j&&z.length===0?jp(o,f,b,E):(o={Vb:b,sb:o,Hb:E,Wb:z},j?(o.Db="spawnThread",postMessage(o,z),0):zp(o))}var Wp=typeof TextDecoder<"u"?new TextDecoder:void 0,Gp=(o,f,b)=>{var E=(f>>>=0)+b;for(b=f;o[b]&&!(b>=E);)++b;if(16(z=(240&z)==224?(15&z)<<12|me<<6|We:(7&z)<<18|me<<12|We<<6|63&o[f++])?E+=String.fromCharCode(z):(z-=65536,E+=String.fromCharCode(55296|z>>10,56320|1023&z))}}else E+=String.fromCharCode(z)}return E},mn=(o,f)=>(o>>>=0)?Gp(n(),o,f):"";function qp(o,f,b){return j?jr(3,1,o,f,b):0}function Hp(o,f){if(j)return jr(4,1,o,f)}var Kp=o=>{for(var f=0,b=0;b=E?f++:2047>=E?f+=2:55296<=E&&57343>=E?(f+=4,++b):f+=3}return f},$a=(o,f,b)=>{var E=n();if(f>>>=0,0=We&&(We=65536+((1023&We)<<10)|1023&o.charCodeAt(++me)),127>=We){if(f>=b)break;E[f++>>>0]=We}else{if(2047>=We){if(f+1>=b)break;E[f++>>>0]=192|We>>6}else{if(65535>=We){if(f+2>=b)break;E[f++>>>0]=224|We>>12}else{if(f+3>=b)break;E[f++>>>0]=240|We>>18,E[f++>>>0]=128|We>>12&63}E[f++>>>0]=128|We>>6&63}E[f++>>>0]=128|63&We}}E[f>>>0]=0,o=f-z}else o=0;return o};function Xp(o,f){if(j)return jr(5,1,o,f)}function Qp(o,f,b){if(j)return jr(6,1,o,f,b)}function Yp(o,f,b){return j?jr(7,1,o,f,b):0}function Zp(o,f){if(j)return jr(8,1,o,f)}function Jp(o,f,b){if(j)return jr(9,1,o,f,b)}function eh(o,f,b,E){if(j)return jr(10,1,o,f,b,E)}function th(o,f,b,E){if(j)return jr(11,1,o,f,b,E)}function rh(o,f,b,E){if(j)return jr(12,1,o,f,b,E)}function nh(o){if(j)return jr(13,1,o)}function sh(o,f){if(j)return jr(14,1,o,f)}function ih(o,f,b){if(j)return jr(15,1,o,f,b)}var ah,zs,kf=()=>{Ta("")},Zn=o=>{for(var f="";n()[o>>>0];)f+=ah[n()[o++>>>0]];return f},Kd={},Xd={};function ps(o,f,b={}){if(!("argPackAdvance"in f))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(E,z,me={}){var We=z.name;if(!E)throw new zs(`type "${We}" must have a positive integer typeid pointer`);if(Xd.hasOwnProperty(E)){if(me.Jb)return;throw new zs(`Cannot register type '${We}' twice`)}Xd[E]=z,Kd.hasOwnProperty(E)&&(z=Kd[E],delete Kd[E],z.forEach(at=>at()))}(o,f,b)}var oh=(o,f,b)=>{switch(f){case 1:return b?E=>r()[E>>>0]:E=>n()[E>>>0];case 2:return b?E=>s()[E>>>1>>>0]:E=>a()[E>>>1>>>0];case 4:return b?E=>i()[E>>>2>>>0]:E=>d()[E>>>2>>>0];case 8:return b?E=>rn[E>>>3]:E=>Mn[E>>>3];default:throw new TypeError(`invalid integer width (${f}): ${o}`)}};function Cf(o,f,b){b>>>=0,ps(o>>>=0,{name:f=Zn(f>>>0),fromWireType:E=>E,toWireType:function(E,z){if(typeof z!="bigint"&&typeof z!="number")throw z=z===null?"null":(E=typeof z)=="object"||E==="array"||E==="function"?z.toString():""+z,new TypeError(`Cannot convert "${z}" to ${this.name}`);return typeof z=="number"&&(z=BigInt(z)),z},argPackAdvance:Ds,readValueFromPointer:oh(f,b,f.indexOf("u")==-1),yb:null})}var Ds=8;function Ef(o,f,b,E){ps(o>>>=0,{name:f=Zn(f>>>0),fromWireType:function(z){return!!z},toWireType:function(z,me){return me?b:E},argPackAdvance:Ds,readValueFromPointer:function(z){return this.fromWireType(n()[z>>>0])},yb:null})}var Qd=[],hs=[];function Yd(o){9<(o>>>=0)&&--hs[o+1]==0&&(hs[o]=void 0,Qd.push(o))}var Rn=o=>{if(!o)throw new zs("Cannot use deleted val. handle = "+o);return hs[o]},Nn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=Qd.pop()||hs.length;return hs[f]=o,hs[f+1]=1,f}};function Zd(o){return this.fromWireType(d()[o>>>2>>>0])}var Sf={name:"emscripten::val",fromWireType:o=>{var f=Rn(o);return Yd(o),f},toWireType:(o,f)=>Nn(f),argPackAdvance:Ds,readValueFromPointer:Zd,yb:null};function Pf(o){return ps(o>>>0,Sf)}var Af=(o,f)=>{switch(f){case 4:return function(b){return this.fromWireType(c()[b>>>2>>>0])};case 8:return function(b){return this.fromWireType(p()[b>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${o}`)}};function If(o,f,b){b>>>=0,ps(o>>>=0,{name:f=Zn(f>>>0),fromWireType:E=>E,toWireType:(E,z)=>z,argPackAdvance:Ds,readValueFromPointer:Af(f,b),yb:null})}function Ff(o,f,b,E,z){if(o>>>=0,b>>>=0,f=Zn(f>>>0),z===-1&&(z=4294967295),z=at=>at,E===0){var me=32-8*b;z=at=>at<>>me}var We=f.includes("unsigned")?function(at,Et){return Et>>>0}:function(at,Et){return Et};ps(o,{name:f,fromWireType:z,toWireType:We,argPackAdvance:Ds,readValueFromPointer:oh(f,b,E!==0),yb:null})}function Of(o,f,b){function E(me){var We=d()[me>>>2>>>0];return me=d()[me+4>>>2>>>0],new z(r().buffer,me,We)}var z=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];ps(o>>>=0,{name:b=Zn(b>>>0),fromWireType:E,argPackAdvance:Ds,readValueFromPointer:E},{Jb:!0})}function zf(o,f){o>>>=0;var b=(f=Zn(f>>>0))==="std::string";ps(o,{name:f,fromWireType:function(E){var z=d()[E>>>2>>>0],me=E+4;if(b)for(var We=me,at=0;at<=z;++at){var Et=me+at;if(at==z||n()[Et>>>0]==0){if(We=mn(We,Et-We),Bt===void 0)var Bt=We;else Bt+="\0",Bt+=We;We=Et+1}}else{for(Bt=Array(z),at=0;at>>0]);Bt=Bt.join("")}return es(E),Bt},toWireType:function(E,z){z instanceof ArrayBuffer&&(z=new Uint8Array(z));var me=typeof z=="string";if(!(me||z instanceof Uint8Array||z instanceof Uint8ClampedArray||z instanceof Int8Array))throw new zs("Cannot pass non-string to std::string");var We=b&&me?Kp(z):z.length,at=bd(4+We+1),Et=at+4;if(d()[at>>>2>>>0]=We,b&&me)$a(z,Et,We+1);else if(me)for(me=0;me>>0]=Bt}else for(me=0;me>>0]=z[me];return E!==null&&E.push(es,at),at},argPackAdvance:Ds,readValueFromPointer:Zd,yb(E){es(E)}})}var lh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Df=(o,f)=>{for(var b=o>>1,E=b+f/2;!(b>=E)&&a()[b>>>0];)++b;if(32<(b<<=1)-o&&lh)return lh.decode(n().slice(o,b));for(b="",E=0;!(E>=f/2);++E){var z=s()[o+2*E>>>1>>>0];if(z==0)break;b+=String.fromCharCode(z)}return b},Bf=(o,f,b)=>{if(b??(b=2147483647),2>b)return 0;var E=f;b=(b-=2)<2*o.length?b/2:o.length;for(var z=0;z>>1>>>0]=me,f+=2}return s()[f>>>1>>>0]=0,f-E},Lf=o=>2*o.length,Rf=(o,f)=>{for(var b=0,E="";!(b>=f/4);){var z=i()[o+4*b>>>2>>>0];if(z==0)break;++b,65536<=z?(z-=65536,E+=String.fromCharCode(55296|z>>10,56320|1023&z)):E+=String.fromCharCode(z)}return E},Nf=(o,f,b)=>{if(f>>>=0,b??(b=2147483647),4>b)return 0;var E=f;b=E+b-4;for(var z=0;z=me&&(me=65536+((1023&me)<<10)|1023&o.charCodeAt(++z)),i()[f>>>2>>>0]=me,(f+=4)+4>b)break}return i()[f>>>2>>>0]=0,f-E},Vf=o=>{for(var f=0,b=0;b=E&&++b,f+=4}return f};function jf(o,f,b){if(o>>>=0,f>>>=0,b=Zn(b>>>=0),f===2)var E=Df,z=Bf,me=Lf,We=at=>a()[at>>>1>>>0];else f===4&&(E=Rf,z=Nf,me=Vf,We=at=>d()[at>>>2>>>0]);ps(o,{name:b,fromWireType:at=>{for(var Et,Bt=d()[at>>>2>>>0],ar=at+4,Cr=0;Cr<=Bt;++Cr){var Ir=at+4+Cr*f;Cr!=Bt&&We(Ir)!=0||(ar=E(ar,Ir-ar),Et===void 0?Et=ar:(Et+="\0",Et+=ar),ar=Ir+f)}return es(at),Et},toWireType:(at,Et)=>{if(typeof Et!="string")throw new zs(`Cannot pass non-string to C++ string type ${b}`);var Bt=me(Et),ar=bd(4+Bt+f);return d()[ar>>>2>>>0]=Bt/f,z(Et,ar+4,Bt+f),at!==null&&at.push(es,ar),ar},argPackAdvance:Ds,readValueFromPointer:Zd,yb(at){es(at)}})}function Uf(o,f){ps(o>>>=0,{Kb:!0,name:f=Zn(f>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Wf=()=>1;function Gf(o){ac(o>>>0,!I,1,!T,131072,!1),Rp()}var uh=o=>{if(!Pn)try{if(o(),!(0>>=0,typeof Atomics.Xb=="function"&&(Atomics.Xb(i(),o>>>2,o).value.then(pd),o+=128,Atomics.store(i(),o>>>2,1))}var pd=()=>{var o=ka();o&&(Jd(o),uh(Bh))};function qf(o,f){(o>>>=0)==f>>>0?setTimeout(pd):j?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=Yn[o])&&o.postMessage({cmd:"checkMailbox"})}var ec=[];function Hf(o,f,b,E,z){for(f>>>=0,E/=2,ec.length=E,b=z>>>0>>>3,z=0;z>>0];return(f?Ud[f]:Om[o])(...ec)}function Kf(o){o>>>=0,j?postMessage({cmd:"cleanupThread",thread:o}):Lp(Yn[o])}function Xf(o){}var tc=(o,f)=>{var b=Xd[o];if(b===void 0)throw o=Fh(o),b=Zn(o),es(o),new zs(`${f} has unknown type ${b}`);return b},dh=(o,f,b)=>{var E=[];return o=o.toWireType(E,b),E.length&&(d()[f>>>2>>>0]=Nn(E)),o};function Qf(o,f,b){return f>>>=0,b>>>=0,o=Rn(o>>>0),f=tc(f,"emval::as"),dh(f,b,o)}var hd=o=>{try{o()}catch(f){Ta(f)}},Bs=0,Jn=null,ch=0,fd=[],ph={},hh={},Yf=0,rc=null,Zf=[];function fh(o){return function(f){if(!Pn){if(Bs===0){var b=!1,E=!1;f((z=0)=>{if(!Pn&&(ch=z,b=!0,E)){Bs=2,hd(()=>jh(Jn)),typeof Browser<"u"&&Browser.Cb.Ib&&Browser.Cb.resume(),z=!1;try{var me=function(){var Et=i()[Jn+8>>>2>>>0];return Et=Gt[hh[Et]],--li,Et()}()}catch(Et){me=Et,z=!0}var We=!1;if(!Jn){var at=rc;at&&(rc=null,(z?at.reject:at.resolve)(me),We=!0)}if(z&&!We)throw me}}),E=!0,b||(Bs=1,Jn=function(){var z=bd(65548),me=z+12;d()[z>>>2>>>0]=me,d()[z+4>>>2>>>0]=me+65536,me=fd[0];var We=ph[me];return We===void 0&&(We=Yf++,ph[me]=We,hh[We]=me),me=We,i()[z+8>>>2>>>0]=me,z}(),typeof Browser<"u"&&Browser.Cb.Ib&&Browser.Cb.pause(),hd(()=>Nh(Jn)))}else Bs===2?(Bs=0,hd(Uh),es(Jn),Jn=null,Zf.forEach(uh)):Ta(`invalid state: ${Bs}`);return ch}}(f=>{o().then(f)})}function Jf(o){return o>>>=0,fh(()=>(o=Rn(o)).then(Nn))}var md=[];function em(o,f,b,E){return b>>>=0,E>>>=0,(o=md[o>>>0])(null,f=Rn(f>>>0),b,E)}var tm={},_d=o=>{var f=tm[o];return f===void 0?Zn(o):f};function rm(o,f,b,E,z){return b>>>=0,E>>>=0,z>>>=0,(o=md[o>>>0])(f=Rn(f>>>0),f[b=_d(b)],E,z)}var mh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function nm(o){return(o>>>=0)==0?Nn(mh()):(o=_d(o),Nn(mh()[o]))}var sm=o=>{var f=md.length;return md.push(o),f},im=(o,f)=>{for(var b=Array(o),E=0;E>>2>>>0],"parameter "+E);return b},_h=(o,f)=>Object.defineProperty(f,"name",{value:o});function am(o,f,b){var E=(f=im(o,f>>>0)).shift();o--;var z=`return function (obj, func, destructorsRef, args) { `,me=0,We=[];b===0&&We.push("obj");for(var at=["retType"],Et=[E],Bt=0;Btar.name).join(", ")}) => ${E.name}>`,sm(_h(b,o))}function om(o){return o=_d(o>>>0),Nn(u[o])}function lm(o,f){return f>>>=0,o=Rn(o>>>0),f=Rn(f),Nn(o[f])}function um(o){9<(o>>>=0)&&(hs[o+1]+=1)}function dm(){return Nn([])}function cm(o){o=Rn(o>>>0);for(var f=Array(o.length),b=0;b>>0))}function hm(){return Nn({})}function fm(o){for(var f=Rn(o>>>=0);f.length;){var b=f.pop();f.pop()(b)}Yd(o)}function mm(o,f,b){f>>>=0,b>>>=0,o=Rn(o>>>0),f=Rn(f),b=Rn(b),o[f]=b}function _m(o,f){return f>>>=0,o=(o=tc(o>>>0,"_emval_take_value")).readValueFromPointer(f),Nn(o)}function gm(o,f){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[f>>>2>>>0]=o.getUTCSeconds(),i()[f+4>>>2>>>0]=o.getUTCMinutes(),i()[f+8>>>2>>>0]=o.getUTCHours(),i()[f+12>>>2>>>0]=o.getUTCDate(),i()[f+16>>>2>>>0]=o.getUTCMonth(),i()[f+20>>>2>>>0]=o.getUTCFullYear()-1900,i()[f+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[f+28>>>2>>>0]=o}var gh=o=>o%4==0&&(o%100!=0||o%400==0),wh=[0,31,60,91,121,152,182,213,244,274,305,335],yh=[0,31,59,90,120,151,181,212,243,273,304,334];function wm(o,f){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[f>>>2>>>0]=o.getSeconds(),i()[f+4>>>2>>>0]=o.getMinutes(),i()[f+8>>>2>>>0]=o.getHours(),i()[f+12>>>2>>>0]=o.getDate(),i()[f+16>>>2>>>0]=o.getMonth(),i()[f+20>>>2>>>0]=o.getFullYear()-1900,i()[f+24>>>2>>>0]=o.getDay();var b=(gh(o.getFullYear())?wh:yh)[o.getMonth()]+o.getDate()-1|0;i()[f+28>>>2>>>0]=b,i()[f+36>>>2>>>0]=-60*o.getTimezoneOffset(),b=new Date(o.getFullYear(),6,1).getTimezoneOffset();var E=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(b!=E&&o.getTimezoneOffset()==Math.min(E,b)),i()[f+32>>>2>>>0]=o}function ym(o){o>>>=0;var f=new Date(i()[o+20>>>2>>>0]+1900,i()[o+16>>>2>>>0],i()[o+12>>>2>>>0],i()[o+8>>>2>>>0],i()[o+4>>>2>>>0],i()[o>>>2>>>0],0),b=i()[o+32>>>2>>>0],E=f.getTimezoneOffset(),z=new Date(f.getFullYear(),6,1).getTimezoneOffset(),me=new Date(f.getFullYear(),0,1).getTimezoneOffset(),We=Math.min(me,z);return 0>b?i()[o+32>>>2>>>0]=+(z!=me&&We==E):0>>2>>>0]=f.getDay(),b=(gh(f.getFullYear())?wh:yh)[f.getMonth()]+f.getDate()-1|0,i()[o+28>>>2>>>0]=b,i()[o>>>2>>>0]=f.getSeconds(),i()[o+4>>>2>>>0]=f.getMinutes(),i()[o+8>>>2>>>0]=f.getHours(),i()[o+12>>>2>>>0]=f.getDate(),i()[o+16>>>2>>>0]=f.getMonth(),i()[o+20>>>2>>>0]=f.getYear(),o=f.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function bh(o,f,b,E,z,me,We){return j?jr(16,1,o,f,b,E,z,me,We):-52}function vh(o,f,b,E,z,me){if(j)return jr(17,1,o,f,b,E,z,me)}function bm(o,f,b,E){o>>>=0,f>>>=0,b>>>=0,E>>>=0;var z=new Date().getFullYear(),me=new Date(z,0,1),We=new Date(z,6,1);z=me.getTimezoneOffset();var at=We.getTimezoneOffset(),Et=Math.max(z,at);d()[o>>>2>>>0]=60*Et,i()[f>>>2>>>0]=+(z!=at),me=(o=Bt=>Bt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(me),We=o(We),at{nc.length=0;for(var b;b=n()[o++>>>0];){var E=b!=105;f+=(E&=b!=112)&&f%8?4:0,nc.push(b==112?d()[f>>>2>>>0]:b==106?rn[f>>>3]:b==105?i()[f>>>2>>>0]:p()[f>>>3>>>0]),f+=E?8:4}return nc};function vm(o,f,b){return o>>>=0,f=Mh(f>>>0,b>>>0),Ud[o](...f)}function Mm(o,f,b){return o>>>=0,f=Mh(f>>>0,b>>>0),Ud[o](...f)}var xm=()=>{},Tm=()=>Date.now();function $m(o,f){return tr(mn(o>>>0,f>>>0))}var xh,km=()=>{throw li+=1,"unwind"};function Cm(){return 4294901760}xh=()=>performance.timeOrigin+performance.now();var Em=()=>navigator.hardwareConcurrency;function Sm(){return Ta("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Pm(o){o>>>=0;var f=n().length;if(o<=f||4294901760=b;b*=2){var E=f*(1+.2/b);E=Math.min(E,o+100663296);var z=Math;E=Math.max(o,E);e:{z=(z.min.call(z,4294901760,E+(65536-E%65536)%65536)-Mr.buffer.byteLength+65535)/65536;try{Mr.grow(z),un();var me=1;break e}catch{}me=void 0}if(me)return!0}return!1}var gd=()=>(Ta("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Su={},Th=o=>{o.forEach(f=>{gd()})};function Am(){var o=Error().stack.toString().split(` `);return o[0]=="Error"&&o.shift(),Th(o),Su.Gb=gd(),Su.Tb=o,Su.Gb}function Im(o,f,b){if(o>>>=0,f>>>=0,Su.Gb==o)var E=Su.Tb;else(E=Error().stack.toString().split(` `))[0]=="Error"&&E.shift(),Th(E);for(var z=3;E[z]&&gd()!=o;)++z;for(o=0;o>>2>>>0]=gd();return o}var sc,ic={},$h=()=>{if(!sc){var o,f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:Ke};for(o in ic)ic[o]===void 0?delete f[o]:f[o]=ic[o];var b=[];for(o in f)b.push(`${o}=${f[o]}`);sc=b}return sc};function kh(o,f){if(j)return jr(18,1,o,f);o>>>=0,f>>>=0;var b=0;return $h().forEach((E,z)=>{var me=f+b;for(z=d()[o+4*z>>>2>>>0]=me,me=0;me>>0]=E.charCodeAt(me);r()[z>>>0]=0,b+=E.length+1}),0}function Ch(o,f){if(j)return jr(19,1,o,f);o>>>=0,f>>>=0;var b=$h();d()[o>>>2>>>0]=b.length;var E=0;return b.forEach(z=>E+=z.length+1),d()[f>>>2>>>0]=E,0}function Eh(o){return j?jr(20,1,o):52}function Sh(o,f,b,E){return j?jr(21,1,o,f,b,E):52}function Ph(o,f,b,E){return j?jr(22,1,o,f,b,E):70}var Fm=[null,[],[]];function Ah(o,f,b,E){if(j)return jr(23,1,o,f,b,E);f>>>=0,b>>>=0,E>>>=0;for(var z=0,me=0;me>>2>>>0],at=d()[f+4>>>2>>>0];f+=8;for(var Et=0;Et>>0],ar=Fm[o];Bt===0||Bt===10?((o===1?ir:tr)(Gp(ar,0)),ar.length=0):ar.push(Bt)}z+=at}return d()[E>>>2>>>0]=z,0}j||function(){for(var o=u.numThreads-1;o--;)Vp();Eu.unshift(()=>{Ln++,function(f){j?f():Promise.all(Os.map(Np)).then(f)}(()=>dd())})}();for(var Ih=Array(256),wd=0;256>wd;++wd)Ih[wd]=String.fromCharCode(wd);ah=Ih,zs=u.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},u.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},hs.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>hs.length/2-5-Qd.length;var Om=[qd,Dp,jp,qp,Hp,Xp,Qp,Yp,Zp,Jp,eh,th,rh,nh,sh,ih,bh,vh,kh,Ch,Eh,Sh,Ph,Ah],Gt=function(){function o(b,E){return Gt=b.exports,Gt=function(){var z=Gt,me={};for(let[We,at]of Object.entries(z))me[We]=typeof at=="function"?(...Et)=>{fd.push(We);try{return at(...Et)}finally{Pn||(fd.pop(),Jn&&Bs===1&&fd.length===0&&(Bs=0,li+=1,hd(Vh),typeof Fibers<"u"&&Fibers.ac()))}}:at;return me}(),Gt=function(){var z=Gt,me=at=>Et=>at(Et)>>>0,We=at=>()=>at()>>>0;return(z=Object.assign({},z)).Aa=me(z.Aa),z.db=We(z.db),z.eb=me(z.eb),z.emscripten_main_runtime_thread_id=We(z.emscripten_main_runtime_thread_id),z.qb=me(z.qb),z.rb=We(z.rb),z}(),Bp.push(Gt.gb),dn.unshift(Gt.za),zr=E,dd(),Gt}var f=Op();if(Ln++,u.instantiateWasm)try{return u.instantiateWasm(f,o)}catch(b){tr(`Module.instantiateWasm callback failed with error: ${b}`),y(b)}return jd||(jd=u.locateFile?Pp("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",ht):ht+"ort-wasm-simd-threaded.jsep.wasm":new URL(l("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),l.b).href),function(b,E){var z=jd;return It||typeof WebAssembly.instantiateStreaming!="function"||Pp(z)||Ap(z)||typeof fetch!="function"?Fp(z,b,E):fetch(z,{credentials:"same-origin"}).then(me=>WebAssembly.instantiateStreaming(me,b).then(E,function(We){return tr(`wasm streaming compile failed: ${We}`),tr("falling back to ArrayBuffer instantiation"),Fp(z,b,E)}))}(f,function(b){o(b.instance,b.module)}).catch(y),{}}(),Fh=o=>(Fh=Gt.Aa)(o),Oh=()=>(Oh=Gt.Ba)();u._OrtInit=(o,f)=>(u._OrtInit=Gt.Ca)(o,f),u._OrtGetLastError=(o,f)=>(u._OrtGetLastError=Gt.Da)(o,f),u._OrtCreateSessionOptions=(o,f,b,E,z,me,We,at,Et,Bt)=>(u._OrtCreateSessionOptions=Gt.Ea)(o,f,b,E,z,me,We,at,Et,Bt),u._OrtAppendExecutionProvider=(o,f)=>(u._OrtAppendExecutionProvider=Gt.Fa)(o,f),u._OrtAddFreeDimensionOverride=(o,f,b)=>(u._OrtAddFreeDimensionOverride=Gt.Ga)(o,f,b),u._OrtAddSessionConfigEntry=(o,f,b)=>(u._OrtAddSessionConfigEntry=Gt.Ha)(o,f,b),u._OrtReleaseSessionOptions=o=>(u._OrtReleaseSessionOptions=Gt.Ia)(o),u._OrtCreateSession=(o,f,b)=>(u._OrtCreateSession=Gt.Ja)(o,f,b),u._OrtReleaseSession=o=>(u._OrtReleaseSession=Gt.Ka)(o),u._OrtGetInputOutputCount=(o,f,b)=>(u._OrtGetInputOutputCount=Gt.La)(o,f,b),u._OrtGetInputName=(o,f)=>(u._OrtGetInputName=Gt.Ma)(o,f),u._OrtGetOutputName=(o,f)=>(u._OrtGetOutputName=Gt.Na)(o,f),u._OrtFree=o=>(u._OrtFree=Gt.Oa)(o),u._OrtCreateTensor=(o,f,b,E,z,me)=>(u._OrtCreateTensor=Gt.Pa)(o,f,b,E,z,me),u._OrtGetTensorData=(o,f,b,E,z)=>(u._OrtGetTensorData=Gt.Qa)(o,f,b,E,z),u._OrtReleaseTensor=o=>(u._OrtReleaseTensor=Gt.Ra)(o),u._OrtCreateRunOptions=(o,f,b,E)=>(u._OrtCreateRunOptions=Gt.Sa)(o,f,b,E),u._OrtAddRunConfigEntry=(o,f,b)=>(u._OrtAddRunConfigEntry=Gt.Ta)(o,f,b),u._OrtReleaseRunOptions=o=>(u._OrtReleaseRunOptions=Gt.Ua)(o),u._OrtCreateBinding=o=>(u._OrtCreateBinding=Gt.Va)(o),u._OrtBindInput=(o,f,b)=>(u._OrtBindInput=Gt.Wa)(o,f,b),u._OrtBindOutput=(o,f,b,E)=>(u._OrtBindOutput=Gt.Xa)(o,f,b,E),u._OrtClearBoundOutputs=o=>(u._OrtClearBoundOutputs=Gt.Ya)(o),u._OrtReleaseBinding=o=>(u._OrtReleaseBinding=Gt.Za)(o),u._OrtRunWithBinding=(o,f,b,E,z)=>(u._OrtRunWithBinding=Gt._a)(o,f,b,E,z),u._OrtRun=(o,f,b,E,z,me,We,at)=>(u._OrtRun=Gt.$a)(o,f,b,E,z,me,We,at),u._OrtEndProfiling=o=>(u._OrtEndProfiling=Gt.ab)(o),u._JsepOutput=(o,f,b)=>(u._JsepOutput=Gt.bb)(o,f,b),u._JsepGetNodeName=o=>(u._JsepGetNodeName=Gt.cb)(o);var yd,ka=()=>(ka=Gt.db)(),bd=u._malloc=o=>(bd=u._malloc=Gt.eb)(o),es=u._free=o=>(es=u._free=Gt.fb)(o),ac=(o,f,b,E,z,me)=>(ac=Gt.ib)(o,f,b,E,z,me),zh=()=>(zh=Gt.jb)(),Dh=(o,f,b,E,z)=>(Dh=Gt.kb)(o,f,b,E,z),oc=o=>(oc=Gt.lb)(o),vd=o=>(vd=Gt.mb)(o),Bh=()=>(Bh=Gt.nb)(),Lh=(o,f)=>(Lh=Gt.ob)(o,f),Md=o=>(Md=Gt.pb)(o),lc=o=>(lc=Gt.qb)(o),uc=()=>(uc=Gt.rb)(),Rh=u.dynCall_ii=(o,f)=>(Rh=u.dynCall_ii=Gt.tb)(o,f),Nh=o=>(Nh=Gt.ub)(o),Vh=()=>(Vh=Gt.vb)(),jh=o=>(jh=Gt.wb)(o),Uh=()=>(Uh=Gt.xb)();function Wh(){0uc(),u.stackRestore=o=>Md(o),u.stackAlloc=o=>lc(o),u.UTF8ToString=mn,u.stringToUTF8=$a,u.lengthBytesUTF8=Kp,Fs=function o(){yd||Wh(),yd||(Fs=o)},Wh(),$}),Tt=pt,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&pt()}),He,Nt,Rt,qt,Ht,Yt,Wt,xr,Vr=D(()=>{var e,t;H(),He=self.location.href??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),Nt=typeof location>"u"?void 0:location.origin,Rt=(r,n)=>{try{let s=n??He;return(s?new URL(r,s):new URL(r)).origin===Nt}catch{return!1}},qt=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Ht=(ut(),P(be)).default,Yt=async()=>{if(!He)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Rt(He))return[void 0,Ht()];let r=await qt(He);return[r,Ht(r)]},Wt=(Lt(),P(nt)).default,xr=async(r,n,s)=>[void 0,Wt]}),Tr,Ze,Ct,Dt,Ur,Vn,An,Or,Xr=D(()=>{Vr(),Ze=!1,Ct=!1,Dt=!1,Ur=()=>{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}},Vn=()=>{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}},An=async e=>{if(Ze)return Promise.resolve();if(Ct)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Dt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ct=!0;let t=e.initTimeout,r=e.numThreads;if(!Vn())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Ur();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,i=s==null?void 0:s.mjs,d=(i==null?void 0:i.href)??i,c=s==null?void 0:s.wasm,p=(c==null?void 0:c.href)??c,w=e.wasmBinary,[y,u]=await xr(d,a,r>1),$=!1,T=[];if(t>0&&T.push(new Promise(I=>{setTimeout(()=>{$=!0,I()},t)})),T.push(new Promise((I,j)=>{let G={numThreads:r};w?G.wasmBinary=w:(p||a)&&(G.locateFile=(L,le)=>p??(a??le)+L),u(G).then(L=>{Ct=!1,Ze=!0,Tr=L,I(),y&&URL.revokeObjectURL(y)},L=>{Ct=!1,Dt=!0,j(L)})})),await Promise.race(T),$)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Or=()=>{if(Ze&&Tr)return Tr;throw new Error("WebAssembly is not initialized yet.")}}),Dr,kn,Er,jn=D(()=>{Xr(),Dr=(e,t)=>{let r=Or(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},kn=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let i=t?t+s:s;if(typeof a=="object")kn(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Er=e=>{let t=Or(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let s=t.HEAP32[n/4],a=t.HEAPU32[n/4+1],i=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),In,Rs=D(()=>{Xr(),jn(),In=e=>{let t=Or(),r=0,n=[],s=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)s.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(s.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Dr(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Er("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&kn(e.extra,"",new WeakSet,(i,d)=>{let c=Dr(i,n),p=Dr(d,n);t._OrtAddRunConfigEntry(r,c,p)!==0&&Er(`Can't set a run config entry: ${i} - ${d}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),fs,ms,_s,gs,Un,Ns=D(()=>{Xr(),jn(),fs=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}`)}},ms=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},_s=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)},gs=(e,t,r)=>{for(let n of t){let s=typeof n=="string"?n:n.name;switch(s){case"webnn":if(s="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let d=Dr("deviceType",r),c=Dr(i,r);Or()._OrtAddSessionConfigEntry(e,d,c)!==0&&Er(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(s="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let d=Dr("preferredLayout",r),c=Dr(i.preferredLayout,r);Or()._OrtAddSessionConfigEntry(e,d,c)!==0&&Er(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Dr(s,r);Or()._OrtAppendExecutionProvider(e,a)!==0&&Er(`Can't append execution provider: ${s}.`)}},Un=e=>{let t=Or(),r=0,n=[],s=e||{};_s(s);try{let a=fs(s.graphOptimizationLevel??"all"),i=ms(s.executionMode??"sequential"),d=typeof s.logId=="string"?Dr(s.logId,n):0,c=s.logSeverityLevel??2;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log serverity level is not valid: ${c}`);let p=s.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let w=typeof s.optimizedModelFilePath=="string"?Dr(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,d,c,p,w),r===0&&Er("Can't create session options."),s.executionProviders&&gs(r,s.executionProviders,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);let y=Dr("enableGraphCapture",n),u=Dr(s.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,y,u)!==0&&Er(`Can't set a session config entry: 'enableGraphCapture' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[y,u]of Object.entries(s.freeDimensionOverrides)){if(typeof y!="string")throw new Error(`free dimension override name must be a string: ${y}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let $=Dr(y,n);t._OrtAddFreeDimensionOverride(r,$,u)!==0&&Er(`Can't set a free dimension override: ${y} - ${u}.`)}return s.extra!==void 0&&kn(s.extra,"",new WeakSet,(y,u)=>{let $=Dr(y,n),T=Dr(u,n);t._OrtAddSessionConfigEntry(r,$,T)!==0&&Er(`Can't set a session config entry: ${y} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(i=>t._free(i)),a}}}),rs,Cn,Fn,On,Kn,ns,ss,Kt=D(()=>{rs=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}`)}},Cn=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}`)}},Fn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},On=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}`)}},Kn=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}`)}},ns=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",ss=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}}),Xn,ws=D(()=>{H(),Xn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(d){if(d instanceof RangeError){let c=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:c,maximum:c}).buffer}else throw d}let i=0;for(;;){let{done:d,value:c}=await s.read();if(d)break;let p=c.byteLength;new Uint8Array(a,i,p).set(c),i+=p}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),ys,is,bs,vs,as,Ms,Fr,pn=D(()=>{Kt(),ys=["V","I","W","E","F"],is=(e,t)=>{console.log(`[${ys[e]},${new Date().toISOString()}]${t}`)},as=(e,t)=>{bs=e,vs=t},Ms=(e,t)=>{let r=Kn(e),n=Kn(bs);r>=n&&is(r,typeof t=="function"?t():t)},Fr=(...e)=>{vs&&Ms(...e)}}),ve,_=D(()=>{Kt(),ve=(e,t)=>new(On(t))(e)}),O=D(()=>{}),Y,de,ce,Oe,_t,yt,wt,St,Qt,$r=D(()=>{pn(),O(),Y=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),de=[],ce=e=>Math.ceil(e/16)*16,Oe=e=>{for(let t=0;t_t++,wt=async(e,t,r,n)=>{let s=ce(r),a=e.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,s),e.flush(),await a.mapAsync(GPUMapMode.READ);let d=a.getMappedRange();if(n){let c=n();return c.set(new Uint8Array(d,0,r)),c}else return new Uint8Array(d.slice(0,r))}finally{a.destroy()}},St=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[t]of Y)de.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,s=t.byteLength,a=ce(s),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${s}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=d.getMappedRange();new Uint8Array(c).set(new Uint8Array(r,n,s)),d.unmap();let p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(d,0,i.gpuData.buffer,0,a),Fr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(d)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=ce(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(e,t,r){let n;if(r){if(n=this.externalBuffers.get(r),n===void 0)throw new Error("previous buffer is not registered");if(e===r)return Fr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`);this.externalBuffers.delete(r)}else n=yt();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,n),Fr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(e),Fr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=Oe(e),n,s=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||a){let d=(s?this.freeBuffers:this.freeUniformBuffers).get(r);d?d.length>0?n=d.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let i={id:yt(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:e}),Fr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return Fr("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 wt(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=Y.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e))}},Qt=(...e)=>new St(...e)}),er,Ut,pr=D(()=>{er=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}},Ut=e=>new er(e)}),nn,Kr,Ne,gn,yr,Wr,on,Xt=D(()=>{nn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Kr=class{static calcShape(e,t,r=!1){let n=e.length,s=t.length;if(n===0)return t;if(s===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(r){if(n<2||s<2)return;let d=nn.calcMatMulShape([e[n-2],e[n-1]],[t[s-2],t[s-1]]);if(d===void 0)return;[i[a-2],i[a-1]]=d}for(let d=r?3:1;d<=a;d++){let c=n-d<0?1:e[n-d],p=s-d<0?1:t[s-d];if(c!==p&&c>1&&p>1)return;let w=Math.max(c,p);if(c&&p)i[a-d]=Math.max(c,p);else{if(w>1)return;i[a-d]=0}}return i}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let s=1;s<=r;s++)if(e[r-s]!==1&&e[r-s]!==t[n-s])return!1;return!0}},Ne=class xd{static size(t){return xd.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let s=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){s[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");s[a]=1,r/=t[a],a--}for(a--;a>=0;a--)s[a]=t[a];return s}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return xd.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 xd.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let s=1;for(let a=r;a=0;--s)n[s]=n[s+1]*t[s+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((s,a)=>s+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,s)=>n===r[s])}},gn=class Pu{static adjustPoolAttributes(t,r,n,s,a,i){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let d=0;d=n.length?n.push(r[d+2]):n[d]=r[d+2];for(let d=0;d=n[d]||i[d+n.length]>=n[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,s,a,i,d){if(d){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let c=0;c{Kt(),Xt(),hn=64,Qr=(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"];default:throw new Error(`Unknown data type: ${e}`)}},br=(e,t=1)=>{let r=Qr(e,t);return typeof r=="string"?r:r[0]},vr=(e,t=1)=>{let r=Qr(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:Ne.computeStrides(r)})}),t},_r=e=>e%4===0?4:e%2===0?2:1,Sr=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Br=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,fn=(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,Ot=(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,Vs=(e,t,r,n,s)=>{let a=typeof r=="number",i=a?r:r.length,d=[...new Array(i).keys()],c=i<2?"u32":i<=4?`vec${i}`:`array`,p=Qr(t,s),w=typeof p=="string"?p:p[1],y=typeof p=="string"?p:p[0],u={indices:c,value:w,storage:y,tensor:t},$=Qe=>typeof Qe=="string"?Qe:`${Qe}u`,T={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},I=a?"uniforms.":"",j=`${I}${e}_shape`,G=`${I}${e}_strides`,L="";for(let Qe=0;Qe ${u.indices} { var indices: ${u.indices}; var current = offset; ${L} return indices; }`,q=Qe=>(T.offsetToIndices=!0,i<2?Qe:`o2i_${e}(${Qe})`),oe=[];if(i>=2)for(let Qe=i-1;Qe>=0;Qe--)oe.push(`${Ot(G,Qe,i)} * (indices[${Qe}])`);let Ke=i<2?"":` fn i2o_${e}(indices: ${u.indices}) -> u32 { return ${oe.join("+")}; }`,Ae=Qe=>(T.indicesToOffset=!0,i<2?Qe:`i2o_${e}(${Qe})`),ht=(...Qe)=>i===0?"0u":`${u.indices}(${Qe.map($).join(",")})`,It=(Qe,Ft)=>i<2?`${Qe}`:`${Ot(Qe,Ft,i)}`,zt=(Qe,Ft,rr)=>i<2?`${Qe}=${rr};`:`${Ot(Qe,Ft,i)}=${rr};`,cr={},ir=(Qe,Ft)=>{T.broadcastedIndicesToOffset=!0;let rr=`${Ft.name}broadcastedIndicesTo${e}Offset`;if(rr in cr)return`${rr}(${Qe})`;let Rr=[];for(let qr=i-1;qr>=0;qr--){let rn=Ft.indicesGet("outputIndices",qr+Ft.rank-i);Rr.push(`${It(G,qr)} * (${rn} % ${It(j,qr)})`)}return cr[rr]=`fn ${rr}(outputIndices: ${Ft.type.indices}) -> u32 { return ${Rr.length>0?Rr.join("+"):"0u"}; }`,`${rr}(${Qe})`},tr=(Qe,Ft)=>(()=>{if(u.storage===u.value)return`${e}[${Qe}]=${Ft};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${Qe}]=vec2(u32(${Ft}), select(0u, 0xFFFFFFFFu, ${Ft} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${Qe}]=vec2(u32(${Ft}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${Qe}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Ft}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),mr=Qe=>(()=>{if(u.storage===u.value)return`${e}[${Qe}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${Qe}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${Qe}].x)`;if(u.storage==="u32"&&u.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 ${u.storage} and value type ${u.value} yet`)})(),Lr=i<2?"":` fn get_${e}ByIndices(indices: ${u.indices}) -> ${w} { return ${mr(`i2o_${e}(indices)`)}; }`,Mr=i<2?"":(()=>{let Qe=d.map(rr=>`d${rr}: u32`).join(", "),Ft=d.map(rr=>`d${rr}`).join(", ");return` fn get_${e}(${Qe}) -> ${w} { return get_${e}ByIndices(${ht(Ft)}); }`})(),zr=(...Qe)=>{if(Qe.length!==i)throw new Error(`indices length must be ${i}`);let Ft=Qe.map($).join(",");return i===0?mr("0u"):i===1?mr(Ft[0]):(T.get=!0,T.getByIndices=!0,T.indicesToOffset=!0,`get_${e}(${Ft})`)},At=Qe=>i<2?mr(Qe):(T.getByIndices=!0,T.indicesToOffset=!0,`get_${e}ByIndices(${Qe})`),Jt=i<2?"":` fn set_${e}ByIndices(indices: ${u.indices}, value: ${w}) { ${tr(`i2o_${e}(indices)`,"value")} }`,Zt=i<2?"":(()=>{let Qe=d.map(rr=>`d${rr}: u32`).join(", "),Ft=d.map(rr=>`d${rr}`).join(", ");return` fn set_${e}(${Qe}, value: ${w}) { set_${e}ByIndices(${ht(Ft)}, value); }`})();return{impl:()=>{let Qe=[],Ft=!1;return T.offsetToIndices&&(Qe.push(le),Ft=!0),T.indicesToOffset&&(Qe.push(Ke),Ft=!0),T.broadcastedIndicesToOffset&&(Object.values(cr).forEach(rr=>Qe.push(rr)),Ft=!0),T.set&&(Qe.push(Zt),Ft=!0),T.setByIndices&&(Qe.push(Jt),Ft=!0),T.get&&(Qe.push(Mr),Ft=!0),T.getByIndices&&(Qe.push(Lr),Ft=!0),!a&&Ft&&Qe.unshift(`const ${j} = ${u.indices}(${r.join(",")});`,`const ${G} = ${u.indices}(${Ne.computeStrides(r).join(",")});`),Qe.join(` `)},type:u,offsetToIndices:q,indicesToOffset:Ae,broadcastedIndicesToOffset:ir,indices:ht,indicesGet:It,indicesSet:zt,set:(...Qe)=>{if(Qe.length!==i+1)throw new Error(`indices length must be ${i}`);let Ft=Qe[i];if(typeof Ft!="string")throw new Error("value must be string");let rr=Qe.slice(0,i).map($).join(",");return i===0?tr("0u",Ft):i===1?tr(rr[0],Ft):(T.set=!0,T.setByIndices=!0,T.indicesToOffset=!0,`set_${e}(${rr}, ${Ft})`)},setByOffset:tr,setByIndices:(Qe,Ft)=>i<2?tr(Qe,Ft):(T.setByIndices=!0,T.indicesToOffset=!0,`set_${e}ByIndices(${Qe}, ${Ft});`),get:zr,getByOffset:mr,getByIndices:At,usage:n,name:e,strides:G,shape:j,rank:i}},rt=(e,t,r,n=1)=>Vs(e,t,r,"input",n),Vt=(e,t,r,n=1)=>Vs(e,t,r,"output",n),di=(e,t,r,n=1)=>Vs(e,t,r,"internal",n),ci=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=hn){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=s?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,i=s?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) fn main(${a}) { ${i} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",n=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${s}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Ea=(e,t)=>new ci(e,t),os=(e,t)=>{let r=e.length,n=[];for(let s=0;s1&&i===1&&n.unshift(a)}return n}}),Sa,pi,xs,Pa,En,Aa,hi,ls=D(()=>{Kt(),Xt(),pr(),nr(),Sa=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},pi=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,xs=(e,t)=>Ne.sortBasedOnPerm(e,pi(e.length,t)),Pa=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let a=0;a{let r=e.dataType,n=e.dims.length,s=pi(n,t),a=xs(e.dims,s),i=Vt("output",r,a.length),d=rt("a",r,n),c;if(s.length===2&&s[0]===1&&s[1]===0){let p=i.type.value,w=[16,16,1];c=y=>` ${y.registerUniform("output_size","u32").declareVariables(d,i)} var tile : array, ${w[0]}>; ${y.mainStart(w)} var x = workgroup_id.x * ${w[0]}u + local_id.x; var y = workgroup_id.y * ${w[0]}u + local_id.y; let width = uniforms.output_shape[0]; let height = uniforms.output_shape[1]; if (x < width && y < height) { tile[local_id.y][local_id.x] = ${d.getByOffset("y * width + x")}; } workgroupBarrier(); x = workgroup_id.y * ${w[0]}u + local_id.x; y = workgroup_id.x * ${w[0]}u + local_id.y; if (x < height && y < width) { ${i.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} } }`}else c=p=>` ${p.registerUniform("output_size","u32").declareVariables(d,i)} ${Pa(s,n,d,i)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${i.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${i.setByOffset("global_idx",d.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:p=>{let w=Ne.size(a);return{outputs:[{dims:a,dataType:p[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},...kt(p[0].dims,a)]}},getShaderSource:c}},Aa=(e,t)=>{Sa(e.inputs),e.compute(En(e.inputs[0],t.perm))},hi=e=>Ut({perm:e.perm})}),Ia,Fa,Oa,za,fi,Da,Ba,mi,La,Ra,wn,Na,Va,_i,ja,Ua,gi,Wa,Ga,wi,qa,Iu=D(()=>{Kt(),Xt(),nr(),$i(),ls(),Ia={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"},Fa={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"},Oa={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},za={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},fi=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,s]},Ba=(e,t)=>{let r=e.length+t.length,n=[],s=0;for(let a=0;a{for(let r=0;r{let r=[];if(!mi(e,t)){for(let n=0;nr.push(n))}return r},Ra=(e,t,r,n,s,a,i)=>{let d=r[0].dims,c=Ne.size(a),p=Ne.size(i),w=rt("_A",r[0].dataType,d),y=Vt("output",s,a),u=32,$=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:T=>` ${T.registerUniform("reduceSize","u32").declareVariables(w,y)} ${$} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${T.mainStart(u)} let outputIndex = global_idx / ${u}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${Oa[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${u}) { let candidate = f32(${w.getByOffset("offset + k")}); bestValue = ${Ia[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${u}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 = ${Fa[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${y.setByOffset("outputIndex",`${n==="mean"?`${y.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${y.type.storage}(${za[n]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:c},programUniforms:[{type:12,data:p}]})}},wn=(e,t,r,n)=>{let s=e.inputs.length===1?r:Us(e.inputs,r),a=s.axes;a.length===0&&!s.noopWithEmptyAxes&&(a=e.inputs[0].dims.map(($,T)=>T));let i=Ne.normalizeAxes(a,e.inputs[0].dims.length),d=i,c=e.inputs[0],p=La(d,e.inputs[0].dims.length);p.length>0&&(c=e.compute(En(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],d=fi(d.length,c.dims.length));let[w,y]=Da(c.dims,d),u=w;s.keepDims&&(u=Ba(w,i)),e.compute(Ra(t,{hint:s.cacheKey,inputDependencies:["type"]},[c],n,e.inputs[0].dataType,u,y),{inputs:[c]})},Na=(e,t)=>{wn(e,"ReduceMeanShared",t,"mean")},Va=(e,t)=>{wn(e,"ReduceL1Shared",t,"l1")},_i=(e,t)=>{wn(e,"ReduceL2Shared",t,"l2")},ja=(e,t)=>{wn(e,"ReduceLogSumExpShared",t,"logSumExp")},Ua=(e,t)=>{wn(e,"ReduceMaxShared",t,"max")},gi=(e,t)=>{wn(e,"ReduceMinShared",t,"min")},Wa=(e,t)=>{wn(e,"ReduceProdShared",t,"prod")},Ga=(e,t)=>{wn(e,"ReduceSumShared",t,"sum")},wi=(e,t)=>{wn(e,"ReduceSumSquareShared",t,"sumSquare")},qa=(e,t)=>{wn(e,"ReduceLogSumShared",t,"logSum")}}),yn,Ha,js,Us,Tn,Ka,yi,Xa,Qa,bi,Ya,Za,vi,Ja,eo,bn,to,ro,Mi,no,so,xi,io,ao,Ti,oo,$i=D(()=>{Kt(),Xt(),pr(),nr(),Iu(),yn=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.")},Ha=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],js=(e,t,r,n,s,a,i=!1,d=!1)=>{let c=[],p=r[0].dims,w=p.length,y=Ne.normalizeAxes(s,w),u=!d&&y.length===0;p.forEach((I,j)=>{u||y.indexOf(j)>=0?i&&c.push(1):c.push(I)});let $=c.length,T=Ne.size(c);return{name:e,shaderCache:t,getShaderSource:I=>{let j=[],G=rt("_A",r[0].dataType,w),L=Vt("output",a,$),le=n(G,L,y),q=le[2];for(let oe=0,Ke=0;oe=0?(i&&Ke++,q=`for(var j${oe}: u32 = 0; j${oe} < ${p[oe]}; j${oe}++) { ${le[2].includes("last_index")?`let last_index = j${oe};`:""} ${G.indicesSet("input_indices",oe,`j${oe}`)} ${q} }`):(j.push(`${G.indicesSet("input_indices",oe,L.indicesGet("output_indices",Ke))};`),Ke++);return` ${I.registerUniform("output_size","u32").declareVariables(G,L)} ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${G.type.indices}; let output_indices = ${L.offsetToIndices("global_idx")}; ${j.join(` `)} ${le[0]} // init ops for reduce max/min ${le[1]} ${q} ${le[3]} ${le.length===4?L.setByOffset("global_idx","value"):le.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:c,dataType:a}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:[{type:12,data:T},...kt(p,c)]})}},Us=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),Ut({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Tn=(e,t,r,n)=>{let s=e.inputs,a=s.length===1?r:Us(s,r);e.compute(js(t,{hint:a.cacheKey,inputDependencies:["rank"]},[s[0]],a.noopWithEmptyAxes&&a.axes.length===0?Ha:n,a.axes,s[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Ka=(e,t)=>{yn(e.inputs),Tn(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},yi=(e,t)=>{yn(e.inputs),Tn(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Xa=(e,t)=>{yn(e.inputs),Tn(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);"])},Qa=(e,t)=>{yn(e.inputs),Tn(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},bi=(e,t)=>{yn(e.inputs),Tn(e,"ReduceMax",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(r.indicesSet("input_indices",i,0));return[`${a.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},Ya=(e,t)=>{yn(e.inputs),Tn(e,"ReduceMean",t,(r,n,s)=>{let a=1;for(let i=0;i=0||s.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Za=(e,t)=>{yn(e.inputs),Tn(e,"ReduceMin",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},vi=(e,t)=>{yn(e.inputs),Tn(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Ja=(e,t)=>{yn(e.inputs),Tn(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},eo=(e,t)=>{yn(e.inputs),Tn(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;`,""])},bn=(e,t,r)=>{if(t.length===0)return r;let n=1,s=1;for(let a=0;a1024},to=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ya(e,t):Na(e,t)},ro=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?yi(e,t):Va(e,t)},Mi=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xa(e,t):_i(e,t)},no=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Qa(e,t):ja(e,t)},so=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bi(e,t):Ua(e,t)},xi=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Za(e,t):gi(e,t)},io=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vi(e,t):Wa(e,t)},ao=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ja(e,t):Ga(e,t)},Ti=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?eo(e,t):wi(e,t)},oo=(e,t)=>{bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ka(e,t):qa(e,t)}}),Ws,lo,uo,Gs,Fu=D(()=>{Kt(),pr(),$i(),Ws=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.")},lo=(e,t)=>{Ws(e.inputs);let r=(n,s,a)=>{let i=[];for(let d=0;d=0||a.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",s.setByOffset("global_idx","best_index")]};e.compute(js("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},uo=(e,t)=>{Ws(e.inputs);let r=(n,s,a)=>{let i=[];for(let d=0;d=0||a.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",s.setByOffset("global_idx","best_index")]};e.compute(js("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Gs=e=>Ut(e)}),co,ki,po,ho,us,fo,mo,qs=D(()=>{Kt(),Xt(),O(),nr(),co=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4],d=e[5];if(i&&d)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 c=r.dims[0],p=r.dims[1],w=r.dims[2];if(s.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==w)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(s.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let y=s.dims[0]/3,u=y,$=u;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let le of t.qkvHiddenSizes)if(le%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");y=t.qkvHiddenSizes[0],u=t.qkvHiddenSizes[1],$=t.qkvHiddenSizes[2]}let T=p;if(y!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==y+u+$)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let I=0;if(i){if(u!==$)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==c)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(I=i.dims[3])}let j=T+I,G=-1,L=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(d.dims[0]!==c||d.dims[1]!==t.numHeads||d.dims[2]!==p||d.dims[3]!==j)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:c,sequenceLength:p,pastSequenceLength:I,kvSequenceLength:T,totalSequenceLength:j,maxSequenceLength:G,inputHiddenSize:w,hiddenSize:y,vHiddenSize:$,headSize:Math.floor(y/t.numHeads),vHeadSize:Math.floor($/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:L,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ki=(e,t,r)=>{let n=_r(r),s=64,a=r/n;a{let $=Vt("x",e.dataType,e.dims,n),T=vr(e.dataType),I=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${u.registerUniforms(I).declareVariables($)} ${u.mainStart([s,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${s}) * uniforms.d_comp + local_offset; var thread_max_vector = ${p}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${p}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(n){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${n}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${s}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${p}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${p}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(n){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${n}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${s}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${$.type.value}(${T}(uniforms.d_inv)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${p}(x[offset + i]); x[offset + i] = ${$.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${c};${n}`,inputDependencies:w},getShaderSource:y,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:d})}},po=(e,t,r,n,s,a,i,d)=>{let c=d+a.kvSequenceLength,p=[a.batchSize,a.numHeads,a.sequenceLength,c],w=a.kvNumHeads===void 0&&e>1&&n,y=w?[a.batchSize,a.numHeads,c,a.headSize]:void 0,u=i.scale===0?1/Math.sqrt(a.headSize):i.scale,$=_r(a.headSize),T=a.headSize/$,I=12,j={x:Math.ceil(c/I),y:Math.ceil(a.sequenceLength/I),z:a.batchSize*a.numHeads},G=[{type:12,data:a.sequenceLength},{type:12,data:T},{type:12,data:c},{type:12,data:a.numHeads},{type:1,data:u},{type:12,data:d},{type:12,data:a.kvSequenceLength}],L=w&&n&&Ne.size(n.dims)>0,le=["type","type"];L&&le.push("type"),s&&le.push("type");let q=[{dims:p,dataType:t.dataType,gpuDataType:0}];w&&q.push({dims:y,dataType:t.dataType,gpuDataType:0});let oe=Ke=>{let Ae=rt("q",t.dataType,t.dims,$),ht=rt("key",r.dataType,r.dims,$),It=[Ae,ht];if(L){let mr=rt("past_key",n.dataType,n.dims,$);It.push(mr)}s&&It.push(rt("attention_bias",s.dataType,s.dims));let zt=Vt("output",t.dataType,p),cr=[zt];w&&cr.push(Vt("present_key",t.dataType,y,$));let ir=vr(1,$),tr=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${I}u; var tileQ: array<${Ae.type.storage}, ${I*I}>; var tileK: array<${Ae.type.storage}, ${I*I}>; ${Ke.registerUniforms(tr).declareVariables(...It,...cr)} ${Ke.mainStart([I,I,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; ${L&&w?` let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} ${w?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} var value = ${ir}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${L&&w?` if (n + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else { tileK[idx] = key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} ${w?"present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];":""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${ir}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch($){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: ${$}`)}})()}; output[outputIdx] = ${zt.type.value} (sum * uniforms.alpha) + ${s?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${$};${s!==void 0};${n!==void 0};${e}`,inputDependencies:le},getRunData:()=>({outputs:q,dispatchGroup:j,programUniforms:G}),getShaderSource:oe}},ho=(e,t,r,n,s,a)=>{let i=a+s.kvSequenceLength,d=s.nReps?s.nReps:1,c=s.vHiddenSize*d,p=s.kvNumHeads==null&&e>1&&n,w=p?[s.batchSize,s.numHeads,i,s.headSize]:void 0,y=[s.batchSize,s.sequenceLength,c],u=12,$={x:Math.ceil(s.vHeadSize/u),y:Math.ceil(s.sequenceLength/u),z:s.batchSize*s.numHeads},T=[{type:12,data:s.sequenceLength},{type:12,data:i},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:c},{type:12,data:a},{type:12,data:s.kvSequenceLength}],I=p&&n&&Ne.size(n.dims)>0,j=["type","type"];I&&j.push("type");let G=[{dims:y,dataType:t.dataType,gpuDataType:0}];p&&G.push({dims:w,dataType:t.dataType,gpuDataType:0});let L=le=>{let q=rt("probs",t.dataType,t.dims),oe=rt("v",r.dataType,r.dims),Ke=[q,oe];I&&Ke.push(rt("past_value",n.dataType,n.dims));let Ae=[Vt("output",t.dataType,y)];p&&Ae.push(Vt("present_value",t.dataType,w));let ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${u}u; var tileQ: array<${q.type.value}, ${u*u}>; var tileK: array<${q.type.value}, ${u*u}>; ${le.registerUniforms(ht).declareVariables(...Ke,...Ae)} ${le.mainStart([u,u,1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; ${I&&p?` let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; `:` let offsetB = headIdx * uniforms.N * uniforms.K + n; `} ${p?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} var value = ${q.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${I&&p?` if (w + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else { tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; } `:` tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; `} ${p?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:j},getRunData:()=>({outputs:G,dispatchGroup:$,programUniforms:T}),getShaderSource:L}},us=(e,t,r,n,s,a,i,d,c,p,w)=>{let y=Math.min(e.outputCount,1+(i?1:0)+(d?1:0)),u=p.kvNumHeads!==void 0||y>1?p.pastSequenceLength:0,$=u+p.kvSequenceLength,T=c&&Ne.size(c.dims)>0?c:void 0,I=[t,r];p.kvNumHeads===void 0&&y>1&&i&&Ne.size(i.dims)>0&&I.push(i),T&&I.push(T);let j=e.compute(po(y,t,r,i,T,p,w,u),{inputs:I,outputs:p.kvNumHeads===void 0&&y>1?[-1,1]:[-1]})[0];e.compute(ki(j,p.batchSize*p.numHeads*p.sequenceLength,$),{inputs:[j],outputs:[]});let G=[j,n];p.kvNumHeads===void 0&&y>1&&d&&Ne.size(d.dims)>0&&G.push(d),e.compute(ho(y,j,n,d,p,u),{inputs:G,outputs:p.kvNumHeads===void 0&&y>1?[0,2]:[0]})},fo=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,s=t.inputHiddenSize,a=t.headSize,i=12,d={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},c=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:s},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],w=y=>{let u=Vt("output_q",c[0].dataType,r),$=Vt("output_k",c[0].dataType,r),T=Vt("output_v",c[0].dataType,r),I=rt("input",c[0].dataType,c[0].dims),j=rt("weight",c[1].dataType,c[1].dims),G=rt("bias",c[2].dataType,c[2].dims),L=I.type.storage,le=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${i}u; var tileInput: array<${L}, ${i*i}>; var tileWeightQ: array<${L}, ${i*i}>; var tileWeightK: array<${L}, ${i*i}>; var tileWeightV: array<${L}, ${i*i}>; ${y.registerUniforms(le).declareVariables(I,j,G,u,$,T)} ${y.mainStart([i,i,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${L}(0); var valueK = ${L}(0); var valueV = ${L}(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:d,programUniforms:p}),getShaderSource:w},{inputs:c,outputs:[-1,-1,-1]})},mo=(e,t)=>{let r=co(e.inputs,t),[n,s,a]=fo(e,r);return us(e,n,s,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),_o,go,wo,yo,bo=D(()=>{k(),Kt(),Xt(),pr(),nr(),_o=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,s,a)=>{let i=s.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);s.forEach((d,c)=>{if(d!==n[c])throw new Error(`${a}: dim[${c}] 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")},go=(e,t)=>{let{epsilon:r,spatial:n,format:s}=t,a=e[0].dims,i=n?_r(a[a.length-1]):1,d=s==="NHWC"&&a.length>1?i:1,c=Ne.size(a)/i,p=n,w=p?a.length:a,y=rt("x",e[0].dataType,e[0].dims,i),u=rt("scale",e[1].dataType,e[1].dims,d),$=rt("bias",e[2].dataType,e[2].dims,d),T=rt("inputMean",e[3].dataType,e[3].dims,d),I=rt("inputVar",e[4].dataType,e[4].dims,d),j=Vt("y",e[0].dataType,w,i),G=()=>{let le="";if(n)le=`let cOffset = ${a.length===1?"0u":s==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(s==="NCHW")le=` ${j.indicesSet("outputIndices","0","0")} let cOffset = ${j.indicesToOffset("outputIndices")};`;else{le=`var cIndices = ${u.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let q=1;q` const epsilon = ${r}; ${le.registerUniform("outputSize","u32").declareVariables(y,u,$,T,I,j)} ${le.mainStart()} ${le.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${j.offsetToIndices(`global_idx * ${i}`)}; ${G()} let scale = ${u.getByOffset("cOffset")}; let bias = ${$.getByOffset("cOffset")}; let inputMean = ${T.getByOffset("cOffset")}; let inputVar = ${I.getByOffset("cOffset")}; let x = ${y.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${j.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:L,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p?[{type:12,data:c},...kt(a)]:[{type:12,data:c}]})}},wo=e=>Ut(e),yo=(e,t)=>{let{inputs:r,outputCount:n}=e,s=wo({...t,outputCount:n});if(A.webgpu.validateInputContent&&_o(r,s),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(go(r,s))}}),vo,Mo,Ci,Ou=D(()=>{Xt(),nr(),vo=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")},Mo=e=>{let t=e[0].dims,r=e[0].dims[2],n=Ne.size(t)/4,s=e[0].dataType,a=rt("input",s,t,4),i=rt("bias",s,[r],4),d=rt("residual",s,t,4),c=Vt("output",s,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:p=>` const channels = ${r}u / 4; ${p.declareVariables(a,i,d,c)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${a.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; ${c.setByOffset("global_idx","value")} }`}},Ci=e=>{vo(e.inputs),e.compute(Mo(e.inputs))}}),xo,gr,To,$o,Ei,ko,Co,Si,Eo,So,Hs,Po,Ao,Io,Pi,Fo,ds,Oo,Ks,zo,Ai,Do,Bo,Lo,Ii,Ro,No,Fi,Vo,jo,Oi,Uo,Wo,zi,Go,Di,Bi,Li,Ri,qo,Ho,Ni,Ko,Xo,Qo,Vi=D(()=>{Kt(),Xt(),pr(),nr(),xo=(e,t,r,n,s,a)=>{let i=Math.ceil(t/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let c=rt("inputData",r,[i],4),p=Vt("outputData",n,[i],4);return` ${e.registerUniform("vec_size","u32").declareVariables(c,p)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${c.getByOffset("global_idx")}; ${p.setByOffset("global_idx",d)} }`},gr=(e,t,r,n,s,a=e.dataType)=>({name:t,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:i=>xo(i,Ne.size(e.dims),e.dataType,a,r,n),getRunData:i=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Ne.size(i[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(Ne.size(e.dims)/4)}]})}),To=e=>{e.compute(gr(e.inputs[0],"Abs","abs"))},$o=e=>{e.compute(gr(e.inputs[0],"Acos","acos"))},Ei=e=>{e.compute(gr(e.inputs[0],"Acosh","acosh"))},ko=e=>{e.compute(gr(e.inputs[0],"Asin","asin"))},Co=e=>{e.compute(gr(e.inputs[0],"Asinh","asinh"))},Si=e=>{e.compute(gr(e.inputs[0],"Atan","atan"))},Eo=e=>{e.compute(gr(e.inputs[0],"Atanh","atanh"))},So=e=>Ut(e),Hs=(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(gr(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Po=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Wr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:on;return Ut({min:t,max:r})},Ao=(e,t)=>{let r=e.inputs.length===1?t:Po(e.inputs),n=vr(e.inputs[0].dataType);e.compute(gr(e.inputs[0],"Clip",s=>`clamp(${s}, clip_min_, clip_max_)`,` const clip_min_: vec4<${n}> = vec4(${n}(${r.min})); const clip_max_: vec4<${n}> = vec4(${n}(${r.max})); `,r.cacheKey),{inputs:[0]})},Io=e=>{e.compute(gr(e.inputs[0],"Ceil","ceil"))},Pi=e=>{e.compute(gr(e.inputs[0],"Cos","cos"))},Fo=e=>{e.compute(gr(e.inputs[0],"Cosh","cosh"))},ds=e=>Ut(e),Oo=(e,t)=>{let r=vr(e.inputs[0].dataType);e.compute(gr(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))},Ks=(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)); }`,zo=e=>{let t=vr(e.inputs[0].dataType);e.compute(gr(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Ks(t)))},Ai=e=>{e.compute(gr(e.inputs[0],"Exp","exp"))},Do=e=>{e.compute(gr(e.inputs[0],"Floor","floor"))},Bo=e=>{let t=vr(e.inputs[0].dataType);e.compute(gr(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Ks(t)))},Lo=(e,t)=>{let r=vr(e.inputs[0].dataType);e.compute(gr(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))},Ii=e=>{e.compute(gr(e.inputs[0],"Not",t=>`!${t}`))},Ro=e=>{e.compute(gr(e.inputs[0],"Neg",t=>`-${t}`))},No=e=>{e.compute(gr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Fi=e=>{let t=vr(e.inputs[0].dataType);e.compute(gr(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Vo=e=>{e.compute(gr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},jo=e=>Ut(e),Oi=(e,t)=>{let r=vr(e.inputs[0].dataType);e.compute(gr(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))},Uo=e=>{e.compute(gr(e.inputs[0],"Sin","sin"))},Wo=e=>{e.compute(gr(e.inputs[0],"Sinh","sinh"))},zi=e=>{e.compute(gr(e.inputs[0],"Sqrt","sqrt"))},Go=e=>{e.compute(gr(e.inputs[0],"Tan","tan"))},Di=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Bi=e=>{e.compute(gr(e.inputs[0],"Tanh",Di))},Li=(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 ${Di("v")}; } `,Ri=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,qo=e=>{let t=vr(e.inputs[0].dataType);e.compute(gr(e.inputs[0],"FastGelu",Ri,Li(t),void 0,e.inputs[0].dataType))},Ho=(e,t)=>{let r=vr(e.inputs[0].dataType);return e.compute(gr(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},Ni=e=>{e.compute(gr(e.inputs[0],"Log","log"))},Ko=(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; } `,Xo=e=>`quick_gelu_impl(${e})`,Qo=(e,t)=>{let r=vr(e.inputs[0].dataType);e.compute(gr(e.inputs[0],"QuickGelu",Xo,Ko(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),ji,Yo,Zo,Jo=D(()=>{Xt(),nr(),Vi(),ji=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")},Yo=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=rt("input",e[0].dataType,e[0].dims,4),n=rt("bias",e[0].dataType,[e[0].dims[2]],4),s=Vt("output",e[0].dataType,t,4),a=Ne.size(t)/4,i=br(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:d=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${d.declareVariables(r,n,s)} ${Ks(i)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(a)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${s.setByOffset("global_idx","valueLeft * geluRight")} }`}},Zo=e=>{ji(e.inputs),e.compute(Yo(e.inputs))}}),el,tl,vn,rl,nl,Ui,sl,il,al,ol,ll,ul,Wi,zu=D(()=>{Kt(),Xt(),nr(),el=(e,t,r,n,s,a,i,d,c,p,w,y)=>{let u,$;typeof d=="string"?u=$=(L,le)=>`${d}((${L}),(${le}))`:typeof d=="function"?u=$=d:(u=d.scalar,$=d.vector);let T=Vt("outputData",w,n.length,4),I=rt("aData",c,t.length,4),j=rt("bData",p,r.length,4),G;if(s)if(a){let L=Ne.size(t)===1,le=Ne.size(r)===1,q=t.length>0&&t[t.length-1]%4===0,oe=r.length>0&&r[r.length-1]%4===0;L||le?G=T.setByOffset("global_idx",$(L?`${I.type.value}(${I.getByOffset("0")}.x)`:I.getByOffset("global_idx"),le?`${j.type.value}(${j.getByOffset("0")}.x)`:j.getByOffset("global_idx"))):G=` let outputIndices = ${T.offsetToIndices("global_idx * 4u")}; let offsetA = ${I.broadcastedIndicesToOffset("outputIndices",T)}; let offsetB = ${j.broadcastedIndicesToOffset("outputIndices",T)}; ${T.setByOffset("global_idx",$(i||q?I.getByOffset("offsetA / 4u"):`${I.type.value}(${I.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||oe?j.getByOffset("offsetB / 4u"):`${j.type.value}(${j.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else G=T.setByOffset("global_idx",$(I.getByOffset("global_idx"),j.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let L=(le,q,oe="")=>{let Ke=`aData[indexA${q}][componentA${q}]`,Ae=`bData[indexB${q}][componentB${q}]`;return` let outputIndices${q} = ${T.offsetToIndices(`global_idx * 4u + ${q}u`)}; let offsetA${q} = ${I.broadcastedIndicesToOffset(`outputIndices${q}`,T)}; let offsetB${q} = ${j.broadcastedIndicesToOffset(`outputIndices${q}`,T)}; let indexA${q} = offsetA${q} / 4u; let indexB${q} = offsetB${q} / 4u; let componentA${q} = offsetA${q} % 4u; let componentB${q} = offsetB${q} % 4u; ${le}[${q}] = ${oe}(${u(Ke,Ae)}); `};w===9?G=` var data = vec4(0); ${L("data",0,"u32")} ${L("data",1,"u32")} ${L("data",2,"u32")} ${L("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:G=` ${L("outputData[global_idx]",0)} ${L("outputData[global_idx]",1)} ${L("outputData[global_idx]",2)} ${L("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(I,j,T)} ${y??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${G} }`},tl=(e,t,r,n,s,a,i=r.dataType)=>{let d=!Ne.areEqual(r.dims,n.dims),c=r.dims,p=Ne.size(r.dims),w=!1,y=!1,u=[d];if(d){let $=Kr.calcShape(r.dims,n.dims,!1);if(!$)throw new Error("Can't perform binary op on the given tensors");c=$,p=Ne.size(c);let T=Ne.size(r.dims)===1,I=Ne.size(n.dims)===1,j=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,G=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;u.push(T),u.push(I),u.push(j),u.push(G);let L=1;for(let le=1;le$.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:$=>el($,r.dims,n.dims,c,w,d,y,s,r.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:c,dataType:i}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:[{type:12,data:Math.ceil(Ne.size(c)/4)},...kt(r.dims,n.dims,c)]})}},vn=(e,t,r,n,s,a)=>{e.compute(tl(t,s??"",e.inputs[0],e.inputs[1],r,n,a))},rl=e=>{vn(e,"Add",(t,r)=>`${t}+${r}`)},nl=e=>{vn(e,"Div",(t,r)=>`${t}/${r}`)},Ui=e=>{vn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},sl=e=>{vn(e,"Mul",(t,r)=>`${t}*${r}`)},il=e=>{let t=rt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;vn(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)); } `)},al=e=>{vn(e,"Sub",(t,r)=>`${t}-${r}`)},ol=e=>{vn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},ll=e=>{vn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},ul=e=>{vn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Wi=e=>{vn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),dl,Gi,cl,pl,Wn,hl,Du=D(()=>{Kt(),Xt(),pr(),nr(),dl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],s=n.dataType,a=n.dims.length;e.forEach((i,d)=>{if(d!==r){if(i.dataType!==s)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((c,p)=>{if(p!==t&&c!==n.dims[p])throw new Error("non concat dimensions must match")})}})},Gi=(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; }`,cl=(e,t)=>{let r=e.length,n=[];for(let s=0;s{let s=Ne.size(r),a=new Array(e.length),i=new Array(e.length),d=0,c=[],p=[],w=[{type:12,data:s}];for(let I=0;I`uniforms.sizeInConcatAxis${I}`).join(","),T=I=>` ${(()=>{I.registerUniform("outputSize","u32");for(let j=0;j(${$}); ${u} -= sizeInConcatAxis[inputIndex - 1u]; } ${cl(i,y)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:w}),getShaderSource:T}},Wn=(e,t)=>{let r=e.inputs,n=r[0].dims,s=Ne.normalizeAxis(t.axis,n.length);dl(r,s);let a=n.slice();a[s]=r.reduce((d,c)=>d+(c.dims.length>s?c.dims[s]:0),0);let i=r.filter(d=>Ne.size(d.dims)>0);e.compute(pl(i,s,a,r[0].dataType),{inputs:i})},hl=e=>Ut({axis:e.axis})}),Gn,qn,zn,qi,Hn=D(()=>{Kt(),Xt(),Gn=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},qn=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},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"})},qi=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)||[Wr,on];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}}}),Yr,Hi,cs=D(()=>{Yr=(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.`)}},Hi=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),Ki,fl=D(()=>{Ki=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)); } `}),ml,Ts,Xs,Xi,_l,Qs,Ys,Qi,Zs=D(()=>{Kt(),Xt(),nr(),Hn(),cs(),ml=(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":""}); `,Ts=(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];"} }`,Xs=(e,t,r="f32",n,s=!1,a=32,i=!1,d=32)=>{let c=t[1]*e[1],p=t[0]*e[0],w=s?c:a,y=s?a:c,u=w/t[0],$=a/t[1];if(!((s&&u===4&&e[1]===4||!s&&(u===3||u===4))&&w%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${u} must be 3 or 4. tileAWidth ${w} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${w/u}>, ${y}>; var mm_Bsub: array, ${p/e[0]}>, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${u}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${i?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${c}; let num_tiles = ${i?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${$}; 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; ${ml(s,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${$}; 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]; ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Ts(s,u)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Xi=(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":""}); `,_l=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Qs=(e,t,r="f32",n,s=!1,a=32,i=!1,d=32,c=!1)=>{let p=e[1]*t[1],w=e[0]*t[0],y=s?p:a,u=s?a:p;if(!(u%t[1]===0&&y%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${y} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let $=u/t[1],T=y/t[0],I=a/t[1],j=c?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${p}; let globalColStart = i32(workgroupId.x) * ${w}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${y}; inputCol = inputCol + ${t[0]}) { ${Xi(s,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${w}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${s?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${p}; let tileRowA = i32(localId.y) * ${$}; let tileColA = i32(localId.x) * ${T}; let tileRowB = i32(localId.y) * ${I}; // 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 < ${$}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${T}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Xi(s,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${I}; 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) { ${_l(s)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${u}>; var mm_Bsub : array, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${i?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${i?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; var acc : array, rowPerThread>; ${j} } `},Ys=(e,t,r,n,s,a=!1)=>{let[i,d,c]=s,[p,w,y,u]=n,$=os(i,c),T=os(d,c),I=br(n[0].type.tensor),j=()=>{let L=w.rank,le=p.rank,q=`var aIndices: ${w.type.indices};`;for(let oe=L-2-1,Ke=le-1;oe>=0;oe--,Ke--)q+=` aIndices[${oe}] = ${le>1?`batchIndices[${Ke}]`:"batchIndices"};`;return $.forEach(oe=>{q+=` aIndices[${oe}] = 0;`}),q+=` aIndices[${L-2}] = u32(row); aIndices[${L-1}] = u32(colIn);`,q},G=()=>{let L=y.rank,le=p.rank,q=`var bIndices: ${y.type.indices};`;for(let oe=L-2-1,Ke=le-1;oe>=0;oe--,Ke--)q+=` bIndices[${oe}] = ${le>1?`batchIndices[${Ke}]`:"batchIndices"};`;return T.forEach(oe=>{q+=` bIndices[${oe}] = 0;`}),q+=` bIndices[${L-2}] = u32(row); bIndices[${L-1}] = u32(colIn);`,q};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Yr(e,I)} { var value = ${Yr(e,I)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${j()} value = ${w.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Yr(e,I)} { var value = ${Yr(e,I)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${G()} value = ${y.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Yr(e,I)}) { 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]":`${Yr(e,I)}(bias[row])`};`:""} ${r} ${u.setByIndices("vec3(coords)","value")} } } `},Qi=(e,t,r,n,s=!1)=>{let a=e[0].dims,i=e[1].dims,d=a.slice(0,-2),c=i.slice(0,-2),p=n?n.slice(0,-2):r.slice(0,-2),w=Ne.size(p),y=a[a.length-2],u=a[a.length-1],$=i[i.length-1],T=u%4===0&&$%4===0,I=y<=8?[4,1,1]:[4,4,1],j=[8,8,1],G=[Math.ceil($/j[0]/I[0]),Math.ceil(y/j[1]/I[1]),Math.ceil(w/j[2]/I[2])],L=T?4:1,le=[...d,y,u/L],q=le.length,oe=[...c,u,$/L],Ke=oe.length,Ae=[w,y,$/L],ht=[{type:6,data:y},{type:6,data:$},{type:6,data:u}];qn(t,ht),ht.push(...kt(p,le,oe));let It=["rank","rank"],zt=e.length>2;zt&&(ht.push(...kt(e[2].dims)),It.push("rank")),ht.push(...kt(Ae));let cr=ir=>{let tr=p.length,mr=di("batchDims",e[0].dataType,tr,1),Lr=br(e[0].dataType),Mr=rt("a",e[0].dataType,q,L),zr=rt("b",e[1].dataType,Ke,L),At=Vt("result",e[0].dataType,Ae.length,L),Jt=[Mr,zr];if(zt){let Rr=s?L:1;Jt.push(rt("bias",e[2].dataType,e[2].dims.length,Rr))}let Zt=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];zn(t,Zt);let Qe=br(At.type.tensor),Ft=Gn(t,At.type.value,Qe),rr=Ys(L,zt,Ft,[mr,Mr,zr,At],[d,c,p],s);return` ${ir.registerUniforms(Zt).registerInternalVariables(mr).declareVariables(...Jt,At)} ${rr} ${T?Xs(I,j,Lr,mr):Qs(I,j,Lr,mr)} `};return{name:"MatMul",shaderCache:{hint:`${I};${t.activation};${T};${s}`,inputDependencies:It},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:G[0],y:G[1],z:G[2]},programUniforms:ht}),getShaderSource:cr}}}),gl,Bu,Lu=D(()=>{Kt(),pn(),nr(),Hn(),cs(),fl(),Zs(),gl=(e,t,r,n,s=!1,a,i=4,d=4,c=4,p="f32")=>{let w=It=>{switch(It){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${It} is not supported.`)}},y=It=>{switch(It){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${It} is not supported.`)}},u=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,$=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,T=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",I=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",j=e?"row":"col",G=e?"col":"row",L=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${j} / outWidth; let outCol = ${j} % outWidth; let WRow = ${G} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${G} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${G} % inChannels; var resData = ${Yr(i,p)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${T} && xCol >= 0 && xCol < ${I}) { ${u} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${w(i)} } return resData;`,le=e?t&&n?` let col = colIn * ${i}; ${L}`:` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${L} } return ${Yr(i,p)}(0.0);`:n&&r?` let col = colIn * ${i}; ${L}`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${L} } return ${Yr(i,p)}(0.0);`,q=`${y(d)}`,oe=Yr(c,p),Ke=Yr(e?i:d,p),Ae=Yr(e?d:i,p),ht=Gn(a,oe,p);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ke} { ${e?le:q} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ae} { ${e?q:le} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${oe}) { let col = colIn * ${c}; 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])"}; ${$} ${Hi(s)} ${ht} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Bu=(e,t,r,n,s,a,i,d)=>{let c=t.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],w=r[0],y=c?r[2]:r[3],u=c?r[1]:r[2],$=c?r[3]:r[1],T=c&&(p%4===0||p%3===0)&&$%4===0,I=c?$:y*u,j=c?y*u:$,G=[8,8,1],L=n<=8?[4,1,1]:[4,4,1],le=[Math.ceil(I/G[0]/L[0]),Math.ceil(j/G[1]/L[1]),Math.ceil(w/G[2]/L[2])];Fr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${le}`);let q=T?c&&p%4!==0?3:4:1,oe=G[1]*L[1],Ke=G[0]*L[0],Ae=Math.max(G[0]*q,G[1]),ht=n%oe===0,It=s%Ke===0,zt=a%Ae===0,cr=T?[q,4,4]:[1,1,1],ir=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];qn(t,ir),ir.push(...kt(e[0].dims,e[1].dims));let tr=["rank","rank"];i&&(ir.push(...kt(e[2].dims)),tr.push("rank")),ir.push(...kt(r));let mr=Lr=>{let Mr=[{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,Mr);let zr=T?4:1,At=br(e[0].dataType),Jt=` fn setOutputAtIndex(flatIndex : i32, value : ${T?`vec4<${At}>`:At}) { result[flatIndex] = ${T?`vec4<${At}>`:At}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${T?`vec4<${At}>`:At}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${T?"/ 4":""}, value); }`,Zt=rt("x",e[0].dataType,e[0].dims.length,q===3?1:q),Qe=rt("w",e[1].dataType,e[1].dims.length,zr),Ft=[Zt,Qe],rr=Vt("result",e[0].dataType,r.length,zr);if(i){let Rr=rt("bias",e[2].dataType,e[2].dims.length,zr);Ft.push(Rr),Jt+=` fn getBiasByOutputCoords(coords : vec4) -> ${T?`vec4<${At}>`:At} { return bias[coords.${c?"w":"y"}${T?"/ 4":""}]; }`}return` ${Ki("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 }; ${Lr.registerUniforms(Mr).declareVariables(...Ft,rr)} ${Jt} ${gl(c,ht,It,zt,i,t,cr[0],cr[1],cr[2],At)} ${T?Xs(L,G,At,void 0,!c,Ae):Qs(L,G,At,void 0,!c,Ae,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${q};${T};${ht};${It};${zt};${oe};${Ke};${Ae}`,inputDependencies:tr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:le[0],y:le[1],z:le[2]},programUniforms:ir}),getShaderSource:mr}}}),wl,Yi,Dn,yl,Zi,bl,vl,Ml,Ji=D(()=>{Kt(),pn(),Xt(),nr(),Hn(),cs(),wl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Dn=(e,t)=>t<=1?e:e+(e-1)*(t-1),yl=(e,t,r,n=1)=>{let s=Dn(t,n);return Math.floor((e[0]*(r-1)-r+s)/2)},Zi=(e,t,r,n,s)=>{s==null&&(s=yl(e,t[0],n[0]));let a=[0,0,0,r];for(let i=0;i<3;i++)e[i]+2*s>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*s)/n[i]+1));return a},bl=(e,t,r,n,s,a,i,d,c,p)=>{let w,y,u,$;if(e==="VALID"&&(e=0),typeof e=="number"){w={top:e,bottom:e,left:e,right:e,front:e,back:e};let T=Zi([t,r,n,1],[d,c,p],1,[s,a,i],e);y=T[0],u=T[1],$=T[2]}else if(Array.isArray(e)){if(!e.every((I,j,G)=>I===G[0]))throw Error(`Unsupported padding parameter: ${e}`);w={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let T=Zi([t,r,n,1],[d,c,p],1,[s,a,i],e[0]);y=T[0],u=T[1],$=T[2]}else if(e==="SAME_UPPER"){y=Math.ceil(t/s),u=Math.ceil(r/a),$=Math.ceil(n/i);let T=(y-1)*s+d-t,I=(u-1)*a+c-r,j=($-1)*i+p-n,G=Math.floor(T/2),L=T-G,le=Math.floor(I/2),q=I-le,oe=Math.floor(j/2),Ke=j-oe;w={top:le,bottom:q,left:oe,right:Ke,front:G,back:L}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:w,outDepth:y,outHeight:u,outWidth:$}},vl=(e,t,r,n,s,a=!1,i="channelsLast")=>{let d,c,p,w,y;if(i==="channelsLast")[d,c,p,w,y]=e;else if(i==="channelsFirst")[d,y,c,p,w]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,$,T,I]=t,[j,G,L]=Yi(r),[le,q,oe]=Yi(n),Ke=Dn($,le),Ae=Dn(T,q),ht=Dn(I,oe),{padInfo:It,outDepth:zt,outHeight:cr,outWidth:ir}=bl(s,c,p,w,j,G,L,Ke,Ae,ht),tr=a?u*y:u,mr=[0,0,0,0,0];return i==="channelsFirst"?mr=[d,tr,zt,cr,ir]:i==="channelsLast"&&(mr=[d,zt,cr,ir,tr]),{batchSize:d,dataFormat:i,inDepth:c,inHeight:p,inWidth:w,inChannels:y,outDepth:zt,outHeight:cr,outWidth:ir,outChannels:tr,padInfo:It,strideDepth:j,strideHeight:G,strideWidth:L,filterDepth:$,filterHeight:T,filterWidth:I,effectiveFilterDepth:Ke,effectiveFilterHeight:Ae,effectiveFilterWidth:ht,dilationDepth:le,dilationHeight:q,dilationWidth:oe,inShape:e,outShape:mr,filterShape:t}},Ml=(e,t,r,n,s,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let d=[64,1,1],c={x:r.map((j,G)=>G)},p=[Math.ceil(wl(c.x.map(j=>r[j]))/d[0]),1,1];Fr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);let w=1,y=Ne.size(r),u=[{type:12,data:y},{type:12,data:n},{type:12,data:s},{type:12,data:t.strides},{type:12,data:t.dilations}];qn(t,u),u.push(...kt(e[0].dims,e[1].dims));let $=["rank","rank"],T=e.length===3;T&&(u.push(...kt(e[2].dims)),$.push("rank")),u.push(...kt(r));let I=j=>{let G=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:s.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];zn(t,G);let L=1,le=br(e[0].dataType),q=rt("x",e[0].dataType,e[0].dims.length,w),oe=rt("W",e[1].dataType,e[1].dims.length,L),Ke=[q,oe],Ae=Vt("result",e[0].dataType,r.length,L),ht="";if(T){let cr=rt("bias",e[2].dataType,e[2].dims.length,L);Ke.push(cr),ht+=` fn getBiasByOutputCoords(coords : array) -> ${le} { return bias[${i?Ot("coords",4,5):Ot("coords",1,5)}]; }`}let It=Yr(w,le),zt=Gn(t,It,le);return` ${ht} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${q.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${oe.getByIndices("aIndices")}; } ${j.registerUniforms(G).declareVariables(...Ke,Ae)} ${j.mainStart()} ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Ae.offsetToIndices("global_idx")}; let batch = ${Ot("coords",0,q.rank)}; let d2 = ${i?Ot("coords",q.rank-1,q.rank):Ot("coords",1,q.rank)}; let xFRCCorner = vec3(${i?Ot("coords",1,q.rank):Ot("coords",2,q.rank)}, ${i?Ot("coords",2,q.rank):Ot("coords",3,q.rank)}, ${i?Ot("coords",3,q.rank):Ot("coords",4,q.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${i?Ot("uniforms.x_shape",1,q.rank):Ot("uniforms.x_shape",2,q.rank)}; let xShapeZ = ${i?Ot("uniforms.x_shape",2,q.rank):Ot("uniforms.x_shape",3,q.rank)}; let xShapeW = ${i?Ot("uniforms.x_shape",3,q.rank):Ot("uniforms.x_shape",4,q.rank)}; let xShapeU = ${i?Ot("uniforms.x_shape",4,q.rank):Ot("uniforms.x_shape",1,q.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${i?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${i?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${i?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${T?"value = value + getBiasByOutputCoords(coords)":""}; ${zt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${w};${T}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:u}),getShaderSource:I}}}),xl,Tl,Ru=D(()=>{Kt(),Xt(),nr(),Sl(),Hn(),xl=(e,t,r)=>{let n=e.length>2,s=n?"value += b[output_channel];":"",a=e[0].dims,i=e[1].dims,d=i[0]/t.group,c=t.format==="NHWC",p=Js(a,i,t.dilations,t.pads,t.strides,c),w=Ne.size(p),y=[{type:12,data:w},{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:d}];qn(t,y),y.push(...kt(a,i));let u=["rank","rank"];n&&(y.push(...kt(e[2].dims)),u.push("rank")),y.push(...kt(p));let $=T=>{let I=Vt("output",e[0].dataType,p.length),j=br(I.type.tensor),G=Gn(t,I.type.value,j),L=rt("x",e[0].dataType,a.length),le=rt("w",e[1].dataType,i.length),q=[L,le];n&&q.push(rt("b",e[2].dataType,e[2].dims.length));let oe=[{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"}];return zn(t,oe),` ${T.registerUniforms(oe).declareVariables(...q,I)} ${T.mainStart()} ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${I.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${c?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${c?1:2}], outputIndices[${c?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${I.type.value} = ${I.type.value}(0); for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = group_id * uniforms.w_shape[1] + 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[${c?1: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[${c?2:3}]) { continue; } let xVal = ${c?L.get("batch","xHeight","xWidth","input_channel"):L.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${le.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${s} ${G} ${I.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:u},getRunData:()=>({outputs:[{dims:r?r(p):p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:y}),getShaderSource:$}},Tl=(e,t,r)=>{let n=e.length>2,s=_r(r[3]),a=_r(r[2]),i=Ne.size(r)/s/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/s],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/s],p=[r[0],r[1],r[2],r[3]/s],w=[{type:12,data:i},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];qn(t,w),w.push(...kt(d,c,p));let y=(a-1)*t.strides[1]+c[1],u=$=>{let T=Vt("output",e[0].dataType,p.length,s),I=br(T.type.tensor),j=Gn(t,T.type.value,I),G=rt("x",e[0].dataType,d.length,s),L=rt("w",e[1].dataType,c.length,s),le=[G,L];n&&le.push(rt("b",e[2].dataType,e[2].dims,s));let q=n?"value += b[output_channel];":"",oe=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return zn(t,oe),` ${$.registerUniforms(oe).declareVariables(...le,T)} ${$.mainStart()} ${$.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] / ${a}u; let col = (index1 % width1) * ${a}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<${G.type.value}, ${y}>; var values: array<${T.type.value}, ${a}>; 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 < ${y}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${G.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${G.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { let w_val = ${L.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${a}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${a}u; i++) { var value = values[i]; ${q} ${j} ${T.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${s};${a};${y};${c[0]};${c[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:w}),getShaderSource:u}}}),ea,$l,kl,ta=D(()=>{Kt(),Xt(),Zs(),nr(),Hn(),ea=(e,t,r,n,s=!1)=>{let a=e[0].dims,i=e[1].dims,d=a[a.length-2],c=i[i.length-1],p=a[a.length-1],w=_r(c),y=_r(p),u=_r(d),$=Ne.size(r)/w/u,T=e.length>2,I=n?n.slice(0,-2):r.slice(0,-2),j=[Ne.size(I),d,c],G=[{type:12,data:$},{type:12,data:d},{type:12,data:c},{type:12,data:p}];qn(t,G),G.push(...kt(I,a,i)),T&&G.push(...kt(e[2].dims)),G.push(...kt(j));let L=le=>{let q=di("batch_dims",e[0].dataType,I.length),oe=rt("a",e[0].dataType,a.length,y),Ke=rt("b",e[1].dataType,i.length,w),Ae=Vt("output",e[0].dataType,j.length,w),ht=br(Ae.type.tensor),It=Gn(t,Ae.type.value,ht),zt=[oe,Ke],cr="";if(T){let Jt=s?w:1;zt.push(rt("bias",e[2].dataType,e[2].dims.length,Jt)),cr=`${s?`value += bias[col / ${Jt}];`:`value += ${Ae.type.value}(bias[row + i]);`}`}let ir=a.slice(0,-2),tr=i.slice(0,-2),mr=os(ir,I),Lr=os(tr,I),Mr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];zn(t,Mr);let zr=(Jt,Zt)=>{let Qe=Jt.rank,Ft=Jt.name;if(Qe===2)return`var ${Ft}_indices = ${Jt.type.indices}(0u, 0u);`;let rr=q.rank,Rr=`var ${Ft}_indices: ${Jt.type.indices};`;for(let qr=Qe-2-1,rn=rr-1;qr>=0;qr--,rn--)Rr+=` ${Ft}_indices[${qr}] = ${rr>1?`batch_indices[${rn}]`:"batch_indices"};`;return Zt.forEach(qr=>{Rr+=` ${Ft}_indices[${qr}] = 0;`}),Rr+=`${Ft}_indices[${Qe-2}] = 0u; ${Ft}_indices[${Qe-1}] = 0u;`,Rr},At=()=>{let Jt=`var a_data: ${oe.type.value};`;for(let Zt=0;Zt; for (var k: u32 = 0u; k < uniforms.K; k = k + ${y}) { ${At()} } for (var i = 0u; i < ${u}u; i++) { var value = values[i]; ${cr} ${It} let cur_indices = ${Ae.type.indices}(batch, row + i, col); let offset = ${Ae.indicesToOffset("cur_indices")}; ${Ae.setByOffset(`offset / ${w}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${w};${y};${u};${s}`,inputDependencies:T?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:G}),getShaderSource:L}},$l=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},kl=e=>{$l(e.inputs);let t=Kr.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(ea(e.inputs,{activation:""},t)):e.compute(Qi(e.inputs,{activation:""},t))}}),Js,ei,ra,ti,na,sa,Cl,El,$s,Sl=D(()=>{Xt(),Lu(),Ji(),Zs(),Ru(),Hn(),ta(),ls(),Js=(e,t,r,n,s,a)=>{let i=e[0],d=e.slice(a?1:2,a?3:4),c=d.length,p=t[0],w=t.slice(2).map((u,$)=>u+(u-1)*(r[$]-1)),y=d.map((u,$)=>u+n[$]+n[$+c]).map((u,$)=>Math.floor((u-w[$]+s[$])/s[$]));return y.splice(0,0,i),y.splice(a?3:1,0,p),y},ei=[2,3,1,0],ra=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ti=(e,t)=>{let r=e.kernelShape.slice();for(let a=2;a{let t=qi(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],s=e.dilations,a=e.group,i=e.kernel_shape,d=e.pads,c=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,pads:d,strides:c,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},sa=(e,t,r)=>{let n=ti(r,t),s=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&s&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let Ke=Js(t[0].dims,t[1].dims,r.dilations,n.pads,r.strides,s),Ae=e.kernelCustomData.wT??e.compute(En(t[1],ei),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ae);let ht=[t[0],Ae];t.length===3&&ht.push(t[2]),e.compute(Tl(ht,n,Ke),{inputs:ht})}else e.compute(xl(t,n));return}let a=t.length===3,i=t[0].dims[s?1:2],d=t[0].dims[s?2:3],c=t[0].dims[s?3:1],p=t[1].dims[2],w=t[1].dims[3],y=Js(t[0].dims,t[1].dims,r.dilations,n.pads,r.strides,s),u=y[s?1:2],$=y[s?2:3],T=y[s?3:1],I=s&&p===i&&w===d&&r.pads[0]===0&&r.pads[1]===0;if(I||p===1&&w===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let Ke=y[0],Ae,ht,It,zt=[];if(s){let tr=e.kernelCustomData.wT??e.compute(En(t[1],ei),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=tr),I){let mr=i*d*c;Ae=t[0].reshape([1,Ke,mr]),ht=tr.reshape([1,mr,T]),It=[1,Ke,T]}else Ae=t[0].reshape([Ke,i*d,c]),ht=tr.reshape([1,c,T]),It=[Ke,u*$,T];zt.push(Ae),zt.push(ht)}else Ae=t[0].reshape([Ke,c,i*d]),ht=t[1].reshape([1,T,c]),It=[Ke,T,u*$],zt.push(ht),zt.push(Ae);a&&zt.push(t[2]);let cr=It[2],ir=zt[0].dims[zt[0].dims.length-1];cr<8&&ir<8?e.compute(ea(zt,n,y,It,s),{inputs:zt}):e.compute(Qi(zt,n,y,It,s),{inputs:zt});return}let j=!0,G=e.kernelCustomData.wT??e.compute(En(t[1],ei),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=G);let L=[t[0],G];a&&L.push(t[2]);let le=s?u*$:T,q=s?T:u*$,oe=p*w*c;e.compute(Bu(L,n,y,le,q,oe,a,j),{inputs:L})},Cl=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),d=[1].concat(t.kernelShape),c=ti({...t,pads:s,strides:a,dilations:i,kernelShape:d},n);e.compute(xl(n,c,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},El=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",s=ti(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,i=vl(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(Ml(t,s,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},$s=(e,t)=>{ra(e.inputs,t),e.inputs[0].dims.length===3?Cl(e,t):e.inputs[0].dims.length===5?El(e,e.inputs,t):sa(e,e.inputs,t)}}),Pl,Al,Nu=D(()=>{Kt(),pn(),nr(),Hn(),cs(),fl(),Zs(),Pl=(e,t=!1,r,n,s=4)=>{let a=j=>{switch(j){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 ${j} is not supported.`)}},i=e?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,d=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,c=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",p=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",w=e?"row":"col",y=e?"col":"row",u=` let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${w} / outWidth; let outCol = ${w} % outWidth; let WRow = ${y} / (uniforms.filter_dims[1] * inChannels); let WCol = ${y} / 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(${c}) || fract(xR) > 0.0) { return ${n}(0.0); } if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) { return ${n}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${y} % inChannels; ${i} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,$=e?` let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${u} } return ${n}(0.0);`:` let col = colIn * ${s}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${u} } return ${n}(0.0);`,T=` let col = colIn * ${s}; let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${a(s)} } return ${n}(0.0); `,I=Gn(r,n);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?$:T} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?T:$} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${d} ${Hi(t)} ${I} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; } }`},Al=(e,t,r,n,s,a,i,d)=>{let c=t.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],w=r[0],y=c?r[2]:r[3],u=c?r[1]:r[2],$=c?r[3]:r[1],T=c&&p%4===0&&p%3&&$%4===0,I=c?$:y*u,j=c?y*u:$,G=[8,8,1],L=n<=8?[4,1,1]:[4,4,1],le=[Math.ceil(I/G[0]/L[0]),Math.ceil(j/G[1]/L[1]),Math.ceil(w/G[2]/L[2])];Fr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${le}`);let q=T?4:1,oe=Math.max(G[0]*q,G[1]),Ke=T?4:1,Ae=[t.kernelShape[c?1:2],t.kernelShape[c?2:3]],ht=[Ae[0]+(t.dilations[0]<=1?0:(Ae[0]-1)*(t.dilations[0]-1)),Ae[1]+(t.dilations[1]<=1?0:(Ae[1]-1)*(t.dilations[1]-1))],It=[ht[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),ht[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],zt=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Ae},{type:6,data:It}];qn(t,zt),zt.push(...kt(e[0].dims,e[1].dims));let cr=["rank","rank"];i&&(zt.push(...kt(e[2].dims)),cr.push("rank")),zt.push(...kt(r));let ir=tr=>{let mr=rt("x",e[0].dataType,e[0].dims.length,Ke),Lr=rt("w",e[1].dataType,e[1].dims.length,1),Mr=Vt("result",e[0].dataType,r.length,Ke),zr=[mr,Lr],At="";if(i){let Qe=rt("bias",e[2].dataType,e[2].dims.length,Ke);zr.push(Qe),At+=` fn getBiasByOutputCoords(coords : vec4) -> ${Qe.type.value} { return bias[coords.${c?"w":"y"}${T?"/ 4":""}]; }`}let Jt=[{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:Ae.length},{name:"pads",type:"i32",length:It.length}];zn(t,Jt);let Zt=br(e[0].dataType,1);if(Zt!=="f16"&&Zt!=="f32")throw new Error(`elemType ${Zt} is not supported.`);return` ${Ki("uniforms.result_strides")} ${tr.registerUniforms(Jt).declareVariables(...zr,Mr)}; ${At} ${Pl(c,i,t,mr.type.value,q)} ${T?Xs(L,G,Zt,void 0,!c,oe):Qs(L,G,Zt,void 0,!c,oe,!1,void 0,d)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${L};${G};${T}`,inputDependencies:cr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:le[0],y:le[1],z:le[2]},programUniforms:zt}),getShaderSource:ir}}}),ia,ks,$d=D(()=>{Kt(),pn(),Xt(),nr(),ia=(e,t,r,n,s,a=!1,i,d,c=!1)=>{let p=c?1:2,w=c?2:3,y=c?3:1,u=a?2:1,$=` fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${i}>`:i}) { result[flatIndex] = ${a?`vec4<${i}>`:i}(value); }`;n&&($+=` fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${i}>`:i} { return bias[coords.${c?"w":"y"}${a?"/ 4":""}]; }`);let T=a?4:1,I=rt("W",t[1].dataType,t[1].dims.length,T),j=rt("Dy",t[0].dataType,t[0].dims.length,T),G=[j,I];n&&G.push(rt("bias",t[2].dataType,[r[y]].length,T));let L=Vt("result",t[0].dataType,r.length,T),le=`{ let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${s?"global_id.y":"workgroup_id.y"} * ${u}; let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${u}>; for (var i = 0; i < ${u}; i++) { dotProd[i] = vec4<${i}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${i}(dyCorner.x) + ${i}(wR)) / ${i}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${i}(dyCorner.y) + ${i}(wC)) / ${i}(uniforms.strides.y); let dyC2 = (${i}(dyCorner.y) + 1.0 + ${i}(wC)) / ${i}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${i}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${j.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${j.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${y}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${j.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${j.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${u}; i = i + 1) { let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${i}>(0.0)`}; ${L.set("batch","r","c + i","d1","value")}; } }`,q=` let outputIndices = ${L.offsetToIndices("global_idx")}; let batch = ${L.indicesGet("outputIndices",0)}; let d1 = ${L.indicesGet("outputIndices",y)}; let r = ${L.indicesGet("outputIndices",p)}; let c = ${L.indicesGet("outputIndices",w)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${i}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[${p}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[${w}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${c?j.get("batch","idyR","idyC","inputChannel"):j.get("batch","inputChannel","idyR","idyC")}; let wValue = ${I.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${n?"bias[d1]":`${i}(0.0)`}; ${L.setByOffset("global_idx","value")}; `;return` ${e.registerUniforms(d).declareVariables(...G,L)} ${$} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${a?le:q}}`},ks=(e,t,r)=>{let n=e.length>2,s=t.outputShape,a=Ne.size(s),i=[Math.ceil(a/64),1,1];Fr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let d=t.format==="NHWC",c=["rank","rank"],p=[t.strides[0],t.strides[1]],w=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],y=[t.dilations[0],t.dilations[1]],u=[w[0]+(t.dilations[0]<=1?0:(t.kernelShape[d?1:2]-1)*(t.dilations[0]-1)),w[1]+(t.dilations[1]<=1?0:(t.kernelShape[d?2:3]-1)*(t.dilations[1]-1))],$=[u[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),u[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],T=!1,I=t.group,j=e[1].dims,G=j[0]/I,L=j[1],le=[{type:12,data:a},{type:12,data:p},{type:12,data:w},{type:12,data:y},{type:12,data:u},{type:6,data:$},{type:12,data:G},{type:12,data:L},...kt(e[0].dims,e[1].dims)];n&&(le.push(...kt(e[2].dims)),c.push("rank")),le.push(...kt(s));let q=i[1]===1&&i[2]===1,oe=Ke=>{let Ae=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:p.length},{name:"filter_dims",type:"u32",length:w.length},{name:"dilations",type:"u32",length:w.length},{name:"effective_filter_dims",type:"u32",length:u.length},{name:"pads",type:"i32",length:$.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],ht=br(e[0].dataType);return`${ia(Ke,e,s,n,q,T,ht,Ae,d)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:c},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:r?r(s):s,dataType:e[0].dataType}],programUniforms:le}),getShaderSource:oe}}}),Il,Fl,aa,oa,Ol,la,zl,Dl,ua,Vu,kd=D(()=>{Nu(),$d(),Hn(),ls(),Il=(e,t,r,n,s,a)=>(e-1)*t+r+(n-1)*s+1-a,Fl=(e,t,r,n,s)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[s]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[s]=a)},aa=(e,t,r,n,s,a,i,d,c,p)=>{let w=e.length-2,y=p.length===0;if(c.length===0)for(let T=0;T{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((y,u)=>y*u,1)===0){r.length=0;for(let y=2;yy+u,0)===0){let y=t[0].dims.length-2;c=new Array(y).fill(1)}let p=e.strides.slice();if(p.reduce((y,u)=>y+u,0)===0){let y=t[0].dims.length-2;p=new Array(y).fill(1)}aa(d,r,c,e.autoPad,e.group,s,p,n,i,a);let w=Object.assign({},e);return Object.assign(w,{kernelShape:r,pads:s,outputPadding:i,outputShape:a,dilations:c,strides:p}),w},Ol=e=>{let t=qi(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],s=e.dilations,a=e.group,i=e.kernelShape,d=e.pads,c=e.strides,p=e.wIsConst(),w=e.outputPadding,y=e.outputShape;return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,outputPadding:w,outputShape:y,pads:d,strides:c,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},la=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==s))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,d)=>i+d,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,d)=>i+d,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,d)=>i+d,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,d)=>i+d,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")},zl=[2,3,1,0],Dl=(e,t,r)=>{let n=oa(r,t),s=r.format==="NHWC",a=n.outputShape,i=a[s?3:1],d=t[0].dims[s?3:1];if(n.group!==1||i===1&&d===1){e.compute(ks(t,n));return}let c=a[s?1:2],p=a[s?2:3],w=t[1].dims[2],y=t[1].dims[3],u=s?c*p:i,$=s?i:c*p,T=w*y*d,I=!0,j=e.kernelCustomData.wT??e.compute(En(t[1],zl),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=j);let G=[t[0],j],L=t.length===3;L&&(!s&&t[2].dims.length===1?G.push(t[2].reshape([t[2].dims[0],1,1])):G.push(t[2])),e.compute(Al(G,n,a,u,$,T,L,I),{inputs:G})},ua=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=t.kernelShape;(s.length===0||s[0]===0)&&(s=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let d=t.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],i=[1].concat(i),a=[1].concat(a),s=[1].concat(s);let c=oa({...t,pads:d,strides:i,dilations:a,kernelShape:s},n);e.compute(ks(n,c,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},Vu=(e,t)=>{la(e.inputs,t),e.inputs[0].dims.length===3?ua(e,t):Dl(e,e.inputs,t)}}),da,ca,Bl,ju=D(()=>{Kt(),Xt(),pr(),nr(),da=(e,t,r,n)=>{let s=Ne.size(t),a=t.length,i=rt("input",e,a),d=Vt("output",e,a),c=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=Ne.normalizeAxis(c,a),w=y=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,$=Ot("uniforms.input_shape","uniforms.axis",a),T=n.reverse?u+(n.exclusive?" + 1":""):"0",I=n.reverse?$:u+(n.exclusive?"":" + 1");return` ${y.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,d)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${d.offsetToIndices("global_idx")}; var sum = ${d.type.value}(0); let first : i32 = ${T}; let last : i32 = ${I}; for (var i : i32 = first; i < last; i++) { ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${i.getByIndices("inputIndices")}; } ${d.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},{type:12,data:p},...kt(t,t)]}),getShaderSource:w}},ca=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,s=e.inputs[1];e.compute(da(n,r,s,t),{inputs:[0]})},Bl=e=>{let t=e.exclusive===1,r=e.reverse===1;return Ut({exclusive:t,reverse:r})}}),pa,Ll,Rl,ha,Nl,Uu=D(()=>{Kt(),Xt(),pr(),nr(),pa=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.")},Ll=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let a=0;a{let r,n,s,a,i,d,c=t.format==="NHWC",p=t.blocksize,w=t.mode==="DCR";c?([r,n,s,a]=e.dims,i=w?[r,n,s,p,p,a/p**2]:[r,n,s,a/p**2,p,p],d=w?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,s,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=w?[r,p,p,a/p**2,n,s]:[r,a/p**2,p,p,n,s],d=w?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let y=e.reshape(i),u=y.dims.length,$=e.dataType,T=rt("a",$,u),I=Vt("output",$,u),j=G=>` ${G.registerUniform("output_size","u32").declareVariables(T,I)} ${Ll(d,u,T,I)} ${G.mainStart()} ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${I.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${I.setByOffset("global_idx",T.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:G=>{let L=c?[r,n*p,s*p,a/p**2]:[r,a/p**2,n*p,s*p],le=Ne.size(L),q=y.dims,oe=Ne.sortBasedOnPerm(q,d);return{outputs:[{dims:L,dataType:G[0].dataType}],dispatchGroup:{x:Math.ceil(le/64)},programUniforms:[{type:12,data:le},...kt(q,oe)]}},getShaderSource:j}},ha=(e,t)=>{pa(e.inputs),e.compute(Rl(e.inputs[0],t))},Nl=e=>Ut({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Cs,Es,fa,Pr,Wu,Gu,qu,ri,Vl,jl,Ul,Hu=D(()=>{Kt(),Xt(),pr(),nr(),Cs="[a-zA-Z]|\\.\\.\\.",Es="("+Cs+")+",fa="^"+Es+"$",Pr="("+Es+",)*"+Es,Wu="^"+Pr+"$",Gu=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},qu=class{constructor(e,t){var s;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(Wu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let d=e[i].dims.slice();if(!a.match(RegExp(fa)))throw new Error("Invalid LHS term");let c=this.processTerm(a,!0,d,i);this.lhs.push(c)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Es)))throw new Error("Invalid RHS");(s=n.match(RegExp(Cs,"g")))==null||s.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let s=r.length,a=!1,i=[],d=0;if(!e.match(RegExp(fa))&&!t&&e!=="")throw new Error("Invalid LHS term");let c=e.match(RegExp(Cs,"g")),p=new Gu(n);return c==null||c.forEach((w,y)=>{if(w==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let u=s-c.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(d,d+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let $=0;$e+"_max",Vl=(e,t,r,n)=>{let s=e.map(p=>p.length).map((p,w)=>rt(`input${w}`,t,p)),a=Ne.size(n),i=Vt("output",t,n.length),d=[...r.symbolToInfo.keys()].filter(p=>!r.rhs.symbolToIndices.has(p)),c=p=>{let w=[],y="var prod = 1.0;",u="var sum = 0.0;",$="sum += prod;",T=[],I=[],j=[],G=[],L=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((q,oe)=>{var Ke;if(r.rhs.symbolToIndices.has(oe)){let Ae=(Ke=r.rhs.symbolToIndices.get(oe))==null?void 0:Ke[0];Ae!==void 0&&r.lhs.forEach((ht,It)=>{if(q.inputIndices.includes(It)){let zt=ht.symbolToIndices.get(oe);if(zt===void 0)throw new Error("Invalid symbol error");zt.forEach(cr=>{w.push(`${s[It].indicesSet(`input${It}Indices`,cr,i.indicesGet("outputIndices",Ae))}`)})}})}else r.lhs.forEach((Ae,ht)=>{if(q.inputIndices.includes(ht)){let It=Ae.symbolToIndices.get(oe);if(It===void 0)throw new Error("Invalid symbol error");It.forEach(zt=>{T.push(`${s[ht].indicesSet(`input${ht}Indices`,zt,`${oe}`)}`)}),G.push(`prod *= ${s[ht].getByIndices(`input${ht}Indices`)};`)}}),I.push(`for(var ${oe}: u32 = 0; ${oe} < uniforms.${ri(oe)}; ${oe}++) {`),j.push("}")});let le=L?[...w,`let sum = ${s.map((q,oe)=>q.getByIndices(`input${oe}Indices`)).join(" * ")};`]:[...w,u,...I,...T,y,...G,$,...j];return` ${p.registerUniforms(d.map(q=>({name:`${ri(q)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,i)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${i.offsetToIndices("global_idx")}; ${s.map((q,oe)=>`var input${oe}Indices: ${s[oe].type.indices};`).join(` `)} ${le.join(` `)}; ${i.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=d.filter(y=>r.symbolToInfo.has(y)).map(y=>{var u;return{type:12,data:((u=r.symbolToInfo.get(y))==null?void 0:u.dimValue)||0}});p.push({type:12,data:a});let w=e.map((y,u)=>[...kt(y)]).reduce((y,u)=>y.concat(u),p);return w.push(...kt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:w}},getShaderSource:c}},jl=(e,t)=>{let r=new qu(e.inputs,t.equation),n=r.outputDims,s=e.inputs.map((a,i)=>a.dims);e.compute(Vl(s,e.inputs[0].dataType,r,n))},Ul=e=>{let t=e.equation.replace(/\s+/g,"");return Ut({equation:t})}}),ma,ni,Wl,Gl,_a,Cd=D(()=>{Kt(),Xt(),nr(),ma=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let s=0;se.length>t.length?ni(e,t):ni(t,e),Gl=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Wl(t,r),s=e[0].dataType,a=s===9?4:1,i=Math.ceil(Ne.size(n)/a),d=p=>{let w=rt("input",s,t.length,a),y=Vt("output",s,n.length,a),u;if(s===9){let $=(T,I,j="")=>` let outputIndices${I} = ${y.offsetToIndices(`outputOffset + ${I}u`)}; let offset${I} = ${w.broadcastedIndicesToOffset(`outputIndices${I}`,y)}; let index${I} = offset${I} / 4u; let component${I} = offset${I} % 4u; ${T}[${I}] = ${j}(${w.getByOffset(`index${I}`)}[component${I}]); `;u=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${$("data",0,"u32")} ${$("data",1,"u32")} ${$("data",2,"u32")} ${$("data",3,"u32")} ${y.setByOffset("global_idx","data")} }`}else u=` let outputIndices = ${y.offsetToIndices("global_idx")}; let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",y)}; ${y.setByOffset("global_idx",w.getByOffset("inputOffset"))} }`;return` ${p.registerUniform("vec_size","u32").declareVariables(w,y)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${u}`},c=[{type:12,data:i},...kt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:c})}},_a=e=>{ma(e.inputs),e.compute(Gl(e.inputs),{inputs:[0]})}}),Ku,ql,Xu=D(()=>{Kt(),Xt(),nr(),Vi(),Ku=e=>{let t=e[0].dataType,r=Ne.size(e[0].dims),n=Ne.size(e[1].dims),s=n%4===0,a=i=>{let d=rt("x",t,[1],4),c=rt("bias",t,[1],4),p=Vt("y",t,[1],4),w=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],y=$=>` let bias${$}_offset: u32 = (global_idx * 4 + ${$}) % uniforms.bias_size; let bias${$} = ${c.getByOffset(`bias${$}_offset / 4`)}[bias${$}_offset % 4];`,u=s?` let bias = ${c.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${y(0)}${y(1)}${y(2)}${y(3)} let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(w).declareVariables(d,c,p)} ${Li(vr(t))} ${i.mainStart(hn)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${d.getByOffset("global_idx")}; ${u} let x_in = x + bias; ${p.setByOffset("global_idx",Ri("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/hn/4)}})}},ql=e=>{e.inputs.length<2||Ne.size(e.inputs[1].dims)===0?qo(e):e.compute(Ku(e.inputs))}}),Hl,Kl,Xl,Ql,Qu=D(()=>{Kt(),Xt(),pr(),nr(),Hl=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Kl=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Ne.normalizeAxis(t.axis,s),i=r.slice(0);i.splice(a,1,...n);let d=r[a],c=e[0].dataType===9?4:1,p=Math.ceil(Ne.size(i)/c),w=[{type:12,data:p},{type:6,data:d},{type:12,data:a},...kt(e[0].dims,e[1].dims,i)],y=u=>{let $=rt("data",e[0].dataType,e[0].dims.length,c),T=rt("inputIndices",e[1].dataType,e[1].dims.length),I=Vt("output",e[0].dataType,i.length,c),j=L=>{let le=n.length,q=`var indicesIndices${L} = ${T.type.indices}(0);`;for(let oe=0;oe1?`indicesIndices${L}[${oe}]`:`indicesIndices${L}`} = ${i.length>1?`outputIndices${L}[uniforms.axis + ${oe}]`:`outputIndices${L}`};`;q+=` var idx${L} = ${T.getByIndices(`indicesIndices${L}`)}; if (idx${L} < 0) { idx${L} = idx${L} + uniforms.axisDimLimit; } var dataIndices${L} : ${$.type.indices}; `;for(let oe=0,Ke=0;oe1?`dataIndices${L}[${oe}]`:`dataIndices${L}`} = u32(idx${L});`,Ke+=le):(q+=`${s>1?`dataIndices${L}[${oe}]`:`dataIndices${L}`} = ${i.length>1?`outputIndices${L}[${Ke}]`:`outputIndices${L}`};`,Ke++);return q},G;if(e[0].dataType===9){let L=(le,q,oe="")=>` let outputIndices${q} = ${I.offsetToIndices(`outputOffset + ${q}u`)}; ${j(q)}; let offset${q} = ${$.indicesToOffset(`dataIndices${q}`)}; let index${q} = offset${q} / 4u; let component${q} = offset${q} % 4u; ${le}[${q}] = ${oe}(${$.getByOffset(`index${q}`)}[component${q}]); `;G=` let outputOffset = global_idx * ${c}; var value = vec4(0); ${L("value",0,"u32")} ${L("value",1,"u32")} ${L("value",2,"u32")} ${L("value",3,"u32")} ${I.setByOffset("global_idx","value")} `}else G=` let outputIndices = ${I.offsetToIndices("global_idx")}; ${j("")}; let value = ${$.getByIndices("dataIndices")}; ${I.setByOffset("global_idx","value")}; `;return` ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables($,T,I)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${G} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:w}),getShaderSource:y}},Xl=e=>Ut({axis:e.axis}),Ql=(e,t)=>{let r=e.inputs;Hl(r),e.compute(Kl(e.inputs,t))}}),Yl,Zl,Jl,eu,Yu=D(()=>{Kt(),Xt(),pr(),nr(),Yl=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.`)},Zl=(e,t)=>{let r=e[0].dims,n=e[0].dataType,s=r.length,a=e[1].dims,i=e[1].dataType,d=Ne.normalizeAxis(t.axis,s),c=r[d],p=a.slice(0),w=Ne.size(p),y=rt("input",n,s),u=rt("indicesInput",i,a.length),$=Vt("output",n,p.length),T=[{type:12,data:w},{type:6,data:c},{type:12,data:d}];return T.push(...kt(r,a,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:T}),getShaderSource:I=>` ${I.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(y,u,$)} ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${$.offsetToIndices("global_idx")}; var idx = ${u.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${y.type.indices}(outputIndices); ${y.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${y.getByIndices("inputIndices")}; ${$.setByOffset("global_idx","value")}; }`}},Jl=e=>Ut({axis:e.axis}),eu=(e,t)=>{let r=e.inputs;Yl(r),e.compute(Zl(e.inputs,t))}}),tu,ru,nu,Zu,su=D(()=>{Kt(),Xt(),nr(),tu=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},ru=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[s,a,i]=yr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),d=[s,a];if(!d)throw new Error("Can't use gemm on the given tensors");let c=Ne.size(d),p=[{type:12,data:c},{type:12,data:s},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],w=["type","type"];e.length===3&&(p.push(...kt(e[2].dims)),w.push("rank")),p.push(...kt(d));let y=u=>{let $="";t.transA&&t.transB?$="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?$="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?$="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&($="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let T=t.alpha===1?"":"value *= uniforms.alpha;",I=rt("a",e[0].dataType,e[0].dims),j=rt("b",e[1].dataType,e[1].dims),G=I.type.value,L=null,le=[I,j];e.length===3&&(L=rt("c",e[2].dataType,e[2].dims.length),le.push(L));let q=Vt("output",e[0].dataType,d.length);le.push(q);let oe=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${u.registerUniforms(oe).declareVariables(...le)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${G}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${$} } ${T} ${L!=null?`let cOffset = ${L.broadcastedIndicesToOffset("vec2(m, n)",q)}; value += ${G}(uniforms.beta) * ${L.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:y}},nu=e=>{let t=e.transA,r=e.transB,n=e.alpha,s=e.beta;return{transA:t,transB:r,alpha:n,beta:s,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Zu=(e,t)=>{tu(e.inputs),e.compute(ru(e.inputs,t))}}),sn,iu,au,ga,ou,Ss,lu,uu=D(()=>{Kt(),Xt(),pr(),O(),qs(),nr(),ls(),sn=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,iu=(e,t)=>{let r=e[0],n=sn(e,1),s=sn(e,2),a=sn(e,3),i=sn(e,4),d=sn(e,5),c=sn(e,6),p=sn(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let w=r.dims[0],y=r.dims[1],u=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],$=y,T=0,I=0,j=Math.floor(u/t.numHeads);if(c&&p){if(c.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(c.dims[0]!==w||c.dims[1]!==t.numHeads||c.dims[3]!==j)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==w||p.dims[1]!==t.numHeads||p.dims[3]!==j)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[2]!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');T=c.dims[2],I=c.dims[2]}else if(c||p)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let G;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');G=2,$=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==j)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');G=5,$=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==j)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');G=0,$=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');G=3}if(a){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 L=T+$,le=0;if(i){le=8;let Ae=i.dims;throw Ae.length===1?Ae[0]===w?le=1:Ae[0]===3*w+2&&(le=3):Ae.length===2&&Ae[0]===w&&Ae[1]===L&&(le=5),le===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let q=!1,oe=u;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if($!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');oe=s.dims[2]}else{if($!==s.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');oe=s.dims[1]*s.dims[3],q=!0}}let Ke=!1;if(i)throw new Error("Key padding mask is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(d.dims[0]!==w||d.dims[1]!==t.numHeads||d.dims[2]!==y||d.dims[3]!==L)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:w,sequenceLength:y,pastSequenceLength:T,kvSequenceLength:$,totalSequenceLength:L,maxSequenceLength:I,inputHiddenSize:0,hiddenSize:u,vHiddenSize:oe,headSize:j,vHeadSize:Math.floor(oe/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:le,scale:t.scale,broadcastResPosBias:Ke,passPastInKv:q,qkvFormat:G}},au=e=>Ut({...e}),ga=Ut({perm:[0,2,1,3]}),ou=(e,t,r,n,s,a,i)=>{let d=[n,s,a],c=Ne.size(d),p=[{type:12,data:c},{type:12,data:i},{type:12,data:a}],w=y=>{let u=Vt("qkv_with_bias",t.dataType,d),$=rt("qkv",t.dataType,d),T=rt("bias",r.dataType,d),I=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${y.registerUniforms(I).declareVariables($,T,u)} ${y.mainStart()} ${y.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:d,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:w},{inputs:[t,r],outputs:[-1]})[0]},Ss=(e,t,r,n,s,a,i,d)=>{let c=a;if(i){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return c=ou(e,a,i,t,n,r*s,d),c=c.reshape([t,n,r,s]),e.compute(En(c,ga.perm),{inputs:[c],outputs:[-1]})[0]}else return a.dims.length===3&&(c=a.reshape([t,n,r,s])),e.compute(En(c,ga.perm),{inputs:[c],outputs:[-1]})[0]},lu=(e,t)=>{let r=iu(e.inputs,t),n=e.inputs[0],s=sn(e.inputs,1),a=sn(e.inputs,2),i=sn(e.inputs,3),d=sn(e.inputs,4),c=sn(e.inputs,5),p=sn(e.inputs,6),w=sn(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((s==null?void 0:s.dims.length)===5)throw new Error("Packed KV is not implemented");let y=s&&a&&s.dims.length===4&&a.dims.length===4,u=Ss(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(y)return us(e,u,s,a,d,void 0,p,w,c,r,t);if(!s||!a)throw new Error("key and value must be provided");let $=Ss(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,s,i,r.hiddenSize),T=Ss(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,i,2*r.hiddenSize);us(e,u,$,T,d,void 0,p,w,c,r,t)}}),wa,du,cu,ya,pu,hu=D(()=>{Kt(),Xt(),nr(),wa=e=>Array.from(e.getBigInt64Array(),Number),du=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(wa(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},cu=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??wa(e[1]),s=cu(r,n),a=Ne.size(s),i=e[0].dataType,d=rt("input",i,r.length),c=Vt("output",i,s.length),p=w=>` const inputShape = ${d.indices(...r)}; ${w.registerUniform("output_size","u32").declareVariables(d,c)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${c.offsetToIndices("global_idx")}; var input_indices: ${d.type.indices}; for (var i = 0; i < ${r.length}; i++) { let input_dim_i = ${d.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${c.indicesGet("output_indices","i")} % input_dim_i; ${d.indicesSet("input_indices","i","input_dim_value")} } ${c.setByOffset("global_idx",d.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...kt(e[0].dims,s)]}),getShaderSource:p}},pu=e=>{du(e.inputs),e.compute(ya(e.inputs),{inputs:[0]})}}),fu,ba,mu,_u,va,gu,Ju=D(()=>{Kt(),Xt(),pr(),qs(),nr(),uu(),hu(),ls(),fu=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,c=r.dims[0],p=r.dims[1],w=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],y=p,u=0,$=0,T=Math.floor(w/t.numHeads),I=a&&a.dims.length!==0,j=i&&i.dims.length!==0,G=!0;if(I&&j){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=a.dims[1],$=a.dims[1]}else if(I||j)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let L;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');L=2,y=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==T)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');L=5,y=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==T)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');L=0,y=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');L=3}let le=0,q=!1,oe=w;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(y!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');oe=s.dims[2]}else{if(y!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');oe=s.dims[1]*s.dims[3],q=!0}}let Ke=u+y;return{batchSize:c,sequenceLength:p,pastSequenceLength:u,kvSequenceLength:y,totalSequenceLength:Ke,maxSequenceLength:$,inputHiddenSize:0,hiddenSize:w,vHiddenSize:oe,headSize:T,vHeadSize:Math.floor(oe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:le,scale:t.scale,broadcastResPosBias:!1,passPastInKv:q,qkvFormat:L,isPastkvBSNH:G}},ba=(e,t,r,n)=>{let s=[n.batchSize,n.totalSequenceLength,n.kvNumHeads,n.headSize],a=4,i=Ne.size(s)/a,d=n.totalSequenceLength,c=Vt("present_kv",r,s.length,a),p=rt("new_kv",e.dataType,e.dims.length,a),w=t?rt("past_kv",t.dataType,t.dims.length,a):void 0,y=Math.ceil(n.headSize/a),u={x:d,y:e.dims[0],z:1},$=t?["rank","rank"]:["rank"],T=[{type:12,data:i},{type:12,data:n.pastSequenceLength},{type:12,data:n.kvSequenceLength},{type:12,data:n.totalSequenceLength}],I=[p];w?(T.push(...kt(e.dims),...kt(t.dims),...kt(s)),I.push(w)):T.push(...kt(e.dims),...kt(s));let j=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],G=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; var past_head_stride = uniforms.past_seqlen * H; if (is_bsnh) { past_head_stride = H; } let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; present_kv[out_offset] = past_kv[in_offset];`,L=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; let new_row_stride = num_heads * H; let new_head_stride = H; let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; present_kv[out_offset] = new_kv[in_offset];`,le=t?`if (s < past_seqlen) { ${G} } else if (s < past_seqlen + uniforms.new_seqlen) { ${L} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${L} }`,q=oe=>` ${oe.registerUniforms(j).declareVariables(...I,c)} ${oe.mainStart([y,n.kvNumHeads,1])} ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${c.offsetToIndices("global_idx")}; let h = local_id.x; let n = local_id.y; let s = workgroup_id.x; let b = workgroup_id.y; let num_heads = ${n.kvNumHeads}u; let H = ${y}u; let present_seqlen = uniforms.present_seqlen; let present_batch_stride = present_seqlen * num_heads * H; var row_stride = H; let is_bsnh = ${n.isPastkvBSNH}; if (is_bsnh) { row_stride = num_heads * H; } var present_head_stride = present_seqlen * H; if (is_bsnh) { present_head_stride = H; } let past_seqlen = uniforms.past_seqlen; let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; ${le} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${n.kvNumHeads}${y}${!!t}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:u,programUniforms:T}),getShaderSource:q}},mu=e=>Ut({...e}),_u=Ut({perm:[0,2,1,3]}),va=(e,t,r,n,s)=>{let a=t,i=n.kvNumHeads,d=n.nReps;return t.dims.length===3&&n.kvSequenceLength!==0&&(a=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize])),r?a=e.compute(ba(a,r,a.dataType,n),{inputs:[a,r],outputs:[n.isPastkvBSNH?s:-1]})[0]:a=e.compute(ba(a,void 0,a.dataType,n),{inputs:[a],outputs:[n.isPastkvBSNH?s:-1]})[0],d!==1&&(a=e.compute(ya([a],[1,1,1,d]),{inputs:[a],outputs:[-1]})[0],a=a.reshape([n.batchSize,n.totalSequenceLength,i*d,n.headSize])),e.compute(En(a,_u.perm),{inputs:[a],outputs:[-1]})[0]},gu=(e,t)=>{var c;let r=fu(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((c=e.inputs[1])==null?void 0:c.dims.length)===5)throw new Error("Packed KV is not implemented");let n=Ss(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],void 0,0),s=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,i=va(e,e.inputs[1],s,r,1),d=va(e,e.inputs[2],a,r,2);us(e,n,i,d,void 0,void 0,void 0,void 0,void 0,r,t)}}),wu,yu,bu,vu,Ed=D(()=>{Kt(),Xt(),nr(),wu=(e,t)=>{let r=e[0].dims,n=r,s=2,a=Ne.sizeToDimension(r,s),i=Ne.sizeFromDimension(r,s),d=_r(i),c=i/d,p=[r[0],r[1],c],w=["rank","type","type"],y=[{type:12,data:i},{type:12,data:c}];y.push(...kt(p,p));let u=$=>{let T=rt("x",e[0].dataType,p.length,d),I=rt("scale",e[1].dataType,e[1].dims),j=rt("bias",e[2].dataType,e[2].dims),G=Vt("output",e[0].dataType,p.length,d),L=[T,I,j,G],le=T.type.value,q=d===1?"f32":`vec${d}`,oe=64,Ke=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${q}, ${oe}>; const workgroupSize = ${oe}u; ${$.registerUniforms(Ke).declareVariables(...L)} ${$.mainStart(oe)} let norm = global_idx / workgroupSize; let batch = norm / uniforms.x_shape[1]; let channel = norm % uniforms.x_shape[1]; let localIndex = local_id.x; // initialize workgroup memory var initial = ${q}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${q}(${T.get("batch","channel","h")}); } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the mean of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { meanShared = ${fn("workgroupShared[0]",d)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${q}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${q}(${T.get("batch","channel","h")}) - ${q}(meanShared); initial = initial + deviation * deviation; } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the sum of square of deviation of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { squaredNormShared = ${fn("workgroupShared[0]",d)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); let channelScale = invStdDev * f32(${I.getByOffset("channel")}); let channelShift = f32(${j.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${T.get("batch","channel","h")} * ${le}(${q}(channelScale)) + ${le}(${q}(channelShift)); ${G.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${d}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:a},programUniforms:y}),getShaderSource:u}},yu=(e,t,r,n,s,a,i,d)=>{let c=_r(i),p=64,w=c===1?"vec2f":`mat2x${c}f`,y=c===1?"f32":`vec${c}f`,u=(Ke,Ae)=>`${w}(${Ke}, ${Ae})`,$=s*i/c,T=Math.ceil(a/p),I=["type"],j=[{type:12,data:T},{type:12,data:a},{type:12,data:Math.floor(i/c)},{type:12,data:Math.floor(a*i/c)}],G=Ke=>{let Ae=rt("input",t.dataType,t.dims,c);return` ${Ke.declareVariables(Ae)} @group(0) @binding(1) var output : array<${w}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${Ke.mainStart(p)} let currentImageNumber = global_idx / ${p} / uniforms.C; let currentChannelNumber = (global_idx / ${p}) % uniforms.C; let wgOffset = local_id.x * uniforms.wg_size; if (wgOffset >= uniforms.H) { return; } let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; var sum = ${Sr("f32",c)}; var squaredSum = ${Sr("f32",c)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${y}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${u("sum","squaredSum")}; }`},L=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${c}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:[s,i,p,2],dataType:1}],dispatchGroup:{x:s*i/c},programUniforms:j}),getShaderSource:G},{inputs:[t],outputs:[-1]})[0],le=[{type:12,data:$},{type:12,data:a},{type:12,data:Math.floor(i/c)},{type:12,data:Math.floor(p*i/c)}],q=["type","type","type"],oe=Ke=>{let Ae=rt("scale",r.dataType,r.dims,c),ht=rt("bias",n.dataType,n.dims,c);return` @group(0) @binding(0) var input : array<${w}>; @group(0) @binding(1) var scale : array<${Ae.type.storage}>; @group(0) @binding(2) var bias : array<${ht.type.storage}>; @group(0) @binding(3) var output : array<${w}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${Ke.mainStart()} ${Ke.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} let currentImageNumber = global_idx / uniforms.C; let currentChannelNumber = global_idx % uniforms.C; let offset = currentImageNumber * uniforms.image_size; var sum = ${Sr("f32",c)}; var squaredSum = ${Sr("f32",c)}; for (var i: u32 = 0; i < min(${p}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${p}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${d})); let channelScale = invStdDev * ${y}(scale[currentChannelNumber]); let channelShift = ${y}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${u("channelScale","channelShift")}; }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${c};${d}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:[s,i,2],dataType:1}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:le}),getShaderSource:oe},{inputs:[L,r,n],outputs:[-1]})[0]},bu=(e,t,r)=>{let n=t[0].dims,s=n,a=n[0],i=n[n.length-1],d=Ne.sizeFromDimension(n,1)/i,c=_r(i),p=Ne.size(s)/c,w=[{type:12,data:d},{type:12,data:Math.floor(i/c)}],y=["type","type"],u=yu(e,t[0],t[1],t[2],a,d,i,r.epsilon),$=T=>{let I=br(t[0].dataType),j=c===1?"vec2f":`mat2x${c}f`,G=c===1?I:`vec${c}<${I}>`,L=rt("input",t[0].dataType,t[0].dims,c),le=Vt("output",t[0].dataType,s,c);return` @group(0) @binding(0) var input : array<${L.type.storage}>; @group(0) @binding(1) var scaleInput : array<${j}>; @group(0) @binding(2) var output : array<${le.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${T.mainStart()} let currentImageNumber = global_idx / (uniforms.C * uniforms.H); let currentChannelNumber = global_idx % uniforms.C; let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; let scale = scaleInput[scaleOffset]; output[global_idx] = fma(input[global_idx], ${G}(scale[0]), ${G}(scale[1])); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${c}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:w}),getShaderSource:$},{inputs:[t[0],u]})},vu=(e,t)=>{t.format==="NHWC"?bu(e,e.inputs,t):e.compute(wu(e.inputs,t))}}),or,Mu,Hr,Zr=D(()=>{Kt(),Xt(),nr(),or=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Mu=(e,t,r)=>{let n=t.simplified,s=e[0].dims,a=e[1],i=!n&&e[2],d=s,c=Ne.normalizeAxis(t.axis,s.length),p=Ne.sizeToDimension(s,c),w=Ne.sizeFromDimension(s,c),y=Ne.size(a.dims),u=i?Ne.size(i.dims):0;if(y!==w||i&&u!==w)throw new Error(`Size of X.shape()[axis:] == ${w}. Size of scale and bias (if provided) must match this. Got scale size of ${y} and bias size of ${u}`);let $=[];for(let oe=0;oe1,L=r>2,le=oe=>{let Ke=br(e[0].dataType),Ae=[rt("x",e[0].dataType,e[0].dims,T),rt("scale",a.dataType,a.dims,T)];i&&Ae.push(rt("bias",i.dataType,i.dims,T)),Ae.push(Vt("output",e[0].dataType,d,T)),G&&Ae.push(Vt("mean_data_output",1,$)),L&&Ae.push(Vt("inv_std_output",1,$));let ht=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${oe.registerUniforms(ht).declareVariables(...Ae)} ${oe.mainStart()} ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Sr("f32",T)}; var mean_square_vector = ${Sr("f32",T)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Br(Ke,T,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${fn("mean_vector",T)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${fn("mean_square_vector",T)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Br(Ke,T,"x[j + offset]")}; let f32scale = ${Br(Ke,T,"scale[j]")}; output[j + offset] = ${Ae[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${i?`+ ${Br(Ke,T,"bias[j]")}`:""} ); } ${G?"mean_data_output[global_idx] = mean":""}; ${L?"inv_std_output[global_idx] = inv_std_dev":""}; }`},q=[{dims:d,dataType:e[0].dataType}];return G&&q.push({dims:$,dataType:1}),L&&q.push({dims:$,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${T};${r};${n}`,inputDependencies:I},getRunData:()=>({outputs:q,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:j}),getShaderSource:le}},Hr=(e,t)=>{or(e.inputs),e.compute(Mu(e.inputs,t,e.outputCount))}}),Jr,Qn,ed,xu,td=D(()=>{Kt(),Xt(),pr(),nr(),Jr=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let s=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!Ne.areEqual(i.dims,[t.n,s,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(Ne.size(d)!==t.n*s)throw new Error("scales input size error.");if(e.length===4){let c=e[3].dims,p=t.bits>4?t.n*s:t.n*Math.floor((s+1)/2);if(Ne.size(c)!==p)throw new Error("zeroPoints input size error.")}},Qn=(e,t,r,n)=>{let s=e[0].dims,a=s.length,i=Math.floor((t.k+t.blockSize-1)/t.blockSize),d=s[a-2],c=t.k,p=t.n,w=s.slice(0,a-2),y=Ne.size(w),u=t.blockSize/8*t.bits/4,$=e[0].dataType,T=_r(d),I=_r(t.k),j=_r(u),G=Fn($,d*i),L=Math.floor(n/G),le=i<=r[0]&&L>0,q=!le||L>=4?_r(p):L>=2&&_r(p)>=2?2:1,oe=w.concat([d,p]),Ke=Ne.size(oe)/q/T,Ae=le?[]:[{type:12,data:Ke},{type:12,data:t.blockSize}],ht=[y,d,c/I],It=Ne.convertShape(e[1].dims).slice();It.splice(-1,1,u/j),Ae.push(...kt(ht)),Ae.push(...kt(It)),Ae.push(...kt(e[2].dims)),e.length===4&&Ae.push(...kt(Ne.convertShape(e[3].dims)));let zt=[y,d,p/q];Ae.push(...kt(zt));let cr=ir=>{let tr=ht.length,mr=rt("a",e[0].dataType,tr,I),Lr=rt("b",12,It.length,j),Mr=rt("scales",e[2].dataType,e[2].dims.length),zr=[mr,Lr,Mr],At=e.length===4?rt("zero_points",12,e[3].dims.length):void 0;At&&zr.push(At);let Jt=zt.length,Zt=Vt("output",e[0].dataType,Jt,q),Qe=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],Ft=br(e[0].dataType),rr=(()=>{switch(I){case 1:return`array<${Ft}, 8>`;case 2:return`mat4x2<${Ft}>`;case 4:return`mat2x4<${Ft}>`;default:throw new Error(`${I}-component is not supported.`)}})(),Rr=` for (var word: u32 = 0; word < ${u}; word += ${j}) { ${Lr.indicesSet("b_indices","2","word")}; let b_data = ${Lr.getByIndices("b_indices")}; for (var i: u32 = 0; i < ${j}; i++) { let b_value: u32 = ${j===1?"b_data":"b_data[word + i]"}; let b_mask: u32 = 0x0F0F0F0Fu; let b_value_lower: vec4 = unpack4xU8(b_value & b_mask); let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask); let b_quantized_values = ${rr}(${Array.from({length:4},(rn,Mn)=>`${Ft}(b_value_lower[${Mn}]), ${Ft}(b_value_upper[${Mn}])`).join(", ")}); let b_dequantized_values = ${I===1?`${rr}(${Array.from({length:8},(rn,Mn)=>`(b_quantized_values[${Mn}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${rr}(${Array(8).fill("zero_point").join(",")})) * scale;`}; // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 for (var m: u32 = 0; m < ${le?d:T}u; m++) { ${mr.indicesSet("a_indices",tr-2,le?"m":`row * ${T} + m`)}; ${mr.indicesSet("a_indices",tr-1,"word_offset")}; var input_offset = ${mr.indicesToOffset("a_indices")}; var a_data: ${rr}; for (var j: u32 = 0; j < ${8/I}; j++) { a_data[j] = ${mr.getByOffset("input_offset")}; input_offset++; } ${le?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${q>1?"[c]":""} += ${Array.from({length:8/I},(rn,Mn)=>`${I===1?`a_data[${Mn}] * b_dequantized_values[${Mn}]`:`dot(a_data[${Mn}], b_dequantized_values[${Mn}])`}`).join(" + ")}; } word_offset += ${8/I}; } }`,qr=At?` zero_point_offset += 4; if (zero_point_offset == 32) { zero_point_offset = 0; zero_point_index++; zero_point_word = ${At.getByOffset("zero_point_index")}; }`:"";return le?` var workgroup_shared: array<${Zt.type.value}, ${d*i}>; ${ir.declareVariables(...zr,Zt)} ${ir.mainStart([i,1,1])} var a_indices: ${mr.type.indices}; var block = local_id.x; var col = workgroup_id.y; var batch = workgroup_id.z; ${mr.indicesSet("a_indices","0","batch")}; // Two zero points are packed into one byte when uniforms.bits is 4. for (var c: u32 = 0; c < ${q}; c++) { let col_times_components_plus_c = col * ${q} + c; ${At?` var zero_point_bytes_per_col: u32 = (${i} + 1) / 2; var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; var zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); var zero_point_word: u32 = ${At.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} var b_indices: ${Lr.type.indices}; ${Lr.indicesSet("b_indices","0","col_times_components_plus_c")}; // The scale and zero points are computed per block. var scales_index = col_times_components_plus_c * ${i} + block; let scale = ${Mr.getByOffset("scales_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Ft}(${At?"(zero_point_word) & 0xFu":8}); ${Lr.indicesSet("b_indices","1","block")}; var word_offset: u32 = block * ${t.blockSize/I}; var workgroup_shared_offset: u32 = block * ${d}; ${Rr} } workgroupBarrier(); var output_indices: ${Zt.type.indices}; var elements_per_thread: u32 = ${Math.ceil(d/i)}; ${Zt.indicesSet("output_indices","0","batch")}; ${Zt.indicesSet("output_indices",Jt-1,"col")}; ${Zt.indicesSet("output_indices",Jt-2,"local_id.x * elements_per_thread")}; var output_offset = ${Zt.indicesToOffset("output_indices")}; for (var m: u32 = 0u; m < elements_per_thread; m++) { var row = m + local_id.x * elements_per_thread; if (row < ${d}) { var output_value: ${Zt.type.value} = ${Zt.type.value}(0); var workgroup_shared_offset: u32 = row; for (var b: u32 = 0u; b < ${i}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${d}; } ${Zt.setByOffset("output_offset","output_value")}; output_offset += ${p/q}; } } }`:` ${ir.registerUniforms(Qe).declareVariables(...zr,Zt)} ${ir.mainStart()} ${ir.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var output_values: array<${Zt.type.value}, ${T}>; var output_indices = ${Zt.offsetToIndices("global_idx")}; var col = ${Zt.indicesGet("output_indices",Jt-1)}; var row = ${Zt.indicesGet("output_indices",Jt-2)}; var a_indices: ${mr.type.indices} = output_indices; // Two zero points are packed into one byte because uniforms.bits <= 4. // zero_point_offset is either 0 or 4. It is bit offset within one byte. // TODO support zero_point_offset for bits > 4 ${At?` var zero_point_abs_offset = col * ${q} * ((${i} + 1) / 2); var zero_point_index: u32 = zero_point_abs_offset / 4; var zero_point_word: u32 = ${At.getByOffset("zero_point_index")}; var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} var scale_index = col * ${i*q}; var b_indices: ${Lr.type.indices}; for (var c: u32 = 0; c < ${q}; c++) { ${Lr.indicesSet("b_indices","0",`col * ${q} + c`)}; var block_offset: u32 = 0; for (var block: u32 = 0; block < ${i}; block++) { // The scale and zero points are computed per block. let scale = ${Mr.getByOffset("scale_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Ft}(${At?"extractBits(zero_point_word, zero_point_offset, 4)":8}); ${Lr.indicesSet("b_indices","1","block")}; var word_offset: u32 = block_offset; ${Rr} scale_index++; ${qr} block_offset += uniforms.block_size / ${I}; } // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. ${At?`if (zero_point_offset % 8 > 0) { ${qr} }`:""} } for (var k: u32 = 0u; k < ${T}u; k++) { ${Zt.indicesSet("output_indices",Jt-2,`${T} * row + k`)}; ${Zt.setByIndices("output_indices","output_values[k]")} } }`};return{name:le?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${d};${$};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:oe,dataType:$}],name:le?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:le?{x:1,y:Math.ceil(p/q),z:y}:{x:Math.ceil(Ke/64)},programUniforms:Ae}),getShaderSource:cr}},ed=(e,t)=>{Jr(e.inputs,t);let r=e.getMaxComputeWorkgroupSizes(),n=e.getMaxComputeWorkgroupStoragesize();e.compute(Qn(e.inputs,t,r,n))},xu=e=>Ut(e)}),m,g,C,X,Pe,De,it,$t,jt,lr=D(()=>{Kt(),Xt(),nr(),m=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].")}},g=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Ot("uniforms.pads",s,r)}; if (k < 0) { break; } if (k >= i32(${Ot("uniforms.x_shape",s,t)})) { break; } offset += k * i32(${Ot("uniforms.x_strides",s,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `},C=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Ot("uniforms.pads",s,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Ot("uniforms.x_shape",s,t)}) - 1); k = k % _2n_1; if(k >= i32(${Ot("uniforms.x_shape",s,t)})) { k = _2n_1 - k; } } offset += k * i32(${Ot("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},X=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Ot("uniforms.pads",s,r)}; if (k < 0) { k = 0; } if (k >= i32(${Ot("uniforms.x_shape",s,t)})) { k = i32(${Ot("uniforms.x_shape",s,t)}) - 1; } offset += k * i32(${Ot("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},Pe=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Ot("uniforms.pads",s,r)}; if (k < 0) { k += i32(${Ot("uniforms.x_shape",s,t)}]); } if (k >= i32(${Ot("uniforms.x_shape",s,t)})) { k -= i32(${Ot("uniforms.x_shape",s,t)}); } offset += k * i32(${Ot("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},De=(e,t,r)=>{switch(r.mode){case 0:return g(e,t,r.pads.length);case 1:return C(e,t,r.pads.length);case 2:return X(e,t,r.pads.length);case 3:return Pe(e,t,r.pads.length);default:throw new Error("Invalid mode")}},it=(e,t)=>{let r=Ne.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,s=Ne.size(r),a=[{type:12,data:s},{type:6,data:t.pads}];t.mode===0&&a.push({type:e[0].dataType,data:t.value}),a.push(...kt(e[0].dims,r));let i=["rank"],d=c=>{let p=Vt("output",e[0].dataType,r.length),w=rt("x",e[0].dataType,n.length),y=w.type.value,u=De(p,n.length,t),$=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&$.push({name:"constant_value",type:y}),` ${c.registerUniforms($).declareVariables(w,p)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${p.offsetToIndices("global_idx")}; var value = ${y}(0); ${u} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Ne.size(r)/64)},programUniforms:a}),getShaderSource:d}},$t=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,s=e[0].dims.length,a=new Int32Array(2*s).fill(0);if(e.length>=4){let d=e[3].getBigInt64Array();for(let c=0;ca[Number(c)]=Number(d));let i=[];return a.forEach(d=>i.push(d)),{mode:t.mode,value:n,pads:i}}else return t},jt=(e,t)=>{m(e.inputs);let r=$t(e.inputs,t);e.compute(it(e.inputs,r),{inputs:[0]})}}),sr,kr,ur,fr,dr,hr,wr,Ar,an,ln,Bn,en,Gr,tn,si,ii,Ma,Sd,Sn,Ps=D(()=>{k(),Kt(),Xt(),nr(),sr=e=>{if(A.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},kr=(e,t,r)=>{let n=t.format==="NHWC",s=e.dims.slice();n&&s.splice(1,0,s.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),d=t.strides.slice(),c=a?t.dilations.slice():[],p=t.pads.slice();gn.adjustPoolAttributes(r,s,i,d,c,p);let w=gn.computePoolOutputShape(r,s,d,c,i,p,t.autoPad),y=Object.assign({},t);a?Object.assign(y,{kernelShape:i,strides:d,pads:p,dilations:c,cacheKey:t.cacheKey}):Object.assign(y,{kernelShape:i,strides:d,pads:p,cacheKey:t.cacheKey});let u=w.slice();return u.push(u.splice(1,1)[0]),[y,n?u:w]},ur=(e,t)=>{let r=t.format==="NHWC",n=Ne.size(e),s=Ne.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:s}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let d=t.kernelShape[t.kernelShape.length-1],c=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],w=t.pads[t.pads.length-1],y=!!(p+w);a.push({type:12,data:d},{type:12,data:c},{type:12,data:p},{type:12,data:w}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(t.kernelShape.length===2){let $=t.kernelShape[t.kernelShape.length-2],T=t.strides[t.strides.length-2],I=t.pads[t.pads.length/2-2],j=t.pads[t.pads.length-2];u=!!(I+j),a.push({type:12,data:$},{type:12,data:T},{type:12,data:I},{type:12,data:j}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,y,u]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=Ne.computeStrides(t.kernelShape);a.push({type:12,data:d},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:d.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let c=t.pads.reduce((p,w)=>p+w);return[a,i,!!c,!1,!1]}},fr=(e,t,r,n,s,a,i,d,c,p,w,y)=>{let u=s.format==="NHWC",$=t.type.value,T=Vt("output",t.type.tensor,n);if(s.kernelShape.length<=2){let I="",j="",G="",L=r-(u?2:1);if(w?I=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${L}] = indices[${L}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${L}] < 0 || xIndices[${L}] >= uniforms.x_shape[${L}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:I=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${L}] = indices[${L}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`,s.kernelShape.length===2){let le=r-(u?3:2);y?j=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${le}] = indices[${le}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${le}] < 0 || xIndices[${le}] >= uniforms.x_shape[${le}]) { pad += i32(uniforms.kw); continue; } `:j=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${le}] = indices[${le}] * uniforms.sh - uniforms.phStart + j; `,G=` } `}return` ${e.registerUniforms(c).declareVariables(t,T)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${T.offsetToIndices("global_idx")}; var xIndices = ${T.offsetToIndices("global_idx")}; var value = ${$}(${d}); var pad = 0; ${j} ${I} ${G} ${i} output[global_idx] = value; }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let I=s.kernelShape.length,j=s.pads.length,G="";return p?G=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:G=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} `,` ${e.registerUniforms(c).declareVariables(t,T)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${T.offsetToIndices("global_idx")}; var xIndices = ${T.offsetToIndices("global_idx")}; var offsets: array; var value = ${$}(${d}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${I-1}u; j++) { offsets[j] = offset / ${Ot("uniforms.kernelStrides","j",I)}; offset -= offsets[j] * ${Ot("uniforms.kernelStrides","j",I)}; } offsets[${I-1}] = offset; isPad = false; for (var j = ${r-I}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${Ot("uniforms.strides",`j - ${r-I}u`,I)} + offsets[j - ${r-I}u] - ${Ot("uniforms.pads","j - 2u",j)}; ${G} } ${i} output[global_idx] = value; }`}},dr=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,hr=e=>`${dr(e)};${e.countIncludePad}`,wr=e=>`${dr(e)};${e.storageOrder};${e.dilations}`,Ar=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}),an=(e,t,r,n)=>{let[s,a]=kr(t,n,r),i=rt("x",t.dataType,t.dims.length),d=i.type.value,c="value += x_val;",p="";s.countIncludePad?p+=`value /= ${d}(uniforms.kernelSize);`:p+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[w,y,u,$,T]=ur(a,s);w.push(...kt(t.dims,a));let I=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${u};${$};${T}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Ne.size(a)/64)},programUniforms:w}),getShaderSource:j=>fr(j,i,t.dims.length,a.length,s,c,p,0,y,u,$,T)}},ln=e=>{let t=e.count_include_pad!==0,r=Ar(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:hr(n)}},Bn=(e,t)=>{sr(e.inputs),e.compute(an("AveragePool",e.inputs[0],!1,t))},en={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Gr=e=>{let t=e.format;return{format:t,...en,cacheKey:t}},tn=(e,t)=>{sr(e.inputs),e.compute(an("GlobalAveragePool",e.inputs[0],!0,t))},si=(e,t,r,n)=>{let[s,a]=kr(t,n,r),i=` value = max(x_val, value); `,d="",c=rt("x",t.dataType,t.dims.length),p=["rank"],[w,y,u,$,T]=ur(a,s);return w.push(...kt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${u};${$};${T}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Ne.size(a)/64)},programUniforms:w}),getShaderSource:I=>fr(I,c,t.dims.length,a.length,s,i,d,t.dataType===10?-65504:-1e5,y,u,$,T)}},ii=(e,t)=>{sr(e.inputs),e.compute(si("MaxPool",e.inputs[0],!1,t))},Ma=e=>{let t=e.storage_order,r=e.dilations,n=Ar(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let s={storageOrder:t,dilations:r,...n,cacheKey:""};return{...s,cacheKey:wr(s)}},Sd=e=>{let t=e.format;return{format:t,...en,cacheKey:t}},Sn=(e,t)=>{sr(e.inputs),e.compute(si("GlobalMaxPool",e.inputs[0],!0,t))}}),rd,nd,sd,Tu,tf=D(()=>{Kt(),Xt(),pr(),nr(),rd=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((s,a)=>a===t.axis||s===e[0].dims[a]).reduce((s,a)=>s&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},nd=(e,t)=>{let r=Ne.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,s=n===3,a=e[0].dims,i=e[1].dataType,d=Ne.size(a),c=n===3||n===2,p=c?[Math.ceil(Ne.size(e[0].dims)/4)]:e[0].dims,w=e[1].dims,y=e.length>2?e[2]:void 0,u=y?c?[Math.ceil(Ne.size(y.dims)/4)]:y.dims:void 0,$=w.length===0||w.length===1&&w[0]===1,T=$===!1&&w.length===1,I=_r(d),j=$&&(!c||I===4),G=j?I:1,L=j&&!c?I:1,le=rt("input",c?12:n,p.length,L),q=rt("scale",i,w.length),oe=y?rt("zero_point",c?12:n,u.length):void 0,Ke=Vt("output",i,a.length,G),Ae=[le,q];oe&&Ae.push(oe);let ht=[p,w];y&&ht.push(u);let It=[{type:12,data:d/G},{type:12,data:r},{type:12,data:t.blockSize},...kt(...ht,a)],zt=cr=>{let ir=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${cr.registerUniforms(ir).declareVariables(...Ae,Ke)} ${cr.mainStart()} ${cr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${Ke.offsetToIndices("global_idx")}; // Set input x ${c?` let input = ${le.getByOffset("global_idx / 4")}; let x_vec = ${s?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${G===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${le.getByOffset("global_idx")};`}; // Set scale input ${$?`let scale_value= ${q.getByOffset("0")}`:T?` let scale_index = ${Ke.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${q.getByOffset("scale_index")};`:` var scale_indices: ${q.type.indices} = output_indices; let index = ${q.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${q.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${q.getByIndices("scale_indices")};`}; // Set zero-point input ${oe?$?c?` let zero_point_input = ${oe.getByOffset("0")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${oe.getByOffset("0")}`:T?c?` let zero_point_index = ${Ke.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${oe.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${Ke.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${oe.getByOffset("zero_point_index")};`:c?` let zero_point_offset = ${q.indicesToOffset("scale_indices")}; let zero_point_input = ${oe.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${oe.getByIndices("scale_indices")};`:`let zero_point_value = ${c?s?"i32":"u32":le.type.value}(0);`}; // Compute and write output ${Ke.setByOffset("global_idx",`${Ke.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:oe?["rank","rank","rank"]:["rank","rank"]},getShaderSource:zt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(d/G/64),y:1,z:1},programUniforms:It})}},sd=(e,t)=>{rd(e.inputs,t),e.compute(nd(e.inputs,t))},Tu=e=>Ut({axis:e.axis,blockSize:e.blockSize})}),dc,cc,pc,rf=D(()=>{k(),Kt(),nr(),dc=(e,t,r)=>{let n=e===t,s=et&&r>0;if(n||s||a)throw new Error("Range these inputs' contents are invalid.")},cc=(e,t,r,n)=>{let s=Math.abs(Math.ceil((t-e)/r)),a=[s],i=s,d=[{type:12,data:i},{type:n,data:e},{type:n,data:r},...kt(a)],c=p=>{let w=Vt("output",n,a.length),y=w.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:y},{name:"delta",type:y}];return` ${p.registerUniforms(u).declareVariables(w)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${y}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:c,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d})}},pc=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]),A.webgpu.validateInputContent&&dc(t,r,n),e.compute(cc(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),hc,fc,mc,_c,gc,wc,yc,bc,vc,Mc,xc,Pd,Tc,$c,kc,Cc,Ec,Sc,Pc,nf=D(()=>{Kt(),Xt(),pr(),nr(),hc=(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")}},fc=(e,t,r)=>{t.every(s=>s>=0&&s{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((s,a)=>n[s]=e[a]),n},mc=(e,t,r,n,s,a)=>{let[i,d,c]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(w=>a.push(w));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(d>0&&e.length>d&&e[d].dims.length>0){if(e[d].getFloat32Array().forEach(w=>n.push(w)),n.length!==0&&n.length!==p&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");hc(n,t),t.axes.length>0&&fc(n,t.axes,p).forEach((w,y)=>n[y]=w)}if(c>0&&e.length>c&&(e[c].getBigInt64Array().forEach(w=>s.push(Number(w))),s.length!==p||r>=18&&s.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(s.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof s<"u"&&n.length>0&&s.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},_c=(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`)}})()+"}",gc=(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`)}})()+"}",wc=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),s=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=s[i],n[i+r]=s[t.length+i]}),n):s},yc=(e,t,r,n)=>{let s=[];if(r.length>0)if(n.length>0){if(e.forEach(a=>s.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>s[a]=r[i])}else r.forEach(a=>s.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");s=e.map((a,i)=>Math.round(a*t[i]))}return s},bc=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let s=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.axes.forEach(a=>s[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),s.forEach((a,i)=>s[i]=Math.round(a*t[i]))),s},vc=(e,t,r,n,s)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${Ot("uniforms.scales","i",n)}; var roi_low = ${Ot("uniforms.roi","i",s)}; var roi_hi = ${Ot("uniforms.roi",`i + ${t.length}`,s)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Ot("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Ot("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; }`,Mc=(e,t,r,n,s,a,i)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${Ot("uniforms.scales","i",s)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Ot("uniforms.roi","i",a)}; var roi_hi = ${Ot("uniforms.roi",`i + ${r.length}`,a)}; var input_shape_i = ${Ot("uniforms.input_shape","i",r.length)}; var output_shape_i = ${Ot("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${i} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,xc=(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 >= ${Ot("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,Pd=(e,t,r,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",Tc=(e,t,r,n,s)=>{let[a,i,d,c]=r.length===2?[-1,0,1,-1]:[0,2,3,1],p=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(row, ${r[i]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(col, ${r[d]} - 1))`)}; ${Pd(e,c,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${p} = originalIndices[${i}]; var col:${p} = originalIndices[${d}]; ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[d]} - 1)) { return ${s}; }`:""}; row = max(0, min(row, ${r[i]} - 1)); col = max(0, min(col, ${r[d]} - 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[${c}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${p} = getInputValue(batch, channel, row1, col1); var x12: ${p} = getInputValue(batch, channel, row1, col2); var x21: ${p} = getInputValue(batch, channel, row2, col1); var x22: ${p} = getInputValue(batch, channel, row2, col2); var dx1: ${p} = abs(row - ${p}(row1)); var dx2: ${p} = abs(${p}(row2) - row); var dy1: ${p} = abs(col - ${p}(col1)); var dy2: ${p} = abs(${p}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},$c=(e,t,r,n,s,a,i,d,c,p)=>{let w=r.length===2,[y,u]=w?[0,1]:[2,3],$=e.type.value,T=I=>{let j=I===y?"row":"col";return` fn ${j}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${$} { var output_index = ${t.indicesGet("output_indices",I)}; var originalIdx: ${$} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[I]}, ${n[I]}, ${r[I]}, ${a[I]}, ${a[I]} + ${r.length}); var fractOriginalIdx: ${$} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${d} && (originalIdx < 0 || originalIdx > (${r[I]} - 1))) { return ${c}; } var data: array<${$}, 4> = array<${$}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${j}: ${$} = originalIdx + ${$}(i); if (${j} < 0 || ${j} >= ${r[I]}) { ${p?`coefs[i + 1] = 0.0; continue;`:d?`return ${c};`:`${j} = max(0, min(${j}, ${r[I]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",I,`u32(${j})`)}; data[i + 1] = ${I===y?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${T(y)}; ${T(u)}; fn getCubicInterpolationCoefs(s: ${$}) -> array<${$}, 4> { var absS = abs(s); var coeffs: array<${$}, 4> = array<${$}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${$} = 1.0 - absS; var twoMinusAbsS: ${$} = 2.0 - absS; var onePlusAbsS: ${$} = 1.0 + absS; coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; return coeffs; } fn cubicInterpolation1D(x: array<${$}, 4>, coefs: array<${$}, 4>) -> ${$} { var coefsSum: ${$} = 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}) -> ${$} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},kc=(e,t,r,n,s)=>{let[a,i,d,c,p]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],w=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${w} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(depth, ${r[i]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(height, ${r[d]} - 1))`)}; ${e.indicesSet("input_indices",c,`max(0, min(width, ${r[c]} - 1))`)}; ${Pd(e,p,a,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${w} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${w} = originalIndices[${i}]; var height:${w} = originalIndices[${d}]; var width:${w} = originalIndices[${c}]; ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[c]} - 1)) { return ${s}; }`:""}; depth = max(0, min(depth, ${r[i]} - 1)); height = max(0, min(height, ${r[d]} - 1)); width = max(0, min(width, ${r[c]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${r.length>3?`u32(originalIndices[${p}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${w} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${w} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${w} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${w} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${w} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${w} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${w} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${w} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${w} = abs(depth - ${w}(depth1)); var dx2: ${w} = abs(${w}(depth2) - depth); var dy1: ${w} = abs(height - ${w}(height1)); var dy2: ${w} = abs(${w}(height2) - height); var dz1: ${w} = abs(width - ${w}(width1)); var dz2: ${w} = abs(${w}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},Cc=(e,t,r,n,s,a)=>{let i=e.dims,d=wc(a,t.axes,i.length),c=yc(i,n,s,t.axes),p=n.slice();n.length===0&&(p=i.map((L,le)=>L===0?1:c[le]/L),t.keepAspectRatioPolicy!=="stretch"&&(c=bc(i,p,t)));let w=Vt("output",e.dataType,c.length),y=rt("input",e.dataType,i.length),u=Ne.size(c),$=i.length===c.length&&i.every((L,le)=>L===c[le]),T=t.coordinateTransformMode==="tf_crop_and_resize",I=t.extrapolationValue,j=y.type.value,G=L=>` ${$?"":` ${_c(t.coordinateTransformMode,j)}; ${(()=>{switch(t.mode){case"nearest":return` ${xc(y,i)}; ${gc(t.nearestMode,r,j)}; ${Mc(y,w,i,c,p.length,d.length,T)}; `;case"linear":return` ${vc(w,i,c,p.length,d.length)}; ${(()=>{if(i.length===2||i.length===4)return`${Tc(y,w,i,T,I)}`;if(i.length===3||i.length===5)return`${kc(y,w,i,T,I)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(i.length===2||i.length===4)return`${$c(y,w,i,c,p,d,t.cubicCoeffA,T,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${L.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",d.length).declareVariables(y,w)} ${L.mainStart()} ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${$?"output[global_idx] = input[global_idx];":` let output_indices = ${w.offsetToIndices("global_idx")}; var input_indices: ${y.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${y.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${s.length>0?s:""}|${d.length>0?d:""}|${$}|${i}`,inputDependencies:["rank"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:c,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:p},{type:1,data:d},...kt(i,c)]})}},Ec=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Sc=(e,t)=>{let r=[],n=[],s=[],a=Ec(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");mc(e.inputs,t,a,r,n,s),e.compute(Cc(e.inputs[0],t,a,r,n,s),{inputs:[0]})},Pc=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,s=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,d=e.keepAspectRatioPolicy,c=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return Ut({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:s,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:d,mode:c,nearestMode:p})}}),Ac,Ic,Fc,sf=D(()=>{Kt(),Xt(),pr(),nr(),Ac=(e,t)=>{let[r,n,s,a]=e,{numHeads:i,rotaryEmbeddingDim:d}=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(!Ne.areEqual(n.dims,[])&&!Ne.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(s.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Ne.areEqual(s.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let c=r.dims[0],p=r.dims[r.dims.length-2],w=s.dims[0],y=Ne.sizeFromDimension(r.dims,1)/p,u=d===0?s.dims[1]*2:y/i;if(d>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(c!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(p!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(u/2!==s.dims[1]&&d/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(p>w)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Ic=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:s,scale:a}=t,i=e[0].dims[0],d=Ne.sizeFromDimension(e[0].dims,1),c=e[0].dims[e[0].dims.length-2],p=d/c,w=e[2].dims[1],y=s===0?w*2:p/n,u=new Array(i,c,p/y,y-w),$=Ne.computeStrides(u),T=[{type:1,data:a},{type:12,data:u},{type:12,data:$},...e[0].dims.length===3?new Array({type:12,data:[d,p,y,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,y,c*y,1]}):[],...kt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],I=j=>{let G=rt("input",e[0].dataType,e[0].dims.length),L=rt("position_ids",e[1].dataType,e[1].dims.length),le=rt("cos_cache",e[2].dataType,e[2].dims.length),q=rt("sin_cache",e[3].dataType,e[3].dims.length),oe=Vt("output",e[0].dataType,e[0].dims.length);return j.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:$.length},{name:"input_output_strides",type:"u32",length:$.length}]),` ${j.declareVariables(G,L,le,q,oe)} ${j.mainStart(hn)} let half_rotary_emb_dim = uniforms.${le.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${j.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${L.broadcastedIndicesToOffset("bsnh.xy",Vt("",L.type.tensor,2))}; let position_id = u32(${L.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); let j = i + select(half_rotary_emb_dim, 1, ${r}); let re = ${G.getByOffset("i")} * ${le.get("position_id","bsnh[3]")} - ${G.getByOffset("j")} * ${q.get("position_id","bsnh[3]")}; ${oe.setByOffset("i","re")} let im = ${G.getByOffset("i")} * ${q.get("position_id","bsnh[3]")} + ${G.getByOffset("j")} * ${le.get("position_id","bsnh[3]")}; ${oe.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${oe.setByOffset("k",G.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:Ut({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:I,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Ne.size(u)/hn)},programUniforms:T})}},Fc=(e,t)=>{Ac(e.inputs,t),e.compute(Ic(e.inputs,t))}}),Oc,zc,Dc,af=D(()=>{Kt(),Xt(),nr(),Oc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let s=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==s)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==s)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},zc=(e,t,r,n)=>{let s=t.simplified,a=e[0].dims,i=Ne.size(a),d=a,c=i,p=a.slice(-1)[0],w=n?a.slice(0,-1).concat(1):[],y=!s&&e.length>3,u=e.length>4,$=n&&r>1,T=n&&r>2,I=r>3,j=64,G=_r(p),L=[{type:12,data:c},{type:12,data:G},{type:12,data:p},{type:1,data:t.epsilon}],le=oe=>{let Ke=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ae=[rt("x",e[0].dataType,e[0].dims,G),rt("skip",e[1].dataType,e[1].dims,G),rt("gamma",e[2].dataType,e[2].dims,G)];y&&Ae.push(rt("beta",e[3].dataType,e[3].dims,G)),u&&Ae.push(rt("bias",e[4].dataType,e[4].dims,G)),Ae.push(Vt("output",e[0].dataType,d,G)),$&&Ae.push(Vt("mean_output",1,w)),T&&Ae.push(Vt("inv_std_output",1,w)),I&&Ae.push(Vt("input_skip_bias_sum",e[0].dataType,d,G));let ht=br(e[0].dataType),It=br(1,G);return` ${oe.registerUniforms(Ke).declareVariables(...Ae)} var sum_shared : array<${It}, ${j}>; var sum_squared_shared : array<${It}, ${j}>; ${oe.mainStart([j,1,1])} let ix = local_id.x; let iy = global_id.x / ${j}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${j}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${j-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${u?"bias[offset1d + i]":ht+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${I?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Br(ht,G,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${j}; 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 = ${fn("sum",G)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${fn("square_sum",G)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); ${$?"mean_output[global_idx] = mean;":""} ${T?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${s?"":`- ${ht}(mean)`}) * ${ht}(inv_std_dev) * gamma[offset1d + i] ${y?"+ beta[offset1d + i]":""}; } }`},q=[{dims:d,dataType:e[0].dataType}];return r>1&&q.push({dims:w,dataType:1}),r>2&&q.push({dims:w,dataType:1}),r>3&&q.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${G};${$};${T};${I}`,inputDependencies:e.map((oe,Ke)=>"type")},getShaderSource:le,getRunData:()=>({outputs:q,dispatchGroup:{x:Math.ceil(c/p)},programUniforms:L})}},Dc=(e,t)=>{Oc(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(zc(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Bc,$u,Lc,Ad,Rc,Nc,Vc,jc,of=D(()=>{Kt(),Xt(),pr(),nr(),Bc=(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`)})},$u=(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},Lc=(e,t)=>{if(e.length>1){let r=$u(e,1),n=$u(e,2),s=$u(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),Ut({starts:r,ends:n,axes:s})}else return t},Ad=(e,t,r,n,s)=>{let a=e;return e<0&&(a+=r[n[t]]),s[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},Rc=(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 = ${Ot("uniforms.input_shape","i",r.length)}; let steps_i = ${Ot("uniforms.steps","i",r.length)}; let signs_i = ${Ot("uniforms.signs","i",r.length)}; let starts_i = ${Ot("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; }`,Nc=(e,t)=>{let r=e[0].dims,n=Ne.size(r),s=t.axes.length>0?Ne.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=$u(e,4);a.forEach(G=>G!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(s.length).fill(1));let i=t.starts.map((G,L)=>Ad(G,L,r,s,a)),d=t.ends.map((G,L)=>Ad(G,L,r,s,a));if(s.length!==i.length||s.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==r.length)for(let G=0;GMath.sign(G));a.forEach((G,L,le)=>{if(G<0){let q=(d[L]-i[L])/G,oe=i[L],Ke=oe+q*a[L];i[L]=Ke,d[L]=oe,le[L]=-G}});let p=r.slice(0);s.forEach((G,L)=>{p[G]=Math.ceil((d[G]-i[G])/a[G])});let w={dims:p,dataType:e[0].dataType},y=Vt("output",e[0].dataType,p.length),u=rt("input",e[0].dataType,e[0].dims.length),$=Ne.size(p),T=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:c.length},{name:"steps",type:"u32",length:a.length}],I=[{type:12,data:$},{type:12,data:i},{type:6,data:c},{type:12,data:a},...kt(e[0].dims,p)],j=G=>` ${G.registerUniforms(T).declareVariables(u,y)} ${Rc(u,y,r)} ${G.mainStart()} ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${y.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${y.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${c.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:j,getRunData:()=>({outputs:[w],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:I})}},Vc=(e,t)=>{Bc(e.inputs,t);let r=Lc(e.inputs,t);e.compute(Nc(e.inputs,r),{inputs:[0]})},jc=e=>{let t=e.starts,r=e.ends,n=e.axes;return Ut({starts:t,ends:r,axes:n})}}),Uc,Wc,Gc,qc,lf=D(()=>{Kt(),Xt(),pr(),nr(),Uc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Wc=(e,t)=>{let r=e.dims,n=Ne.size(r),s=64,a=t.axis;if(a<0&&(a=r.length+a),aG===4?`max(max(${j}.x, ${j}.y), max(${j}.z, ${j}.w))`:G===2?`max(${j}.x, ${j}.y)`:G===3?`max(max(${j}.x, ${j}.y), ${j}.z)`:j,y=rt("x",e.dataType,e.dims,c),u=Vt("result",e.dataType,e.dims,c),$=y.type.value,T=br(e.dataType)==="f32"?`var threadMax = ${$}(-3.402823e+38f);`:`var threadMax = ${$}(-65504.0h);`,I=j=>` var rowMaxShared : ${$}; var rowSumShared : ${$}; var threadShared : array<${$}, ${s}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${$} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${$}) { let index = row * row_stride + col; result[index] = value; } ${j.registerUniform("packedCols","i32").declareVariables(y,u)} ${j.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${s}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${T} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${$}(${w("threadShared[0]",c)}); } workgroupBarrier(); // find the rows sum var threadSum = ${$}(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 = ${$}(${fn("threadShared[0]",c)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`;return{name:"Softmax",shaderCache:{hint:`${c}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:p}]}),getShaderSource:I}},Gc=(e,t)=>{Uc(e.inputs),e.compute(Wc(e.inputs[0],t))},qc=e=>Ut({axis:e.axis})}),Hc,Kc,Xc,Qc,Yc,Zc,Jc,uf=D(()=>{Kt(),Xt(),pr(),nr(),Hc=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Kc=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),n=r.length),Ut({numOutputs:n,axis:t.axis,splitSizes:r})},Xc=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Ot("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Qc=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=Ne.size(r),s=e[0].dataType,a=Ne.normalizeAxis(t.axis,r.length),i=new Array(t.numOutputs),d=rt("input",s,r.length),c=new Array(t.numOutputs),p=[],w=[],y=0,u=[{type:12,data:n}];for(let T=0;T` ${T.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",c.length).declareVariables(d,...i)} ${Xc(c.length)} ${Qc(i)} ${T.mainStart()} ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${d.offsetToIndices("global_idx")}; var index = ${d.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Ot("uniforms.size_in_split_axis","output_number - 1u",c.length)}; ${d.indicesSet("indices",a,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u})}},Zc=(e,t)=>{Hc(e.inputs);let r=e.inputs.length===1?t:Kc(e.inputs,t);e.compute(Yc(e.inputs,r),{inputs:[0]})},Jc=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 Ut({axis:t,numOutputs:n,splitSizes:r})}}),ep,tp,rp,df=D(()=>{Kt(),Xt(),nr(),ep=(e,t,r,n,s)=>{let a=Vt("output_data",s,r.length,4),i=rt("a_data",t[1].dataType,t[1].dims.length,4),d=rt("b_data",t[2].dataType,t[2].dims.length,4),c=rt("c_data",t[0].dataType,t[0].dims.length,4),p,w=(y,u,$)=>`select(${u}, ${y}, ${$})`;if(!n)p=a.setByOffset("global_idx",w(i.getByOffset("global_idx"),d.getByOffset("global_idx"),c.getByOffset("global_idx")));else{let y=(u,$,T="")=>{let I=`a_data[index_a${$}][component_a${$}]`,j=`b_data[index_b${$}][component_b${$}]`,G=`bool(c_data[index_c${$}] & (0xffu << (component_c${$} * 8)))`;return` let output_indices${$} = ${a.offsetToIndices(`global_idx * 4u + ${$}u`)}; let offset_a${$} = ${i.broadcastedIndicesToOffset(`output_indices${$}`,a)}; let offset_b${$} = ${d.broadcastedIndicesToOffset(`output_indices${$}`,a)}; let offset_c${$} = ${c.broadcastedIndicesToOffset(`output_indices${$}`,a)}; let index_a${$} = offset_a${$} / 4u; let index_b${$} = offset_b${$} / 4u; let index_c${$} = offset_c${$} / 4u; let component_a${$} = offset_a${$} % 4u; let component_b${$} = offset_b${$} % 4u; let component_c${$} = offset_c${$} % 4u; ${u}[${$}] = ${T}(${w(I,j,G)}); `};s===9?p=` var data = vec4(0); ${y("data",0,"u32")} ${y("data",1,"u32")} ${y("data",2,"u32")} ${y("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=` ${y("output_data[global_idx]",0)} ${y("output_data[global_idx]",1)} ${y("output_data[global_idx]",2)} ${y("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(c,i,d,a)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${p} }`},tp=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,s=e[1].dataType,a=!(Ne.areEqual(t,r)&&Ne.areEqual(r,n)),i=t,d=Ne.size(t);if(a){let p=Kr.calcShape(Kr.calcShape(t,r,!1),n,!1);if(!p)throw new Error("Can't perform where op on the given tensors");i=p,d=Ne.size(i)}let c=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>ep(p,e,i,a,s),getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:c},...kt(n,t,r,i)]})}},rp=e=>{e.compute(tp(e.inputs))}}),np,cf=D(()=>{Fu(),qs(),bo(),Ou(),Jo(),zu(),Du(),Sl(),kd(),ju(),Uu(),Hu(),Cd(),Xu(),Qu(),Yu(),su(),Ju(),Ed(),Zr(),ta(),td(),uu(),lr(),Ps(),tf(),rf(),$i(),nf(),sf(),af(),of(),lf(),uf(),hu(),ls(),Vi(),df(),np=new Map([["Abs",[To]],["Acos",[$o]],["Acosh",[Ei]],["Add",[rl]],["ArgMax",[uo,Gs]],["ArgMin",[lo,Gs]],["Asin",[ko]],["Asinh",[Co]],["Atan",[Si]],["Atanh",[Eo]],["Attention",[mo]],["AveragePool",[Bn,ln]],["BatchNormalization",[yo]],["BiasAdd",[Ci]],["BiasSplitGelu",[Zo]],["Cast",[Hs,So]],["Ceil",[Io]],["Clip",[Ao]],["Concat",[Wn,hl]],["Conv",[$s,na]],["ConvTranspose",[Vu,Ol]],["Cos",[Pi]],["Cosh",[Fo]],["CumSum",[ca,Bl]],["DepthToSpace",[ha,Nl]],["DequantizeLinear",[sd,Tu]],["Div",[nl]],["Einsum",[jl,Ul]],["Elu",[Oo,ds]],["Equal",[Ui]],["Erf",[zo]],["Exp",[Ai]],["Expand",[_a]],["FastGelu",[ql]],["Floor",[Do]],["FusedConv",[$s,na]],["Gather",[Ql,Xl]],["GatherElements",[eu,Jl]],["Gelu",[Bo]],["Gemm",[Zu,nu]],["GlobalAveragePool",[tn,Gr]],["GlobalMaxPool",[Sn,Sd]],["Greater",[ol]],["GreaterOrEqual",[ul]],["GroupQueryAttention",[gu,mu]],["HardSigmoid",[Oi,jo]],["InstanceNormalization",[vu]],["LayerNormalization",[Hr]],["LeakyRelu",[Lo,ds]],["Less",[ll]],["LessOrEqual",[Wi]],["Log",[Ni]],["MatMul",[kl]],["MatMulNBits",[ed,xu]],["MaxPool",[ii,Ma]],["Mul",[sl]],["MultiHeadAttention",[lu,au]],["Neg",[Ro]],["Not",[Ii]],["Pad",[jt]],["Pow",[il]],["QuickGelu",[Qo,ds]],["Range",[pc]],["Reciprocal",[No]],["ReduceMin",[xi]],["ReduceMean",[to]],["ReduceMax",[so]],["ReduceSum",[ao]],["ReduceProd",[io]],["ReduceL1",[ro]],["ReduceL2",[Mi]],["ReduceLogSum",[oo]],["ReduceLogSumExp",[no]],["ReduceSumSquare",[Ti]],["Relu",[Fi]],["Resize",[Sc,Pc]],["RotaryEmbedding",[Fc]],["Sigmoid",[Vo]],["Sin",[Uo]],["Sinh",[Wo]],["Slice",[Vc,jc]],["SkipLayerNormalization",[Dc]],["Split",[Zc,Jc]],["Sqrt",[zi]],["Softmax",[Gc,qc]],["Sub",[al]],["Tan",[Go]],["Tanh",[Bi]],["ThresholdedRelu",[Ho,ds]],["Tile",[pu]],["Transpose",[Aa,hi]],["Where",[rp]]])}),sp,pf=D(()=>{k(),pn(),nr(),sp=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,s){Ue(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let p of t)d.push({binding:d.length,resource:{buffer:p.buffer}});for(let p of r)d.push({binding:d.length,resource:{buffer:p.buffer}});s&&d.push({binding:d.length,resource:s});let c=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:d,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:c,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}i.setPipeline(e.computePipeline),i.setBindGroup(0,c),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),je(e.programInfo.name)}dispose(){}build(e,t){Ue(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let s=Ea(t,this.backend.device.limits),a=e.getShaderSource(s),i=`${n.join(` `)} ${s.additionalImplementations} ${a}`,d=r.createShaderModule({code:i,label:e.name});Fr("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let c=r.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return je(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:s.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=s&&r<=s&&n<=s)return[t,r,n];let a=t*r*n,i=Math.ceil(Math.sqrt(a));if(i>s){if(i=Math.ceil(Math.cbrt(a)),i>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),ip,ap,op,lp,hf=D(()=>{k(),Kt(),pn(),_(),$r(),cf(),pf(),ip=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{var s,a;let n=e.name;return(s=e.shaderCache)!=null&&s.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${ip(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},op=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},lp=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};t.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&r.push("timestamp-query"),t.features.has("shader-f16")&&r.push("shader-f16"),this.device=await t.requestDevice(n),this.adapterInfo=new op(t.info||await t.requestAdapterInfo()),this.gpuDataManager=Qt(this),this.programManager=new sp(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,as(e.logLevel,!!e.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ue(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=$);let I=Number($-this.queryTimeBase),j=Number(T-this.queryTimeBase);if(!Number.isSafeInteger(I)||!Number.isSafeInteger(j))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:y.map(G=>({dims:G.dims,dataType:Cn(G.dataType)})),outputsMetadata:u.map(G=>({dims:G.dims,dataType:Cn(G.dataType)})),kernelId:i,kernelType:c,kernelName:p,programName:w,startTime:I,endTime:j});else{let G="";y.forEach((le,q)=>{G+=`input[${q}]: [${le.dims}] | ${Cn(le.dataType)}, `});let L="";u.forEach((le,q)=>{L+=`output[${q}]: [${le.dims}] | ${Cn(le.dataType)}, `}),console.log(`[profiling] kernel "${i}|${c}|${p}|${w}" ${G}${L}execution time: ${j-I} ns`)}Ce("GPU",`${w}::${$}::${T}`)}e.unmap(),this.pendingQueries.delete(e)}),je()}run(e,t,r,n,s,a){Ue(e.name);let i=[];for(let L=0;Lle):r;if(w.length!==d.length)throw new Error(`Output size ${w.length} must be equal to ${d.length}.`);let y=[],u=[];for(let L=0;L=a)throw new Error(`Invalid output index: ${w[L]}`);if(w[L]===-3)continue;let le=w[L]===-1,q=w[L]===-2,oe=le||q?s(d[L].dataType,d[L].dims):n(w[L],d[L].dataType,d[L].dims);if(y.push(oe),oe.data===0)continue;let Ke=this.gpuDataManager.get(oe.data);if(!Ke)throw new Error(`no GPU data for output: ${oe.data}`);if(le&&this.temporaryData.push(Ke),q){let Ae=this.kernelPersistentData.get(this.currentKernelId);Ae||(Ae=[],this.kernelPersistentData.set(this.currentKernelId,Ae)),Ae.push(Ke)}u.push(Ke)}if(i.length!==t.length||u.length!==y.length){if(u.length===0)return je(e.name),y;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let $;if(p){let L=0,le=[];p.forEach(Ae=>{let ht=typeof Ae.data=="number"?[Ae.data]:Ae.data;if(ht.length===0)return;let It=Ae.type===10?2:4,zt,cr;Ae.type===10?(cr=ht.length>4?16:ht.length>2?8:ht.length*It,zt=ht.length>4?16:It*ht.length):(cr=ht.length<=2?ht.length*It:16,zt=16),L=Math.ceil(L/cr)*cr,le.push(L);let ir=Ae.type===10?8:4;L+=ht.length>4?Math.ceil(ht.length/ir)*zt:ht.length*It});let q=16;L=Math.ceil(L/q)*q;let oe=new ArrayBuffer(L);p.forEach((Ae,ht)=>{let It=le[ht],zt=typeof Ae.data=="number"?[Ae.data]:Ae.data;if(Ae.type===6)new Int32Array(oe,It,zt.length).set(zt);else if(Ae.type===12)new Uint32Array(oe,It,zt.length).set(zt);else if(Ae.type===10)new Uint16Array(oe,It,zt.length).set(zt);else if(Ae.type===1)new Float32Array(oe,It,zt.length).set(zt);else throw new Error(`Unsupported uniform type: ${Cn(Ae.type)}`)});let Ke=this.gpuDataManager.create(L,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ke.buffer,0,oe,0,L),this.gpuDataManager.release(Ke.id),$={offset:0,size:L,buffer:Ke.buffer}}let T=this.programManager.normalizeDispatchGroupSize(c),I=T[1]===1&&T[2]===1,j=ap(e,t,I),G=this.programManager.getArtifact(j);if(G||(G=this.programManager.build(e,T),this.programManager.setArtifact(j,G),Fr("info",()=>`[artifact] key: ${j}, programName: ${e.name}`)),p&&G.uniformVariablesInfo){if(p.length!==G.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${G.uniformVariablesInfo.length}, got ${p.length} in program "${G.programInfo.name}".`);for(let L=0;L`[ProgramManager] run "${e.name}" (key=${j}) with ${T[0]}x${T[1]}x${T[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let L={kernelId:this.currentKernelId,programName:G.programInfo.name,inputTensorViews:t,outputTensorViews:y};this.pendingKernels.push(L),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(L)}return this.programManager.run(G,i,u,T,$),je(e.name),y}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,n){let s=np.get(e);if(!s)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:s[0],attributes:[s[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let s=n.kernelType,a=n.kernelName,i=n.kernelEntry,d=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),Fr("info",()=>`[WebGPU] Start to run kernel "[${s}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope("validation"),i(t,d[1]),0}catch(p){return r.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${a}" failed. ${p}`)),1}finally{c&&r.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${s}] ${a}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let s=this.sessionExternalDataMapping.get(e);s||(s=new Map,this.sessionExternalDataMapping.set(e,s));let a=s.get(t),i=this.gpuDataManager.registerExternalBuffer(r,n,a==null?void 0:a[1]);return s.set(t,[i,r]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[1])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let n=await wt(this,e,t);return ve(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(){Fr("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(){Fr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Fr("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),up={};x(up,{init:()=>cp});var id,dp,cp,ff=D(()=>{Kt(),hf(),pn(),Xt(),id=class Hh{constructor(t,r,n,s){this.module=t,this.dataType=r,this.data=n,this.dims=s}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Ne.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=Ne.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=Ne.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Ne.size(t)!==Ne.size(this.dims))throw new Error("Invalid new shape");return new Hh(this.module,this.dataType,this.data,t)}},dp=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.HEAPU32,s=r>>>2;this.opKernelContext=n[s++];let a=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let i=[];for(let d=0;dtypeof d=="number"?this.inputs[d]:d))??this.inputs,n=(t==null?void 0:t.outputs)??[],s=(d,c,p)=>new id(this.module,c,this.output(d,p),p),a=(d,c)=>{let p=Fn(d,c);if(!p)throw new Error(`Unsupported data type: ${d}`);let w=p>0?this.backend.gpuDataManager.create(p).id:0;return new id(this.module,d,w,c)};return this.backend.run(e,r,n,s,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),s=n>>2;this.module.HEAPU32[s++]=t.length;for(let a=0;a{let s=t.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new lp;await a.initialize(r,n),s("webgpu",[a,i=>a.alloc(i),i=>a.free(i),(i,d,c,p=!1)=>{if(p)Fr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${d}, size=${c}`),a.memcpy(i,d);else{Fr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${d}, size=${c}`);let w=t.HEAPU8.subarray(i>>>0,(i>>>0)+c);a.upload(d,w)}},async(i,d,c)=>{Fr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${d}, size=${c}`),await a.download(i,()=>t.HEAPU8.subarray(d>>>0,(d>>>0)+c))},(i,d,c)=>a.createKernel(i,d,c,t.UTF8ToString(t._JsepGetNodeName(d))),i=>a.releaseKernel(i),(i,d,c,p)=>{Fr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${i}, contextDataOffset=${d}`);let w=new dp(t,a,d);return a.computeKernel(i,w,p)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else s("webnn")}}),pp,Id,Fd,As,hp,ad,Od,zd,Dd,Bd,Ld,Rd,fp=D(()=>{Rs(),Ns(),Kt(),Xr(),jn(),ws(),pp=(e,t)=>{Or()._OrtInit(e,t)!==0&&Er("Can't initialize onnxruntime.")},Id=async e=>{pp(e.wasm.numThreads,Kn(e.logLevel))},Fd=async(e,t)=>{{let r=(ff(),P(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 s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",Or(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Or(),e)}}},As=new Map,hp=e=>{let t=Or(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Er("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},ad=e=>{let t=Or(),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]},Od=async(e,t)=>{var y,u;let r,n,s=Or();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=ad(e);let a=0,i=0,d=0,c=[],p=[],w=[];try{if([i,c]=Un(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let q=[];for(let oe of t.externalData){let Ke=typeof oe=="string"?oe:oe.path;q.push(Xn(typeof oe=="string"?oe:oe.data).then(Ae=>{s.mountExternalData(Ke,Ae)}))}await Promise.all(q)}for(let q of(t==null?void 0:t.executionProviders)??[])if((typeof q=="string"?q:q.name)==="webnn"){if(s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof q!="string"){let oe=q,Ke=oe==null?void 0:oe.context,Ae=oe==null?void 0:oe.gpuDevice,ht=oe==null?void 0:oe.deviceType,It=oe==null?void 0:oe.numThreads,zt=oe==null?void 0:oe.powerPreference;Ke?s.currentContext=Ke:Ae?s.currentContext=await navigator.ml.createContext(Ae):s.currentContext=await navigator.ml.createContext({deviceType:ht,numThreads:It,powerPreference:zt})}else s.currentContext=await navigator.ml.createContext();break}a=await s._OrtCreateSession(r,n,i),a===0&&Er("Can't create a session."),s.currentContext&&(s.currentContext=void 0);let[$,T]=hp(a),I=!!(t!=null&&t.enableGraphCapture),j=[],G=[],L=[];for(let q=0;q<$;q++){let oe=s._OrtGetInputName(a,q);oe===0&&Er("Can't get an input name."),p.push(oe),j.push(s.UTF8ToString(oe))}for(let q=0;qq==="gpu-buffer")&&(d=s._OrtCreateBinding(a),d===0&&Er("Can't create IO binding."),le={handle:d,outputPreferredLocations:L,outputPreferredLocationsEncoded:L.map(q=>ss(q))}),As.set(a,[a,p,w,le,I,!1]),[a,j,G]}catch($){throw p.forEach(T=>s._OrtFree(T)),w.forEach(T=>s._OrtFree(T)),d!==0&&s._OrtReleaseBinding(d),a!==0&&s._OrtReleaseSession(a),$}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i),c.forEach($=>s._free($)),(u=s.unmountExternalData)==null||u.call(s)}},zd=e=>{var c;let t=Or(),r=As.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,i,d]=r;i&&(d&&t._OrtClearBoundOutputs(i.handle),t._OrtReleaseBinding(i.handle)),(c=t.jsepOnReleaseSession)==null||c.call(t,e),s.forEach(p=>t._OrtFree(p)),a.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n),As.delete(e)},Dd=(e,t,r,n,s,a=!1)=>{if(!e){t.push(0);return}let i=Or(),d=e[0],c=e[1],p=e[3],w,y;if(d==="string"&&p==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let T=e[2].gpuBuffer;y=Fn(rs(d),c);let I=i.jsepRegisterBuffer;if(!I)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');w=I(n,s,T,y)}else{let T=e[2];if(Array.isArray(T)){y=4*T.length,w=i._malloc(y),r.push(w);let I=w/4;for(let j=0;ji.HEAP32[T++]=j);let I=i._OrtCreateTensor(rs(d),w,y,$,c.length,ss(p));I===0&&Er(`Can't create tensor for input/output. session=${n}, index=${s}.`),t.push(I)}finally{i.stackRestore(u)}},Bd=async(e,t,r,n,s,a)=>{var zt,cr;let i=Or(),d=As.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=d[0],p=d[1],w=d[2],y=d[3],u=d[4],$=d[5],T=t.length,I=n.length,j=0,G=[],L=[],le=[],q=[],oe=i.stackSave(),Ke=i.stackAlloc(T*4),Ae=i.stackAlloc(T*4),ht=i.stackAlloc(I*4),It=i.stackAlloc(I*4);try{[j,G]=In(a);for(let At=0;Atdn*xn,1);rr=Cn(rn);let Eu=y==null?void 0:y.outputPreferredLocations[n[At]];if(rr==="string"){if(Eu==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let dn=[],xn=Rr/4;for(let Ln=0;Ln0){let dn=i.jsepGetBuffer;if(!dn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xn=dn(Rr),Ln=Fn(rn,un);if(Ln===void 0||!ns(rr))throw new Error(`Unsupported data type: ${rr}`);Ft=!0,zr.push([rr,Pn,{gpuBuffer:xn,download:i.jsepCreateDownloader(xn,Ln,rr),dispose:()=>{i._OrtReleaseTensor(Jt)}},"gpu-buffer"])}else{let dn=On(rr),xn=new dn(un);new Uint8Array(xn.buffer,xn.byteOffset,xn.byteLength).set(i.HEAPU8.subarray(Rr,Rr+xn.byteLength)),zr.push([rr,Pn,xn,"cpu"])}}finally{i.stackRestore(Zt),rr==="string"&&Rr&&i._free(Rr),Ft||i._OrtReleaseTensor(Jt)}}return y&&!u&&(i._OrtClearBoundOutputs(y.handle),As.set(e,[c,p,w,y,u,!1])),zr}finally{i.stackRestore(oe),L.forEach(ir=>i._OrtReleaseTensor(ir)),le.forEach(ir=>i._OrtReleaseTensor(ir)),q.forEach(ir=>i._free(ir)),j!==0&&i._OrtReleaseRunOptions(j),G.forEach(ir=>i._free(ir))}},Ld=e=>{let t=Or(),r=As.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Er("Can't get an profile file name."),t._OrtFree(s)},Rd=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Is,$n,xa,ku,Cu,od,Nd,ld,ai,oi,mp,_p,gp,wp,yp,bp,vp,Mp,xp=D(()=>{k(),fp(),Xr(),Vr(),Is=()=>!!A.wasm.proxy&&typeof document<"u",xa=!1,ku=!1,Cu=!1,ld=new Map,ai=(e,t)=>{let r=ld.get(e);r?r.push(t):ld.set(e,[t])},oi=()=>{if(xa||!ku||Cu||!$n)throw new Error("worker not ready")},mp=e=>{switch(e.data.type){case"init-wasm":xa=!1,e.data.err?(Cu=!0,Nd[1](e.data.err)):(ku=!0,Nd[0]()),od&&(URL.revokeObjectURL(od),od=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=ld.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},_p=async()=>{if(!ku){if(xa)throw new Error("multiple calls to 'initWasm()' detected.");if(Cu)throw new Error("previous call to 'initWasm()' failed.");if(xa=!0,Is())return new Promise((e,t)=>{$n==null||$n.terminate(),Yt().then(([r,n])=>{try{$n=n,$n.onerror=a=>t(a),$n.onmessage=mp,Nd=[e,t];let s={type:"init-wasm",in:A};$n.postMessage(s),od=r}catch(s){t(s)}},t)});try{await An(A.wasm),await Id(A),ku=!0}catch(e){throw Cu=!0,e}finally{xa=!1}}},gp=async e=>{if(Is())return oi(),new Promise((t,r)=>{ai("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:A}};$n.postMessage(n)});await Fd(A,e)},wp=async e=>Is()?(oi(),new Promise((t,r)=>{ai("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};$n.postMessage(n,[e.buffer])})):ad(e),yp=async(e,t)=>{if(Is()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return oi(),new Promise((r,n)=>{ai("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),$n.postMessage(s,a)})}else return Od(e,t)},bp=async e=>{if(Is())return oi(),new Promise((t,r)=>{ai("release",[t,r]);let n={type:"release",in:e};$n.postMessage(n)});zd(e)},vp=async(e,t,r,n,s,a)=>{if(Is()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return oi(),new Promise((i,d)=>{ai("run",[i,d]);let c=r,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:c,outputIndices:n,options:a}};$n.postMessage(p,Rd(c))})}else return Bd(e,t,r,n,s,a)},Mp=async e=>{if(Is())return oi(),new Promise((t,r)=>{ai("end-profiling",[t,r]);let n={type:"end-profiling",in:e};$n.postMessage(n)});Ld(e)}}),Vd,Tp,$p,mf=D(()=>{k(),xp(),Kt(),H(),ws(),Vd=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Tp=e=>{switch(e[3]){case"cpu":return new ze(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ns(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return ze.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},$p=class{async fetchModelAndCopyToWasmMemory(e){return wp(await Xn(e))}async loadModel(e,t){Ue();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await yp(r,t),je()}async dispose(){return bp(this.sessionId)}async run(e,t,r){Ue();let n=[],s=[];Object.entries(e).forEach(y=>{let u=y[0],$=y[1],T=this.inputNames.indexOf(u);if(T===-1)throw new Error(`invalid input '${u}'`);n.push($),s.push(T)});let a=[],i=[];Object.entries(t).forEach(y=>{let u=y[0],$=y[1],T=this.outputNames.indexOf(u);if(T===-1)throw new Error(`invalid output '${u}'`);a.push($),i.push(T)});let d=n.map((y,u)=>Vd(y,()=>`input "${this.inputNames[s[u]]}"`)),c=a.map((y,u)=>y?Vd(y,()=>`output "${this.outputNames[i[u]]}"`):null),p=await vp(this.sessionId,s,d,i,c,r),w={};for(let y=0;y{k(),xp(),mf(),Vr(),kp=()=>{if((typeof A.wasm.initTimeout!="number"||A.wasm.initTimeout<0)&&(A.wasm.initTimeout=0),A.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 A.wasm.proxy!="boolean"&&(A.wasm.proxy=!1),typeof A.wasm.trace!="boolean"&&(A.wasm.trace=!1),typeof A.wasm.numThreads!="number"||!Number.isInteger(A.wasm.numThreads)||A.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)A.wasm.numThreads=1;else{let e=typeof navigator>"u"?xe("node:os").cpus().length:navigator.hardwareConcurrency;A.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Cp=class{async init(e){kp(),await _p(),await gp(e)}async createInferenceSessionHandler(e,t){let r=new $p;return await r.loadModel(e,t),Promise.resolve(r)}}}),Ep={};x(Ep,{wasmBackend:()=>Sp});var Sp,gf=D(()=>{_f(),Sp=new Cp});k(),k(),k();var wf="1.20.0-dev.20240821-009209e016",yf=Ee;{let e=(gf(),P(Ep)).wasmBackend;ne("webgpu",e,5),ne("webnn",e,5),ne("cpu",e,10),ne("wasm",e,10)}Object.defineProperty(A.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":(bt,fe,l)=>{var M;l.r(fe),l.d(fe,{Tensor:()=>xe.Tensor,createInferenceSession:()=>ie,deviceToExecutionProviders:()=>te,isONNXProxy:()=>se,isONNXTensor:()=>R});var K=l("./src/env.js"),ge=l("?2ce3"),Me=l("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),xe=l("./node_modules/onnxruntime-common/dist/esm/index.js");const D=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"}}),x=[];let V,P;if(K.apis.IS_NODE_ENV){switch(P=ge??(M||(M=l.t(ge,2))),process.platform){case"win32":x.push("dml");break;case"linux":process.arch==="x64"&&x.push("cuda");break}x.push("cpu"),V=["cpu"]}else P=Me,K.apis.IS_WEBNN_AVAILABLE&&x.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),K.apis.IS_WEBGPU_AVAILABLE&&x.push("webgpu"),x.push("wasm"),V=["wasm"];const J=P.InferenceSession;function te(ue=null){if(!ue)return V;switch(ue){case"auto":return x;case"gpu":return x.filter(ae=>["webgpu","cuda","dml","webnn-gpu"].includes(ae))}if(x.includes(ue))return[D[ue]??ue];throw new Error(`Unsupported device: "${ue}". Should be one of: ${x.join(", ")}.`)}let ne=null;async function ie(ue,ae){ne&&await ne;const N=J.create(ue,ae);return ne??(ne=N),await N}function R(ue){return ue instanceof P.Tensor}const Z=P==null?void 0:P.env;Z!=null&&Z.wasm&&(Z.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${K.env.version}/dist/`,Z.wasm.proxy=!K.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(Z.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(Z.wasm.simd=!1)),Z!=null&&Z.webgpu&&(Z.webgpu.powerPreference="high-performance");function se(){var ue;return(ue=Z==null?void 0:Z.wasm)==null?void 0:ue.proxy}K.env.backends.onnx=Z},"./src/configs.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{AutoConfig:()=>x,PretrainedConfig:()=>D,getKeyValueShapes:()=>xe});var M=l("./src/utils/core.js"),K=l("./src/utils/hub.js");async function ge(V,P){return await(0,K.getModelJSON)(V,"config.json",!0,P)}function Me(V){const P={};let J={};switch(V.model_type){case"llava":case"paligemma":case"florence2":J=Me(V.text_config);break;case"moondream1":J=Me(V.phi_config);break;case"musicgen":J=Me(V.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":P.num_heads="num_attention_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size",P.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.dim_kv="head_dim";break;case"openelm":P.num_heads="num_kv_heads",P.num_layers="num_transformer_layers",P.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":P.num_heads="num_heads",P.num_layers="num_layers",P.hidden_size="hidden_size";break;case"bloom":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="hidden_size";break;case"mpt":P.num_heads="n_heads",P.num_layers="n_layers",P.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":P.num_decoder_layers="num_decoder_layers",P.num_decoder_heads="num_heads",P.decoder_dim_kv="d_kv",P.num_encoder_layers="num_layers",P.num_encoder_heads="num_heads",P.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="d_model",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="d_model";break;case"speecht5":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="hidden_size",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="hidden_size";break;case"trocr":P.num_encoder_layers=P.num_decoder_layers="decoder_layers",P.num_encoder_heads=P.num_decoder_heads="decoder_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="d_model";break;case"musicgen_decoder":P.num_encoder_layers=P.num_decoder_layers="num_hidden_layers",P.num_encoder_heads=P.num_decoder_heads="num_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const ne=Me(V.decoder),ie="num_decoder_layers"in ne,R=(0,M.pick)(V,["model_type","is_encoder_decoder"]);return ie?(R.num_decoder_layers=ne.num_decoder_layers,R.num_decoder_heads=ne.num_decoder_heads,R.decoder_hidden_size=ne.decoder_hidden_size,R.num_encoder_layers=ne.num_encoder_layers,R.num_encoder_heads=ne.num_encoder_heads,R.encoder_hidden_size=ne.encoder_hidden_size):(R.num_layers=ne.num_layers,R.num_heads=ne.num_heads,R.hidden_size=ne.hidden_size),R}const te={...J,...(0,M.pick)(V,["model_type","multi_query","is_encoder_decoder"])};for(const ne in P)te[ne]=V[P[ne]];return te}function xe(V,{prefix:P="past_key_values"}={}){const J={},te=V.normalized_config,ne=1;if(te.is_encoder_decoder&&"num_encoder_heads"in te&&"num_decoder_heads"in te){const ie=te.encoder_dim_kv??te.encoder_hidden_size/te.num_encoder_heads,R=te.decoder_dim_kv??te.decoder_hidden_size/te.num_decoder_heads,Z=[ne,te.num_encoder_heads,0,ie],se=[ne,te.num_decoder_heads,0,R];for(let ue=0;ue{var A;l.r(fe),l.d(fe,{apis:()=>R,env:()=>F});var M=l("?569f"),K=l("?3f59"),ge=l("?154a");const Me="3.0.0-alpha.9",xe=typeof self<"u",D=xe&&self.constructor.name==="DedicatedWorkerGlobalScope",x=xe&&"caches"in self,V=typeof navigator<"u"&&"gpu"in navigator,P=typeof navigator<"u"&&"ml"in navigator,J=typeof process<"u",te=J&&((A=process==null?void 0:process.release)==null?void 0:A.name)==="node",ne=!B(M),ie=!B(K),R=Object.freeze({IS_BROWSER_ENV:xe,IS_WEBWORKER_ENV:D,IS_WEB_CACHE_AVAILABLE:x,IS_WEBGPU_AVAILABLE:V,IS_WEBNN_AVAILABLE:P,IS_PROCESS_AVAILABLE:J,IS_NODE_ENV:te,IS_FS_AVAILABLE:ne,IS_PATH_AVAILABLE:ie}),Z=ne&&ie,se=Z?K.dirname(K.dirname(ge.fileURLToPath(self.location.href))):"./",ue=Z?K.join(se,"/.cache/"):null,ae="/models/",N=Z?K.join(se,ae):ae,F={version:Me,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!xe,localModelPath:N,useFS:ne,useBrowserCache:x,useFSCache:ne,cacheDir:ue,useCustomCache:!1,customCache:null};function B(_e){return Object.keys(_e).length===0}},"./src/generation/configuration_utils.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{GenerationConfig:()=>K});var M=l("./src/utils/core.js");class K{constructor(Me){Te(this,"max_length",20);Te(this,"max_new_tokens",null);Te(this,"min_length",0);Te(this,"min_new_tokens",null);Te(this,"early_stopping",!1);Te(this,"max_time",null);Te(this,"do_sample",!1);Te(this,"num_beams",1);Te(this,"num_beam_groups",1);Te(this,"penalty_alpha",null);Te(this,"use_cache",!0);Te(this,"temperature",1);Te(this,"top_k",50);Te(this,"top_p",1);Te(this,"typical_p",1);Te(this,"epsilon_cutoff",0);Te(this,"eta_cutoff",0);Te(this,"diversity_penalty",0);Te(this,"repetition_penalty",1);Te(this,"encoder_repetition_penalty",1);Te(this,"length_penalty",1);Te(this,"no_repeat_ngram_size",0);Te(this,"bad_words_ids",null);Te(this,"force_words_ids",null);Te(this,"renormalize_logits",!1);Te(this,"constraints",null);Te(this,"forced_bos_token_id",null);Te(this,"forced_eos_token_id",null);Te(this,"remove_invalid_values",!1);Te(this,"exponential_decay_length_penalty",null);Te(this,"suppress_tokens",null);Te(this,"begin_suppress_tokens",null);Te(this,"forced_decoder_ids",null);Te(this,"guidance_scale",null);Te(this,"num_return_sequences",1);Te(this,"output_attentions",!1);Te(this,"output_hidden_states",!1);Te(this,"output_scores",!1);Te(this,"return_dict_in_generate",!1);Te(this,"pad_token_id",null);Te(this,"bos_token_id",null);Te(this,"eos_token_id",null);Te(this,"encoder_no_repeat_ngram_size",0);Te(this,"decoder_start_token_id",null);Te(this,"generation_kwargs",{});Object.assign(this,(0,M.pick)(Me,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{ClassifierFreeGuidanceLogitsProcessor:()=>Z,ForcedBOSTokenLogitsProcessor:()=>D,ForcedEOSTokenLogitsProcessor:()=>x,LogitsProcessor:()=>ge,LogitsProcessorList:()=>xe,LogitsWarper:()=>Me,MinLengthLogitsProcessor:()=>ne,MinNewTokensLengthLogitsProcessor:()=>ie,NoBadWordsLogitsProcessor:()=>R,NoRepeatNGramLogitsProcessor:()=>J,RepetitionPenaltyLogitsProcessor:()=>te,SuppressTokensAtBeginLogitsProcessor:()=>V,TemperatureLogitsWarper:()=>se,TopKLogitsWarper:()=>ae,TopPLogitsWarper:()=>ue,WhisperTimeStampLogitsProcessor:()=>P});var M=l("./src/utils/generic.js");l("./src/utils/tensor.js");var K=l("./src/utils/maths.js");class ge extends M.Callable{_call(F,B){throw Error("`_call` should be implemented in a subclass")}}class Me extends M.Callable{_call(F,B){throw Error("`_call` should be implemented in a subclass")}}class xe extends M.Callable{constructor(){super(),this.processors=[]}push(F){this.processors.push(F)}extend(F){this.processors.push(...F)}_call(F,B){let A=B;for(const _e of this.processors)A=_e(F,A);return A}[Symbol.iterator](){return this.processors.values()}}class D extends ge{constructor(F){super(),this.bos_token_id=F}_call(F,B){for(let A=0;A=1&&$e[$e.length-1]>=this.timestamp_begin,Fe=$e.length<2||$e[$e.length-2]>=this.timestamp_begin;if(Se&&(Fe?ye.subarray(this.timestamp_begin).fill(-1/0):ye.subarray(0,this.eos_token_id).fill(-1/0)),F[A].length===this.begin_index&&this.max_initial_timestamp_index!==null){const we=this.timestamp_begin+this.max_initial_timestamp_index;ye.subarray(we+1).fill(-1/0)}const et=(0,K.log_softmax)(ye),Xe=Math.log(et.subarray(this.timestamp_begin).map(Math.exp).reduce((we,U)=>we+U)),ct=(0,K.max)(et.subarray(0,this.timestamp_begin))[0];Xe>ct&&ye.subarray(0,this.timestamp_begin).fill(-1/0)}return B}}class J extends ge{constructor(F){super(),this.no_repeat_ngram_size=F}getNgrams(F){const B=F.length,A=[];for(let ye=0;ye1 to use the classifier free guidance processor, got guidance scale ${F}.`);this.guidance_scale=F}_call(F,B){if(B.dims[0]!==2*F.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${B.dims[0]} for the logits and ${F.length} for the input ids.`);const A=F.length,_e=B.slice([0,A],null),ye=B.slice([A,B.dims[0]],null);for(let $e=0;$e1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${F}`);if(!Number.isInteger(A)||A<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${A}`);this.top_p=F,this.filter_value=B,this.min_tokens_to_keep=A}}class ae extends Me{constructor(F,{filter_value:B=-1/0,min_tokens_to_keep:A=1}={}){if(super(),!Number.isInteger(F)||F<0)throw new Error(`\`top_k\` must be a positive integer, but is ${F}`);this.top_k=Math.max(F,A),this.filter_value=B}}},"./src/generation/logits_sampler.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{LogitsSampler:()=>Me});var M=l("./src/utils/generic.js"),K=l("./src/utils/tensor.js"),ge=l("./src/utils/maths.js");l("./src/generation/configuration_utils.js");class Me extends M.Callable{constructor(P){super(),this.generation_config=P}async _call(P){return this.sample(P)}async sample(P){throw Error("sample should be implemented in subclasses.")}getLogits(P,J){let te=P.dims.at(-1),ne=P.data;if(J===-1)ne=ne.slice(-te);else{let ie=J*te;ne=ne.slice(ie,ie+te)}return ne}randomSelect(P){let J=0;for(let ne=0;ne1)return new x(P);if(P.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${P.num_return_sequences}.`);return new xe(P)}}class xe extends Me{async sample(P){const J=(0,ge.max)(P.data)[1];return[[BigInt(J),0]]}}class D extends Me{async sample(P){let J=P.dims.at(-1);this.generation_config.top_k>0&&(J=Math.min(this.generation_config.top_k,J));const[te,ne]=await(0,K.topk)(P,J),ie=(0,ge.softmax)(te.data);return Array.from({length:this.generation_config.num_beams},()=>{const R=this.randomSelect(ie);return[ne.data[R],Math.log(ie[R])]})}}class x extends Me{async sample(P){let J=P.dims.at(-1);this.generation_config.top_k>0&&(J=Math.min(this.generation_config.top_k,J));const[te,ne]=await(0,K.topk)(P,J),ie=(0,ge.softmax)(te.data);return Array.from({length:this.generation_config.num_beams},(R,Z)=>[ne.data[Z],Math.log(ie[Z])])}}},"./src/generation/stopping_criteria.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{EosTokenCriteria:()=>xe,InterruptableStoppingCriteria:()=>D,MaxLengthCriteria:()=>Me,StoppingCriteria:()=>K,StoppingCriteriaList:()=>ge});var M=l("./src/utils/generic.js");class K extends M.Callable{_call(V,P){throw Error("StoppingCriteria needs to be subclassed")}}class ge extends M.Callable{constructor(){super(),this.criteria=[]}push(V){this.criteria.push(V)}extend(V){V instanceof ge?V=V.criteria:V instanceof K&&(V=[V]),this.criteria.push(...V)}_call(V,P){const J=new Array(V.length).fill(!1);for(const te of this.criteria){const ne=te(V,P);for(let ie=0;ieP.length>=this.max_length)}}class xe extends K{constructor(V){super(),Array.isArray(V)||(V=[V]),this.eos_token_id=V}_call(V,P){return V.map(J=>{const te=J.at(-1);return this.eos_token_id.some(ne=>te==ne)})}}class D extends K{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(V,P){return new Array(V.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{BaseStreamer:()=>Me,TextStreamer:()=>D,WhisperTextStreamer:()=>x});var M=l("./src/utils/core.js"),K=l("./src/tokenizers.js"),ge=l("./src/env.js");class Me{put(P){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const xe=ge.apis.IS_PROCESS_AVAILABLE?V=>process.stdout.write(V):V=>console.log(V);class D extends Me{constructor(P,{skip_prompt:J=!1,callback_function:te=null,token_callback_function:ne=null,decode_kwargs:ie={},...R}={}){super(),this.tokenizer=P,this.skip_prompt=J,this.callback_function=te??xe,this.token_callback_function=ne,this.decode_kwargs={...ie,...R},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(P){var ie;if(P.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const J=P[0];(ie=this.token_callback_function)==null||ie.call(this,J),this.token_cache=(0,M.mergeArrays)(this.token_cache,J);const te=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let ne;te.endsWith(` `)?(ne=te.slice(this.print_len),this.token_cache=[],this.print_len=0):te.length>0&&(0,K.is_chinese_char)(te.charCodeAt(te.length-1))?(ne=te.slice(this.print_len),this.print_len+=ne.length):(ne=te.slice(this.print_len,te.lastIndexOf(" ")+1),this.print_len+=ne.length),this.on_finalized_text(ne,!1)}end(){let P;this.token_cache.length>0?(P=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):P="",this.next_tokens_are_prompt=!0,this.on_finalized_text(P,!0)}on_finalized_text(P,J){var te,ne;P.length>0&&((te=this.callback_function)==null||te.call(this,P)),J&&this.callback_function===xe&&ge.apis.IS_PROCESS_AVAILABLE&&((ne=this.callback_function)==null||ne.call(this,` `))}}class x extends D{constructor(P,{skip_prompt:J=!1,callback_function:te=null,token_callback_function:ne=null,on_chunk_start:ie=null,on_chunk_end:R=null,on_finalize:Z=null,time_precision:se=.02,skip_special_tokens:ue=!0,decode_kwargs:ae={}}={}){super(P,{skip_prompt:J,callback_function:te,token_callback_function:ne,decode_kwargs:{skip_special_tokens:ue,...ae}}),this.timestamp_begin=P.timestamp_begin,this.on_chunk_start=ie,this.on_chunk_end=R,this.on_finalize=Z,this.time_precision=se,this.waiting_for_timestamp=!1}put(P){var te,ne;if(P.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const J=P[0];if(J.length===1){const ie=Number(J[0])-this.timestamp_begin;if(ie>=0){const R=ie*this.time_precision;this.waiting_for_timestamp?(te=this.on_chunk_end)==null||te.call(this,R):(ne=this.on_chunk_start)==null||ne.call(this,R),this.waiting_for_timestamp=!this.waiting_for_timestamp,P=[[]]}}return super.put(P)}end(){var P;super.end(),(P=this.on_finalize)==null||P.call(this)}}},"./src/models.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{ASTForAudioClassification:()=>Vs,ASTModel:()=>Ot,ASTPreTrainedModel:()=>fn,AlbertForMaskedLM:()=>Kt,AlbertForQuestionAnswering:()=>ss,AlbertForSequenceClassification:()=>ns,AlbertModel:()=>Kn,AlbertPreTrainedModel:()=>On,AutoModel:()=>su,AutoModelForAudioClassification:()=>_u,AutoModelForAudioFrameClassification:()=>gu,AutoModelForCTC:()=>mu,AutoModelForCausalLM:()=>lu,AutoModelForDepthEstimation:()=>bu,AutoModelForDocumentQuestionAnswering:()=>Ju,AutoModelForImageClassification:()=>cu,AutoModelForImageFeatureExtraction:()=>vu,AutoModelForImageMatting:()=>wu,AutoModelForImageSegmentation:()=>ya,AutoModelForImageToImage:()=>yu,AutoModelForMaskGeneration:()=>ba,AutoModelForMaskedLM:()=>uu,AutoModelForObjectDetection:()=>hu,AutoModelForQuestionAnswering:()=>wa,AutoModelForSemanticSegmentation:()=>pu,AutoModelForSeq2SeqLM:()=>au,AutoModelForSequenceClassification:()=>sn,AutoModelForSpeechSeq2Seq:()=>ga,AutoModelForTextToSpectrogram:()=>ou,AutoModelForTextToWaveform:()=>Ss,AutoModelForTokenClassification:()=>iu,AutoModelForVision2Seq:()=>du,AutoModelForXVector:()=>va,AutoModelForZeroShotObjectDetection:()=>fu,BartForConditionalGeneration:()=>_,BartForSequenceClassification:()=>O,BartModel:()=>ve,BartPretrainedModel:()=>pn,BaseModelOutput:()=>dt,BeitForImageClassification:()=>So,BeitModel:()=>Eo,BeitPreTrainedModel:()=>Si,BertForMaskedLM:()=>Le,BertForQuestionAnswering:()=>ze,BertForSequenceClassification:()=>st,BertForTokenClassification:()=>xt,BertModel:()=>ot,BertPreTrainedModel:()=>tt,BlenderbotForConditionalGeneration:()=>St,BlenderbotModel:()=>wt,BlenderbotPreTrainedModel:()=>yt,BlenderbotSmallForConditionalGeneration:()=>er,BlenderbotSmallModel:()=>$r,BlenderbotSmallPreTrainedModel:()=>Qt,BloomForCausalLM:()=>uo,BloomModel:()=>lo,BloomPreTrainedModel:()=>Ws,CLIPModel:()=>Pa,CLIPPreTrainedModel:()=>xs,CLIPSegForImageSegmentation:()=>Ba,CLIPSegModel:()=>Da,CLIPSegPreTrainedModel:()=>fi,CLIPTextModelWithProjection:()=>En,CLIPVisionModelWithProjection:()=>Aa,CamembertForMaskedLM:()=>be,CamembertForQuestionAnswering:()=>Re,CamembertForSequenceClassification:()=>Be,CamembertForTokenClassification:()=>Ie,CamembertModel:()=>H,CamembertPreTrainedModel:()=>k,CausalLMOutput:()=>Qn,CausalLMOutputWithPast:()=>ed,ChineseCLIPModel:()=>za,ChineseCLIPPreTrainedModel:()=>Oa,ClapAudioModelWithProjection:()=>Al,ClapModel:()=>Sl,ClapPreTrainedModel:()=>$s,ClapTextModelWithProjection:()=>Pl,CodeGenForCausalLM:()=>js,CodeGenModel:()=>Ha,CodeGenPreTrainedModel:()=>yn,CohereForCausalLM:()=>Qa,CohereModel:()=>Xa,CoherePreTrainedModel:()=>yi,ConvBertForMaskedLM:()=>v,ConvBertForQuestionAnswering:()=>Q,ConvBertForSequenceClassification:()=>W,ConvBertForTokenClassification:()=>S,ConvBertModel:()=>Mt,ConvBertPreTrainedModel:()=>gt,ConvNextForImageClassification:()=>Zo,ConvNextModel:()=>Yo,ConvNextPreTrainedModel:()=>ji,ConvNextV2ForImageClassification:()=>tl,ConvNextV2Model:()=>el,ConvNextV2PreTrainedModel:()=>Jo,DPTForDepthEstimation:()=>Ri,DPTModel:()=>Li,DPTPreTrainedModel:()=>Bi,DebertaForMaskedLM:()=>vt,DebertaForQuestionAnswering:()=>Lt,DebertaForSequenceClassification:()=>pt,DebertaForTokenClassification:()=>Tt,DebertaModel:()=>nt,DebertaPreTrainedModel:()=>ut,DebertaV2ForMaskedLM:()=>Rt,DebertaV2ForQuestionAnswering:()=>Yt,DebertaV2ForSequenceClassification:()=>qt,DebertaV2ForTokenClassification:()=>Ht,DebertaV2Model:()=>Nt,DebertaV2PreTrainedModel:()=>He,DeiTForImageClassification:()=>No,DeiTModel:()=>Ro,DeiTPreTrainedModel:()=>Ii,DepthAnythingForDepthEstimation:()=>Ho,DepthAnythingPreTrainedModel:()=>qo,DetrForObjectDetection:()=>Ao,DetrForSegmentation:()=>Io,DetrModel:()=>Po,DetrObjectDetectionOutput:()=>Pi,DetrPreTrainedModel:()=>Hs,DetrSegmentationOutput:()=>Fo,Dinov2ForImageClassification:()=>nl,Dinov2Model:()=>rl,Dinov2PreTrainedModel:()=>vn,DistilBertForMaskedLM:()=>Ct,DistilBertForQuestionAnswering:()=>Ze,DistilBertForSequenceClassification:()=>Vr,DistilBertForTokenClassification:()=>Tr,DistilBertModel:()=>xr,DistilBertPreTrainedModel:()=>Wt,DonutSwinModel:()=>Vi,DonutSwinPreTrainedModel:()=>Qo,EfficientNetForImageClassification:()=>Dl,EfficientNetModel:()=>zl,EfficientNetPreTrainedModel:()=>la,ElectraForMaskedLM:()=>Je,ElectraForQuestionAnswering:()=>Ee,ElectraForSequenceClassification:()=>Pt,ElectraForTokenClassification:()=>mt,ElectraModel:()=>Ye,ElectraPreTrainedModel:()=>he,EsmForMaskedLM:()=>Vn,EsmForSequenceClassification:()=>An,EsmForTokenClassification:()=>Or,EsmModel:()=>Ur,EsmPreTrainedModel:()=>Dt,FalconForCausalLM:()=>El,FalconModel:()=>Cl,FalconPreTrainedModel:()=>sa,FastViTForImageClassification:()=>go,FastViTModel:()=>_o,FastViTPreTrainedModel:()=>qs,Florence2ForConditionalGeneration:()=>pi,Florence2PreTrainedModel:()=>Sa,GLPNForDepthEstimation:()=>Xo,GLPNModel:()=>Ko,GLPNPreTrainedModel:()=>Ni,GPT2LMHeadModel:()=>Ra,GPT2Model:()=>La,GPT2PreTrainedModel:()=>mi,GPTBigCodeForCausalLM:()=>Iu,GPTBigCodeModel:()=>qa,GPTBigCodePreTrainedModel:()=>wi,GPTJForCausalLM:()=>Ga,GPTJModel:()=>Wa,GPTJPreTrainedModel:()=>gi,GPTNeoForCausalLM:()=>Va,GPTNeoModel:()=>Na,GPTNeoPreTrainedModel:()=>wn,GPTNeoXForCausalLM:()=>Ua,GPTNeoXModel:()=>ja,GPTNeoXPreTrainedModel:()=>_i,Gemma2ForCausalLM:()=>eo,Gemma2Model:()=>Ja,Gemma2PreTrainedModel:()=>vi,GemmaForCausalLM:()=>Za,GemmaModel:()=>Ya,GemmaPreTrainedModel:()=>bi,HubertForCTC:()=>wl,HubertForSequenceClassification:()=>Yi,HubertModel:()=>Lu,HubertPreTrainedModel:()=>Bu,ImageMattingOutput:()=>xu,LlamaForCausalLM:()=>Ka,LlamaModel:()=>Tn,LlamaPreTrainedModel:()=>Us,LlavaForConditionalGeneration:()=>os,LlavaPreTrainedModel:()=>Ea,LongT5ForConditionalGeneration:()=>vs,LongT5Model:()=>bs,LongT5PreTrainedModel:()=>is,M2M100ForConditionalGeneration:()=>pl,M2M100Model:()=>cl,M2M100PreTrainedModel:()=>Gi,MBartForCausalLM:()=>_t,MBartForConditionalGeneration:()=>ce,MBartForSequenceClassification:()=>Oe,MBartModel:()=>de,MBartPreTrainedModel:()=>Y,MPNetForMaskedLM:()=>fs,MPNetForQuestionAnswering:()=>gs,MPNetForSequenceClassification:()=>ms,MPNetForTokenClassification:()=>_s,MPNetModel:()=>Rs,MPNetPreTrainedModel:()=>In,MT5ForConditionalGeneration:()=>Fr,MT5Model:()=>Ms,MT5PreTrainedModel:()=>as,MarianMTModel:()=>dl,MarianModel:()=>zu,MarianPreTrainedModel:()=>Wi,MaskedLMOutput:()=>Zr,MistralForCausalLM:()=>ei,MistralModel:()=>Js,MistralPreTrainedModel:()=>ta,MobileBertForMaskedLM:()=>kn,MobileBertForQuestionAnswering:()=>jn,MobileBertForSequenceClassification:()=>Er,MobileBertModel:()=>Dr,MobileBertPreTrainedModel:()=>Xr,MobileNetV1ForImageClassification:()=>ju,MobileNetV1Model:()=>Bl,MobileNetV1PreTrainedModel:()=>ca,MobileNetV2ForImageClassification:()=>Rl,MobileNetV2Model:()=>Ll,MobileNetV2PreTrainedModel:()=>pa,MobileNetV3ForImageClassification:()=>Uu,MobileNetV3Model:()=>Nl,MobileNetV3PreTrainedModel:()=>ha,MobileNetV4ForImageClassification:()=>fa,MobileNetV4Model:()=>Es,MobileNetV4PreTrainedModel:()=>Cs,MobileViTForImageClassification:()=>Mo,MobileViTModel:()=>vo,MobileViTPreTrainedModel:()=>bo,MobileViTV2ForImageClassification:()=>xo,MobileViTV2Model:()=>Ou,MobileViTV2PreTrainedModel:()=>Ci,ModelOutput:()=>Ge,Moondream1ForConditionalGeneration:()=>nr,MptForCausalLM:()=>co,MptModel:()=>Fu,MptPreTrainedModel:()=>Gs,MusicgenForCausalLM:()=>kd,MusicgenForConditionalGeneration:()=>da,MusicgenModel:()=>Vu,MusicgenPreTrainedModel:()=>ua,NomicBertModel:()=>Ce,NomicBertPreTrainedModel:()=>re,OPTForCausalLM:()=>ho,OPTModel:()=>po,OPTPreTrainedModel:()=>ki,OpenELMForCausalLM:()=>ro,OpenELMModel:()=>to,OpenELMPreTrainedModel:()=>bn,OwlViTForObjectDetection:()=>$o,OwlViTModel:()=>To,OwlViTPreTrainedModel:()=>gr,Owlv2ForObjectDetection:()=>Co,Owlv2Model:()=>ko,Owlv2PreTrainedModel:()=>Ei,Phi3ForCausalLM:()=>$i,Phi3Model:()=>oo,Phi3PreTrainedModel:()=>Ti,PhiForCausalLM:()=>ao,PhiModel:()=>io,PhiPreTrainedModel:()=>xi,PreTrainedModel:()=>ee,PretrainedMixin:()=>Pr,PyAnnoteForAudioFrameClassification:()=>Hn,PyAnnoteModel:()=>qi,PyAnnotePreTrainedModel:()=>zn,QuestionAnsweringModelOutput:()=>Jr,Qwen2ForCausalLM:()=>so,Qwen2Model:()=>no,Qwen2PreTrainedModel:()=>Mi,RTDetrForObjectDetection:()=>Ks,RTDetrModel:()=>Oo,RTDetrObjectDetectionOutput:()=>zo,RTDetrPreTrainedModel:()=>ds,ResNetForImageClassification:()=>jo,ResNetModel:()=>Vo,ResNetPreTrainedModel:()=>Fi,RoFormerForMaskedLM:()=>je,RoFormerForQuestionAnswering:()=>ft,RoFormerForSequenceClassification:()=>qe,RoFormerForTokenClassification:()=>lt,RoFormerModel:()=>Ue,RoFormerPreTrainedModel:()=>Ve,RobertaForMaskedLM:()=>nn,RobertaForQuestionAnswering:()=>gn,RobertaForSequenceClassification:()=>Kr,RobertaForTokenClassification:()=>Ne,RobertaModel:()=>pr,RobertaPreTrainedModel:()=>Ut,SamImageSegmentationOutput:()=>ul,SamModel:()=>ll,SamPreTrainedModel:()=>ol,SegformerForImageClassification:()=>Il,SegformerForSemanticSegmentation:()=>Fl,SegformerModel:()=>$d,SegformerPreTrainedModel:()=>ks,Seq2SeqLMOutput:()=>Ed,SequenceClassifierOutput:()=>or,SiglipModel:()=>ls,SiglipPreTrainedModel:()=>hi,SiglipTextModel:()=>Ia,SiglipVisionModel:()=>Fa,SpeechT5ForSpeechToText:()=>Tl,SpeechT5ForTextToSpeech:()=>Ru,SpeechT5HifiGan:()=>ea,SpeechT5Model:()=>xl,SpeechT5PreTrainedModel:()=>Ji,SqueezeBertForMaskedLM:()=>rs,SqueezeBertForQuestionAnswering:()=>Fn,SqueezeBertForSequenceClassification:()=>Cn,SqueezeBertModel:()=>Ns,SqueezeBertPreTrainedModel:()=>Un,StableLmForCausalLM:()=>Ol,StableLmModel:()=>oa,StableLmPreTrainedModel:()=>aa,Starcoder2ForCausalLM:()=>na,Starcoder2Model:()=>ti,Starcoder2PreTrainedModel:()=>ra,Swin2SRForImageSuperResolution:()=>Di,Swin2SRModel:()=>Go,Swin2SRPreTrainedModel:()=>zi,SwinForImageClassification:()=>Wo,SwinModel:()=>Uo,SwinPreTrainedModel:()=>Oi,T5ForConditionalGeneration:()=>ys,T5Model:()=>ws,T5PreTrainedModel:()=>Xn,TableTransformerForObjectDetection:()=>Bo,TableTransformerModel:()=>Do,TableTransformerObjectDetectionOutput:()=>Lo,TableTransformerPreTrainedModel:()=>Ai,TokenClassifierOutput:()=>Hr,TrOCRForCausalLM:()=>kl,TrOCRPreTrainedModel:()=>$l,UniSpeechForCTC:()=>fl,UniSpeechForSequenceClassification:()=>ml,UniSpeechModel:()=>Ki,UniSpeechPreTrainedModel:()=>cs,UniSpeechSatForAudioFrameClassification:()=>Qs,UniSpeechSatForCTC:()=>Xi,UniSpeechSatForSequenceClassification:()=>_l,UniSpeechSatModel:()=>Xs,UniSpeechSatPreTrainedModel:()=>Ts,ViTForImageClassification:()=>mo,ViTModel:()=>fo,ViTPreTrainedModel:()=>us,VisionEncoderDecoderModel:()=>ci,VitMatteForImageMatting:()=>yo,VitMattePreTrainedModel:()=>wo,VitsModel:()=>ia,VitsModelOutput:()=>td,VitsPreTrainedModel:()=>Nu,Wav2Vec2BertForCTC:()=>Zs,Wav2Vec2BertForSequenceClassification:()=>gl,Wav2Vec2BertModel:()=>Qi,Wav2Vec2BertPreTrainedModel:()=>Ys,Wav2Vec2ForAudioFrameClassification:()=>qn,Wav2Vec2ForCTC:()=>Du,Wav2Vec2ForSequenceClassification:()=>Gn,Wav2Vec2Model:()=>hl,Wav2Vec2PreTrainedModel:()=>Wn,WavLMForAudioFrameClassification:()=>Ml,WavLMForCTC:()=>Zi,WavLMForSequenceClassification:()=>bl,WavLMForXVector:()=>vl,WavLMModel:()=>yl,WavLMPreTrainedModel:()=>Dn,WeSpeakerResNetModel:()=>Hi,WeSpeakerResNetPreTrainedModel:()=>Yr,WhisperForConditionalGeneration:()=>di,WhisperModel:()=>Vt,WhisperPreTrainedModel:()=>rt,XLMForQuestionAnswering:()=>Qr,XLMForSequenceClassification:()=>Xt,XLMForTokenClassification:()=>hn,XLMModel:()=>Wr,XLMPreTrainedModel:()=>yr,XLMRobertaForMaskedLM:()=>kt,XLMRobertaForQuestionAnswering:()=>Br,XLMRobertaForSequenceClassification:()=>_r,XLMRobertaForTokenClassification:()=>Sr,XLMRobertaModel:()=>vr,XLMRobertaPreTrainedModel:()=>br,XLMWithLMHeadModel:()=>on,XVectorOutput:()=>Mu,YolosForObjectDetection:()=>il,YolosModel:()=>sl,YolosObjectDetectionOutput:()=>al,YolosPreTrainedModel:()=>Ui});var M=l("./src/configs.js"),K=l("./src/backends/onnx.js"),ge=l("./src/utils/dtypes.js"),Me=l("./src/utils/generic.js"),xe=l("./src/utils/core.js"),D=l("./src/utils/hub.js"),x=l("./src/generation/logits_process.js"),V=l("./src/generation/configuration_utils.js"),P=l("./src/utils/tensor.js"),J=l("./src/utils/maths.js"),te=l("./src/generation/stopping_criteria.js"),ne=l("./src/generation/logits_sampler.js"),ie=l("./src/env.js"),R=l("./src/models/whisper/generation_whisper.js"),Z=l("./src/models/whisper/common_whisper.js");const se={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},ue=new Map,ae=new Map,N=new Map;async function F(m,g,C){let X=C.device;X&&typeof X!="string"&&(X.hasOwnProperty(g)?X=X[g]:(console.warn(`device not specified for "${g}". Using the default device.`),X=null));const Pe=X??(ie.apis.IS_NODE_ENV?"cpu":"wasm"),De=(0,K.deviceToExecutionProviders)(Pe);let it=C.dtype;typeof it!="string"&&(it&&it.hasOwnProperty(g)?it=it[g]:(it=ge.DEFAULT_DEVICE_DTYPE_MAPPING[Pe]??ge.DATA_TYPES.fp32,console.warn(`dtype not specified for "${g}". Using the default dtype (${it}) for this device (${Pe}).`)));const $t=it;if(ge.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty($t)){if($t===ge.DATA_TYPES.fp16&&Pe==="webgpu"&&!await(0,ge.isWebGpuFp16Supported)())throw new Error(`The device (${Pe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${$t}. Should be one of: ${Object.keys(ge.DATA_TYPES).join(", ")}`);const jt=ge.DEFAULT_DTYPE_SUFFIX_MAPPING[$t],lr=`${C.subfolder??""}/${g}${jt}.onnx`,sr={...C.session_options};sr.executionProviders??(sr.executionProviders=De);const kr=(0,D.getModelFile)(m,lr,!0,C);let ur=[];if(C.use_external_data_format&&(C.use_external_data_format===!0||typeof C.use_external_data_format=="object"&&C.use_external_data_format.hasOwnProperty(g)&&C.use_external_data_format[g]===!0)){if(ie.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const dr=`${g}${jt}.onnx_data`,hr=`${C.subfolder??""}/${dr}`;ur.push(new Promise(async(wr,Ar)=>{const an=await(0,D.getModelFile)(m,hr,!0,C);wr({path:dr,data:an})}))}else sr.externalData!==void 0&&(ur=sr.externalData.map(async dr=>{if(typeof dr.data=="string"){const hr=await(0,D.getModelFile)(m,dr.data,!0,C);return{...dr,data:hr}}return dr}));if(ur.length>0&&(sr.externalData=await Promise.all(ur)),Pe==="webgpu"){const dr=(0,M.getKeyValueShapes)(C.config,{prefix:"present"});if(Object.keys(dr).length>0&&!(0,K.isONNXProxy)()){const hr={};for(const wr in dr)hr[wr]="gpu-buffer";sr.preferredOutputLocation=hr}}return{buffer:await kr,session_options:sr}}async function B(m,g,C){return Object.fromEntries(await Promise.all(Object.keys(g).map(async X=>{const{buffer:Pe,session_options:De}=await F(m,g[X],C),it=await(0,K.createInferenceSession)(Pe,De);return[X,it]})))}function A(m,g){const C=Object.create(null),X=[];for(const it of m.inputNames){const $t=g[it];if(!($t instanceof P.Tensor)){X.push(it);continue}C[it]=(0,K.isONNXProxy)()?$t.clone():$t}if(X.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${X.join(", ")}.`);const Pe=Object.keys(g).length,De=m.inputNames.length;if(Pe>De){let it=Object.keys(g).filter($t=>!m.inputNames.includes($t));console.warn(`WARNING: Too many inputs were provided (${Pe} > ${De}). The following inputs will be ignored: "${it.join(", ")}".`)}return C}async function _e(m,g){const C=A(m,g);try{const X=Object.fromEntries(Object.entries(C).map(([De,it])=>[De,it.ort_tensor]));let Pe=await m.run(X);return Pe=ye(Pe),Pe}catch(X){throw console.error(`An error occurred during model execution: "${X}".`),console.error("Inputs given to model:",C),X}}function ye(m){for(let g in m)(0,K.isONNXTensor)(m[g])?m[g]=new P.Tensor(m[g]):typeof m[g]=="object"&&ye(m[g]);return m}function $e(m){if(m instanceof P.Tensor)return m;if(m.length===0)throw Error("items must be non-empty");if(Array.isArray(m[0])){if(m.some(g=>g.length!==m[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new P.Tensor("int64",BigInt64Array.from(m.flat().map(g=>BigInt(g))),[m.length,m[0].length])}else return new P.Tensor("int64",BigInt64Array.from(m.map(g=>BigInt(g))),[1,m.length])}function Se(m){return new P.Tensor("bool",[m],[1])}async function Fe(m,g){let{encoder_outputs:C,input_ids:X,decoder_input_ids:Pe,...De}=g;if(!C){const $t=(0,xe.pick)(g,m.sessions.model.inputNames);C=(await et(m,$t)).last_hidden_state}return De.input_ids=Pe,De.encoder_hidden_states=C,m.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(De.encoder_attention_mask=g.attention_mask),await Xe(m,De,!0)}async function et(m,g){const C=m.sessions.model,X=(0,xe.pick)(g,C.inputNames);if(C.inputNames.includes("inputs_embeds")&&!X.inputs_embeds){if(!g.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");X.inputs_embeds=await m.encode_text({input_ids:g.input_ids})}return C.inputNames.includes("token_type_ids")&&!X.token_type_ids&&(X.token_type_ids=new P.Tensor("int64",new BigInt64Array(X.input_ids.data.length),X.input_ids.dims)),await _e(C,X)}async function Xe(m,g,C=!1){const X=m.sessions[C?"decoder_model_merged":"model"],{past_key_values:Pe,...De}=g;X.inputNames.includes("use_cache_branch")&&(De.use_cache_branch=Se(!!Pe)),X.inputNames.includes("position_ids")&&De.attention_mask&&!De.position_ids&&(De.position_ids=we(De,Pe)),m.addPastKeyValues(De,Pe);const it=(0,xe.pick)(De,X.inputNames);return await _e(X,it)}async function ct(m,{input_ids:g=null,attention_mask:C=null,pixel_values:X=null,position_ids:Pe=null,inputs_embeds:De=null,past_key_values:it=null,generation_config:$t=null,logits_processor:jt=null,...lr}){if(!De){if(De=await m.encode_text({input_ids:g}),X&&g.dims[1]!==1){const kr=await m.encode_image({pixel_values:X});({inputs_embeds:De,attention_mask:C}=m._merge_input_ids_with_image_features({image_features:kr,inputs_embeds:De,input_ids:g,attention_mask:C}))}else if(it&&X&&g.dims[1]===1){const kr=g.dims[1],ur=Object.values(it)[0].dims.at(-2);C=(0,P.cat)([(0,P.ones)([g.dims[0],ur]),C.slice(null,[C.dims[1]-kr,C.dims[1]])],1)}}return await Xe(m,{inputs_embeds:De,past_key_values:it,attention_mask:C,position_ids:Pe,generation_config:$t,logits_processor:jt},!0)}function we(m,g=null){const{input_ids:C,inputs_embeds:X,attention_mask:Pe}=m,[De,it]=Pe.dims,$t=new BigInt64Array(Pe.data.length);for(let lr=0;lrDe.dims[1])){if(Pe$t==m.config.image_token_index)){const $t=m.config.num_image_tokens;if(!$t)throw new Error("`num_image_tokens` is missing in the model configuration.");const jt=De.dims[1]-(Pe-$t);C.input_ids=De.slice(null,[-jt,null]),C.attention_mask=(0,P.ones)([1,Pe+jt])}}}return C}function pe(m,g,C,X){return C.past_key_values&&(g=g.map(Pe=>[Pe.at(-1)])),{...C,decoder_input_ids:$e(g)}}function ke(m,...g){return m.config.is_encoder_decoder?pe(m,...g):U(m,...g)}class ee extends Me.Callable{constructor(C,X){super();Te(this,"main_input_name","input_ids");Te(this,"forward_params",["input_ids","attention_mask"]);this.config=C,this.sessions=X;const Pe=N.get(this.constructor),De=ue.get(Pe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,De){case se.DecoderOnly:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=U;break;case se.Seq2Seq:case se.Vision2Seq:case se.Musicgen:this.can_generate=!0,this._forward=Fe,this._prepare_inputs_for_generation=pe;break;case se.EncoderDecoder:this._forward=Fe;break;case se.ImageTextToText:this.can_generate=!0,this._forward=ct,this._prepare_inputs_for_generation=ke;break;default:this._forward=et;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var X;const C=[];for(const Pe of Object.values(this.sessions))(X=Pe==null?void 0:Pe.handler)!=null&&X.dispose&&C.push(Pe.handler.dispose());return await Promise.all(C)}static async from_pretrained(C,{progress_callback:X=null,config:Pe=null,cache_dir:De=null,local_files_only:it=!1,revision:$t="main",model_file_name:jt=null,subfolder:lr="onnx",device:sr=null,dtype:kr=null,use_external_data_format:ur=null,session_options:fr={}}={}){let dr={progress_callback:X,config:Pe,cache_dir:De,local_files_only:it,revision:$t,model_file_name:jt,subfolder:lr,device:sr,dtype:kr,use_external_data_format:ur,session_options:fr};const hr=N.get(this),wr=ue.get(hr);Pe=dr.config=await M.AutoConfig.from_pretrained(C,dr);let Ar;if(wr===se.DecoderOnly)Ar=await Promise.all([B(C,{model:dr.model_file_name??"model"},dr),(0,D.getModelJSON)(C,"generation_config.json",!1,dr)]);else if(wr===se.Seq2Seq||wr===se.Vision2Seq)Ar=await Promise.all([B(C,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},dr),(0,D.getModelJSON)(C,"generation_config.json",!1,dr)]);else if(wr===se.MaskGeneration)Ar=await Promise.all([B(C,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},dr)]);else if(wr===se.EncoderDecoder)Ar=await Promise.all([B(C,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},dr)]);else if(wr===se.ImageTextToText){const an={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Pe.is_encoder_decoder&&(an.model="encoder_model"),Ar=await Promise.all([B(C,an,dr),(0,D.getModelJSON)(C,"generation_config.json",!1,dr)])}else wr===se.Musicgen?Ar=await Promise.all([B(C,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},dr),(0,D.getModelJSON)(C,"generation_config.json",!1,dr)]):(wr!==se.EncoderOnly&&console.warn(`Model type for '${hr??(Pe==null?void 0:Pe.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),Ar=await Promise.all([B(C,{model:dr.model_file_name??"model"},dr)]));return new this(Pe,...Ar)}async _call(C){return await this.forward(C)}async forward(C){return await this._forward(this,C)}_get_logits_warper(C){const X=new x.LogitsProcessorList;return C.temperature!==null&&C.temperature!==1&&X.push(new x.TemperatureLogitsWarper(C.temperature)),C.top_k!==null&&C.top_k!==0&&X.push(new x.TopKLogitsWarper(C.top_k)),C.top_p!==null&&C.top_p<1&&X.push(new x.TopPLogitsWarper(C.top_p)),X}_get_logits_processor(C,X,Pe=null){const De=new x.LogitsProcessorList;if(C.repetition_penalty!==null&&C.repetition_penalty!==1&&De.push(new x.RepetitionPenaltyLogitsProcessor(C.repetition_penalty)),C.no_repeat_ngram_size!==null&&C.no_repeat_ngram_size>0&&De.push(new x.NoRepeatNGramLogitsProcessor(C.no_repeat_ngram_size)),C.bad_words_ids!==null&&De.push(new x.NoBadWordsLogitsProcessor(C.bad_words_ids,C.eos_token_id)),C.min_length!==null&&C.eos_token_id!==null&&C.min_length>0&&De.push(new x.MinLengthLogitsProcessor(C.min_length,C.eos_token_id)),C.min_new_tokens!==null&&C.eos_token_id!==null&&C.min_new_tokens>0&&De.push(new x.MinNewTokensLengthLogitsProcessor(X,C.min_new_tokens,C.eos_token_id)),C.forced_bos_token_id!==null&&De.push(new x.ForcedBOSTokenLogitsProcessor(C.forced_bos_token_id)),C.forced_eos_token_id!==null&&De.push(new x.ForcedEOSTokenLogitsProcessor(C.max_length,C.forced_eos_token_id)),C.begin_suppress_tokens!==null){const it=X>1||C.forced_bos_token_id===null?X:X+1;De.push(new x.SuppressTokensAtBeginLogitsProcessor(C.begin_suppress_tokens,it))}return C.guidance_scale!==null&&C.guidance_scale>1&&De.push(new x.ClassifierFreeGuidanceLogitsProcessor(C.guidance_scale)),Pe!==null&&De.extend(Pe),De}_prepare_generation_config(C,X,Pe=V.GenerationConfig){const De={...this.config};for(const $t of["decoder","generator","text_config"])$t in De&&Object.assign(De,De[$t]);const it=new Pe(De);return"generation_config"in this&&Object.assign(it,this.generation_config),C&&Object.assign(it,C),X&&Object.assign(it,(0,xe.pick)(X,Object.getOwnPropertyNames(it))),it}_get_stopping_criteria(C,X=null){const Pe=new te.StoppingCriteriaList;return C.max_length!==null&&Pe.push(new te.MaxLengthCriteria(C.max_length,this.config.max_position_embeddings??null)),C.eos_token_id!==null&&Pe.push(new te.EosTokenCriteria(C.eos_token_id)),X&&Pe.extend(X),Pe}_validate_model_class(){if(!this.can_generate){const C=[ni,_a,ma,ri],X=N.get(this.constructor),Pe=new Set,De=this.config.model_type;for(const $t of C){const jt=$t.get(De);jt&&Pe.add(jt[0])}let it=`The current model class (${X}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Pe.size>0&&(it+=` Please use the following class instead: ${[...Pe].join(", ")}`),Error(it)}}prepare_inputs_for_generation(...C){return this._prepare_inputs_for_generation(this,...C)}_update_model_kwargs_for_generation({generated_input_ids:C,outputs:X,model_inputs:Pe,is_encoder_decoder:De}){return Pe.past_key_values=this.getPastKeyValues(X,Pe.past_key_values),Pe.input_ids=new P.Tensor("int64",C.flat(),[C.length,1]),De||(Pe.attention_mask=(0,P.cat)([Pe.attention_mask,(0,P.ones)([Pe.attention_mask.dims[0],1])],1)),Pe.position_ids=null,Pe}_prepare_model_inputs({inputs:C,bos_token_id:X,model_kwargs:Pe}){const De=(0,xe.pick)(Pe,this.forward_params),it=this.main_input_name;if(it in De){if(C)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else De[it]=C;return{inputs_tensor:De[it],model_inputs:De,model_input_name:it}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:C,model_inputs:X,model_input_name:Pe,generation_config:De}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!X.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:$t,pixel_values:jt,attention_mask:lr,...sr}=X,kr=await this._prepare_inputs_embeds(X);X={...sr,...(0,xe.pick)(kr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:it}=await et(this,X);if(De.guidance_scale!==null&&De.guidance_scale>1)it=(0,P.cat)([it,(0,P.full_like)(it,0)],0),"attention_mask"in X&&(X.attention_mask=(0,P.cat)([X.attention_mask,(0,P.zeros_like)(X.attention_mask)],0));else if(X.decoder_input_ids){const $t=$e(X.decoder_input_ids).dims[0];if($t!==it.dims[0]){if(it.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${it.dims[0]}) than the decoder inputs (${$t}).`);it=(0,P.cat)(Array.from({length:$t},()=>it),0)}}return X.encoder_outputs=it,X}_prepare_decoder_input_ids_for_generation({batch_size:C,model_input_name:X,model_kwargs:Pe,decoder_start_token_id:De,bos_token_id:it,generation_config:$t}){let{decoder_input_ids:jt,...lr}=Pe;if(jt)Array.isArray(jt[0])||(jt=Array.from({length:C},()=>jt));else if(De??(De=it),this.config.model_type==="musicgen")jt=Array.from({length:C*this.config.decoder.num_codebooks},()=>[De]);else if(Array.isArray(De)){if(De.length!==C)throw new Error(`\`decoder_start_token_id\` expcted to have length ${C} but got ${De.length}`);jt=De}else jt=Array.from({length:C},()=>[De]);return jt=$e(jt),Pe.decoder_attention_mask=(0,P.ones_like)(jt),{input_ids:jt,model_inputs:lr}}async generate({inputs:C=null,generation_config:X=null,logits_processor:Pe=null,stopping_criteria:De=null,streamer:it=null,...$t}){this._validate_model_class(),X=this._prepare_generation_config(X,$t);let{inputs_tensor:jt,model_inputs:lr,model_input_name:sr}=this._prepare_model_inputs({inputs:C,model_kwargs:$t});const kr=this.config.is_encoder_decoder;kr&&("encoder_outputs"in lr||(lr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:jt,model_inputs:lr,model_input_name:sr,generation_config:X})));let ur;kr?{input_ids:ur,model_inputs:lr}=this._prepare_decoder_input_ids_for_generation({batch_size:lr[sr].dims.at(0),model_input_name:sr,model_kwargs:lr,decoder_start_token_id:X.decoder_start_token_id,bos_token_id:X.bos_token_id,generation_config:X}):ur=lr[sr];let fr=ur.dims.at(-1);X.max_new_tokens!==null&&(X.max_length=fr+X.max_new_tokens);const dr=this._get_logits_processor(X,fr,Pe),hr=this._get_stopping_criteria(X,De),wr=lr[sr].dims.at(0),Ar=ne.LogitsSampler.getSampler(X),an=new Array(wr).fill(0),ln=ur.tolist();it&&it.put(ln);let Bn=null,en={};for(;;){lr=this.prepare_inputs_for_generation(ln,lr,X);const tn=await this.forward(lr);if(X.output_attentions&&X.return_dict_in_generate){const Sn=this.getAttentions(tn);for(const Ps in Sn)Ps in en||(en[Ps]=[]),en[Ps].push(Sn[Ps])}const si=tn.logits.slice(null,-1,null),ii=dr(ln,si),Ma=[];for(let Sn=0;SnSn)){X.return_dict_in_generate&&(Bn=this.getPastKeyValues(tn,lr.past_key_values,!1));break}lr=this._update_model_kwargs_for_generation({generated_input_ids:Ma,outputs:tn,model_inputs:lr,is_encoder_decoder:kr})}it&&it.end();const Gr=new P.Tensor("int64",ln.flat(),[ln.length,ln[0].length]);return X.return_dict_in_generate?{sequences:Gr,past_key_values:Bn,...en}:Gr}getPastKeyValues(C,X,Pe=!0){const De=Object.create(null);for(const it in C)if(it.startsWith("present")){const $t=it.replace("present","past_key_values");if(X&&it.includes("encoder"))De[$t]=X[$t];else{if(Pe&&X){const jt=X[$t];jt.location==="gpu-buffer"&&jt.dispose()}De[$t]=C[it]}}return De}getAttentions(C){const X={};for(const Pe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const De in C)De.startsWith(Pe)&&(Pe in X||(X[Pe]=[]),X[Pe].push(C[De]));return X}addPastKeyValues(C,X){if(X)Object.assign(C,X);else{const Pe=this.custom_config.kv_cache_dtype??"float32",De=Pe==="float16"?new Uint16Array:[],it=(0,M.getKeyValueShapes)(this.config);for(const $t in it)C[$t]=new P.Tensor(Pe,De,it[$t])}}async encode_image({pixel_values:C}){const X=(await _e(this.sessions.vision_encoder,{pixel_values:C})).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 (${X.dims[1]}).`),this.config.num_image_tokens=X.dims[1]),X}async encode_text({input_ids:C}){return(await _e(this.sessions.embed_tokens,{input_ids:C})).inputs_embeds}}class Ge{}class dt extends Ge{constructor({last_hidden_state:g,hidden_states:C=null,attentions:X=null}){super(),this.last_hidden_state=g,this.hidden_states=C,this.attentions=X}}class tt extends ee{}class ot extends tt{}class Le extends tt{async _call(g){return new Zr(await super._call(g))}}class st extends tt{async _call(g){return new or(await super._call(g))}}class xt extends tt{async _call(g){return new Hr(await super._call(g))}}class ze extends tt{async _call(g){return new Jr(await super._call(g))}}class re extends ee{}class Ce extends re{}class Ve extends ee{}class Ue extends Ve{}class je extends Ve{async _call(g){return new Zr(await super._call(g))}}class qe extends Ve{async _call(g){return new or(await super._call(g))}}class lt extends Ve{async _call(g){return new Hr(await super._call(g))}}class ft extends Ve{async _call(g){return new Jr(await super._call(g))}}class gt extends ee{}class Mt extends gt{}class v extends gt{async _call(g){return new Zr(await super._call(g))}}class W extends gt{async _call(g){return new or(await super._call(g))}}class S extends gt{async _call(g){return new Hr(await super._call(g))}}class Q extends gt{async _call(g){return new Jr(await super._call(g))}}class he extends ee{}class Ye extends he{}class Je extends he{async _call(g){return new Zr(await super._call(g))}}class Pt extends he{async _call(g){return new or(await super._call(g))}}class mt extends he{async _call(g){return new Hr(await super._call(g))}}class Ee extends he{async _call(g){return new Jr(await super._call(g))}}class k extends ee{}class H extends k{}class be extends k{async _call(g){return new Zr(await super._call(g))}}class Be extends k{async _call(g){return new or(await super._call(g))}}class Ie extends k{async _call(g){return new Hr(await super._call(g))}}class Re extends k{async _call(g){return new Jr(await super._call(g))}}class ut extends ee{}class nt extends ut{}class vt extends ut{async _call(g){return new Zr(await super._call(g))}}class pt extends ut{async _call(g){return new or(await super._call(g))}}class Tt extends ut{async _call(g){return new Hr(await super._call(g))}}class Lt extends ut{async _call(g){return new Jr(await super._call(g))}}class He extends ee{}class Nt extends He{}class Rt extends He{async _call(g){return new Zr(await super._call(g))}}class qt extends He{async _call(g){return new or(await super._call(g))}}class Ht extends He{async _call(g){return new Hr(await super._call(g))}}class Yt extends He{async _call(g){return new Jr(await super._call(g))}}class Wt extends ee{}class xr extends Wt{}class Vr extends Wt{async _call(g){return new or(await super._call(g))}}class Tr extends Wt{async _call(g){return new Hr(await super._call(g))}}class Ze extends Wt{async _call(g){return new Jr(await super._call(g))}}class Ct extends Wt{async _call(g){return new Zr(await super._call(g))}}class Dt extends ee{}class Ur extends Dt{}class Vn extends Dt{async _call(g){return new Zr(await super._call(g))}}class An extends Dt{async _call(g){return new or(await super._call(g))}}class Or extends Dt{async _call(g){return new Hr(await super._call(g))}}class Xr extends ee{}class Dr extends Xr{}class kn extends Xr{async _call(g){return new Zr(await super._call(g))}}class Er extends Xr{async _call(g){return new or(await super._call(g))}}class jn extends Xr{async _call(g){return new Jr(await super._call(g))}}class In extends ee{}class Rs extends In{}class fs extends In{async _call(g){return new Zr(await super._call(g))}}class ms extends In{async _call(g){return new or(await super._call(g))}}class _s extends In{async _call(g){return new Hr(await super._call(g))}}class gs extends In{async _call(g){return new Jr(await super._call(g))}}class Un extends ee{}class Ns extends Un{}class rs extends Un{async _call(g){return new Zr(await super._call(g))}}class Cn extends Un{async _call(g){return new or(await super._call(g))}}class Fn extends Un{async _call(g){return new Jr(await super._call(g))}}class On extends ee{}class Kn extends On{}class ns extends On{async _call(g){return new or(await super._call(g))}}class ss extends On{async _call(g){return new Jr(await super._call(g))}}class Kt extends On{async _call(g){return new Zr(await super._call(g))}}class Xn extends ee{constructor(C,X,Pe){super(C,X);Te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Pe}}class ws extends Xn{}class ys extends Xn{}class is extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class bs extends is{}class vs extends is{}class as extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Ms extends as{}class Fr extends as{}class pn extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class ve extends pn{}class _ extends pn{}class O extends pn{async _call(g){return new or(await super._call(g))}}class Y extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class de extends Y{}class ce extends Y{}class Oe extends Y{async _call(g){return new or(await super._call(g))}}class _t extends Y{}class yt extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class wt extends yt{}class St extends yt{}class Qt extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class $r extends Qt{}class er extends Qt{}class Ut extends ee{}class pr extends Ut{}class nn extends Ut{async _call(g){return new Zr(await super._call(g))}}class Kr extends Ut{async _call(g){return new or(await super._call(g))}}class Ne extends Ut{async _call(g){return new Hr(await super._call(g))}}class gn extends Ut{async _call(g){return new Jr(await super._call(g))}}class yr extends ee{}class Wr extends yr{}class on extends yr{async _call(g){return new Zr(await super._call(g))}}class Xt extends yr{async _call(g){return new or(await super._call(g))}}class hn extends yr{async _call(g){return new Hr(await super._call(g))}}class Qr extends yr{async _call(g){return new Jr(await super._call(g))}}class br extends ee{}class vr extends br{}class kt extends br{async _call(g){return new Zr(await super._call(g))}}class _r extends br{async _call(g){return new or(await super._call(g))}}class Sr extends br{async _call(g){return new Hr(await super._call(g))}}class Br extends br{async _call(g){return new Jr(await super._call(g))}}class fn extends ee{}class Ot extends fn{}class Vs extends fn{}class rt extends ee{constructor(C,X,Pe){super(C,X);Te(this,"requires_attention_mask",!1);Te(this,"main_input_name","input_features");Te(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Pe}}class Vt extends rt{}class di extends rt{_prepare_generation_config(g,C){return super._prepare_generation_config(g,C,R.WhisperGenerationConfig)}_retrieve_init_tokens(g){const C=[g.decoder_start_token_id];let X=g.language;const Pe=g.task;if(g.is_multilingual){X||(console.warn("No language specified - defaulting to English (en)."),X="en");const it=`<|${(0,Z.whisper_language_to_code)(X)}|>`;C.push(g.lang_to_id[it]),C.push(g.task_to_id[Pe??"transcribe"])}else if(X||Pe)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!g.return_timestamps&&g.no_timestamps_token_id&&C.at(-1)!==g.no_timestamps_token_id?C.push(g.no_timestamps_token_id):g.return_timestamps&&C.at(-1)===g.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),C.pop()),C.filter(De=>De!=null)}async generate({inputs:g=null,generation_config:C=null,logits_processor:X=null,stopping_criteria:Pe=null,...De}){C=this._prepare_generation_config(C,De);const it=De.decoder_input_ids??this._retrieve_init_tokens(C);if(C.return_timestamps&&(X??(X=new x.LogitsProcessorList),X.push(new x.WhisperTimeStampLogitsProcessor(C,it))),C.begin_suppress_tokens&&(X??(X=new x.LogitsProcessorList),X.push(new x.SuppressTokensAtBeginLogitsProcessor(C.begin_suppress_tokens,it.length))),C.return_token_timestamps){if(!C.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.");C.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),C.output_attentions=!0,C.return_dict_in_generate=!0}const $t=await super.generate({inputs:g,generation_config:C,logits_processor:X,decoder_input_ids:it,...De});return C.return_token_timestamps&&($t.token_timestamps=this._extract_token_timestamps($t,C.alignment_heads,C.num_frames)),$t}_extract_token_timestamps(g,C,X=null,Pe=.02){if(!g.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`.");X==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 De=this.config.median_filter_width;De===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),De=7);const it=g.cross_attentions,$t=Array.from({length:this.config.decoder_layers},(hr,wr)=>(0,P.cat)(it.map(Ar=>Ar[wr]),2)),jt=(0,P.stack)(C.map(([hr,wr])=>{if(hr>=$t.length)throw new Error(`Layer index ${hr} is out of bounds for cross attentions (length ${$t.length}).`);return X?$t[hr].slice(null,wr,null,[0,X]):$t[hr].slice(null,wr)})).transpose(1,0,2,3),[lr,sr]=(0,P.std_mean)(jt,-2,0,!0),kr=jt.clone();for(let hr=0;hrAr[tn+1]-Ar[tn]),Bn=(0,xe.mergeArrays)([1],ln).map(Gr=>!!Gr),en=[];for(let Gr=0;Grur.findIndex(fr=>fr==De)),jt=$t.every(ur=>ur===-1),lr=$t.every(ur=>ur!==-1);if(!jt&&!lr)throw new Error("Every input should contain either 0 or 1 image token.");if(jt)return{inputs_embeds:g,attention_mask:Pe};const sr=[],kr=[];for(let ur=0;ur<$t.length;++ur){const fr=$t[ur],dr=g[ur],hr=C[ur],wr=Pe[ur];sr.push((0,P.cat)([dr.slice([0,fr]),hr,dr.slice([fr+1,dr.dims[0]])],0)),kr.push((0,P.cat)([wr.slice([0,fr]),(0,P.ones)([hr.dims[0]]),wr.slice([fr+1,wr.dims[0]])],0))}return{inputs_embeds:(0,P.stack)(sr,0),attention_mask:(0,P.stack)(kr,0)}}}class nr extends os{}class Sa extends ee{constructor(C,X,Pe){super(C,X);Te(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);Te(this,"main_input_name","inputs_embeds");this.generation_config=Pe}}class pi extends Sa{_merge_input_ids_with_image_features({inputs_embeds:g,image_features:C,input_ids:X,attention_mask:Pe}){return{inputs_embeds:(0,P.cat)([C,g],1),attention_mask:(0,P.cat)([(0,P.ones)(C.dims.slice(0,2)),Pe],1)}}async _prepare_inputs_embeds({input_ids:g,pixel_values:C,inputs_embeds:X,attention_mask:Pe}){if(!g&&!C)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let De,it;return g&&(De=await this.encode_text({input_ids:g})),C&&(it=await this.encode_image({pixel_values:C})),De&&it?{inputs_embeds:X,attention_mask:Pe}=this._merge_input_ids_with_image_features({inputs_embeds:De,image_features:it,input_ids:g,attention_mask:Pe}):X=De||it,{inputs_embeds:X,attention_mask:Pe}}async forward({input_ids:g,pixel_values:C,attention_mask:X,decoder_input_ids:Pe,decoder_attention_mask:De,encoder_outputs:it,past_key_values:$t,inputs_embeds:jt,decoder_inputs_embeds:lr}){if(jt||({inputs_embeds:jt,attention_mask:X}=await this._prepare_inputs_embeds({input_ids:g,pixel_values:C,inputs_embeds:jt,attention_mask:X})),!it){let{last_hidden_state:ur}=await et(this,{inputs_embeds:jt,attention_mask:X});it=ur}if(!lr){if(!Pe)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");lr=await this.encode_text({input_ids:Pe})}return await Xe(this,{inputs_embeds:lr,attention_mask:De,encoder_attention_mask:X,encoder_hidden_states:it,past_key_values:$t},!0)}}class xs extends ee{}class Pa extends xs{}class En extends xs{static async from_pretrained(g,C={}){return C.model_file_name??(C.model_file_name="text_model"),super.from_pretrained(g,C)}}class Aa extends xs{static async from_pretrained(g,C={}){return C.model_file_name??(C.model_file_name="vision_model"),super.from_pretrained(g,C)}}class hi extends ee{}class ls extends hi{}class Ia extends hi{static async from_pretrained(g,C={}){return C.model_file_name??(C.model_file_name="text_model"),super.from_pretrained(g,C)}}class Fa extends xs{static async from_pretrained(g,C={}){return C.model_file_name??(C.model_file_name="vision_model"),super.from_pretrained(g,C)}}class Oa extends ee{}class za extends Oa{}class fi extends ee{}class Da extends fi{}class Ba extends fi{}class mi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class La extends mi{}class Ra extends mi{}class wn extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Na extends wn{}class Va extends wn{}class _i extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class ja extends _i{}class Ua extends _i{}class gi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Wa extends gi{}class Ga extends gi{}class wi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class qa extends wi{}class Iu extends wi{}class yn extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Ha extends yn{}class js extends yn{}class Us extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Tn extends Us{}class Ka extends Us{}class yi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Xa extends yi{}class Qa extends yi{}class bi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Ya extends bi{}class Za extends bi{}class vi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Ja extends vi{}class eo extends vi{}class bn extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class to extends bn{}class ro extends bn{}class Mi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class no extends Mi{}class so extends Mi{}class xi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class io extends xi{}class ao extends xi{}class Ti extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class oo extends Ti{}class $i extends Ti{}class Ws extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class lo extends Ws{}class uo extends Ws{}class Gs extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Fu extends Gs{}class co extends Gs{}class ki extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class po extends ki{}class ho extends ki{}class us extends ee{}class fo extends us{}class mo extends us{async _call(g){return new or(await super._call(g))}}class qs extends ee{}class _o extends qs{}class go extends qs{async _call(g){return new or(await super._call(g))}}class wo extends ee{}class yo extends wo{async _call(g){return new xu(await super._call(g))}}class bo extends ee{}class vo extends bo{}class Mo extends bo{async _call(g){return new or(await super._call(g))}}class Ci extends ee{}class Ou extends Ci{}class xo extends Ci{async _call(g){return new or(await super._call(g))}}class gr extends ee{}class To extends gr{}class $o extends gr{}class Ei extends ee{}class ko extends Ei{}class Co extends Ei{}class Si extends ee{}class Eo extends Si{}class So extends Si{async _call(g){return new or(await super._call(g))}}class Hs extends ee{}class Po extends Hs{}class Ao extends Hs{async _call(g){return new Pi(await super._call(g))}}class Io extends Hs{async _call(g){return new Fo(await super._call(g))}}class Pi extends Ge{constructor({logits:g,pred_boxes:C}){super(),this.logits=g,this.pred_boxes=C}}class Fo extends Ge{constructor({logits:g,pred_boxes:C,pred_masks:X}){super(),this.logits=g,this.pred_boxes=C,this.pred_masks=X}}class ds extends ee{}class Oo extends ds{}class Ks extends ds{async _call(g){return new zo(await super._call(g))}}class zo extends Ge{constructor({logits:g,pred_boxes:C}){super(),this.logits=g,this.pred_boxes=C}}class Ai extends ee{}class Do extends Ai{}class Bo extends Ai{async _call(g){return new Lo(await super._call(g))}}class Lo extends Pi{}class Ii extends ee{}class Ro extends Ii{}class No extends Ii{async _call(g){return new or(await super._call(g))}}class Fi extends ee{}class Vo extends Fi{}class jo extends Fi{async _call(g){return new or(await super._call(g))}}class Oi extends ee{}class Uo extends Oi{}class Wo extends Oi{async _call(g){return new or(await super._call(g))}}class zi extends ee{}class Go extends zi{}class Di extends zi{}class Bi extends ee{}class Li extends Bi{}class Ri extends Bi{}class qo extends ee{}class Ho extends qo{}class Ni extends ee{}class Ko extends Ni{}class Xo extends Ni{}class Qo extends ee{}class Vi extends Qo{}class ji extends ee{}class Yo extends ji{}class Zo extends ji{async _call(g){return new or(await super._call(g))}}class Jo extends ee{}class el extends Jo{}class tl extends Jo{async _call(g){return new or(await super._call(g))}}class vn extends ee{}class rl extends vn{}class nl extends vn{async _call(g){return new or(await super._call(g))}}class Ui extends ee{}class sl extends Ui{}class il extends Ui{async _call(g){return new al(await super._call(g))}}class al extends Ge{constructor({logits:g,pred_boxes:C}){super(),this.logits=g,this.pred_boxes=C}}class ol extends ee{}class ll extends ol{async get_image_embeddings({pixel_values:g}){return await et(this,{pixel_values:g})}async forward(g){if((!g.image_embeddings||!g.image_positional_embeddings)&&(g={...g,...await this.get_image_embeddings(g)}),!g.input_labels&&g.input_points){const X=g.input_points.dims.slice(0,-1),Pe=X.reduce((De,it)=>De*it,1);g.input_labels=new P.Tensor("int64",new BigInt64Array(Pe).fill(1n),X)}const C={image_embeddings:g.image_embeddings,image_positional_embeddings:g.image_positional_embeddings};return g.input_points&&(C.input_points=g.input_points),g.input_labels&&(C.input_labels=g.input_labels),g.input_boxes&&(C.input_boxes=g.input_boxes),await _e(this.sessions.prompt_encoder_mask_decoder,C)}async _call(g){return new ul(await super._call(g))}}class ul extends Ge{constructor({iou_scores:g,pred_masks:C}){super(),this.iou_scores=g,this.pred_masks=C}}class Wi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class zu extends Wi{}class dl extends Wi{}class Gi extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class cl extends Gi{}class pl extends Gi{}class Wn extends ee{}class hl extends Wn{}class Du extends Wn{async _call(g){return new Qn(await super._call(g))}}class Gn extends Wn{async _call(g){return new or(await super._call(g))}}class qn extends Wn{async _call(g){return new Hr(await super._call(g))}}class zn extends ee{}class qi extends zn{}class Hn extends zn{async _call(g){return new Hr(await super._call(g))}}class Yr extends ee{}class Hi extends Yr{}class cs extends ee{}class Ki extends cs{}class fl extends cs{async _call(g){return new Qn(await super._call(g))}}class ml extends cs{async _call(g){return new or(await super._call(g))}}class Ts extends ee{}class Xs extends Ts{}class Xi extends Ts{async _call(g){return new Qn(await super._call(g))}}class _l extends Ts{async _call(g){return new or(await super._call(g))}}class Qs extends Ts{async _call(g){return new Hr(await super._call(g))}}class Ys extends ee{}class Qi extends Ys{}class Zs extends Ys{async _call(g){return new Qn(await super._call(g))}}class gl extends Ys{async _call(g){return new or(await super._call(g))}}class Bu extends ee{}class Lu extends Wn{}class wl extends Wn{async _call(g){return new Qn(await super._call(g))}}class Yi extends Wn{async _call(g){return new or(await super._call(g))}}class Dn extends ee{}class yl extends Dn{}class Zi extends Dn{async _call(g){return new Qn(await super._call(g))}}class bl extends Dn{async _call(g){return new or(await super._call(g))}}class vl extends Dn{async _call(g){return new Mu(await super._call(g))}}class Ml extends Dn{async _call(g){return new Hr(await super._call(g))}}class Ji extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class xl extends Ji{}class Tl extends Ji{}class Ru extends Ji{async generate_speech(g,C,{threshold:X=.5,minlenratio:Pe=0,maxlenratio:De=20,vocoder:it=null}={}){const $t={input_ids:g},{encoder_outputs:jt,encoder_attention_mask:lr}=await et(this,$t),sr=jt.dims[1]/this.config.reduction_factor,kr=Math.floor(sr*De),ur=Math.floor(sr*Pe),fr=this.config.num_mel_bins;let dr=[],hr=null,wr=null,Ar=0;for(;;){++Ar;const Bn=Se(!!wr);let en;wr?en=wr.output_sequence_out:en=new P.Tensor("float32",new Float32Array(fr),[1,1,fr]);let Gr={use_cache_branch:Bn,output_sequence:en,encoder_attention_mask:lr,speaker_embeddings:C,encoder_hidden_states:jt};this.addPastKeyValues(Gr,hr),wr=await _e(this.sessions.decoder_model_merged,Gr),hr=this.getPastKeyValues(wr,hr);const{prob:tn,spectrum:si}=wr;if(dr.push(si),Ar>=ur&&(Array.from(tn.data).filter(ii=>ii>=X).length>0||Ar>=kr))break}const an=(0,P.cat)(dr),{waveform:ln}=await _e(it.sessions.model,{spectrogram:an});return{spectrogram:an,waveform:ln}}}class ea extends ee{constructor(){super(...arguments);Te(this,"main_input_name","spectrogram")}}class $l extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class kl extends $l{}class ta extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Js extends ta{}class ei extends ta{}class ra extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class ti extends ra{}class na extends ra{}class sa extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class Cl extends sa{}class El extends sa{}class $s extends ee{}class Sl extends $s{}class Pl extends $s{static async from_pretrained(g,C={}){return C.model_file_name??(C.model_file_name="text_model"),super.from_pretrained(g,C)}}class Al extends $s{static async from_pretrained(g,C={}){return C.model_file_name??(C.model_file_name="audio_model"),super.from_pretrained(g,C)}}class Nu extends ee{}class ia extends Nu{async _call(g){return new td(await super._call(g))}}class ks extends ee{}class $d extends ks{}class Il extends ks{}class Fl extends ks{}class aa extends ee{constructor(g,C,X){super(g,C),this.generation_config=X}}class oa extends aa{}class Ol extends aa{}class la extends ee{}class zl extends la{}class Dl extends la{async _call(g){return new or(await super._call(g))}}class ua extends ee{}class Vu extends ua{}class kd extends ua{}class da extends ee{constructor(C,X,Pe){super(C,X);Te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Pe}_apply_and_filter_by_delay_pattern_mask(C){const[X,Pe]=C.dims,De=this.config.decoder.num_codebooks,it=Pe-De;let $t=0;for(let sr=0;sr0&&fr<=it&&(C.data[$t++]=C.data[sr])}const jt=Math.floor(X/De),lr=$t/(jt*De);return new P.Tensor(C.type,C.data.slice(0,$t),[jt,De,lr])}prepare_inputs_for_generation(C,X,Pe){let De=structuredClone(C);for(let $t=0;$t=jt&&(De[$t][jt]=BigInt(this.config.decoder.pad_token_id));return Pe.guidance_scale!==null&&Pe.guidance_scale>1&&(De=De.concat(De)),super.prepare_inputs_for_generation(De,X,Pe)}async generate(C){const X=await super.generate(C),Pe=this._apply_and_filter_by_delay_pattern_mask(X).unsqueeze_(0),{audio_values:De}=await _e(this.sessions.encodec_decode,{audio_codes:Pe});return De}}class ca extends ee{}class Bl extends ca{}class ju extends ca{async _call(g){return new or(await super._call(g))}}class pa extends ee{}class Ll extends pa{}class Rl extends pa{async _call(g){return new or(await super._call(g))}}class ha extends ee{}class Nl extends ha{}class Uu extends ha{async _call(g){return new or(await super._call(g))}}class Cs extends ee{}class Es extends Cs{}class fa extends Cs{async _call(g){return new or(await super._call(g))}}class Pr{static async from_pretrained(g,{progress_callback:C=null,config:X=null,cache_dir:Pe=null,local_files_only:De=!1,revision:it="main",model_file_name:$t=null,subfolder:jt="onnx",device:lr=null,dtype:sr=null,use_external_data_format:kr=null,session_options:ur={}}={}){let fr={progress_callback:C,config:X,cache_dir:Pe,local_files_only:De,revision:it,model_file_name:$t,subfolder:jt,device:lr,dtype:sr,use_external_data_format:kr,session_options:ur};if(fr.config=await M.AutoConfig.from_pretrained(g,fr),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let dr of this.MODEL_CLASS_MAPPINGS){const hr=dr.get(fr.config.model_type);if(hr)return await hr[1].from_pretrained(g,fr)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${fr.config.model_type}", attempting to construct from base class.`),await ee.from_pretrained(g,fr);throw Error(`Unsupported model type: ${fr.config.model_type}`)}}Te(Pr,"MODEL_CLASS_MAPPINGS",null),Te(Pr,"BASE_IF_FAIL",!1);const Wu=new Map([["bert",["BertModel",ot]],["nomic_bert",["NomicBertModel",Ce]],["roformer",["RoFormerModel",Ue]],["electra",["ElectraModel",Ye]],["esm",["EsmModel",Ur]],["convbert",["ConvBertModel",Mt]],["camembert",["CamembertModel",H]],["deberta",["DebertaModel",nt]],["deberta-v2",["DebertaV2Model",Nt]],["mpnet",["MPNetModel",Rs]],["albert",["AlbertModel",Kn]],["distilbert",["DistilBertModel",xr]],["roberta",["RobertaModel",pr]],["xlm",["XLMModel",Wr]],["xlm-roberta",["XLMRobertaModel",vr]],["clap",["ClapModel",Sl]],["clip",["CLIPModel",Pa]],["clipseg",["CLIPSegModel",Da]],["chinese_clip",["ChineseCLIPModel",za]],["siglip",["SiglipModel",ls]],["mobilebert",["MobileBertModel",Dr]],["squeezebert",["SqueezeBertModel",Ns]],["wav2vec2",["Wav2Vec2Model",hl]],["wav2vec2-bert",["Wav2Vec2BertModel",Qi]],["unispeech",["UniSpeechModel",Ki]],["unispeech-sat",["UniSpeechSatModel",Xs]],["hubert",["HubertModel",Lu]],["wavlm",["WavLMModel",yl]],["audio-spectrogram-transformer",["ASTModel",Ot]],["vits",["VitsModel",ia]],["pyannote",["PyAnnoteModel",qi]],["wespeaker-resnet",["WeSpeakerResNetModel",Hi]],["detr",["DetrModel",Po]],["rt_detr",["RTDetrModel",Oo]],["table-transformer",["TableTransformerModel",Do]],["vit",["ViTModel",fo]],["fastvit",["FastViTModel",_o]],["mobilevit",["MobileViTModel",vo]],["mobilevitv2",["MobileViTV2Model",Ou]],["owlvit",["OwlViTModel",To]],["owlv2",["Owlv2Model",ko]],["beit",["BeitModel",Eo]],["deit",["DeiTModel",Ro]],["convnext",["ConvNextModel",Yo]],["convnextv2",["ConvNextV2Model",el]],["dinov2",["Dinov2Model",rl]],["resnet",["ResNetModel",Vo]],["swin",["SwinModel",Uo]],["swin2sr",["Swin2SRModel",Go]],["donut-swin",["DonutSwinModel",Vi]],["yolos",["YolosModel",sl]],["dpt",["DPTModel",Li]],["glpn",["GLPNModel",Ko]],["hifigan",["SpeechT5HifiGan",ea]],["efficientnet",["EfficientNetModel",zl]],["mobilenet_v1",["MobileNetV1Model",Bl]],["mobilenet_v2",["MobileNetV2Model",Ll]],["mobilenet_v3",["MobileNetV3Model",Nl]],["mobilenet_v4",["MobileNetV4Model",Es]]]),Gu=new Map([["t5",["T5Model",ws]],["longt5",["LongT5Model",bs]],["mt5",["MT5Model",Ms]],["bart",["BartModel",ve]],["mbart",["MBartModel",de]],["marian",["MarianModel",zu]],["whisper",["WhisperModel",Vt]],["m2m_100",["M2M100Model",cl]],["blenderbot",["BlenderbotModel",wt]],["blenderbot-small",["BlenderbotSmallModel",$r]]]),qu=new Map([["bloom",["BloomModel",lo]],["gpt2",["GPT2Model",La]],["gptj",["GPTJModel",Wa]],["gpt_bigcode",["GPTBigCodeModel",qa]],["gpt_neo",["GPTNeoModel",Na]],["gpt_neox",["GPTNeoXModel",ja]],["codegen",["CodeGenModel",Ha]],["llama",["LlamaModel",Tn]],["cohere",["CohereModel",Xa]],["gemma",["GemmaModel",Ya]],["gemma2",["Gemma2Model",Ja]],["openelm",["OpenELMModel",to]],["qwen2",["Qwen2Model",no]],["phi",["PhiModel",io]],["phi3",["Phi3Model",oo]],["mpt",["MptModel",Fu]],["opt",["OPTModel",po]],["mistral",["MistralModel",Js]],["starcoder2",["Starcoder2Model",ti]],["falcon",["FalconModel",Cl]],["stablelm",["StableLmModel",oa]]]),ri=new Map([["speecht5",["SpeechT5ForSpeechToText",Tl]],["whisper",["WhisperForConditionalGeneration",di]]]),Vl=new Map([["speecht5",["SpeechT5ForTextToSpeech",Ru]]]),jl=new Map([["vits",["VitsModel",ia]],["musicgen",["MusicgenForConditionalGeneration",da]]]),Ul=new Map([["bert",["BertForSequenceClassification",st]],["roformer",["RoFormerForSequenceClassification",qe]],["electra",["ElectraForSequenceClassification",Pt]],["esm",["EsmForSequenceClassification",An]],["convbert",["ConvBertForSequenceClassification",W]],["camembert",["CamembertForSequenceClassification",Be]],["deberta",["DebertaForSequenceClassification",pt]],["deberta-v2",["DebertaV2ForSequenceClassification",qt]],["mpnet",["MPNetForSequenceClassification",ms]],["albert",["AlbertForSequenceClassification",ns]],["distilbert",["DistilBertForSequenceClassification",Vr]],["roberta",["RobertaForSequenceClassification",Kr]],["xlm",["XLMForSequenceClassification",Xt]],["xlm-roberta",["XLMRobertaForSequenceClassification",_r]],["bart",["BartForSequenceClassification",O]],["mbart",["MBartForSequenceClassification",Oe]],["mobilebert",["MobileBertForSequenceClassification",Er]],["squeezebert",["SqueezeBertForSequenceClassification",Cn]]]),Hu=new Map([["bert",["BertForTokenClassification",xt]],["roformer",["RoFormerForTokenClassification",lt]],["electra",["ElectraForTokenClassification",mt]],["esm",["EsmForTokenClassification",Or]],["convbert",["ConvBertForTokenClassification",S]],["camembert",["CamembertForTokenClassification",Ie]],["deberta",["DebertaForTokenClassification",Tt]],["deberta-v2",["DebertaV2ForTokenClassification",Ht]],["mpnet",["MPNetForTokenClassification",_s]],["distilbert",["DistilBertForTokenClassification",Tr]],["roberta",["RobertaForTokenClassification",Ne]],["xlm",["XLMForTokenClassification",hn]],["xlm-roberta",["XLMRobertaForTokenClassification",Sr]]]),ma=new Map([["t5",["T5ForConditionalGeneration",ys]],["longt5",["LongT5ForConditionalGeneration",vs]],["mt5",["MT5ForConditionalGeneration",Fr]],["bart",["BartForConditionalGeneration",_]],["mbart",["MBartForConditionalGeneration",ce]],["marian",["MarianMTModel",dl]],["m2m_100",["M2M100ForConditionalGeneration",pl]],["blenderbot",["BlenderbotForConditionalGeneration",St]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",er]]]),ni=new Map([["bloom",["BloomForCausalLM",uo]],["gpt2",["GPT2LMHeadModel",Ra]],["gptj",["GPTJForCausalLM",Ga]],["gpt_bigcode",["GPTBigCodeForCausalLM",Iu]],["gpt_neo",["GPTNeoForCausalLM",Va]],["gpt_neox",["GPTNeoXForCausalLM",Ua]],["codegen",["CodeGenForCausalLM",js]],["llama",["LlamaForCausalLM",Ka]],["cohere",["CohereForCausalLM",Qa]],["gemma",["GemmaForCausalLM",Za]],["gemma2",["Gemma2ForCausalLM",eo]],["openelm",["OpenELMForCausalLM",ro]],["qwen2",["Qwen2ForCausalLM",so]],["phi",["PhiForCausalLM",ao]],["phi3",["Phi3ForCausalLM",$i]],["mpt",["MptForCausalLM",co]],["opt",["OPTForCausalLM",ho]],["mbart",["MBartForCausalLM",_t]],["mistral",["MistralForCausalLM",ei]],["starcoder2",["Starcoder2ForCausalLM",na]],["falcon",["FalconForCausalLM",El]],["trocr",["TrOCRForCausalLM",kl]],["stablelm",["StableLmForCausalLM",Ol]]]),Wl=new Map([["bert",["BertForMaskedLM",Le]],["roformer",["RoFormerForMaskedLM",je]],["electra",["ElectraForMaskedLM",Je]],["esm",["EsmForMaskedLM",Vn]],["convbert",["ConvBertForMaskedLM",v]],["camembert",["CamembertForMaskedLM",be]],["deberta",["DebertaForMaskedLM",vt]],["deberta-v2",["DebertaV2ForMaskedLM",Rt]],["mpnet",["MPNetForMaskedLM",fs]],["albert",["AlbertForMaskedLM",Kt]],["distilbert",["DistilBertForMaskedLM",Ct]],["roberta",["RobertaForMaskedLM",nn]],["xlm",["XLMWithLMHeadModel",on]],["xlm-roberta",["XLMRobertaForMaskedLM",kt]],["mobilebert",["MobileBertForMaskedLM",kn]],["squeezebert",["SqueezeBertForMaskedLM",rs]]]),Gl=new Map([["bert",["BertForQuestionAnswering",ze]],["roformer",["RoFormerForQuestionAnswering",ft]],["electra",["ElectraForQuestionAnswering",Ee]],["convbert",["ConvBertForQuestionAnswering",Q]],["camembert",["CamembertForQuestionAnswering",Re]],["deberta",["DebertaForQuestionAnswering",Lt]],["deberta-v2",["DebertaV2ForQuestionAnswering",Yt]],["mpnet",["MPNetForQuestionAnswering",gs]],["albert",["AlbertForQuestionAnswering",ss]],["distilbert",["DistilBertForQuestionAnswering",Ze]],["roberta",["RobertaForQuestionAnswering",gn]],["xlm",["XLMForQuestionAnswering",Qr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Br]],["mobilebert",["MobileBertForQuestionAnswering",jn]],["squeezebert",["SqueezeBertForQuestionAnswering",Fn]]]),_a=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ci]]]),Cd=new Map([["llava",["LlavaForConditionalGeneration",os]],["moondream1",["Moondream1ForConditionalGeneration",nr]],["florence2",["Florence2ForConditionalGeneration",pi]]]),Ku=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ci]]]),ql=new Map([["vit",["ViTForImageClassification",mo]],["fastvit",["FastViTForImageClassification",go]],["mobilevit",["MobileViTForImageClassification",Mo]],["mobilevitv2",["MobileViTV2ForImageClassification",xo]],["beit",["BeitForImageClassification",So]],["deit",["DeiTForImageClassification",No]],["convnext",["ConvNextForImageClassification",Zo]],["convnextv2",["ConvNextV2ForImageClassification",tl]],["dinov2",["Dinov2ForImageClassification",nl]],["resnet",["ResNetForImageClassification",jo]],["swin",["SwinForImageClassification",Wo]],["segformer",["SegformerForImageClassification",Il]],["efficientnet",["EfficientNetForImageClassification",Dl]],["mobilenet_v1",["MobileNetV1ForImageClassification",ju]],["mobilenet_v2",["MobileNetV2ForImageClassification",Rl]],["mobilenet_v3",["MobileNetV3ForImageClassification",Uu]],["mobilenet_v4",["MobileNetV4ForImageClassification",fa]]]),Xu=new Map([["detr",["DetrForObjectDetection",Ao]],["rt_detr",["RTDetrForObjectDetection",Ks]],["table-transformer",["TableTransformerForObjectDetection",Bo]],["yolos",["YolosForObjectDetection",il]]]),Hl=new Map([["owlvit",["OwlViTForObjectDetection",$o]],["owlv2",["Owlv2ForObjectDetection",Co]]]),Kl=new Map([["detr",["DetrForSegmentation",Io]],["clipseg",["CLIPSegForImageSegmentation",Ba]]]),Xl=new Map([["segformer",["SegformerForSemanticSegmentation",Fl]]]),Ql=new Map([["sam",["SamModel",ll]]]),Qu=new Map([["wav2vec2",["Wav2Vec2ForCTC",Du]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Zs]],["unispeech",["UniSpeechForCTC",fl]],["unispeech-sat",["UniSpeechSatForCTC",Xi]],["wavlm",["WavLMForCTC",Zi]],["hubert",["HubertForCTC",wl]]]),Yl=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Gn]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",gl]],["unispeech",["UniSpeechForSequenceClassification",ml]],["unispeech-sat",["UniSpeechSatForSequenceClassification",_l]],["wavlm",["WavLMForSequenceClassification",bl]],["hubert",["HubertForSequenceClassification",Yi]],["audio-spectrogram-transformer",["ASTForAudioClassification",Vs]]]),Zl=new Map([["wavlm",["WavLMForXVector",vl]]]),Jl=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Qs]],["wavlm",["WavLMForAudioFrameClassification",Ml]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",qn]],["pyannote",["PyAnnoteForAudioFrameClassification",Hn]]]),eu=new Map([["vitmatte",["VitMatteForImageMatting",yo]]]),Yu=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Di]]]),tu=new Map([["dpt",["DPTForDepthEstimation",Ri]],["depth_anything",["DepthAnythingForDepthEstimation",Ho]],["glpn",["GLPNForDepthEstimation",Xo]]]),ru=new Map([["clip",["CLIPVisionModelWithProjection",Aa]],["siglip",["SiglipVisionModel",Fa]]]),nu=[[Wu,se.EncoderOnly],[Gu,se.EncoderDecoder],[qu,se.DecoderOnly],[Ul,se.EncoderOnly],[Hu,se.EncoderOnly],[ma,se.Seq2Seq],[ri,se.Seq2Seq],[ni,se.DecoderOnly],[Wl,se.EncoderOnly],[Gl,se.EncoderOnly],[_a,se.Vision2Seq],[Cd,se.ImageTextToText],[ql,se.EncoderOnly],[Kl,se.EncoderOnly],[Xl,se.EncoderOnly],[eu,se.EncoderOnly],[Yu,se.EncoderOnly],[tu,se.EncoderOnly],[Xu,se.EncoderOnly],[Hl,se.EncoderOnly],[Ql,se.MaskGeneration],[Qu,se.EncoderOnly],[Yl,se.EncoderOnly],[Vl,se.Seq2Seq],[jl,se.EncoderOnly],[Zl,se.EncoderOnly],[Jl,se.EncoderOnly],[ru,se.EncoderOnly]];for(const[m,g]of nu)for(const[C,X]of m.values())ue.set(C,g),N.set(X,C),ae.set(C,X);const Zu=[["MusicgenForConditionalGeneration",da,se.Musicgen],["CLIPTextModelWithProjection",En,se.EncoderOnly],["SiglipTextModel",Ia,se.EncoderOnly],["ClapTextModelWithProjection",Pl,se.EncoderOnly],["ClapAudioModelWithProjection",Al,se.EncoderOnly]];for(const[m,g,C]of Zu)ue.set(m,C),N.set(g,m),ae.set(m,g);class su extends Pr{}Te(su,"MODEL_CLASS_MAPPINGS",nu.map(g=>g[0])),Te(su,"BASE_IF_FAIL",!0);class sn extends Pr{}Te(sn,"MODEL_CLASS_MAPPINGS",[Ul]);class iu extends Pr{}Te(iu,"MODEL_CLASS_MAPPINGS",[Hu]);class au extends Pr{}Te(au,"MODEL_CLASS_MAPPINGS",[ma]);class ga extends Pr{}Te(ga,"MODEL_CLASS_MAPPINGS",[ri]);class ou extends Pr{}Te(ou,"MODEL_CLASS_MAPPINGS",[Vl]);class Ss extends Pr{}Te(Ss,"MODEL_CLASS_MAPPINGS",[jl]);class lu extends Pr{}Te(lu,"MODEL_CLASS_MAPPINGS",[ni]);class uu extends Pr{}Te(uu,"MODEL_CLASS_MAPPINGS",[Wl]);class wa extends Pr{}Te(wa,"MODEL_CLASS_MAPPINGS",[Gl]);class du extends Pr{}Te(du,"MODEL_CLASS_MAPPINGS",[_a]);class cu extends Pr{}Te(cu,"MODEL_CLASS_MAPPINGS",[ql]);class ya extends Pr{}Te(ya,"MODEL_CLASS_MAPPINGS",[Kl]);class pu extends Pr{}Te(pu,"MODEL_CLASS_MAPPINGS",[Xl]);class hu extends Pr{}Te(hu,"MODEL_CLASS_MAPPINGS",[Xu]);class fu extends Pr{}Te(fu,"MODEL_CLASS_MAPPINGS",[Hl]);class ba extends Pr{}Te(ba,"MODEL_CLASS_MAPPINGS",[Ql]);class mu extends Pr{}Te(mu,"MODEL_CLASS_MAPPINGS",[Qu]);class _u extends Pr{}Te(_u,"MODEL_CLASS_MAPPINGS",[Yl]);class va extends Pr{}Te(va,"MODEL_CLASS_MAPPINGS",[Zl]);class gu extends Pr{}Te(gu,"MODEL_CLASS_MAPPINGS",[Jl]);class Ju extends Pr{}Te(Ju,"MODEL_CLASS_MAPPINGS",[Ku]);class wu extends Pr{}Te(wu,"MODEL_CLASS_MAPPINGS",[eu]);class yu extends Pr{}Te(yu,"MODEL_CLASS_MAPPINGS",[Yu]);class bu extends Pr{}Te(bu,"MODEL_CLASS_MAPPINGS",[tu]);class vu extends Pr{}Te(vu,"MODEL_CLASS_MAPPINGS",[ru]);class Ed extends Ge{constructor({logits:g,past_key_values:C,encoder_outputs:X,decoder_attentions:Pe=null,cross_attentions:De=null}){super(),this.logits=g,this.past_key_values=C,this.encoder_outputs=X,this.decoder_attentions=Pe,this.cross_attentions=De}}class or extends Ge{constructor({logits:g}){super(),this.logits=g}}class Mu extends Ge{constructor({logits:g,embeddings:C}){super(),this.logits=g,this.embeddings=C}}class Hr extends Ge{constructor({logits:g}){super(),this.logits=g}}class Zr extends Ge{constructor({logits:g}){super(),this.logits=g}}class Jr extends Ge{constructor({start_logits:g,end_logits:C}){super(),this.start_logits=g,this.end_logits=C}}class Qn extends Ge{constructor({logits:g}){super(),this.logits=g}}class ed extends Ge{constructor({logits:g,past_key_values:C}){super(),this.logits=g,this.past_key_values=C}}class xu extends Ge{constructor({alphas:g}){super(),this.alphas=g}}class td extends Ge{constructor({waveform:g,spectrogram:C}){super(),this.waveform=g,this.spectrogram=C}}},"./src/models/whisper/common_whisper.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{WHISPER_LANGUAGE_MAPPING:()=>K,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>ge,whisper_language_to_code:()=>Me});const M=[["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"]],K=new Map(M),ge=new Map([...M.map(([xe,D])=>[D,xe]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Me(xe){xe=xe.toLowerCase();let D=ge.get(xe);if(D===void 0)if(K.has(xe))D=xe;else{const V=xe.length===2?K.keys():K.values();throw new Error(`Language "${xe}" is not supported. Must be one of: ${JSON.stringify(V)}`)}return D}},"./src/models/whisper/generation_whisper.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{WhisperGenerationConfig:()=>K});var M=l("./src/generation/configuration_utils.js");class K extends M.GenerationConfig{constructor(){super(...arguments);Te(this,"return_timestamps",null);Te(this,"return_token_timestamps",null);Te(this,"num_frames",null);Te(this,"alignment_heads",null);Te(this,"task",null);Te(this,"language",null);Te(this,"no_timestamps_token_id",null);Te(this,"prompt_ids",null);Te(this,"is_multilingual",null);Te(this,"lang_to_id",null);Te(this,"task_to_id",null);Te(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{TensorOpRegistry:()=>Me});var M=l("./src/backends/onnx.js"),K=l("./src/utils/tensor.js");const ge=async(xe,D,x)=>{const V=await(0,M.createInferenceSession)(new Uint8Array(xe),D);return async P=>{const J=Object.fromEntries(Object.entries(P).map(([ne,ie])=>[ne,ie.ort_tensor])),te=await V.run(J);return Array.isArray(x)?x.map(ne=>new K.Tensor(te[ne])):new K.Tensor(te[x])}};class Me{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=ge([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=ge([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=ge([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=ge([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=ge([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=ge([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}}Te(Me,"session_options",{})},"./src/pipelines.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{AudioClassificationPipeline:()=>Se,AutomaticSpeechRecognitionPipeline:()=>et,DepthEstimationPipeline:()=>tt,DocumentQuestionAnsweringPipeline:()=>ee,FeatureExtractionPipeline:()=>ye,FillMaskPipeline:()=>ue,ImageClassificationPipeline:()=>ct,ImageFeatureExtractionPipeline:()=>$e,ImageSegmentationPipeline:()=>we,ImageToImagePipeline:()=>dt,ImageToTextPipeline:()=>Xe,ObjectDetectionPipeline:()=>pe,Pipeline:()=>ie,QuestionAnsweringPipeline:()=>se,SummarizationPipeline:()=>N,Text2TextGenerationPipeline:()=>ae,TextClassificationPipeline:()=>R,TextGenerationPipeline:()=>A,TextToAudioPipeline:()=>Ge,TokenClassificationPipeline:()=>Z,TranslationPipeline:()=>F,ZeroShotAudioClassificationPipeline:()=>Fe,ZeroShotClassificationPipeline:()=>_e,ZeroShotImageClassificationPipeline:()=>U,ZeroShotObjectDetectionPipeline:()=>ke,pipeline:()=>st});var M=l("./src/tokenizers.js"),K=l("./src/models.js"),ge=l("./src/processors.js"),Me=l("./src/utils/generic.js"),xe=l("./src/utils/core.js"),D=l("./src/utils/maths.js"),x=l("./src/utils/audio.js"),V=l("./src/utils/tensor.js"),P=l("./src/utils/image.js");async function J(ze){return Array.isArray(ze)||(ze=[ze]),await Promise.all(ze.map(re=>P.RawImage.read(re)))}async function te(ze,re){return Array.isArray(ze)||(ze=[ze]),await Promise.all(ze.map(Ce=>typeof Ce=="string"||Ce instanceof URL?(0,x.read_audio)(Ce,re):Ce instanceof Float64Array?new Float32Array(Ce):Ce))}function ne(ze,re){re&&(ze=ze.map(qe=>qe|0));const[Ce,Ve,Ue,je]=ze;return{xmin:Ce,ymin:Ve,xmax:Ue,ymax:je}}class ie extends Me.Callable{constructor({task:re,model:Ce,tokenizer:Ve=null,processor:Ue=null}){super(),this.task=re,this.model=Ce,this.tokenizer=Ve,this.processor=Ue}async dispose(){await this.model.dispose()}}class R extends ie{constructor(re){super(re)}async _call(re,{top_k:Ce=1}={}){const Ve=this.tokenizer(re,{padding:!0,truncation:!0}),Ue=await this.model(Ve),je=this.model.config.problem_type==="multi_label_classification"?ft=>ft.sigmoid():ft=>new V.Tensor("float32",(0,D.softmax)(ft.data),ft.dims),qe=this.model.config.id2label,lt=[];for(const ft of Ue.logits){const gt=je(ft),Mt=await(0,V.topk)(gt,Ce),v=Mt[0].tolist(),S=Mt[1].tolist().map((Q,he)=>({label:qe?qe[Q]:`LABEL_${Q}`,score:v[he]}));Ce===1?lt.push(...S):lt.push(S)}return Array.isArray(re)||Ce===1?lt:lt[0]}}class Z extends ie{constructor(re){super(re)}async _call(re,{ignore_labels:Ce=["O"]}={}){const Ve=Array.isArray(re),Ue=this.tokenizer(Ve?re:[re],{padding:!0,truncation:!0}),qe=(await this.model(Ue)).logits,lt=this.model.config.id2label,ft=[];for(let gt=0;gtmt==this.tokenizer.sep_token_id);ft[v].map((mt,Ee)=>mt==1&&(Ee===0||Ee>S&>.findIndex(k=>k==W[Ee])===-1));const Q=je[v].tolist(),he=qe[v].tolist();for(let mt=1;mtEe==W[mt])!==-1)&&(Q[mt]=-1/0,he[mt]=-1/0);const Ye=(0,D.softmax)(Q).map((mt,Ee)=>[mt,Ee]),Je=(0,D.softmax)(he).map((mt,Ee)=>[mt,Ee]);Ye[0][0]=0,Je[0][0]=0;const Pt=(0,xe.product)(Ye,Je).filter(mt=>mt[0][1]<=mt[1][1]).map(mt=>[mt[0][1],mt[1][1],mt[0][0]*mt[1][0]]).sort((mt,Ee)=>Ee[2]-mt[2]);for(let mt=0;mtQ==this.tokenizer.mask_token_id);if(gt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Mt=Ue[lt][gt],v=await(0,V.topk)(new V.Tensor("float32",(0,D.softmax)(Mt.data),Mt.dims),Ce),W=v[0].tolist(),S=v[1].tolist();je.push(S.map((Q,he)=>{const Ye=ft.slice();return Ye[gt]=Q,{score:W[he],token:Number(Q),token_str:this.tokenizer.model.vocab[Q],sequence:this.tokenizer.decode(Ye,{skip_special_tokens:!0})}}))}return Array.isArray(re)?je:je[0]}}class ae extends ie{constructor(Ce){super(Ce);Te(this,"_key","generated_text")}async _call(Ce,Ve={}){Array.isArray(Ce)||(Ce=[Ce]),this.model.config.prefix&&(Ce=Ce.map(gt=>this.model.config.prefix+gt));const Ue=this.model.config.task_specific_params;Ue&&Ue[this.task]&&Ue[this.task].prefix&&(Ce=Ce.map(gt=>Ue[this.task].prefix+gt));const je=this.tokenizer,qe={padding:!0,truncation:!0};let lt;this instanceof F&&"_build_translation_inputs"in je?lt=je._build_translation_inputs(Ce,qe,Ve):lt=je(Ce,qe);const ft=await this.model.generate({...lt,...Ve});return je.batch_decode(ft,{skip_special_tokens:!0}).map(gt=>({[this._key]:gt}))}}class N extends ae{constructor(Ce){super(Ce);Te(this,"_key","summary_text")}}class F extends ae{constructor(Ce){super(Ce);Te(this,"_key","translation_text")}}function B(ze){return Array.isArray(ze)&&ze.every(re=>"role"in re&&"content"in re)}class A extends ie{constructor(re){super(re)}async _call(re,Ce={}){let Ve=!1,Ue=!1,je;if(typeof re=="string")je=re=[re];else if(Array.isArray(re)&&re.every(S=>typeof S=="string"))Ve=!0,je=re;else{if(B(re))re=[re];else if(Array.isArray(re)&&re.every(B))Ve=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Ue=!0,je=re.map(S=>this.tokenizer.apply_chat_template(S,{tokenize:!1,add_generation_prompt:!0}))}const qe=Ce.add_special_tokens??!1,lt=Ue?!1:Ce.return_full_text??!0;this.tokenizer.padding_side="left";const ft=this.tokenizer(je,{add_special_tokens:qe,padding:!0,truncation:!0}),gt=await this.model.generate({...ft,...Ce}),Mt=this.tokenizer.batch_decode(gt,{skip_special_tokens:!0});let v;!lt&&ft.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(ft.input_ids,{skip_special_tokens:!0}).map(S=>S.length));const W=Array.from({length:re.length},S=>[]);for(let S=0;S[Ce.toLowerCase(),Ve])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(re,Ce,{hypothesis_template:Ve="This example is {}.",multi_label:Ue=!1}={}){const je=Array.isArray(re);je||(re=[re]),Array.isArray(Ce)||(Ce=[Ce]);const qe=Ce.map(gt=>Ve.replace("{}",gt)),lt=Ue||Ce.length===1,ft=[];for(const gt of re){const Mt=[];for(const S of qe){const Q=this.tokenizer(gt,{text_pair:S,padding:!0,truncation:!0}),he=await this.model(Q);lt?Mt.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):Mt.push(he.logits.data[this.entailment_id])}const W=(lt?Mt.map(S=>(0,D.softmax)(S)[1]):(0,D.softmax)(Mt)).map((S,Q)=>[S,Q]).sort((S,Q)=>Q[0]-S[0]);ft.push({sequence:gt,labels:W.map(S=>Ce[S[1]]),scores:W.map(S=>S[0])})}return je?ft:ft[0]}}class ye extends ie{constructor(re){super(re)}async _call(re,{pooling:Ce="none",normalize:Ve=!1,quantize:Ue=!1,precision:je="binary"}={}){const qe=this.tokenizer(re,{padding:!0,truncation:!0}),lt=await this.model(qe);let ft=lt.last_hidden_state??lt.logits??lt.token_embeddings;if(Ce!=="none")if(Ce==="mean")ft=(0,V.mean_pooling)(ft,qe.attention_mask);else if(Ce==="cls")ft=ft.slice(null,0);else throw Error(`Pooling method '${Ce}' not supported.`);return Ve&&(ft=ft.normalize(2,-1)),Ue&&(ft=(0,V.quantize_embeddings)(ft,je)),ft}}class $e extends ie{constructor(re){super(re)}async _call(re,{pool:Ce=null}={}){const Ve=await J(re),{pixel_values:Ue}=await this.processor(Ve),je=await this.model({pixel_values:Ue});let qe;if(Ce){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.");qe=je.pooler_output}else qe=je.last_hidden_state??je.logits??je.image_embeds;return qe}}class Se extends ie{constructor(re){super(re)}async _call(re,{top_k:Ce=5}={}){const Ve=this.processor.feature_extractor.config.sampling_rate,Ue=await te(re,Ve),je=this.model.config.id2label,qe=[];for(const lt of Ue){const ft=await this.processor(lt),Mt=(await this.model(ft)).logits[0],v=await(0,V.topk)(new V.Tensor("float32",(0,D.softmax)(Mt.data),Mt.dims),Ce),W=v[0].tolist(),Q=v[1].tolist().map((he,Ye)=>({label:je?je[he]:`LABEL_${he}`,score:W[Ye]}));qe.push(Q)}return Array.isArray(re)?qe:qe[0]}}class Fe extends ie{constructor(re){super(re)}async _call(re,Ce,{hypothesis_template:Ve="This is a sound of {}."}={}){const Ue=!Array.isArray(re);Ue&&(re=[re]);const je=Ce.map(Mt=>Ve.replace("{}",Mt)),qe=this.tokenizer(je,{padding:!0,truncation:!0}),lt=this.processor.feature_extractor.config.sampling_rate,ft=await te(re,lt),gt=[];for(const Mt of ft){const v=await this.processor(Mt),W=await this.model({...qe,...v}),S=(0,D.softmax)(W.logits_per_audio.data);gt.push([...S].map((Q,he)=>({score:Q,label:Ce[he]})))}return Ue?gt[0]:gt}}class et extends ie{constructor(re){super(re)}async _call(re,Ce={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(re,Ce);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(re,Ce);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(re,Ce){Ce.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Ce.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ve=!Array.isArray(re);Ve&&(re=[re]);const Ue=this.processor.feature_extractor.config.sampling_rate,je=await te(re,Ue),qe=[];for(const lt of je){const ft=await this.processor(lt),Mt=(await this.model(ft)).logits[0],v=[];for(const S of Mt)v.push((0,D.max)(S.data)[1]);const W=this.tokenizer.decode(v);qe.push({text:W})}return Ve?qe[0]:qe}async _call_whisper(re,Ce){const Ve=Ce.return_timestamps??!1,Ue=Ce.chunk_length_s??0,je=Ce.force_full_sequences??!1;let qe=Ce.stride_length_s??null;const lt={...Ce};Ve==="word"&&(lt.return_token_timestamps=!0,lt.return_timestamps=!1);const ft=!Array.isArray(re);ft&&(re=[re]);const gt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Mt=this.processor.feature_extractor.config.hop_length,v=this.processor.feature_extractor.config.sampling_rate,W=await te(re,v),S=[];for(const Q of W){let he=[];if(Ue>0){if(qe===null)qe=Ue/6;else if(Ue<=qe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Pt=v*Ue,mt=v*qe,Ee=Pt-2*mt;let k=0;for(;;){const H=k+Pt,be=Q.subarray(k,H),Be=await this.processor(be),Ie=k===0,Re=H>=Q.length;if(he.push({stride:[be.length,Ie?0:mt,Re?0:mt],input_features:Be.input_features,is_last:Re}),Re)break;k+=Ee}}else he=[{stride:[Q.length,0,0],input_features:(await this.processor(Q)).input_features,is_last:!0}];for(const Pt of he){lt.num_frames=Math.floor(Pt.stride[0]/Mt);const mt=await this.model.generate({inputs:Pt.input_features,...lt});Ve==="word"?(Pt.tokens=mt.sequences.tolist()[0],Pt.token_timestamps=mt.token_timestamps.tolist()[0].map(Ee=>(0,D.round)(Ee,2))):Pt.tokens=mt[0].tolist(),Pt.stride=Pt.stride.map(Ee=>Ee/v)}const[Ye,Je]=this.tokenizer._decode_asr(he,{time_precision:gt,return_timestamps:Ve,force_full_sequences:je});S.push({text:Ye,...Je})}return ft?S[0]:S}}class Xe extends ie{constructor(re){super(re)}async _call(re,Ce={}){const Ve=Array.isArray(re),Ue=await J(re),{pixel_values:je}=await this.processor(Ue),qe=[];for(const lt of je){lt.dims=[1,...lt.dims];const ft=await this.model.generate({inputs:lt,...Ce}),gt=this.tokenizer.batch_decode(ft,{skip_special_tokens:!0}).map(Mt=>({generated_text:Mt.trim()}));qe.push(gt)}return Ve?qe:qe[0]}}class ct extends ie{constructor(re){super(re)}async _call(re,{top_k:Ce=5}={}){const Ve=await J(re),{pixel_values:Ue}=await this.processor(Ve),je=await this.model({pixel_values:Ue}),qe=this.model.config.id2label,lt=[];for(const ft of je.logits){const gt=await(0,V.topk)(new V.Tensor("float32",(0,D.softmax)(ft.data),ft.dims),Ce),Mt=gt[0].tolist(),W=gt[1].tolist().map((S,Q)=>({label:qe?qe[S]:`LABEL_${S}`,score:Mt[Q]}));lt.push(W)}return Array.isArray(re)?lt:lt[0]}}class we extends ie{constructor(re){super(re),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(re,{threshold:Ce=.5,mask_threshold:Ve=.5,overlap_mask_area_threshold:Ue=.8,label_ids_to_fuse:je=null,target_sizes:qe=null,subtask:lt=null}={}){if(Array.isArray(re)&&re.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const gt=await J(re),Mt=gt.map(Je=>[Je.height,Je.width]),{pixel_values:v,pixel_mask:W}=await this.processor(gt),S=await this.model({pixel_values:v,pixel_mask:W});let Q=null;if(lt!==null)Q=this.subtasks_mapping[lt];else for(let[Je,Pt]of Object.entries(this.subtasks_mapping))if(Pt in this.processor.feature_extractor){Q=this.processor.feature_extractor[Pt].bind(this.processor.feature_extractor),lt=Je;break}const he=this.model.config.id2label,Ye=[];if(lt==="panoptic"||lt==="instance"){const Je=Q(S,Ce,Ve,Ue,je,qe??Mt)[0],Pt=Je.segmentation;for(const mt of Je.segments_info){const Ee=new Uint8ClampedArray(Pt.data.length);for(let H=0;HVe.replace("{}",W)),lt=this.tokenizer(qe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ft}=await this.processor(je),gt=await this.model({...lt,pixel_values:ft}),Mt=this.model.config.model_type==="siglip"?W=>W.sigmoid().data:W=>(0,D.softmax)(W.data),v=[];for(const W of gt.logits_per_image){const Q=[...Mt(W)].map((he,Ye)=>({score:he,label:Ce[Ye]}));Q.sort((he,Ye)=>Ye.score-he.score),v.push(Q)}return Ue?v:v[0]}}class pe extends ie{constructor(re){super(re)}async _call(re,{threshold:Ce=.9,percentage:Ve=!1}={}){const Ue=Array.isArray(re);if(Ue&&re.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const je=await J(re),qe=Ve?null:je.map(S=>[S.height,S.width]),{pixel_values:lt,pixel_mask:ft}=await this.processor(je),gt=await this.model({pixel_values:lt,pixel_mask:ft}),Mt=this.processor.feature_extractor.post_process_object_detection(gt,Ce,qe),v=this.model.config.id2label,W=Mt.map(S=>S.boxes.map((Q,he)=>({score:S.scores[he],label:v[S.classes[he]],box:ne(Q,!Ve)})));return Ue?W:W[0]}}class ke extends ie{constructor(re){super(re)}async _call(re,Ce,{threshold:Ve=.1,top_k:Ue=null,percentage:je=!1}={}){const qe=Array.isArray(re),lt=await J(re),ft=this.tokenizer(Ce,{padding:!0,truncation:!0}),gt=await this.processor(lt),Mt=[];for(let v=0;v({score:Ye.scores[mt],label:Ce[Ye.classes[mt]],box:ne(Pt,!je)})).sort((Pt,mt)=>mt.score-Pt.score);Ue!==null&&(Je=Je.slice(0,Ue)),Mt.push(Je)}return qe?Mt:Mt[0]}}class ee extends ie{constructor(re){super(re)}async _call(re,Ce,Ve={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class Ge extends ie{constructor(Ce){super(Ce);Te(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Ce.vocoder??null}async _call(Ce,{speaker_embeddings:Ve=null}={}){return this.processor?this._call_text_to_spectrogram(Ce,{speaker_embeddings:Ve}):this._call_text_to_waveform(Ce)}async _call_text_to_waveform(Ce){const Ve=this.tokenizer(Ce,{padding:!0,truncation:!0}),{waveform:Ue}=await this.model(Ve),je=this.model.config.sampling_rate;return{audio:Ue.data,sampling_rate:je}}async _call_text_to_spectrogram(Ce,{speaker_embeddings:Ve}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await K.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ve=="string"||Ve instanceof URL)&&(Ve=new Float32Array(await(await fetch(Ve)).arrayBuffer())),Ve instanceof Float32Array)Ve=new V.Tensor("float32",Ve,[1,Ve.length]);else if(!(Ve instanceof V.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Ue}=this.tokenizer(Ce,{padding:!0,truncation:!0}),{waveform:je}=await this.model.generate_speech(Ue,Ve,{vocoder:this.vocoder}),qe=this.processor.feature_extractor.config.sampling_rate;return{audio:je.data,sampling_rate:qe}}}class dt extends ie{constructor(re){super(re)}async _call(re){const Ce=await J(re),Ve=await this.processor(Ce),Ue=await this.model(Ve),je=[];for(const qe of Ue.reconstruction){const lt=qe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");je.push(P.RawImage.fromTensor(lt))}return je.length>1?je:je[0]}}class tt extends ie{constructor(re){super(re)}async _call(re){const Ce=await J(re),Ve=await this.processor(Ce),{predicted_depth:Ue}=await this.model(Ve),je=[];for(let qe=0;qe1?je:je[0]}}const ot=Object.freeze({"text-classification":{tokenizer:M.AutoTokenizer,pipeline:R,model:K.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:M.AutoTokenizer,pipeline:Z,model:K.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:M.AutoTokenizer,pipeline:se,model:K.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:M.AutoTokenizer,pipeline:ue,model:K.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:M.AutoTokenizer,pipeline:N,model:K.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:M.AutoTokenizer,pipeline:F,model:K.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:M.AutoTokenizer,pipeline:ae,model:K.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:M.AutoTokenizer,pipeline:A,model:K.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:M.AutoTokenizer,pipeline:_e,model:K.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Se,model:K.AutoModelForAudioClassification,processor:ge.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:M.AutoTokenizer,pipeline:Fe,model:K.AutoModel,processor:ge.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:M.AutoTokenizer,pipeline:et,model:[K.AutoModelForSpeechSeq2Seq,K.AutoModelForCTC],processor:ge.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:M.AutoTokenizer,pipeline:Ge,model:[K.AutoModelForTextToWaveform,K.AutoModelForTextToSpectrogram],processor:[ge.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:M.AutoTokenizer,pipeline:Xe,model:K.AutoModelForVision2Seq,processor:ge.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ct,model:K.AutoModelForImageClassification,processor:ge.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:we,model:[K.AutoModelForImageSegmentation,K.AutoModelForSemanticSegmentation],processor:ge.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:M.AutoTokenizer,pipeline:U,model:K.AutoModel,processor:ge.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:pe,model:K.AutoModelForObjectDetection,processor:ge.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:M.AutoTokenizer,pipeline:ke,model:K.AutoModelForZeroShotObjectDetection,processor:ge.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:M.AutoTokenizer,pipeline:ee,model:K.AutoModelForDocumentQuestionAnswering,processor:ge.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:dt,model:K.AutoModelForImageToImage,processor:ge.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:tt,model:K.AutoModelForDepthEstimation,processor:ge.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:M.AutoTokenizer,pipeline:ye,model:K.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:ge.AutoProcessor,pipeline:$e,model:[K.AutoModelForImageFeatureExtraction,K.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Le=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function st(ze,re=null,{progress_callback:Ce=null,config:Ve=null,cache_dir:Ue=null,local_files_only:je=!1,revision:qe="main",device:lt=null,dtype:ft=null,model_file_name:gt=null,session_options:Mt={}}={}){ze=Le[ze]??ze;const v=ot[ze.split("_",1)[0]];if(!v)throw Error(`Unsupported pipeline: ${ze}. Must be one of [${Object.keys(ot)}]`);re||(re=v.default.model,console.log(`No model specified. Using default model: "${re}".`));const W={progress_callback:Ce,config:Ve,cache_dir:Ue,local_files_only:je,revision:qe,device:lt,dtype:ft,model_file_name:gt,session_options:Mt},S=new Map([["tokenizer",v.tokenizer],["model",v.model],["processor",v.processor]]),Q=await xt(S,re,W);Q.task=ze,(0,xe.dispatchCallback)(Ce,{status:"ready",task:ze,model:re});const he=v.pipeline;return new he(Q)}async function xt(ze,re,Ce){const Ve=Object.create(null),Ue=[];for(let[je,qe]of ze.entries()){if(!qe)continue;let lt;Array.isArray(qe)?lt=new Promise(async(ft,gt)=>{var v,W;let Mt;for(let S of qe){if(S===null){ft(null);return}try{ft(await S.from_pretrained(re,Ce));return}catch(Q){if((v=Q.message)!=null&&v.includes("Unsupported model type"))Mt=Q;else if((W=Q.message)!=null&&W.includes("Could not locate file"))Mt=Q;else{gt(Q);return}}}gt(Mt)}):lt=qe.from_pretrained(re,Ce),Ve[je]=lt,Ue.push(lt)}await Promise.all(Ue);for(let[je,qe]of Object.entries(Ve))Ve[je]=await qe;return Ve}},"./src/processors.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{ASTFeatureExtractor:()=>qe,AutoProcessor:()=>mt,BeitFeatureExtractor:()=>tt,BitImageProcessor:()=>ue,CLIPFeatureExtractor:()=>N,CLIPImageProcessor:()=>F,ChineseCLIPFeatureExtractor:()=>B,ClapFeatureExtractor:()=>lt,ConvNextFeatureExtractor:()=>_e,ConvNextImageProcessor:()=>ye,DPTFeatureExtractor:()=>Z,DPTImageProcessor:()=>se,DeiTFeatureExtractor:()=>dt,DetrFeatureExtractor:()=>st,DonutFeatureExtractor:()=>ot,EfficientNetImageProcessor:()=>Fe,FeatureExtractor:()=>ne,Florence2Processor:()=>Pt,GLPNFeatureExtractor:()=>ae,ImageFeatureExtractor:()=>ie,MobileNetV1FeatureExtractor:()=>et,MobileNetV2FeatureExtractor:()=>Xe,MobileNetV3FeatureExtractor:()=>ct,MobileNetV4FeatureExtractor:()=>we,MobileViTFeatureExtractor:()=>U,MobileViTImageProcessor:()=>pe,NougatImageProcessor:()=>Le,OwlViTFeatureExtractor:()=>ke,OwlViTProcessor:()=>Je,Owlv2ImageProcessor:()=>ee,Processor:()=>v,PyAnnoteFeatureExtractor:()=>ft,PyAnnoteProcessor:()=>he,RTDetrImageProcessor:()=>Ge,SamImageProcessor:()=>ze,SamProcessor:()=>W,SeamlessM4TFeatureExtractor:()=>je,SegformerFeatureExtractor:()=>R,SiglipImageProcessor:()=>A,SpeechT5FeatureExtractor:()=>Mt,SpeechT5Processor:()=>Ye,Swin2SRImageProcessor:()=>re,ViTFeatureExtractor:()=>$e,ViTImageProcessor:()=>Se,VitMatteImageProcessor:()=>Ce,Wav2Vec2FeatureExtractor:()=>Ue,Wav2Vec2ProcessorWithLM:()=>Q,WeSpeakerFeatureExtractor:()=>gt,WhisperFeatureExtractor:()=>Ve,WhisperProcessor:()=>S,YolosFeatureExtractor:()=>xt});var M=l("./src/utils/generic.js"),K=l("./src/utils/core.js"),ge=l("./src/utils/hub.js"),Me=l("./src/utils/maths.js"),xe=l("./src/utils/tensor.js");l("./src/utils/image.js");var D=l("./src/utils/audio.js");function x([Ee,k,H,be]){return[Ee-H/2,k-be/2,Ee+H/2,k+be/2]}function V(Ee,k=.5,H=null,be=!1){const Be=Ee.logits,Ie=Ee.pred_boxes,[Re,ut,nt]=Be.dims;if(H!==null&&H.length!==Re)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let vt=[];for(let pt=0;ptk&&Ht.push(Wt)}else{let Wt=(0,Me.max)(qt.data)[1];if(Wt===nt-1||(Yt=(0,Me.softmax)(qt.data),Yt[Wt]Vr*Tt[(Tr+1)%2])),Lt.boxes.push(xr),Lt.classes.push(Wt),Lt.scores.push(Yt[Wt])}}vt.push(Lt)}return vt}function P(Ee,k){var H;if(!(Ee instanceof Float32Array||Ee instanceof Float64Array))throw new Error(`${k} expects input to be a Float32Array or a Float64Array, but got ${((H=Ee==null?void 0:Ee.constructor)==null?void 0:H.name)??typeof Ee} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function J(Ee,k,H=0,be=null){const Be=Ee/k;let Ie=(0,Me.bankers_round)(Be)*k;return be!==null&&Ie>be&&(Ie=Math.floor(Be)*k),IeIe?vt=Math.floor(Ie*nt/Be):Ie>Be&&(nt=Math.floor(Be*vt/Ie)),await k.resize(vt,nt,{resample:be}))}async crop_margin(k,H=200){const be=k.clone().grayscale(),Be=(0,Me.min)(be.data)[0],Re=(0,Me.max)(be.data)[0]-Be;if(Re===0)return k;const ut=H/255;let nt=be.width,vt=be.height,pt=0,Tt=0;const Lt=be.data;for(let He=0;Hethis.preprocess(Ie)));return{pixel_values:(0,xe.stack)(be.map(Ie=>Ie.pixel_values),0),original_sizes:be.map(Ie=>Ie.original_size),reshaped_input_sizes:be.map(Ie=>Ie.reshaped_input_size)}}}class R extends ie{post_process_semantic_segmentation(k,H=null){const be=k.logits,Be=be.dims[0];if(H!==null&&H.length!==Be)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Ie=[];for(let Re=0;ReLt[Wt]&&(Lt[Wt]=Yt[Wt],He[Wt]=Ht)}const Nt=new Array(nt.dims[0]),Rt=Tt.data;for(let Ht=0;HtHt!==void 0);Ie.push({segmentation:Tt,labels:qt})}return Ie}}class Z extends ie{}class se extends Z{}class ue extends ie{}class ae extends ie{}class N extends ie{}class F extends N{}class B extends ie{}class A extends ie{}class _e extends ie{constructor(k){super(k),this.crop_pct=this.config.crop_pct??.875}async resize(k){var be;const H=(be=this.size)==null?void 0:be.shortest_edge;if(H===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(H<384){const Be=Math.floor(H/this.crop_pct),[Ie,Re]=this.get_resize_output_image_size(k,{shortest_edge:Be});k=await k.resize(Ie,Re,{resample:this.resample}),k=await k.center_crop(H,H)}else k=await k.resize(H,H,{resample:this.resample});return k}}class ye extends _e{}class $e extends ie{}class Se extends ie{}class Fe extends ie{constructor(k){super(k),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(H=>H*H))}}class et extends ie{}class Xe extends ie{}class ct extends ie{}class we extends ie{}class U extends ie{}class pe extends U{}class ke extends ie{post_process_object_detection(...k){return V(...k)}}class ee extends ke{}class Ge extends ie{post_process_object_detection(...k){return V(...k)}}class dt extends ie{}class tt extends ie{}class ot extends ie{pad_image(k,H,be,Be={}){const[Ie,Re,ut]=H;let nt=this.image_mean;Array.isArray(this.image_mean)||(nt=new Array(ut).fill(nt));let vt=this.image_std;Array.isArray(vt)||(vt=new Array(ut).fill(nt));const pt=nt.map((Tt,Lt)=>-Tt/vt[Lt]);return super.pad_image(k,H,be,{center:!0,constant_values:pt,...Be})}}class Le extends ot{}class st extends ie{async _call(k){const H=await super._call(k),be=[H.pixel_values.dims[0],64,64],Be=new xe.Tensor("int64",new BigInt64Array(be.reduce((Ie,Re)=>Ie*Re)).fill(1n),be);return{...H,pixel_mask:Be}}post_process_object_detection(...k){return V(...k)}remove_low_and_no_objects(k,H,be,Be){let Ie=[],Re=[],ut=[];for(let nt=0;ntbe&&(Ie.push(pt),Re.push(He),ut.push(Tt))}return[Ie,Re,ut]}check_segment_validity(k,H,be,Be=.5,Ie=.8){let Re=[],ut=0,nt=0;const vt=H[be].data;for(let Tt=0;Tt=Be&&++nt;let pt=ut>0&&nt>0;return pt&&(pt=ut/nt>Ie),[pt,Re]}compute_segments(k,H,be,Be,Ie,Re=null,ut=null){let[nt,vt]=ut??k[0].dims,pt=new xe.Tensor("int32",new Int32Array(nt*vt),[nt,vt]),Tt=[];if(ut!==null)for(let qt=0;qtHe[Wt]&&(Lt[Wt]=qt,He[Wt]=Yt[Wt])}let Nt=0;const Rt=pt.data;for(let qt=0;qtBe!==H.dims[Ie]))throw Error(`The first ${be.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new xe.Tensor("int64",k.flat(1/0).map(BigInt),be)}async _call(k,{input_points:H=null,input_labels:be=null,input_boxes:Be=null}={}){const Ie=await super._call(k);if(H&&(Ie.input_points=this.reshape_input_points(H,Ie.original_sizes,Ie.reshaped_input_sizes)),be){if(!Ie.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Ie.input_labels=this.add_input_labels(be,Ie.input_points)}return Be&&(Ie.input_boxes=this.reshape_input_points(Be,Ie.original_sizes,Ie.reshaped_input_sizes,!0)),Ie}async post_process_masks(k,H,be,{mask_threshold:Be=0,binarize:Ie=!0,pad_size:Re=null}={}){const ut=[];Re=Re??this.pad_size;const nt=[Re.height,Re.width];for(let vt=0;vtBe&&(Nt[Rt]=1);Lt=new xe.Tensor("bool",Nt,Lt.dims)}ut.push(Lt)}return ut}generate_crop_boxes(k,H,{crop_n_layers:be=0,overlap_ratio:Be=.3413333333333333,points_per_crop:Ie=32,crop_n_points_downscale_factor:Re=1}={}){}}class re extends ie{pad_image(k,H,be,Be={}){const[Ie,Re,ut]=H;return super.pad_image(k,H,{width:Re+(be-Re%be)%be,height:Ie+(be-Ie%be)%be},{mode:"symmetric",center:!1,constant_values:-1,...Be})}}class Ce extends ie{async _call(k,H){Array.isArray(k)||(k=[k]),Array.isArray(H)||(H=[H]);const be=await Promise.all(k.map(Re=>this.preprocess(Re))),Be=await Promise.all(H.map(Re=>this.preprocess(Re,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,xe.stack)(be.map((Re,ut)=>(0,xe.cat)([Re.pixel_values,Be[ut].pixel_values],0)),0),original_sizes:be.map(Re=>Re.original_size),reshaped_input_sizes:be.map(Re=>Re.reshaped_input_size)}}}class Ve extends ne{constructor(k){var H;super(k),(H=this.config).mel_filters??(H.mel_filters=(0,D.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,D.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(k){const H=await(0,D.spectrogram)(k,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}),be=H.data,Be=(0,Me.max)(be)[0];for(let Ie=0;Iethis.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`."),H=k.slice(0,this.config.n_samples)):(H=new Float32Array(this.config.n_samples),H.set(k)),{input_features:(await this._extract_fbank_features(H)).unsqueeze_(0)}}}class Ue extends ne{_zero_mean_unit_var_norm(k){const be=k.reduce((Ie,Re)=>Ie+Re,0)/k.length,Be=k.reduce((Ie,Re)=>Ie+(Re-be)**2,0)/k.length;return k.map(Ie=>(Ie-be)/Math.sqrt(Be+1e-7))}async _call(k){P(k,"Wav2Vec2FeatureExtractor"),k instanceof Float64Array&&(k=new Float32Array(k));let H=k;this.config.do_normalize&&(H=this._zero_mean_unit_var_norm(H));const be=[1,H.length];return{input_values:new xe.Tensor("float32",H,be),attention_mask:new xe.Tensor("int64",new BigInt64Array(H.length).fill(1n),be)}}}class je extends ne{constructor(k){super(k);const H=this.config.sampling_rate,be=(0,D.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(H/2),H,null,"kaldi",!0);for(let Be=0;Bebe*32768),(0,D.spectrogram)(k,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:H,transpose:!0})}async _call(k,{padding:H=!0,pad_to_multiple_of:be=2,do_normalize_per_mel_bins:Be=!0,return_attention_mask:Ie=!0}={}){P(k,"SeamlessM4TFeatureExtractor");let Re=await this._extract_fbank_features(k,this.config.max_length);if(Be){const[Nt,Rt]=Re.dims,qt=Re.data;for(let Ht=0;Ht0){const Yt=new Float32Array(Rt*(Nt+Ht));Yt.set(qt),Yt.fill(this.config.padding_value,qt.length);const Wt=Nt+Ht;Re=new xe.Tensor(Re.type,Yt,[Wt,Rt]),Ie&&(ut=new xe.Tensor("int64",new BigInt64Array(Wt),[1,Wt]),ut.data.fill(1n,0,Nt))}}const[nt,vt]=Re.dims,pt=this.config.stride;if(nt%pt!==0)throw new Error(`The number of frames (${nt}) must be a multiple of the stride (${pt}).`);const Lt=Re.view(1,Math.floor(nt/pt),vt*pt),He={input_features:Lt};if(Ie){const Nt=Lt.dims[1],Rt=new BigInt64Array(Nt);if(ut){const qt=ut.data;for(let Ht=1,Yt=0;Ht0)if(be==="rand_trunc"){const ut=Math.floor(Math.random()*(Re+1));k=k.subarray(ut,ut+H),Ie=await this._extract_fbank_features(k,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${be}" not implemented`);else{if(Re<0){let ut=new Float64Array(H);if(ut.set(k),Be==="repeat")for(let nt=k.length;nt({id:nt,start:vt*be,end:pt*be,confidence:Tt/(pt-vt)})))}return Be}}class gt extends ne{constructor(k){super(k);const H=this.config.sampling_rate,be=(0,D.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(H/2),H,null,"kaldi",!0);for(let Be=0;BeH*32768),(0,D.spectrogram)(k,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(k){P(k,"WeSpeakerFeatureExtractor");const H=(await this._extract_fbank_features(k)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const be=H.mean(1).data,Be=H.data,[Ie,Re,ut]=H.dims;for(let nt=0;nt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(k){typeof k=="string"&&(k=[k]);const H=[];for(const be of k)if(this.task_prompts_without_inputs.has(be))H.push(this.task_prompts_without_inputs.get(be));else{for(const[Be,Ie]of this.task_prompts_with_input)if(be.includes(Be)){H.push(Ie.replaceAll("{input}",be).replaceAll(Be,""));break}H.length!==k.length&&H.push(be)}return H}post_process_generation(k,H,be){const Be=this.tasks_answer_post_processing_type.get(H)??"pure_text";k=k.replaceAll("","").replaceAll("","");let Ie;switch(Be){case"pure_text":Ie=k;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Re=Be==="ocr"?"quad_boxes":"bboxes",ut=k.matchAll(this.regexes[Re]),nt=[],vt=[];for(const[pt,Tt,...Lt]of ut)nt.push(Tt?Tt.trim():nt.at(-1)??""),vt.push(Lt.map((He,Nt)=>(Number(He)+.5)/this.size_per_bin*be[Nt%2]));Ie={labels:nt,[Re]:vt};break;default:throw new Error(`Task "${H}" (of type "${Be}") not yet implemented.`)}return{[H]:Ie}}}class mt{static async from_pretrained(k,{progress_callback:H=null,config:be=null,cache_dir:Be=null,local_files_only:Ie=!1,revision:Re="main"}={}){let ut=be??await(0,ge.getModelJSON)(k,"preprocessor_config.json",!0,{progress_callback:H,config:be,cache_dir:Be,local_files_only:Ie,revision:Re}),nt=ut.feature_extractor_type??ut.image_processor_type,vt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[nt];if(!vt)if(ut.size!==void 0)console.warn(`Feature extractor type "${nt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),vt=ie;else throw new Error(`Unknown Feature Extractor type: ${nt}`);let pt=this.PROCESSOR_CLASS_MAPPING[ut.processor_class]??v,Tt=new vt(ut);return new pt(Tt)}}Te(mt,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:ie,WhisperFeatureExtractor:Ve,ViTFeatureExtractor:$e,MobileViTFeatureExtractor:U,MobileViTImageProcessor:pe,MobileNetV1FeatureExtractor:et,MobileNetV2FeatureExtractor:Xe,MobileNetV3FeatureExtractor:ct,MobileNetV4FeatureExtractor:we,OwlViTFeatureExtractor:ke,Owlv2ImageProcessor:ee,CLIPFeatureExtractor:N,CLIPImageProcessor:F,Florence2Processor:Pt,ChineseCLIPFeatureExtractor:B,SiglipImageProcessor:A,ConvNextFeatureExtractor:_e,ConvNextImageProcessor:ye,SegformerFeatureExtractor:R,BitImageProcessor:ue,DPTImageProcessor:se,DPTFeatureExtractor:Z,GLPNFeatureExtractor:ae,BeitFeatureExtractor:tt,DeiTFeatureExtractor:dt,DetrFeatureExtractor:st,RTDetrImageProcessor:Ge,YolosFeatureExtractor:xt,DonutFeatureExtractor:ot,NougatImageProcessor:Le,EfficientNetImageProcessor:Fe,ViTImageProcessor:Se,VitMatteImageProcessor:Ce,SamImageProcessor:ze,Swin2SRImageProcessor:re,Wav2Vec2FeatureExtractor:Ue,SeamlessM4TFeatureExtractor:je,SpeechT5FeatureExtractor:Mt,ASTFeatureExtractor:qe,ClapFeatureExtractor:lt,PyAnnoteFeatureExtractor:ft,WeSpeakerFeatureExtractor:gt}),Te(mt,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:S,Wav2Vec2ProcessorWithLM:Q,PyAnnoteProcessor:he,SamProcessor:W,SpeechT5Processor:Ye,OwlViTProcessor:Je,Florence2Processor:Pt})},"./src/tokenizers.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{AlbertTokenizer:()=>Rt,AutoTokenizer:()=>pn,BartTokenizer:()=>Or,BertTokenizer:()=>Nt,BlenderbotSmallTokenizer:()=>bs,BlenderbotTokenizer:()=>is,BloomTokenizer:()=>Er,CLIPTokenizer:()=>Kt,CamembertTokenizer:()=>Ct,CodeGenTokenizer:()=>ss,CodeLlamaTokenizer:()=>Rs,CohereTokenizer:()=>Fr,ConvBertTokenizer:()=>Vr,DebertaTokenizer:()=>Yt,DebertaV2Tokenizer:()=>Wt,DistilBertTokenizer:()=>Ze,ElectraTokenizer:()=>Ur,EsmTokenizer:()=>Un,FalconTokenizer:()=>_s,GPT2Tokenizer:()=>An,GPTNeoXTokenizer:()=>gs,GemmaTokenizer:()=>rs,Grok1Tokenizer:()=>Cn,HerbertTokenizer:()=>xr,LlamaTokenizer:()=>In,M2M100Tokenizer:()=>Kn,MBart50Tokenizer:()=>Dr,MBartTokenizer:()=>Xr,MPNetTokenizer:()=>ms,MarianTokenizer:()=>ws,MobileBertTokenizer:()=>qt,NllbTokenizer:()=>On,NougatTokenizer:()=>as,PreTrainedTokenizer:()=>He,Qwen2Tokenizer:()=>Ns,RoFormerTokenizer:()=>Tr,RobertaTokenizer:()=>kn,SiglipTokenizer:()=>Xn,SpeechT5Tokenizer:()=>vs,SqueezeBertTokenizer:()=>Ht,T5Tokenizer:()=>Vn,TokenizerModel:()=>$e,VitsTokenizer:()=>Ms,Wav2Vec2CTCTokenizer:()=>ys,WhisperTokenizer:()=>ns,XLMRobertaTokenizer:()=>fs,XLMTokenizer:()=>Dt,is_chinese_char:()=>ae});var M=l("./src/utils/generic.js"),K=l("./src/utils/core.js"),ge=l("./src/utils/hub.js"),Me=l("./src/utils/maths.js"),xe=l("./src/utils/tensor.js"),D=l("./src/utils/data-structures.js"),x=l("./node_modules/@huggingface/jinja/dist/index.js"),V=l("./src/models/whisper/common_whisper.js"),P=l("./src/utils/constants.js");async function J(ve,_){const O=await Promise.all([(0,ge.getModelJSON)(ve,"tokenizer.json",!0,_),(0,ge.getModelJSON)(ve,"tokenizer_config.json",!0,_)]);return _.legacy!==null&&(O[1].legacy=_.legacy),O}function te(ve,_){const O=[];let Y=0;for(const de of ve.matchAll(_)){const ce=de[0];Y0&&O.push(ce),Y=de.index+ce.length}return Y=19968&&ve<=40959||ve>=13312&&ve<=19903||ve>=131072&&ve<=173791||ve>=173824&&ve<=177983||ve>=177984&&ve<=178207||ve>=178208&&ve<=183983||ve>=63744&&ve<=64255||ve>=194560&&ve<=195103}function N(ve,_,O){const Y=[];let de=0;for(;dethis.tokens_to_ids.get(O)??this.unk_token_id)}convert_ids_to_tokens(_){return _.map(O=>this.vocab[O]??this.unk_token)}}class Se extends $e{constructor(_){super(_),this.tokens_to_ids=ie(_.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[O,Y]of this.tokens_to_ids)this.vocab[Y]=O}encode(_){const O=[];for(const Y of _){const de=[...Y];if(de.length>this.max_input_chars_per_word){O.push(this.unk_token);continue}let ce=!1,Oe=0;const _t=[];for(;Oe0&&(St=this.config.continuing_subword_prefix+St),this.tokens_to_ids.has(St)){wt=St;break}--yt}if(wt===null){ce=!0;break}_t.push(wt),Oe=yt}ce?O.push(this.unk_token):O.push(..._t)}return O}}class Fe extends $e{constructor(_,O){super(_);const Y=_.vocab.length;this.vocab=new Array(Y),this.scores=new Array(Y);for(let de=0;de[de,ce])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=O.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,Me.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new D.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(_){const O=_.sentence,Y=O.length;let de=0;for(;de{const ve=[...Array.from({length:94},(de,ce)=>ce+33),...Array.from({length:12},(de,ce)=>ce+161),...Array.from({length:82},(de,ce)=>ce+174)],_=ve.slice();let O=0;for(let de=0;de<256;++de)ve.includes(de)||(ve.push(de),_.push(256+O),O+=1);const Y=_.map(de=>String.fromCharCode(de));return Object.fromEntries(ve.map((de,ce)=>[de,Y[ce]]))})(),Xe=(0,K.reverseDictionary)(et);class ct extends $e{constructor(_){super(_),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=ie(_.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[O,Y]of this.tokens_to_ids)this.vocab[Y]=O;this.bpe_ranks=new Map(_.merges.map((O,Y)=>[O,Y])),this.merges=_.merges.map(O=>O.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=_.end_of_word_suffix,this.continuing_subword_suffix=_.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(_){if(_.length===0)return[];const O=this.cache.get(_);if(O!==void 0)return O;const Y=Array.from(_);this.end_of_word_suffix&&(Y[Y.length-1]+=this.end_of_word_suffix);let de=[];if(Y.length>1){const ce=new D.PriorityQueue((yt,wt)=>yt.score`<0x${Oe.toString(16).toUpperCase().padStart(2,"0")}>`)):O.push(this.unk_token)}return O}}class we extends $e{constructor(_,O){super(_),this.tokens_to_ids=ie(O.target_lang?_.vocab[O.target_lang]:_.vocab),this.bos_token=O.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=O.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=O.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=O.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[Y,de]of this.tokens_to_ids)this.vocab[de]=Y}encode(_){return _}}class U extends M.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"BertNormalizer":return new xt(_);case"Precompiled":return new Ie(_);case"Sequence":return new st(_);case"Replace":return new pe(_);case"NFC":return new ke(_);case"NFKC":return new ee(_);case"NFKD":return new Ge(_);case"Strip":return new dt(_);case"StripAccents":return new tt(_);case"Lowercase":return new ot(_);case"Prepend":return new Le(_);default:throw new Error(`Unknown Normalizer type: ${_.type}`)}}normalize(_){throw Error("normalize should be implemented in subclass.")}_call(_){return this.normalize(_)}}class pe extends U{normalize(_){const O=ne(this.config.pattern);return O===null?_:_.replaceAll(O,this.config.content)}}class ke extends U{normalize(_){return _=_.normalize("NFC"),_}}class ee extends U{normalize(_){return _=_.normalize("NFKC"),_}}class Ge extends U{normalize(_){return _=_.normalize("NFKD"),_}}class dt extends U{normalize(_){return this.config.strip_left&&this.config.strip_right?_=_.trim():(this.config.strip_left&&(_=_.trimStart()),this.config.strip_right&&(_=_.trimEnd())),_}}class tt extends U{normalize(_){return _=se(_),_}}class ot extends U{normalize(_){return _=_.toLowerCase(),_}}class Le extends U{normalize(_){return _=this.config.prepend+_,_}}class st extends U{constructor(_){super(_),this.normalizers=_.normalizers.map(O=>U.fromConfig(O))}normalize(_){return this.normalizers.reduce((O,Y)=>Y.normalize(O),_)}}class xt extends U{_tokenize_chinese_chars(_){const O=[];for(let Y=0;Y<_.length;++Y){const de=_[Y],ce=de.charCodeAt(0);ae(ce)?(O.push(" "),O.push(de),O.push(" ")):O.push(de)}return O.join("")}stripAccents(_){return _.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}_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 O=[];for(const Y of _){const de=Y.charCodeAt(0);de===0||de===65533||this._is_control(Y)||(/^\s$/.test(Y)?O.push(" "):O.push(Y))}return O.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 ze extends M.Callable{static fromConfig(_){if(_===null)return null;switch(_.type){case"BertPreTokenizer":return new re(_);case"Sequence":return new Re(_);case"Whitespace":return new ut(_);case"WhitespaceSplit":return new nt(_);case"Metaspace":return new be(_);case"ByteLevel":return new Ce(_);case"Split":return new Ve(_);case"Punctuation":return new Ue(_);case"Digits":return new je(_);case"Replace":return new vt(_);default:throw new Error(`Unknown PreTokenizer type: ${_.type}`)}}pre_tokenize_text(_,O){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(_,O){return(Array.isArray(_)?_.map(Y=>this.pre_tokenize_text(Y,O)):this.pre_tokenize_text(_,O)).flat()}_call(_,O){return this.pre_tokenize(_,O)}}class re extends ze{constructor(_){super(),this.pattern=new RegExp(`[^\\s${B}]+|[${B}]`,"gu")}pre_tokenize_text(_,O){return _.trim().match(this.pattern)||[]}}class Ce extends ze{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=et,this.text_encoder=new TextEncoder}pre_tokenize_text(_,O){return this.add_prefix_space&&!_.startsWith(" ")&&(_=" "+_),(this.use_regex?_.match(this.pattern)||[]:[_]).map(de=>Array.from(this.text_encoder.encode(de),ce=>this.byte_encoder[ce]).join(""))}}class Ve extends ze{constructor(_){super(),this.config=_,this.pattern=ne(this.config.pattern,this.config.invert)}pre_tokenize_text(_,O){return this.pattern===null?[]:this.config.invert?_.match(this.pattern)||[]:te(_,this.pattern)}}class Ue extends ze{constructor(_){super(),this.config=_,this.pattern=new RegExp(`[^${B}]+|[${B}]+`,"gu")}pre_tokenize_text(_,O){return _.match(this.pattern)||[]}}class je extends ze{constructor(_){super(),this.config=_;const O=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(O,"gu")}pre_tokenize_text(_,O){return _.match(this.pattern)||[]}}class qe extends M.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"TemplateProcessing":return new gt(_);case"ByteLevel":return new Mt(_);case"RobertaProcessing":return new ft(_);case"BertProcessing":return new lt(_);case"Sequence":return new v(_);default:throw new Error(`Unknown PostProcessor type: ${_.type}`)}}post_process(_,...O){throw Error("post_process should be implemented in subclass.")}_call(_,...O){return this.post_process(_,...O)}}class lt extends qe{constructor(_){super(_),this.cls=_.cls[0],this.sep=_.sep[0]}post_process(_,O=null,{add_special_tokens:Y=!0}={}){Y&&(_=(0,K.mergeArrays)([this.cls],_,[this.sep]));let de=new Array(_.length).fill(0);if(O!==null){const ce=Y&&this instanceof ft?[this.sep]:[],Oe=Y?[this.sep]:[];_=(0,K.mergeArrays)(_,ce,O,Oe),de=(0,K.mergeArrays)(de,new Array(O.length+ce.length+Oe.length).fill(1))}return{tokens:_,token_type_ids:de}}}class ft extends lt{}class gt extends qe{constructor(_){super(_),this.single=_.single,this.pair=_.pair}post_process(_,O=null,{add_special_tokens:Y=!0}={}){const de=O===null?this.single:this.pair;let ce=[],Oe=[];for(const _t of de)"SpecialToken"in _t?Y&&(ce.push(_t.SpecialToken.id),Oe.push(_t.SpecialToken.type_id)):"Sequence"in _t&&(_t.Sequence.id==="A"?(ce=(0,K.mergeArrays)(ce,_),Oe=(0,K.mergeArrays)(Oe,new Array(_.length).fill(_t.Sequence.type_id))):_t.Sequence.id==="B"&&(ce=(0,K.mergeArrays)(ce,O),Oe=(0,K.mergeArrays)(Oe,new Array(O.length).fill(_t.Sequence.type_id))));return{tokens:ce,token_type_ids:Oe}}}class Mt extends qe{post_process(_,O=null){return O&&(_=(0,K.mergeArrays)(_,O)),{tokens:_}}}class v extends qe{constructor(_){super(_),this.processors=_.processors.map(O=>qe.fromConfig(O))}post_process(_,O=null,Y={}){let de;for(const ce of this.processors)if(ce instanceof Mt)_=ce.post_process(_).tokens,O&&(O=ce.post_process(O).tokens);else{const Oe=ce.post_process(_,O,Y);_=Oe.tokens,de=Oe.token_type_ids}return{tokens:_,token_type_ids:de}}}class W extends M.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 Be(_);case"ByteLevel":return new Pt(_);case"Replace":return new S(_);case"ByteFallback":return new Q(_);case"Fuse":return new he(_);case"Strip":return new Ye(_);case"Sequence":return new Ee(_);case"CTC":return new mt(_);case"BPEDecoder":return new k(_);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 S extends W{decode_chain(_){const O=ne(this.config.pattern);return O===null?_:_.map(Y=>Y.replaceAll(O,this.config.content))}}class Q extends W{constructor(_){super(_),this.text_decoder=new TextDecoder}decode_chain(_){const O=[];let Y=[];for(const de of _){let ce=null;if(de.length===6&&de.startsWith("<0x")&&de.endsWith(">")){const Oe=parseInt(de.slice(3,5),16);isNaN(Oe)||(ce=Oe)}if(ce!==null)Y.push(ce);else{if(Y.length>0){const Oe=this.text_decoder.decode(Uint8Array.from(Y));O.push(Oe),Y=[]}O.push(de)}}if(Y.length>0){const de=this.text_decoder.decode(Uint8Array.from(Y));O.push(de),Y=[]}return O}}class he extends W{decode_chain(_){return[_.join("")]}}class Ye extends W{constructor(_){super(_),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(_){return _.map(O=>{let Y=0;for(let ce=0;ce(Y!==0&&(O.startsWith(this.config.prefix)?O=O.replace(this.config.prefix,""):O=" "+O),this.cleanup&&(O=Z(O)),O))}}class Pt extends W{constructor(_){super(_),this.byte_decoder=Xe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(_){const O=_.join(""),Y=new Uint8Array([...O].map(ce=>this.byte_decoder[ce]));return this.text_decoder.decode(Y)}decode_chain(_){const O=[];let Y=[];for(const de of _)this.added_tokens.find(ce=>ce.content===de)!==void 0?(Y.length>0&&(O.push(this.convert_tokens_to_string(Y)),Y=[]),O.push(de)):Y.push(de);return Y.length>0&&O.push(this.convert_tokens_to_string(Y)),O}}class mt extends W{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 O=[_[0]];for(let ce=1;ce<_.length;++ce)_[ce]!==O.at(-1)&&O.push(_[ce]);let de=O.filter(ce=>ce!==this.pad_token).join("");return this.cleanup&&(de=Z(de).replaceAll(this.word_delimiter_token," ").trim()),de}decode_chain(_){return[this.convert_tokens_to_string(_)]}}class Ee extends W{constructor(_){super(_),this.decoders=_.decoders.map(O=>W.fromConfig(O))}decode_chain(_){return this.decoders.reduce((O,Y)=>Y.decode_chain(O),_)}}class k extends W{constructor(_){super(_),this.suffix=this.config.suffix}decode_chain(_){return _.map((O,Y)=>O.replaceAll(this.suffix,Y===_.length-1?"":" "))}}class H extends W{decode_chain(_){let O="";for(let Y=1;Y<_.length;Y+=2)O+=_[Y];return[O]}}class be extends ze{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:O=void 0}={}){let Y=_.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Y.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&O===0)&&(Y=this.strRep+Y),[Y]}}class Be extends W{constructor(_){super(_),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement}decode_chain(_){const O=[];for(let Y=0;Y<_.length;++Y){let de=_[Y].replaceAll(this.replacement," ");this.addPrefixSpace&&Y==0&&de.startsWith(" ")&&(de=de.substring(1)),O.push(de)}return O}}class Ie extends U{constructor(_){super(_),this.charsmap=_.precompiled_charsmap}normalize(_){return _=_.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),_=_.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm," "),_.includes("~")?_=_.split("~").map(Y=>Y.normalize("NFKC")).join("~"):_=_.normalize("NFKC"),_}}class Re extends ze{constructor(_){super(),this.tokenizers=_.pretokenizers.map(O=>ze.fromConfig(O))}pre_tokenize_text(_,O){return this.tokenizers.reduce((Y,de)=>de.pre_tokenize(Y,O),[_])}}class ut extends ze{constructor(_){super()}pre_tokenize_text(_,O){return _.match(/\w+|[^\w\s]+/g)||[]}}class nt extends ze{constructor(_){super()}pre_tokenize_text(_,O){return F(_)}}class vt extends ze{constructor(_){super(),this.config=_,this.pattern=ne(this.config.pattern),this.content=this.config.content}pre_tokenize_text(_,O){return this.pattern===null?[_]:[_.replaceAll(this.pattern,this.config.content)]}}const pt=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Tt(ve,_,O,Y){for(const de of Object.keys(ve)){const ce=_-ve[de].length,Oe=O(de),_t=new Array(ce).fill(Oe);ve[de]=Y==="right"?(0,K.mergeArrays)(ve[de],_t):(0,K.mergeArrays)(_t,ve[de])}}function Lt(ve,_){for(const O of Object.keys(ve))ve[O].length=_}class He extends M.Callable{constructor(O,Y){super();Te(this,"return_token_type_ids",!1);Te(this,"padding_side","right");this._tokenizer_config=Y,this.normalizer=U.fromConfig(O.normalizer),this.pre_tokenizer=ze.fromConfig(O.pre_tokenizer),this.model=$e.fromConfig(O.model,Y),this.post_processor=qe.fromConfig(O.post_processor),this.decoder=W.fromConfig(O.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const de of O.added_tokens){const ce=new ye(de);this.added_tokens.push(ce),this.model.tokens_to_ids.set(ce.content,ce.id),this.model.vocab[ce.id]=ce.content,ce.special&&(this.special_tokens.push(ce.content),this.all_special_ids.push(ce.id))}if(this.additional_special_tokens=Y.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.toSorted((de,ce)=>ce.content.length-de.content.length).map(de=>`${de.lstrip?"\\s*":""}(${(0,K.escapeRegExp)(de.content)})${de.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=Y.model_max_length,this.remove_space=Y.remove_space,this.clean_up_tokenization_spaces=Y.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Y.do_lowercase_and_remove_accent??!1,Y.padding_side&&(this.padding_side=Y.padding_side),this.legacy=!1,this.chat_template=Y.chat_template??null,Array.isArray(this.chat_template)){const de=Object.create(null);for(const{name:ce,template:Oe}of this.chat_template){if(typeof ce!="string"||typeof Oe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');de[ce]=Oe}this.chat_template=de}this._compiled_template_cache=new Map}getToken(...O){for(const Y of O){const de=this._tokenizer_config[Y];if(de)if(typeof de=="object"){if(de.__type==="AddedToken")return de.content;throw Error(`Unknown token: ${de}`)}else return de}return null}static async from_pretrained(O,{progress_callback:Y=null,config:de=null,cache_dir:ce=null,local_files_only:Oe=!1,revision:_t="main",legacy:yt=null}={}){const wt=await J(O,{progress_callback:Y,config:de,cache_dir:ce,local_files_only:Oe,revision:_t,legacy:yt});return new this(...wt)}_call(O,{text_pair:Y=null,add_special_tokens:de=!0,padding:ce=!1,truncation:Oe=null,max_length:_t=null,return_tensor:yt=!0,return_token_type_ids:wt=null}={}){const St=Array.isArray(O);let Qt;if(St){if(O.length===0)throw Error("text array must be non-empty");if(Y!==null){if(Array.isArray(Y)){if(O.length!==Y.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Qt=O.map((er,Ut)=>this._encode_plus(er,{text_pair:Y[Ut],add_special_tokens:de,return_token_type_ids:wt}))}else Qt=O.map(er=>this._encode_plus(er,{add_special_tokens:de,return_token_type_ids:wt}))}else{if(O==null)throw Error("text may not be null or undefined");if(Array.isArray(Y))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Qt=[this._encode_plus(O,{text_pair:Y,add_special_tokens:de,return_token_type_ids:wt})]}if(_t===null?ce==="max_length"?_t=this.model_max_length:_t=(0,Me.max)(Qt.map(er=>er.input_ids.length))[0]:Oe||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."),_t=Math.min(_t,this.model_max_length??1/0),ce||Oe)for(let er=0;er_t?Oe&&Lt(Qt[er],_t):ce&&Tt(Qt[er],_t,Ut=>Ut==="input_ids"?this.pad_token_id:0,this.padding_side));const $r={};if(yt){if(!(ce&&Oe)&&Qt.some(Ut=>{var pr;for(const nn of Object.keys(Ut))if(Ut[nn].length!==((pr=Qt[0][nn])==null?void 0:pr.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const er=[Qt.length,Qt[0].input_ids.length];for(const Ut of Object.keys(Qt[0]))$r[Ut]=new xe.Tensor("int64",BigInt64Array.from(Qt.flatMap(pr=>pr[Ut]).map(BigInt)),er)}else{for(const er of Object.keys(Qt[0]))$r[er]=Qt.map(Ut=>Ut[er]);if(!St)for(const er of Object.keys($r))$r[er]=$r[er][0]}return $r}_encode_text(O){return O===null?null:(this.added_tokens_regex?O.split(this.added_tokens_regex).filter(ce=>ce):[O]).map((ce,Oe)=>{if(this.added_tokens.find(yt=>yt.content===ce)!==void 0)return ce;{if(this.remove_space===!0&&(ce=ce.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ce=ue(ce)),this.normalizer!==null&&(ce=this.normalizer(ce)),ce.length===0)return[];const yt=this.pre_tokenizer!==null?this.pre_tokenizer(ce,{section_index:Oe}):[ce];return this.model(yt)}}).flat()}_encode_plus(O,{text_pair:Y=null,add_special_tokens:de=!0,return_token_type_ids:ce=null}={}){const{tokens:Oe,token_type_ids:_t}=this._tokenize_helper(O,{pair:Y,add_special_tokens:de}),yt=this.model.convert_tokens_to_ids(Oe),wt={input_ids:yt,attention_mask:new Array(yt.length).fill(1)};return(ce??this.return_token_type_ids)&&_t&&(wt.token_type_ids=_t),wt}_tokenize_helper(O,{pair:Y=null,add_special_tokens:de=!1}={}){const ce=this._encode_text(O),Oe=this._encode_text(Y);return this.post_processor?this.post_processor(ce,Oe,{add_special_tokens:de}):{tokens:(0,K.mergeArrays)(ce??[],Oe??[])}}tokenize(O,{pair:Y=null,add_special_tokens:de=!1}={}){return this._tokenize_helper(O,{pair:Y,add_special_tokens:de}).tokens}encode(O,{text_pair:Y=null,add_special_tokens:de=!0,return_token_type_ids:ce=null}={}){return this._encode_plus(O,{text_pair:Y,add_special_tokens:de,return_token_type_ids:ce}).input_ids}batch_decode(O,Y={}){return O instanceof xe.Tensor&&(O=O.tolist()),O.map(de=>this.decode(de,Y))}decode(O,Y={}){if(O instanceof xe.Tensor&&(O=R(O)),!Array.isArray(O)||O.length===0||!(0,K.isIntegralNumber)(O[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(O,Y)}decode_single(O,{skip_special_tokens:Y=!1,clean_up_tokenization_spaces:de=null}){let ce=this.model.convert_ids_to_tokens(O);Y&&(ce=ce.filter(_t=>!this.special_tokens.includes(_t)));let Oe=this.decoder?this.decoder(ce):ce.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Oe=Oe.replaceAll(this.decoder.end_of_word_suffix," "),Y&&(Oe=Oe.trim())),(de??this.clean_up_tokenization_spaces)&&(Oe=Z(Oe)),Oe}apply_chat_template(O,{tools:Y=null,documents:de=null,chat_template:ce=null,add_generation_prompt:Oe=!1,tokenize:_t=!0,padding:yt=!1,truncation:wt=!1,max_length:St=null,return_tensor:Qt=!0,return_dict:$r=!1,tokenizer_kwargs:er={},...Ut}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const Ne=this.chat_template;if(ce!==null&&Object.hasOwn(Ne,ce))ce=Ne[ce];else if(ce===null&&"default"in Ne)ce=Ne.default;else if(ce===null)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(Ne).sort()}.`)}else if(this.chat_template)ce=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");if(typeof ce!="string")throw Error(`chat_template must be a string, but got ${typeof ce}`);let pr=this._compiled_template_cache.get(ce);pr===void 0&&(pr=new x.Template(ce),this._compiled_template_cache.set(ce,pr));const nn=Object.create(null);for(const Ne of pt){const gn=this.getToken(Ne);gn&&(nn[Ne]=gn)}const Kr=pr.render({messages:O,add_generation_prompt:Oe,tools:Y,documents:de,...nn,...Ut});if(_t){const Ne=this._call(Kr,{add_special_tokens:!1,padding:yt,truncation:wt,max_length:St,return_tensor:Qt,...er});return $r?Ne:Ne.input_ids}return Kr}}class Nt extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Rt extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class qt extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Ht extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Yt extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Wt extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class xr extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Vr extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Tr extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Ze extends He{}class Ct extends He{}class Dt extends He{constructor(O,Y){super(O,Y);Te(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 Ur extends He{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Vn extends He{}class An extends He{}class Or extends He{}class Xr extends He{constructor(_,O){super(_,O),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(_,O,Y){return Fn(this,_,O,Y)}}class Dr extends Xr{}class kn extends He{}class Er extends He{constructor(_,O){var ce,Oe;const Y=".,!?…。,、।۔،",de=(Oe=(ce=_.pre_tokenizer)==null?void 0:ce.pretokenizers[0])==null?void 0:Oe.pattern;de&&de.Regex===` ?[^(\\s|[${Y}])]+`&&(de.Regex=` ?[^\\s${Y}]+`),super(_,O)}}const jn="▁";class In extends He{constructor(O,Y){super(O,Y);Te(this,"padding_side","left");this.legacy=Y.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new be({replacement:jn,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(O){if(O===null)return null;if(this.legacy||O.length===0)return super._encode_text(O);let Y=super._encode_text(jn+O.replaceAll(jn," "));return Y.length>1&&Y[0]===jn&&this.special_tokens.includes(Y[1])&&(Y=Y.slice(1)),Y}}class Rs extends He{}class fs extends He{}class ms extends He{}class _s extends He{}class gs extends He{}class Un extends He{}class Ns extends He{}class rs extends He{}class Cn extends He{}function Fn(ve,_,O,Y){if(!("language_codes"in ve)||!Array.isArray(ve.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ve)||!(ve.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ve)||typeof ve.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const de=Y.src_lang,ce=Y.tgt_lang;if(!ve.language_codes.includes(ce))throw new Error(`Target language code "${ce}" is not valid. Must be one of: {${ve.language_codes.join(", ")}}`);if(de!==void 0){if(!ve.language_codes.includes(de))throw new Error(`Source language code "${de}" is not valid. Must be one of: {${ve.language_codes.join(", ")}}`);for(const Oe of ve.post_processor.config.single)if("SpecialToken"in Oe&&ve.languageRegex.test(Oe.SpecialToken.id)){Oe.SpecialToken.id=ve.lang_to_token(de);break}}return Y.forced_bos_token_id=ve.model.convert_tokens_to_ids([ve.lang_to_token(ce)])[0],ve._call(_,O)}class On extends He{constructor(_,O){super(_,O),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(_,O,Y){return Fn(this,_,O,Y)}}class Kn extends He{constructor(_,O){super(_,O),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)).map(Y=>Y.slice(2,-2)),this.lang_to_token=Y=>`__${Y}__`}_build_translation_inputs(_,O,Y){return Fn(this,_,O,Y)}}class ns extends He{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(_,{return_timestamps:O=!1,return_language:Y=!1,time_precision:de=null,force_full_sequences:ce=!0}={}){if(de===null)throw Error("Must specify time_precision");let Oe=null;const _t=O==="word";function yt(){return{language:Oe,timestamp:[null,null],text:""}}const wt=[];let St=yt(),Qt=0;const $r=this.timestamp_begin;let er=[],Ut=[],pr=!1,nn=null;const Kr=new Set(this.all_special_ids);for(const yr of _){const Wr=yr.tokens,on=_t?yr.token_timestamps:null;let Xt=null,hn=$r;if("stride"in yr){const[vr,kt,_r]=yr.stride;if(Qt-=kt,nn=vr-_r,kt&&(hn=kt/de+$r),_r)for(let Sr=Wr.length-1;Sr>=0;--Sr){const Br=Number(Wr[Sr]);if(Br>=$r){if(Xt!==null&&(Br-$r)*de=$r){const _r=(kt-$r)*de+Qt,Sr=(0,Me.round)(_r,2);if(Xt!==null&&kt>=Xt)pr=!0;else if(pr||er.length>0&&kt0?(er.push(Qr),_t&&Ut.push(br)):er.every(vr=>vr.length===0)&&(St=yt(),er=[],Qr=[],Ut=[],br=[])}if(er.length>0){if(ce&&O)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[yr,Wr]=this.findLongestCommonSequence(er,Ut),on=this.decode(yr);St.text=on,_t&&(St.words=this.collateWordTimestamps(yr,Wr,Oe)),wt.push(St)}let Ne=Object.create(null);const gn=wt.map(yr=>yr.text).join("");if(O||Y){for(let yr=0;yr0;let _t=Oe?[]:null,yt=Oe?O[0]:null;for(let wt=1;wt<_.length;++wt){const St=_[wt];let Qt=0,$r=[de,de,0,0];const er=St.length;for(let yr=1;yrSr===br[Br]&&yt[Wr+Br]<=O[wt][hn+Br]).length:vr=Xt.filter((Sr,Br)=>Sr===br[Br]).length;const kt=yr/1e4,_r=vr/yr+kt;vr>1&&_r>Qt&&(Qt=_r,$r=[Wr,on,hn,Qr])}const[Ut,pr,nn,Kr]=$r,Ne=Math.floor((pr+Ut)/2),gn=Math.floor((Kr+nn)/2);ce.push(...Y.slice(0,Ne)),Y=St.slice(gn),de=Y.length,Oe&&(_t.push(...yt.slice(0,Ne)),yt=O[wt].slice(gn))}return ce.push(...Y),Oe?(_t.push(...yt),[ce,_t]):[ce,[]]}collateWordTimestamps(_,O,Y){const[de,ce,Oe]=this.combineTokensIntoWords(_,Y),_t=[];for(let yt=0;yt=de){const _t=((Oe-de)*Y).toFixed(2);ce.push(`<|${_t}|>`),ce.push([])}else ce[ce.length-1].push(Oe);return ce=ce.map(Oe=>typeof Oe=="string"?Oe:super.decode(Oe,O)),ce.join("")}splitTokensOnUnicode(_){const O=this.decode(_,{decode_with_timestamps:!0}),Y="�",de=[],ce=[],Oe=[];let _t=[],yt=[],wt=0;for(let St=0;St<_.length;++St){const Qt=_[St];_t.push(Qt),yt.push(St);const $r=this.decode(_t,{decode_with_timestamps:!0});(!$r.includes(Y)||O[wt+$r.indexOf(Y)]===Y)&&(de.push($r),ce.push(_t),Oe.push(yt),_t=[],yt=[],wt+=$r.length)}return[de,ce,Oe]}splitTokensOnSpaces(_){const[O,Y,de]=this.splitTokensOnUnicode(_),ce=[],Oe=[],_t=[],yt=new RegExp(`^[${B}]$`,"gu");for(let wt=0;wt=this.model.tokens_to_ids.get("<|endoftext|>"),Ut=St.startsWith(" "),pr=St.trim(),nn=yt.test(pr);if(er||Ut||nn||ce.length===0)ce.push(St),Oe.push(Qt),_t.push($r);else{const Kr=ce.length-1;ce[Kr]+=St,Oe[Kr].push(...Qt),_t[Kr].push(...$r)}}return[ce,Oe,_t]}mergePunctuations(_,O,Y,de,ce){const Oe=structuredClone(_),_t=structuredClone(O),yt=structuredClone(Y);let wt=Oe.length-2,St=Oe.length-1;for(;wt>=0;)Oe[wt].startsWith(" ")&&de.includes(Oe[wt].trim())?(Oe[St]=Oe[wt]+Oe[St],_t[St]=(0,K.mergeArrays)(_t[wt],_t[St]),yt[St]=(0,K.mergeArrays)(yt[wt],yt[St]),Oe[wt]="",_t[wt]=[],yt[wt]=[]):St=wt,--wt;for(wt=0,St=1;StQt),_t.filter(Qt=>Qt.length>0),yt.filter(Qt=>Qt.length>0)]}get_decoder_prompt_ids({language:_=null,task:O=null,no_timestamps:Y=!0}={}){const de=[];if(_){const ce=(0,V.whisper_language_to_code)(_),Oe=this.model.tokens_to_ids.get(`<|${ce}|>`);if(Oe===void 0)throw new Error(`Unable to find language "${ce}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);de.push(Oe)}else de.push(null);if(O){if(O=O.toLowerCase(),O!=="transcribe"&&O!=="translate")throw new Error(`Task "${O}" is not supported. Must be one of: ["transcribe", "translate"]`);const ce=this.model.tokens_to_ids.get(`<|${O}|>`);if(ce===void 0)throw new Error(`Unable to find task "${O}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);de.push(ce)}else de.push(null);if(Y){const ce=this.model.tokens_to_ids.get("<|notimestamps|>");if(ce===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);de.push(ce)}return de.map((ce,Oe)=>[Oe+1,ce]).filter(ce=>ce[1]!==null)}}class ss extends He{}class Kt extends He{}class Xn extends He{}class ws extends He{constructor(_,O){super(_,O),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Y=>this.languageRegex.test(Y)),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[O,...Y]=_.trim().split(this.languageRegex);if(Y.length===0)return super._encode_text(O);if(Y.length===2){const[de,ce]=Y;return this.supported_language_codes.includes(de)||console.warn(`Unsupported language code "${de}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,K.mergeArrays)([de],super._encode_text(ce))}}}class ys extends He{}class is extends He{}class bs extends He{}class vs extends He{}class as extends He{}class Ms extends He{constructor(_,O){super(_,O),this.decoder=new H({})}}class Fr extends He{}class pn{static async from_pretrained(_,{progress_callback:O=null,config:Y=null,cache_dir:de=null,local_files_only:ce=!1,revision:Oe="main",legacy:_t=null}={}){var $r;const[yt,wt]=await J(_,{progress_callback:O,config:Y,cache_dir:de,local_files_only:ce,revision:Oe,legacy:_t}),St=(($r=wt.tokenizer_class)==null?void 0:$r.replace(/Fast$/,""))??"PreTrainedTokenizer";let Qt=this.TOKENIZER_CLASS_MAPPING[St];return Qt||(console.warn(`Unknown tokenizer class "${St}", attempting to construct from base class.`),Qt=He),new Qt(yt,wt)}}Te(pn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Vn,DistilBertTokenizer:Ze,CamembertTokenizer:Ct,DebertaTokenizer:Yt,DebertaV2Tokenizer:Wt,BertTokenizer:Nt,HerbertTokenizer:xr,ConvBertTokenizer:Vr,RoFormerTokenizer:Tr,XLMTokenizer:Dt,ElectraTokenizer:Ur,MobileBertTokenizer:qt,SqueezeBertTokenizer:Ht,AlbertTokenizer:Rt,GPT2Tokenizer:An,BartTokenizer:Or,MBartTokenizer:Xr,MBart50Tokenizer:Dr,RobertaTokenizer:kn,WhisperTokenizer:ns,CodeGenTokenizer:ss,CLIPTokenizer:Kt,SiglipTokenizer:Xn,MarianTokenizer:ws,BloomTokenizer:Er,NllbTokenizer:On,M2M100Tokenizer:Kn,LlamaTokenizer:In,CodeLlamaTokenizer:Rs,XLMRobertaTokenizer:fs,MPNetTokenizer:ms,FalconTokenizer:_s,GPTNeoXTokenizer:gs,EsmTokenizer:Un,Wav2Vec2CTCTokenizer:ys,BlenderbotTokenizer:is,BlenderbotSmallTokenizer:bs,SpeechT5Tokenizer:vs,NougatTokenizer:as,VitsTokenizer:Ms,Qwen2Tokenizer:Ns,GemmaTokenizer:rs,Grok1Tokenizer:Cn,CohereTokenizer:Fr,PreTrainedTokenizer:He})},"./src/utils/audio.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{hamming:()=>V,hanning:()=>x,mel_filter_bank:()=>Z,read_audio:()=>xe,spectrogram:()=>F,window_function:()=>B});var M=l("./src/utils/hub.js"),K=l("./src/utils/maths.js"),ge=l("./src/utils/core.js"),Me=l("./src/utils/tensor.js");async function xe(A,_e){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 ye=await(await(0,M.getFile)(A)).arrayBuffer(),$e=new AudioContext({sampleRate:_e});typeof _e>"u"&&console.warn(`No sampling rate provided, using default of ${$e.sampleRate}Hz.`);const Se=await $e.decodeAudioData(ye);let Fe;if(Se.numberOfChannels===2){const et=Math.sqrt(2),Xe=Se.getChannelData(0),ct=Se.getChannelData(1);Fe=new Float32Array(Xe.length);for(let we=0;we2595*Math.log10(1+A/700),kaldi:A=>1127*Math.log(1+A/700),slaney:(A,_e=1e3,ye=15,$e=27/Math.log(6.4))=>A>=_e?ye+Math.log(A/_e)*$e:3*A/200};function J(A,_e="htk"){const ye=P[_e];if(!ye)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof A=="number"?ye(A):A.map($e=>ye($e))}const te={htk:A=>700*(10**(A/2595)-1),kaldi:A=>700*(Math.exp(A/1127)-1),slaney:(A,_e=1e3,ye=15,$e=Math.log(6.4)/27)=>A>=ye?_e*Math.exp($e*(A-ye)):200*A/3};function ne(A,_e="htk"){const ye=te[_e];if(!ye)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof A=="number"?ye(A):A.map($e=>ye($e))}function ie(A,_e){const ye=Float64Array.from({length:_e.length-1},(et,Xe)=>_e[Xe+1]-_e[Xe]),$e=Array.from({length:A.length},()=>new Array(_e.length));for(let et=0;etnew Array(A.length));for(let et=0;etA+$e*Fe)}function Z(A,_e,ye,$e,Se,Fe=null,et="htk",Xe=!1){if(Fe!==null&&Fe!=="slaney")throw new Error('norm must be one of null or "slaney"');const ct=J(ye,et),we=J($e,et),U=R(ct,we,_e+2);let pe=ne(U,et),ke;if(Xe){const Ge=Se/(A*2);ke=J(Float64Array.from({length:A},(dt,tt)=>tt*Ge),et),pe=U}else ke=R(0,Math.floor(Se/2),A);const ee=ie(ke,pe);if(Fe!==null&&Fe==="slaney")for(let Ge=0;Ge<_e;++Ge){const dt=ee[Ge],tt=2/(pe[Ge+2]-pe[Ge]);for(let ot=0;otSe)throw Error(`frame_length (${ye}) may not be larger than fft_length (${Se})`);if(ze!==ye)throw new Error(`Length of the window (${ze}) must equal frame_length (${ye})`);if($e<=0)throw new Error("hop_length must be greater than zero");if(Fe===null&&U!==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(et){if(Xe!=="reflect")throw new Error(`pad_mode="${Xe}" not implemented yet.`);const W=Math.floor((Se-1)/2)+1;A=se(A,W,W)}let re=Math.floor(1+Math.floor((A.length-ye)/$e));ot!==null&&rere?st&&(Ue=Le):Ue=Ve=Le);const je=new K.FFT(Se),qe=new Float64Array(Se),lt=new Float64Array(je.outputBufferSize),ft=new Float32Array(Ce*Ue);for(let W=0;W=1;--he)qe[he]-=we*qe[he-1];qe[0]*=1-we}for(let he=0;he<_e.length;++he)qe[he]*=_e[he];je.realTransform(lt,qe);for(let he=0;heMath.pow(Xe,.85));break;default:throw new Error(`Unknown window type ${_e}.`)}if(ye&&(et=et.subarray(0,A)),$e===null)return et;if(A>$e)throw new Error(`Length of the window (${A}) may not be larger than frame_length (${$e})`);return et}},"./src/utils/constants.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{GITHUB_ISSUE_URL:()=>M});const M="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{calculateDimensions:()=>D,calculateReflectOffset:()=>J,dispatchCallback:()=>M,escapeRegExp:()=>ge,isIntegralNumber:()=>xe,isTypedArray:()=>Me,mergeArrays:()=>V,pick:()=>te,pop:()=>x,product:()=>P,reverseDictionary:()=>K});function M(ne,ie){ne&&ne(ie)}function K(ne){return Object.fromEntries(Object.entries(ne).map(([ie,R])=>[R,ie]))}function ge(ne){return ne.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Me(ne){var ie,R,Z;return((Z=(R=(ie=ne==null?void 0:ne.prototype)==null?void 0:ie.__proto__)==null?void 0:R.constructor)==null?void 0:Z.name)==="TypedArray"}function xe(ne){return Number.isInteger(ne)||typeof ne=="bigint"}function D(ne){const ie=[];let R=ne;for(;Array.isArray(R);)ie.push(R.length),R=R[0];return ie}function x(ne,ie,R=void 0){const Z=ne[ie];if(Z!==void 0)return delete ne[ie],Z;if(R===void 0)throw Error(`Key ${ie} does not exist in object.`);return R}function V(...ne){return Array.prototype.concat.apply([],ne)}function P(...ne){return ne.reduce((ie,R)=>ie.flatMap(Z=>R.map(se=>[Z,se])))}function J(ne,ie){return Math.abs((ne+ie)%(2*ie)-ie)}function te(ne,ie){return Object.assign({},...ie.map(R=>{if(ne[R]!==void 0)return{[R]:ne[R]}}))}},"./src/utils/data-structures.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{CharTrie:()=>K,PriorityQueue:()=>M,TokenLattice:()=>Me});class M{constructor(x=(P,J)=>P>J,V=1/0){this._heap=[],this._comparator=x,this._maxSize=V}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...x){return this.extend(x)}extend(x){for(const V of x)if(this.size0&&this._swap(0,V),this._heap.pop(),this._siftDown(),x}replace(x){const V=this.peek();return this._heap[0]=x,this._siftDown(),V}_parent(x){return(x+1>>>1)-1}_left(x){return(x<<1)+1}_right(x){return x+1<<1}_greater(x,V){return this._comparator(this._heap[x],this._heap[V])}_swap(x,V){const P=this._heap[x];this._heap[x]=this._heap[V],this._heap[V]=P}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(x){for(;x>0&&this._greater(x,this._parent(x));)this._swap(x,this._parent(x)),x=this._parent(x)}_siftDown(){let x=0;for(;this._left(x)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const J=new xe(this.bosTokenId,0,0,0,0),te=new xe(this.eosTokenId,1,this.len,0,0);this.nodes.push(J.clone()),this.nodes.push(te.clone()),this.beginNodes[this.len].push(te),this.endNodes[0].push(J)}insert(x,V,P,J){const te=this.nodes.length,ne=new xe(J,te,x,V,P);this.beginNodes[x].push(ne),this.endNodes[x+V].push(ne),this.nodes.push(ne)}viterbi(){const x=this.len;let V=0;for(;V<=x;){if(this.beginNodes[V].length==0)return[];for(let ie of this.beginNodes[V]){ie.prev=null;let R=0,Z=null;for(let se of this.endNodes[V]){const ue=se.backtraceScore+ie.score;(Z===null||ue>R)&&(Z=se.clone(),R=ue)}if(Z!==null)ie.prev=Z,ie.backtraceScore=R;else return[]}++V}const P=[],te=this.beginNodes[x][0].prev;if(te===null)return[];let ne=te.clone();for(;ne.prev!==null;)P.push(ne.clone()),ne=ne.clone().prev.clone();return P.reverse(),P}piece(x){return this.sentence.slice(x.pos,x.pos+x.length)}tokens(){return this.viterbi().map(V=>this.piece(V))}tokenIds(){return this.viterbi().map(V=>V.tokenId)}}class xe{constructor(x,V,P,J,te){this.tokenId=x,this.nodeId=V,this.pos=P,this.length=J,this.score=te,this.prev=null,this.backtraceScore=0}clone(){const x=new xe(this.tokenId,this.nodeId,this.pos,this.length,this.score);return x.prev=this.prev,x.backtraceScore=this.backtraceScore,x}}},"./src/utils/devices.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{DEVICE_TYPES:()=>M});const M=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":(bt,fe,l)=>{l.r(fe),l.d(fe,{DATA_TYPES:()=>Me,DEFAULT_DEVICE_DTYPE_MAPPING:()=>xe,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>D,isWebGpuFp16Supported:()=>ge});var M=l("./src/env.js"),K=l("./src/utils/devices.js");const ge=function(){let x;return async function(){if(x===void 0)if(!M.apis.IS_WEBGPU_AVAILABLE)x=!1;else try{x=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{x=!1}return x}}(),Me=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),xe=Object.freeze({[K.DEVICE_TYPES.wasm]:Me.q8}),D=Object.freeze({[Me.fp32]:"",[Me.fp16]:"_fp16",[Me.int8]:"_int8",[Me.uint8]:"_uint8",[Me.q8]:"_quantized",[Me.q4]:"_q4",[Me.q4f16]:"_q4f16",[Me.bnb4]:"_bnb4"})},"./src/utils/generic.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{Callable:()=>M});const M=class{constructor(){let K=function(...ge){return K._call(...ge)};return Object.setPrototypeOf(K,new.target.prototype)}_call(...K){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{getFile:()=>V,getModelFile:()=>ie,getModelJSON:()=>R});var M=l("?7a2c"),K=l("?a42a"),ge=l("./src/env.js"),Me=l("./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 D{constructor(ae){if(this.filePath=ae,this.headers=new Headers,this.exists=M.existsSync(ae),this.exists){this.status=200,this.statusText="OK";let N=M.statSync(ae);this.headers.set("content-length",N.size.toString()),this.updateContentType();let F=this;this.body=new ReadableStream({start(B){F.arrayBuffer().then(A=>{B.enqueue(new Uint8Array(A)),B.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const ae=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",xe[ae]??"application/octet-stream")}clone(){let ae=new D(this.filePath);return ae.exists=this.exists,ae.status=this.status,ae.statusText=this.statusText,ae.headers=new Headers(this.headers),ae}async arrayBuffer(){return(await M.promises.readFile(this.filePath)).buffer}async blob(){const ae=await M.promises.readFile(this.filePath);return new Blob([ae],{type:this.headers.get("content-type")})}async text(){return await M.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function x(ue,ae=null,N=null){let F;try{F=new URL(ue)}catch{return!1}return!(ae&&!ae.includes(F.protocol)||N&&!N.includes(F.hostname))}async function V(ue){var ae;if(ge.env.useFS&&!x(ue,["http:","https:","blob:"]))return new D(ue);if(typeof process<"u"&&((ae=process==null?void 0:process.release)==null?void 0:ae.name)==="node"){const N=!!(_n!=null&&_n.TESTING_REMOTELY),F=ge.env.version,B=new Headers;if(B.set("User-Agent",`transformers.js/${F}; is_ci/${N};`),x(ue,["http:","https:"],["huggingface.co","hf.co"])){const _e=(_n==null?void 0:_n.HF_TOKEN)??(_n==null?void 0:_n.HF_ACCESS_TOKEN);_e&&B.set("Authorization",`Bearer ${_e}`)}return fetch(ue,{headers:B})}else return fetch(ue)}const P={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function J(ue,ae,N){if(!N)return null;const F=P[ue]??`Error (${ue}) occurred while trying to load file`;throw Error(`${F}: "${ae}".`)}class te{constructor(ae){this.path=ae}async match(ae){let N=K.join(this.path,ae),F=new D(N);if(F.exists)return F}async put(ae,N){const F=Buffer.from(await N.arrayBuffer());let B=K.join(this.path,ae);try{await M.promises.mkdir(K.dirname(B),{recursive:!0}),await M.promises.writeFile(B,F)}catch(A){console.warn("An error occurred while writing the file to cache:",A)}}}async function ne(ue,...ae){for(let N of ae)try{let F=await ue.match(N);if(F)return F}catch{continue}}async function ie(ue,ae,N=!0,F={}){if(!ge.env.allowLocalModels){if(F.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(!ge.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,Me.dispatchCallback)(F.progress_callback,{status:"initiate",name:ue,file:ae});let B;if(!B&&ge.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{B=await caches.open("transformers-cache")}catch(ke){console.warn("An error occurred while opening the browser cache:",ke)}}if(!B&&ge.env.useFSCache&&(B=new te(F.cache_dir??ge.env.cacheDir)),!B&&ge.env.useCustomCache){if(!ge.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ge.env.customCache.match||!ge.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");B=ge.env.customCache}const A=F.revision??"main";let _e=se(ue,ae),ye=se(ge.env.localModelPath,_e),$e=se(ge.env.remoteHost,ge.env.remotePathTemplate.replaceAll("{model}",ue).replaceAll("{revision}",encodeURIComponent(A)),ae),Se=A==="main"?_e:se(ue,A,ae),Fe,et=B instanceof te?Se:$e,Xe=!1,ct;B&&(ct=await ne(B,ye,et));const we=ct!==void 0;if(ct===void 0){if(ge.env.allowLocalModels)if(x(_e,["http:","https:"])){if(F.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${_e}.`);if(!ge.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${_e}.`)}else try{ct=await V(ye),Fe=ye}catch(ee){console.warn(`Unable to load from local path "${ye}": "${ee}"`)}if(ct===void 0||ct.status===404){if(F.local_files_only||!ge.env.allowRemoteModels){if(N)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ye}".`);return null}if(ct=await V($e),ct.status!==200)return J(ct.status,$e,N);Fe=et}Xe=B&&typeof Response<"u"&&ct instanceof Response&&ct.status===200}(0,Me.dispatchCallback)(F.progress_callback,{status:"download",name:ue,file:ae});const U={status:"progress",name:ue,file:ae};let pe;return F.progress_callback?we&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(pe=new Uint8Array(await ct.arrayBuffer()),(0,Me.dispatchCallback)(F.progress_callback,{...U,progress:100,loaded:pe.length,total:pe.length})):pe=await Z(ct,ke=>{(0,Me.dispatchCallback)(F.progress_callback,{...U,...ke})}):pe=new Uint8Array(await ct.arrayBuffer()),Xe&&Fe&&await B.match(Fe)===void 0&&await B.put(Fe,new Response(pe,{headers:ct.headers})).catch(ke=>{console.warn(`Unable to add response to browser cache: ${ke}.`)}),(0,Me.dispatchCallback)(F.progress_callback,{status:"done",name:ue,file:ae}),pe}async function R(ue,ae,N=!0,F={}){let B=await ie(ue,ae,N,F);if(B===null)return{};let _e=new TextDecoder("utf-8").decode(B);return JSON.parse(_e)}async function Z(ue,ae){const N=ue.headers.get("Content-Length");N===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let F=parseInt(N??"0"),B=new Uint8Array(F),A=0;const _e=ue.body.getReader();async function ye(){const{done:$e,value:Se}=await _e.read();if($e)return;let Fe=A+Se.length;if(Fe>F){F=Fe;let Xe=new Uint8Array(F);Xe.set(B),B=Xe}B.set(Se,A),A=Fe;const et=A/F*100;return ae({progress:et,loaded:A,total:F}),ye()}return await ye(),B}function se(...ue){return ue=ue.map((ae,N)=>(N&&(ae=ae.replace(new RegExp("^/"),"")),N!==ue.length-1&&(ae=ae.replace(new RegExp("/$"),"")),ae)),ue.join("/")}},"./src/utils/image.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{RawImage:()=>ne});var M=l("./src/utils/hub.js"),K=l("./src/env.js"),ge=l("./src/utils/tensor.js"),Me=l("?2b25");const xe=typeof self<"u",D=xe&&self.constructor.name==="DedicatedWorkerGlobalScope";let x,V,P;if(xe)x=(ie,R)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ie,R)},P=self.createImageBitmap,V=self.ImageData;else if(Me)P=async ie=>{const Z=(await ie.metadata()).channels,{data:se,info:ue}=await ie.rotate().raw().toBuffer({resolveWithObject:!0}),ae=new ne(new Uint8ClampedArray(se),ue.width,ue.height,ue.channels);return Z!==void 0&&Z!==ue.channels&&ae.convert(Z),ae};else throw new Error("Unable to load image processing library.");const J={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},te=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class ne{constructor(R,Z,se,ue){this.data=R,this.width=Z,this.height=se,this.channels=ue}get size(){return[this.width,this.height]}static async read(R){if(R instanceof ne)return R;if(typeof R=="string"||R instanceof URL)return await this.fromURL(R);throw new Error(`Unsupported input type: ${typeof R}`)}static fromCanvas(R){if(!xe)throw new Error("fromCanvas() is only supported in browser environments.");const se=R.getContext("2d").getImageData(0,0,R.width,R.height).data;return new ne(se,R.width,R.height,4)}static async fromURL(R){const Z=await(0,M.getFile)(R);if(Z.status!==200)throw new Error(`Unable to read image from "${R}" (${Z.status} ${Z.statusText})`);const se=await Z.blob();return this.fromBlob(se)}static async fromBlob(R){if(xe){const Z=await P(R),se=x(Z.width,Z.height).getContext("2d");return se.drawImage(Z,0,0),new this(se.getImageData(0,0,Z.width,Z.height).data,Z.width,Z.height,4)}else{const Z=Me(await R.arrayBuffer());return await P(Z)}}static fromTensor(R,Z="CHW"){if(R.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${R.dims.length} dimensions.`);if(Z==="CHW")R=R.transpose(1,2,0);else if(Z!=="HWC")throw new Error(`Unsupported channel format: ${Z}`);if(!(R.data instanceof Uint8ClampedArray||R.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${R.type}`);switch(R.dims[2]){case 1:case 2:case 3:case 4:return new ne(R.data,R.dims[1],R.dims[0],R.dims[2]);default:throw new Error(`Unsupported number of channels: ${R.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const R=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let Z=0,se=0;Z=0?B=se:_e=-se,ue>=0?A=ue:ye=-ue,F.drawImage(N,B,A,R,Z,_e,ye,R,Z),new ne(F.getImageData(0,0,R,Z).data,R,Z,4).convert(ae)}else{let ae=this.toSharp();if(se>=0&&ue>=0)ae=ae.extract({left:Math.floor(se),top:Math.floor(ue),width:R,height:Z});else if(se<=0&&ue<=0){const N=Math.floor(-ue),F=Math.floor(-se);ae=ae.extend({top:N,left:F,right:R-this.width-F,bottom:Z-this.height-N})}else{let N=[0,0],F=0;ue<0?(N[0]=Math.floor(-ue),N[1]=Z-this.height-N[0]):F=Math.floor(ue);let B=[0,0],A=0;se<0?(B[0]=Math.floor(-se),B[1]=R-this.width-B[0]):A=Math.floor(se),ae=ae.extend({top:N[0],bottom:N[1],left:B[0],right:B[1]}).extract({left:A,top:F,width:R,height:Z})}return await P(ae)}}async toBlob(R="image/png",Z=1){if(!xe)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:R,quality:Z})}toTensor(R="CHW"){let Z=new ge.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(R!=="HWC")if(R==="CHW")Z=Z.permute(2,0,1);else throw new Error(`Unsupported channel format: ${R}`);return Z}toCanvas(){if(!xe)throw new Error("toCanvas() is only supported in browser environments.");const R=this.clone().rgba(),Z=x(R.width,R.height),se=new V(R.data,R.width,R.height);return Z.getContext("2d").putImageData(se,0,0),Z}_update(R,Z,se,ue=null){return this.data=R,this.width=Z,this.height=se,ue!==null&&(this.channels=ue),this}clone(){return new ne(this.data.slice(),this.width,this.height,this.channels)}convert(R){if(this.channels===R)return this;switch(R){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(R){if(xe){if(D)throw new Error("Unable to save an image from a Web Worker.");const Z=R.split(".").pop().toLowerCase(),se=te.get(Z)??"image/png",ue=await this.toBlob(se),ae=URL.createObjectURL(ue),N=document.createElement("a");N.href=ae,N.download=R,N.click(),N.remove()}else{if(K.env.useFS)return await this.toSharp().toFile(R);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 Me(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{FFT:()=>ie,bankers_round:()=>se,cos_sim:()=>D,dot:()=>xe,dynamic_time_warping:()=>ue,interpolate_data:()=>M,log_softmax:()=>Me,magnitude:()=>x,max:()=>P,medianFilter:()=>R,min:()=>V,permute_data:()=>K,round:()=>Z,softmax:()=>ge});function M(ae,[N,F,B],[A,_e],ye="bilinear",$e=!1){const Se=_e/B,Fe=A/F,et=new ae.constructor(A*_e*N),Xe=F*B,ct=A*_e;for(let we=0;we=0;--$e)A[$e]=Se,B[$e]=N[F[$e]],Se*=B[$e];const _e=F.map(($e,Se)=>A[F.indexOf(Se)]),ye=new ae.constructor(ae.length);for(let $e=0;$e=0;--Fe)Se+=et%N[Fe]*_e[Fe],et=Math.floor(et/N[Fe]);ye[Se]=ae[$e]}return[ye,B]}function ge(ae){const N=P(ae)[0],F=ae.map(_e=>Math.exp(_e-N)),B=F.reduce((_e,ye)=>_e+ye,0);return F.map(_e=>_e/B)}function Me(ae){return ge(ae).map(B=>Math.log(B))}function xe(ae,N){let F=0;for(let B=0;BN+F*F,0))}function V(ae){if(ae.length===0)throw Error("Array must not be empty");let N=ae[0],F=0;for(let B=1;BN&&(N=ae[B],F=B);return[Number(N),F]}function J(ae){return ae>0&&(ae&ae-1)===0}class te{constructor(N){if(this.size=N|0,this.size<=1||!J(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=N<<1,this.table=new Float64Array(this.size*2);for(let B=0;BB;B<<=1)++F;this._width=F%2===0?F-1:F,this._bitrev=new Int32Array(1<>>A&3)<<_e}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(N,F){const B=F||new Array(N.length>>>1);for(let A=0;A>>1]=N[A];return B}toComplexArray(N,F){const B=F||this.createComplexArray();for(let A=0;A>>1],B[A+1]=0;return B}transform(N,F){if(N===F)throw new Error("Input and output buffers must be different");this._transform4(N,F,1)}realTransform(N,F){if(N===F)throw new Error("Input and output buffers must be different");this._realTransform4(N,F,1)}inverseTransform(N,F){if(N===F)throw new Error("Input and output buffers must be different");this._transform4(N,F,-1);for(let B=0;B>=2;ye>=2;ye>>=2){$e=A/ye<<1;const ct=$e>>>2;for(Se=0;Se>>1,ye>>>1)}else for(Se=0,Fe=0;Se>>1,ye>>>1,B)}const Xe=this.table;for(ye>>=2;ye>=2;ye>>=2){$e=A/ye<<1;const we=$e>>>1,U=we>>>1,pe=U>>>1;for(Se=0;Se>>1;for(let we=2;we>1;++et){const Xe=(et+1-N)**2/2,ct=Math.sqrt(Se**2+Fe**2)**Xe,we=Xe*Math.atan2(Fe,Se),U=2*et;_e[U]=ct*Math.cos(we),_e[U+1]=ct*Math.sin(we),ye[U]=_e[U],ye[U+1]=-_e[U+1]}this._slicedChirpBuffer=_e.subarray(F,B),this._f=new te(A>>1),this._f.transform(this._chirpBuffer,ye)}_transform(N,F,B){const A=this._buffer1,_e=this._buffer2,ye=this._outBuffer1,$e=this._outBuffer2,Se=this._chirpBuffer,Fe=this._slicedChirpBuffer,et=this._a;if(B)for(let Xe=0;Xe>1,U=F[we];A[Xe]=U*Fe[Xe],A[ct]=U*Fe[ct]}else for(let Xe=0;Xe=ae.length&&(Se=2*(ae.length-1)-Se),B[ye++]=ae[Se]}B.sort(),F[_e]=B[A]}return F}function Z(ae,N){const F=Math.pow(10,N);return Math.round(ae*F)/F}function se(ae){const N=Math.round(ae);return Math.abs(ae)%1===.5?N%2===0?N:N-1:N}function ue(ae){const N=ae.length,F=ae[0].length,B=[N+1,F+1],A=Array.from({length:B[0]},()=>Array(B[1]).fill(1/0));A[0][0]=0;const _e=Array.from({length:B[0]},()=>Array(B[1]).fill(-1));for(let et=1;et0||$e>0;)switch(Se.push(ye-1),Fe.push($e-1),_e[ye][$e]){case 0:--ye,--$e;break;case 1:--ye;break;case 2:--$e;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ye}, ${$e}]. Please file a bug report.`)}return Se.reverse(),Fe.reverse(),[Se,Fe]}},"./src/utils/tensor.js":(bt,fe,l)=>{l.r(fe),l.d(fe,{Tensor:()=>xe,cat:()=>ae,full:()=>ye,full_like:()=>$e,interpolate:()=>V,interpolate_4d:()=>P,layer_norm:()=>R,matmul:()=>J,mean:()=>B,mean_pooling:()=>ie,ones:()=>Se,ones_like:()=>Fe,permute:()=>x,quantize_embeddings:()=>ct,rfft:()=>te,stack:()=>N,std_mean:()=>F,topk:()=>ne,zeros:()=>et,zeros_like:()=>Xe});var M=l("./src/utils/maths.js"),K=l("./src/backends/onnx.js"),ge=l("./src/ops/registry.js");const Me=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(...U){Te(this,"ort_tensor");return(0,K.isONNXTensor)(U[0])?this.ort_tensor=U[0]:this.ort_tensor=new K.Tensor(U[0],U[1],U[2]),new Proxy(this,{get:(pe,ke)=>{if(typeof ke=="string"){let ee=Number(ke);if(Number.isInteger(ee))return pe._getitem(ee)}return pe[ke]},set:(pe,ke,ee)=>pe[ke]=ee})}get dims(){return this.ort_tensor.dims}set dims(U){this.ort_tensor.dims=U}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[U,...pe]=this.dims;if(pe.length>0){const ke=pe.reduce((ee,Ge)=>ee*Ge);for(let ee=0;ee0){const ee=ke.reduce((Ge,dt)=>Ge*dt);return this._subarray(U,ee,ke)}else return new xe(this.type,[this.data[U]],ke)}indexOf(U){const pe=this.data;for(let ke=0;keze)throw new Error(`Invalid slice: ${st}`);const re=[Math.max(xt,0),Math.min(ze,this.dims[Le])];ke.push(re),pe.push(re[1]-re[0])}else throw new Error(`Invalid slice: ${st}`)}const ee=ke.map(([Le,st])=>st-Le),Ge=ee.reduce((Le,st)=>Le*st),dt=this.data,tt=new dt.constructor(Ge),ot=this.stride();for(let Le=0;Le=0;--xt){const re=ee[xt];st+=(ze%re+ke[xt][0])*ot[xt],ze=Math.floor(ze/re)}tt[Le]=dt[st]}return new xe(this.type,tt,pe)}permute(...U){return x(this,U)}transpose(...U){return this.permute(...U)}sum(U=null,pe=!1){return this.norm(1,U,pe)}norm(U="fro",pe=null,ke=!1){if(U==="fro")U=2;else if(typeof U=="string")throw Error(`Unsupported norm: ${U}`);const ee=this.data;if(pe===null){let tt=ee.reduce((ot,Le)=>ot+Le**U,0)**(1/U);return new xe(this.type,[tt],[])}pe=ue(pe,this.dims.length);const Ge=this.dims.slice();Ge[pe]=1;const dt=new ee.constructor(ee.length/this.dims[pe]);for(let tt=0;tt=0;--Le){const ze=this.dims[Le];if(Le!==pe){const re=st%ze;ot+=re*xt,xt*=Ge[Le]}st=Math.floor(st/ze)}dt[ot]+=ee[tt]**U}if(U!==1)for(let tt=0;tt=0;--ot){const xt=this.dims[ot];if(ot!==pe){const ze=Le%xt;tt+=ze*st,st*=this.dims[ot]}Le=Math.floor(Le/xt)}ee[dt]/=Ge[tt]}return this}normalize(U=2,pe=1){return this.clone().normalize_(U,pe)}stride(){return A(this.dims)}squeeze(U=null){return new xe(this.type,this.data,Z(this.dims,U))}squeeze_(U=null){return this.dims=Z(this.dims,U),this}unsqueeze(U=null){return new xe(this.type,this.data,se(this.dims,U))}unsqueeze_(U=null){return this.dims=se(this.dims,U),this}flatten_(U=0,pe=-1){pe=(pe+this.dims.length)%this.dims.length;let ke=this.dims.slice(0,U),ee=this.dims.slice(U,pe+1),Ge=this.dims.slice(pe+1);return this.dims=[...ke,ee.reduce((dt,tt)=>dt*tt,1),...Ge],this}flatten(U=0,pe=-1){return this.clone().flatten_(U,pe)}view(...U){let pe=-1;for(let ee=0;eett!==pe?Ge*dt:Ge,1);U[pe]=ke.length/ee}return new xe(this.type,ke,U)}neg_(){const U=this.data;for(let pe=0;peGe*dt);if(pe!==ke)throw Error(`cannot reshape array of size ${pe} into shape (${U})`);let ee=we;for(let Ge=U.length-1;Ge>=0;Ge--)ee=ee.reduce((dt,tt)=>{let ot=dt[dt.length-1];return ot.lengthpe!==1):typeof U=="number"?we[U]===1&&we.splice(U,1):Array.isArray(U)&&(we=we.filter((pe,ke)=>pe!==1||!U.includes(ke))),we}function se(we,U){return U=ue(U,we.length+1),we=we.slice(),we.splice(U,0,1),we}function ue(we,U,pe=null,ke=!0){if(ke&&(we<-U||we>=U))throw new Error(`IndexError: index ${we} is out of bounds for dimension${pe===null?"":" "+pe} with size ${U}`);return we<0&&(we=(we%U+U)%U),we}function ae(we,U=0){U=ue(U,we[0].dims.length);const pe=we[0].dims.slice();pe[U]=we.reduce((dt,tt)=>dt+tt.dims[U],0);const ke=pe.reduce((dt,tt)=>dt*tt,1),ee=new we[0].data.constructor(ke),Ge=we[0].type;if(U===0){let dt=0;for(const tt of we){const ot=tt.data;ee.set(ot,dt),dt+=ot.length}}else{let dt=0;for(let tt=0;tt=0;--ze){const Ve=Le[ze];let Ue=re%Ve;ze===U&&(Ue+=dt),xt+=Ue*Ce,Ce*=pe[ze],re=Math.floor(re/Ve)}ee[xt]=ot[st]}dt+=Le[U]}}return new xe(Ge,ee,pe)}function N(we,U=0){return ae(we.map(pe=>pe.unsqueeze(U)),U)}function F(we,U=null,pe=1,ke=!1){const ee=we.data,Ge=we.dims;if(U===null){const ze=ee.reduce((Ue,je)=>Ue+je,0)/ee.length,re=Math.sqrt(ee.reduce((Ue,je)=>Ue+(je-ze)**2,0)/(ee.length-pe)),Ce=new xe(we.type,[ze],[]);return[new xe(we.type,[re],[]),Ce]}U=ue(U,Ge.length);const dt=B(we,U,ke),tt=dt.data,ot=Ge.slice();ot[U]=1;const Le=new ee.constructor(ee.length/Ge[U]);for(let xt=0;xt=0;--re){const Ue=Ge[re];if(re!==U){const je=Ce%Ue;ze+=je*Ve,Ve*=ot[re]}Ce=Math.floor(Ce/Ue)}Le[ze]+=(ee[xt]-tt[ze])**2}for(let xt=0;xtot+Le,0);return new xe(we.type,[tt/ke.length],[])}const ee=we.dims;U=ue(U,ee.length);const Ge=ee.slice();Ge[U]=1;const dt=new ke.constructor(ke.length/ee[U]);for(let tt=0;tt=0;--Le){const ze=ee[Le];if(Le!==U){const re=st%ze;ot+=re*xt,xt*=Ge[Le]}st=Math.floor(st/ze)}dt[ot]+=ke[tt]}if(ee[U]!==1)for(let tt=0;tt=0;--pe)U[pe]=ke,ke*=we[pe];return U}function _e(we,U,pe,ke){const ee=we.reduce((Ge,dt)=>Ge*dt,1);return new xe(pe,new ke(ee).fill(U),we)}function ye(we,U){let pe,ke;if(typeof U=="number")pe="float32",ke=Float32Array;else if(typeof U=="bigint")pe="int64",ke=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof U}`);return _e(we,U,pe,ke)}function $e(we,U){return ye(we.dims,U)}function Se(we){return _e(we,1n,"int64",BigInt64Array)}function Fe(we){return Se(we.dims)}function et(we){return _e(we,0n,"int64",BigInt64Array)}function Xe(we){return et(we.dims)}function ct(we,U){if(we.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(we.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(U))throw new Error("The precision must be either 'binary' or 'ubinary'");const pe=U==="binary",ke=pe?"int8":"uint8",ee=pe?Int8Array:Uint8Array,Ge=we.data,dt=new ee(Ge.length/8);for(let tt=0;tt0?1:0,Le=Math.floor(tt/8),st=tt%8;dt[Le]|=ot<<7-st,pe&&st===0&&(dt[Le]-=128)}return new xe(ke,dt,[we.dims[0],we.dims[1]/8])}}},Ls={};function Nr(bt){var fe=Ls[bt];if(fe!==void 0)return fe.exports;var l=Ls[bt]={exports:{}};return ts[bt](l,l.exports,Nr),l.exports}(()=>{var bt=Object.getPrototypeOf?l=>Object.getPrototypeOf(l):l=>l.__proto__,fe;Nr.t=function(l,M){if(M&1&&(l=this(l)),M&8||typeof l=="object"&&l&&(M&4&&l.__esModule||M&16&&typeof l.then=="function"))return l;var K=Object.create(null);Nr.r(K);var ge={};fe=fe||[null,bt({}),bt([]),bt(bt)];for(var Me=M&2&&l;typeof Me=="object"&&!~fe.indexOf(Me);Me=bt(Me))Object.getOwnPropertyNames(Me).forEach(xe=>ge[xe]=()=>l[xe]);return ge.default=()=>l,Nr.d(K,ge),K}})(),Nr.d=(bt,fe)=>{for(var l in fe)Nr.o(fe,l)&&!Nr.o(bt,l)&&Object.defineProperty(bt,l,{enumerable:!0,get:fe[l]})},Nr.o=(bt,fe)=>Object.prototype.hasOwnProperty.call(bt,fe),Nr.r=bt=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(bt,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(bt,"__esModule",{value:!0})},(()=>{var bt;if(typeof self.location.href=="string"&&(bt=self.location.href),!bt)throw new Error("Automatic publicPath is not supported in this browser");bt=bt.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Nr.p=bt})(),Nr.b=void 0;var h={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/Nr.r(h),Nr.d(h,{ASTFeatureExtractor:()=>K.ASTFeatureExtractor,ASTForAudioClassification:()=>l.ASTForAudioClassification,ASTModel:()=>l.ASTModel,ASTPreTrainedModel:()=>l.ASTPreTrainedModel,AlbertForMaskedLM:()=>l.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>l.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>l.AlbertForSequenceClassification,AlbertModel:()=>l.AlbertModel,AlbertPreTrainedModel:()=>l.AlbertPreTrainedModel,AlbertTokenizer:()=>M.AlbertTokenizer,AudioClassificationPipeline:()=>fe.AudioClassificationPipeline,AutoConfig:()=>ge.AutoConfig,AutoModel:()=>l.AutoModel,AutoModelForAudioClassification:()=>l.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>l.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>l.AutoModelForCTC,AutoModelForCausalLM:()=>l.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>l.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>l.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>l.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>l.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>l.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>l.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>l.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>l.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>l.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>l.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>l.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>l.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>l.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>l.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>l.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>l.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>l.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>l.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>l.AutoModelForVision2Seq,AutoModelForXVector:()=>l.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>l.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>K.AutoProcessor,AutoTokenizer:()=>M.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>fe.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>l.BartForConditionalGeneration,BartForSequenceClassification:()=>l.BartForSequenceClassification,BartModel:()=>l.BartModel,BartPretrainedModel:()=>l.BartPretrainedModel,BartTokenizer:()=>M.BartTokenizer,BaseModelOutput:()=>l.BaseModelOutput,BaseStreamer:()=>V.BaseStreamer,BeitFeatureExtractor:()=>K.BeitFeatureExtractor,BeitForImageClassification:()=>l.BeitForImageClassification,BeitModel:()=>l.BeitModel,BeitPreTrainedModel:()=>l.BeitPreTrainedModel,BertForMaskedLM:()=>l.BertForMaskedLM,BertForQuestionAnswering:()=>l.BertForQuestionAnswering,BertForSequenceClassification:()=>l.BertForSequenceClassification,BertForTokenClassification:()=>l.BertForTokenClassification,BertModel:()=>l.BertModel,BertPreTrainedModel:()=>l.BertPreTrainedModel,BertTokenizer:()=>M.BertTokenizer,BitImageProcessor:()=>K.BitImageProcessor,BlenderbotForConditionalGeneration:()=>l.BlenderbotForConditionalGeneration,BlenderbotModel:()=>l.BlenderbotModel,BlenderbotPreTrainedModel:()=>l.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>l.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>l.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>l.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>M.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>M.BlenderbotTokenizer,BloomForCausalLM:()=>l.BloomForCausalLM,BloomModel:()=>l.BloomModel,BloomPreTrainedModel:()=>l.BloomPreTrainedModel,BloomTokenizer:()=>M.BloomTokenizer,CLIPFeatureExtractor:()=>K.CLIPFeatureExtractor,CLIPImageProcessor:()=>K.CLIPImageProcessor,CLIPModel:()=>l.CLIPModel,CLIPPreTrainedModel:()=>l.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>l.CLIPSegForImageSegmentation,CLIPSegModel:()=>l.CLIPSegModel,CLIPSegPreTrainedModel:()=>l.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>l.CLIPTextModelWithProjection,CLIPTokenizer:()=>M.CLIPTokenizer,CLIPVisionModelWithProjection:()=>l.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>l.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>l.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>l.CamembertForSequenceClassification,CamembertForTokenClassification:()=>l.CamembertForTokenClassification,CamembertModel:()=>l.CamembertModel,CamembertPreTrainedModel:()=>l.CamembertPreTrainedModel,CamembertTokenizer:()=>M.CamembertTokenizer,CausalLMOutput:()=>l.CausalLMOutput,CausalLMOutputWithPast:()=>l.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>K.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>l.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>l.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>l.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>K.ClapFeatureExtractor,ClapModel:()=>l.ClapModel,ClapPreTrainedModel:()=>l.ClapPreTrainedModel,ClapTextModelWithProjection:()=>l.ClapTextModelWithProjection,CodeGenForCausalLM:()=>l.CodeGenForCausalLM,CodeGenModel:()=>l.CodeGenModel,CodeGenPreTrainedModel:()=>l.CodeGenPreTrainedModel,CodeGenTokenizer:()=>M.CodeGenTokenizer,CodeLlamaTokenizer:()=>M.CodeLlamaTokenizer,CohereForCausalLM:()=>l.CohereForCausalLM,CohereModel:()=>l.CohereModel,CoherePreTrainedModel:()=>l.CoherePreTrainedModel,CohereTokenizer:()=>M.CohereTokenizer,ConvBertForMaskedLM:()=>l.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>l.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>l.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>l.ConvBertForTokenClassification,ConvBertModel:()=>l.ConvBertModel,ConvBertPreTrainedModel:()=>l.ConvBertPreTrainedModel,ConvBertTokenizer:()=>M.ConvBertTokenizer,ConvNextFeatureExtractor:()=>K.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>l.ConvNextForImageClassification,ConvNextImageProcessor:()=>K.ConvNextImageProcessor,ConvNextModel:()=>l.ConvNextModel,ConvNextPreTrainedModel:()=>l.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>l.ConvNextV2ForImageClassification,ConvNextV2Model:()=>l.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>l.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>K.DPTFeatureExtractor,DPTForDepthEstimation:()=>l.DPTForDepthEstimation,DPTImageProcessor:()=>K.DPTImageProcessor,DPTModel:()=>l.DPTModel,DPTPreTrainedModel:()=>l.DPTPreTrainedModel,DebertaForMaskedLM:()=>l.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>l.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>l.DebertaForSequenceClassification,DebertaForTokenClassification:()=>l.DebertaForTokenClassification,DebertaModel:()=>l.DebertaModel,DebertaPreTrainedModel:()=>l.DebertaPreTrainedModel,DebertaTokenizer:()=>M.DebertaTokenizer,DebertaV2ForMaskedLM:()=>l.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>l.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>l.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>l.DebertaV2ForTokenClassification,DebertaV2Model:()=>l.DebertaV2Model,DebertaV2PreTrainedModel:()=>l.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>M.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>K.DeiTFeatureExtractor,DeiTForImageClassification:()=>l.DeiTForImageClassification,DeiTModel:()=>l.DeiTModel,DeiTPreTrainedModel:()=>l.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>l.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>l.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>fe.DepthEstimationPipeline,DetrFeatureExtractor:()=>K.DetrFeatureExtractor,DetrForObjectDetection:()=>l.DetrForObjectDetection,DetrForSegmentation:()=>l.DetrForSegmentation,DetrModel:()=>l.DetrModel,DetrObjectDetectionOutput:()=>l.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>l.DetrPreTrainedModel,DetrSegmentationOutput:()=>l.DetrSegmentationOutput,Dinov2ForImageClassification:()=>l.Dinov2ForImageClassification,Dinov2Model:()=>l.Dinov2Model,Dinov2PreTrainedModel:()=>l.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>l.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>l.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>l.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>l.DistilBertForTokenClassification,DistilBertModel:()=>l.DistilBertModel,DistilBertPreTrainedModel:()=>l.DistilBertPreTrainedModel,DistilBertTokenizer:()=>M.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>fe.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>K.DonutFeatureExtractor,DonutSwinModel:()=>l.DonutSwinModel,DonutSwinPreTrainedModel:()=>l.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>l.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>K.EfficientNetImageProcessor,EfficientNetModel:()=>l.EfficientNetModel,EfficientNetPreTrainedModel:()=>l.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>l.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>l.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>l.ElectraForSequenceClassification,ElectraForTokenClassification:()=>l.ElectraForTokenClassification,ElectraModel:()=>l.ElectraModel,ElectraPreTrainedModel:()=>l.ElectraPreTrainedModel,ElectraTokenizer:()=>M.ElectraTokenizer,EosTokenCriteria:()=>P.EosTokenCriteria,EsmForMaskedLM:()=>l.EsmForMaskedLM,EsmForSequenceClassification:()=>l.EsmForSequenceClassification,EsmForTokenClassification:()=>l.EsmForTokenClassification,EsmModel:()=>l.EsmModel,EsmPreTrainedModel:()=>l.EsmPreTrainedModel,EsmTokenizer:()=>M.EsmTokenizer,FFT:()=>x.FFT,FalconForCausalLM:()=>l.FalconForCausalLM,FalconModel:()=>l.FalconModel,FalconPreTrainedModel:()=>l.FalconPreTrainedModel,FalconTokenizer:()=>M.FalconTokenizer,FastViTForImageClassification:()=>l.FastViTForImageClassification,FastViTModel:()=>l.FastViTModel,FastViTPreTrainedModel:()=>l.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>fe.FeatureExtractionPipeline,FeatureExtractor:()=>K.FeatureExtractor,FillMaskPipeline:()=>fe.FillMaskPipeline,Florence2ForConditionalGeneration:()=>l.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>l.Florence2PreTrainedModel,Florence2Processor:()=>K.Florence2Processor,GLPNFeatureExtractor:()=>K.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>l.GLPNForDepthEstimation,GLPNModel:()=>l.GLPNModel,GLPNPreTrainedModel:()=>l.GLPNPreTrainedModel,GPT2LMHeadModel:()=>l.GPT2LMHeadModel,GPT2Model:()=>l.GPT2Model,GPT2PreTrainedModel:()=>l.GPT2PreTrainedModel,GPT2Tokenizer:()=>M.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>l.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>l.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>l.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>l.GPTJForCausalLM,GPTJModel:()=>l.GPTJModel,GPTJPreTrainedModel:()=>l.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>l.GPTNeoForCausalLM,GPTNeoModel:()=>l.GPTNeoModel,GPTNeoPreTrainedModel:()=>l.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>l.GPTNeoXForCausalLM,GPTNeoXModel:()=>l.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>l.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>M.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>l.Gemma2ForCausalLM,Gemma2Model:()=>l.Gemma2Model,Gemma2PreTrainedModel:()=>l.Gemma2PreTrainedModel,GemmaForCausalLM:()=>l.GemmaForCausalLM,GemmaModel:()=>l.GemmaModel,GemmaPreTrainedModel:()=>l.GemmaPreTrainedModel,GemmaTokenizer:()=>M.GemmaTokenizer,Grok1Tokenizer:()=>M.Grok1Tokenizer,HerbertTokenizer:()=>M.HerbertTokenizer,HubertForCTC:()=>l.HubertForCTC,HubertForSequenceClassification:()=>l.HubertForSequenceClassification,HubertModel:()=>l.HubertModel,HubertPreTrainedModel:()=>l.HubertPreTrainedModel,ImageClassificationPipeline:()=>fe.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>fe.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>K.ImageFeatureExtractor,ImageMattingOutput:()=>l.ImageMattingOutput,ImageSegmentationPipeline:()=>fe.ImageSegmentationPipeline,ImageToImagePipeline:()=>fe.ImageToImagePipeline,ImageToTextPipeline:()=>fe.ImageToTextPipeline,InterruptableStoppingCriteria:()=>P.InterruptableStoppingCriteria,LlamaForCausalLM:()=>l.LlamaForCausalLM,LlamaModel:()=>l.LlamaModel,LlamaPreTrainedModel:()=>l.LlamaPreTrainedModel,LlamaTokenizer:()=>M.LlamaTokenizer,LlavaForConditionalGeneration:()=>l.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>l.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>l.LongT5ForConditionalGeneration,LongT5Model:()=>l.LongT5Model,LongT5PreTrainedModel:()=>l.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>l.M2M100ForConditionalGeneration,M2M100Model:()=>l.M2M100Model,M2M100PreTrainedModel:()=>l.M2M100PreTrainedModel,M2M100Tokenizer:()=>M.M2M100Tokenizer,MBart50Tokenizer:()=>M.MBart50Tokenizer,MBartForCausalLM:()=>l.MBartForCausalLM,MBartForConditionalGeneration:()=>l.MBartForConditionalGeneration,MBartForSequenceClassification:()=>l.MBartForSequenceClassification,MBartModel:()=>l.MBartModel,MBartPreTrainedModel:()=>l.MBartPreTrainedModel,MBartTokenizer:()=>M.MBartTokenizer,MPNetForMaskedLM:()=>l.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>l.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>l.MPNetForSequenceClassification,MPNetForTokenClassification:()=>l.MPNetForTokenClassification,MPNetModel:()=>l.MPNetModel,MPNetPreTrainedModel:()=>l.MPNetPreTrainedModel,MPNetTokenizer:()=>M.MPNetTokenizer,MT5ForConditionalGeneration:()=>l.MT5ForConditionalGeneration,MT5Model:()=>l.MT5Model,MT5PreTrainedModel:()=>l.MT5PreTrainedModel,MarianMTModel:()=>l.MarianMTModel,MarianModel:()=>l.MarianModel,MarianPreTrainedModel:()=>l.MarianPreTrainedModel,MarianTokenizer:()=>M.MarianTokenizer,MaskedLMOutput:()=>l.MaskedLMOutput,MaxLengthCriteria:()=>P.MaxLengthCriteria,MistralForCausalLM:()=>l.MistralForCausalLM,MistralModel:()=>l.MistralModel,MistralPreTrainedModel:()=>l.MistralPreTrainedModel,MobileBertForMaskedLM:()=>l.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>l.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>l.MobileBertForSequenceClassification,MobileBertModel:()=>l.MobileBertModel,MobileBertPreTrainedModel:()=>l.MobileBertPreTrainedModel,MobileBertTokenizer:()=>M.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>K.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>l.MobileNetV1ForImageClassification,MobileNetV1Model:()=>l.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>l.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>K.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>l.MobileNetV2ForImageClassification,MobileNetV2Model:()=>l.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>l.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>K.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>l.MobileNetV3ForImageClassification,MobileNetV3Model:()=>l.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>l.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>K.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>l.MobileNetV4ForImageClassification,MobileNetV4Model:()=>l.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>l.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>K.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>l.MobileViTForImageClassification,MobileViTImageProcessor:()=>K.MobileViTImageProcessor,MobileViTModel:()=>l.MobileViTModel,MobileViTPreTrainedModel:()=>l.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>l.MobileViTV2ForImageClassification,MobileViTV2Model:()=>l.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>l.MobileViTV2PreTrainedModel,ModelOutput:()=>l.ModelOutput,Moondream1ForConditionalGeneration:()=>l.Moondream1ForConditionalGeneration,MptForCausalLM:()=>l.MptForCausalLM,MptModel:()=>l.MptModel,MptPreTrainedModel:()=>l.MptPreTrainedModel,MusicgenForCausalLM:()=>l.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>l.MusicgenForConditionalGeneration,MusicgenModel:()=>l.MusicgenModel,MusicgenPreTrainedModel:()=>l.MusicgenPreTrainedModel,NllbTokenizer:()=>M.NllbTokenizer,NomicBertModel:()=>l.NomicBertModel,NomicBertPreTrainedModel:()=>l.NomicBertPreTrainedModel,NougatImageProcessor:()=>K.NougatImageProcessor,NougatTokenizer:()=>M.NougatTokenizer,OPTForCausalLM:()=>l.OPTForCausalLM,OPTModel:()=>l.OPTModel,OPTPreTrainedModel:()=>l.OPTPreTrainedModel,ObjectDetectionPipeline:()=>fe.ObjectDetectionPipeline,OpenELMForCausalLM:()=>l.OpenELMForCausalLM,OpenELMModel:()=>l.OpenELMModel,OpenELMPreTrainedModel:()=>l.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>K.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>l.OwlViTForObjectDetection,OwlViTModel:()=>l.OwlViTModel,OwlViTPreTrainedModel:()=>l.OwlViTPreTrainedModel,OwlViTProcessor:()=>K.OwlViTProcessor,Owlv2ForObjectDetection:()=>l.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>K.Owlv2ImageProcessor,Owlv2Model:()=>l.Owlv2Model,Owlv2PreTrainedModel:()=>l.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>l.Phi3ForCausalLM,Phi3Model:()=>l.Phi3Model,Phi3PreTrainedModel:()=>l.Phi3PreTrainedModel,PhiForCausalLM:()=>l.PhiForCausalLM,PhiModel:()=>l.PhiModel,PhiPreTrainedModel:()=>l.PhiPreTrainedModel,Pipeline:()=>fe.Pipeline,PreTrainedModel:()=>l.PreTrainedModel,PreTrainedTokenizer:()=>M.PreTrainedTokenizer,PretrainedConfig:()=>ge.PretrainedConfig,PretrainedMixin:()=>l.PretrainedMixin,Processor:()=>K.Processor,PyAnnoteFeatureExtractor:()=>K.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>l.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>l.PyAnnoteModel,PyAnnotePreTrainedModel:()=>l.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>K.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>l.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>fe.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>l.Qwen2ForCausalLM,Qwen2Model:()=>l.Qwen2Model,Qwen2PreTrainedModel:()=>l.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>M.Qwen2Tokenizer,RTDetrForObjectDetection:()=>l.RTDetrForObjectDetection,RTDetrImageProcessor:()=>K.RTDetrImageProcessor,RTDetrModel:()=>l.RTDetrModel,RTDetrObjectDetectionOutput:()=>l.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>l.RTDetrPreTrainedModel,RawImage:()=>xe.RawImage,ResNetForImageClassification:()=>l.ResNetForImageClassification,ResNetModel:()=>l.ResNetModel,ResNetPreTrainedModel:()=>l.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>l.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>l.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>l.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>l.RoFormerForTokenClassification,RoFormerModel:()=>l.RoFormerModel,RoFormerPreTrainedModel:()=>l.RoFormerPreTrainedModel,RoFormerTokenizer:()=>M.RoFormerTokenizer,RobertaForMaskedLM:()=>l.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>l.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>l.RobertaForSequenceClassification,RobertaForTokenClassification:()=>l.RobertaForTokenClassification,RobertaModel:()=>l.RobertaModel,RobertaPreTrainedModel:()=>l.RobertaPreTrainedModel,RobertaTokenizer:()=>M.RobertaTokenizer,SamImageProcessor:()=>K.SamImageProcessor,SamImageSegmentationOutput:()=>l.SamImageSegmentationOutput,SamModel:()=>l.SamModel,SamPreTrainedModel:()=>l.SamPreTrainedModel,SamProcessor:()=>K.SamProcessor,SeamlessM4TFeatureExtractor:()=>K.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>K.SegformerFeatureExtractor,SegformerForImageClassification:()=>l.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>l.SegformerForSemanticSegmentation,SegformerModel:()=>l.SegformerModel,SegformerPreTrainedModel:()=>l.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>l.Seq2SeqLMOutput,SequenceClassifierOutput:()=>l.SequenceClassifierOutput,SiglipImageProcessor:()=>K.SiglipImageProcessor,SiglipModel:()=>l.SiglipModel,SiglipPreTrainedModel:()=>l.SiglipPreTrainedModel,SiglipTextModel:()=>l.SiglipTextModel,SiglipTokenizer:()=>M.SiglipTokenizer,SiglipVisionModel:()=>l.SiglipVisionModel,SpeechT5FeatureExtractor:()=>K.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>l.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>l.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>l.SpeechT5HifiGan,SpeechT5Model:()=>l.SpeechT5Model,SpeechT5PreTrainedModel:()=>l.SpeechT5PreTrainedModel,SpeechT5Processor:()=>K.SpeechT5Processor,SpeechT5Tokenizer:()=>M.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>l.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>l.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>l.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>l.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>l.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>M.SqueezeBertTokenizer,StableLmForCausalLM:()=>l.StableLmForCausalLM,StableLmModel:()=>l.StableLmModel,StableLmPreTrainedModel:()=>l.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>l.Starcoder2ForCausalLM,Starcoder2Model:()=>l.Starcoder2Model,Starcoder2PreTrainedModel:()=>l.Starcoder2PreTrainedModel,StoppingCriteria:()=>P.StoppingCriteria,StoppingCriteriaList:()=>P.StoppingCriteriaList,SummarizationPipeline:()=>fe.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>l.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>K.Swin2SRImageProcessor,Swin2SRModel:()=>l.Swin2SRModel,Swin2SRPreTrainedModel:()=>l.Swin2SRPreTrainedModel,SwinForImageClassification:()=>l.SwinForImageClassification,SwinModel:()=>l.SwinModel,SwinPreTrainedModel:()=>l.SwinPreTrainedModel,T5ForConditionalGeneration:()=>l.T5ForConditionalGeneration,T5Model:()=>l.T5Model,T5PreTrainedModel:()=>l.T5PreTrainedModel,T5Tokenizer:()=>M.T5Tokenizer,TableTransformerForObjectDetection:()=>l.TableTransformerForObjectDetection,TableTransformerModel:()=>l.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>l.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>l.TableTransformerPreTrainedModel,Tensor:()=>D.Tensor,Text2TextGenerationPipeline:()=>fe.Text2TextGenerationPipeline,TextClassificationPipeline:()=>fe.TextClassificationPipeline,TextGenerationPipeline:()=>fe.TextGenerationPipeline,TextStreamer:()=>V.TextStreamer,TextToAudioPipeline:()=>fe.TextToAudioPipeline,TokenClassificationPipeline:()=>fe.TokenClassificationPipeline,TokenClassifierOutput:()=>l.TokenClassifierOutput,TokenizerModel:()=>M.TokenizerModel,TrOCRForCausalLM:()=>l.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>l.TrOCRPreTrainedModel,TranslationPipeline:()=>fe.TranslationPipeline,UniSpeechForCTC:()=>l.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>l.UniSpeechForSequenceClassification,UniSpeechModel:()=>l.UniSpeechModel,UniSpeechPreTrainedModel:()=>l.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>l.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>l.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>l.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>l.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>l.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>K.ViTFeatureExtractor,ViTForImageClassification:()=>l.ViTForImageClassification,ViTImageProcessor:()=>K.ViTImageProcessor,ViTModel:()=>l.ViTModel,ViTPreTrainedModel:()=>l.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>l.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>l.VitMatteForImageMatting,VitMatteImageProcessor:()=>K.VitMatteImageProcessor,VitMattePreTrainedModel:()=>l.VitMattePreTrainedModel,VitsModel:()=>l.VitsModel,VitsModelOutput:()=>l.VitsModelOutput,VitsPreTrainedModel:()=>l.VitsPreTrainedModel,VitsTokenizer:()=>M.VitsTokenizer,Wav2Vec2BertForCTC:()=>l.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>l.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>l.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>l.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>M.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>K.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>l.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>l.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>l.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>l.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>l.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>K.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>l.WavLMForAudioFrameClassification,WavLMForCTC:()=>l.WavLMForCTC,WavLMForSequenceClassification:()=>l.WavLMForSequenceClassification,WavLMForXVector:()=>l.WavLMForXVector,WavLMModel:()=>l.WavLMModel,WavLMPreTrainedModel:()=>l.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>K.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>l.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>l.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>K.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>l.WhisperForConditionalGeneration,WhisperModel:()=>l.WhisperModel,WhisperPreTrainedModel:()=>l.WhisperPreTrainedModel,WhisperProcessor:()=>K.WhisperProcessor,WhisperTextStreamer:()=>V.WhisperTextStreamer,WhisperTokenizer:()=>M.WhisperTokenizer,XLMForQuestionAnswering:()=>l.XLMForQuestionAnswering,XLMForSequenceClassification:()=>l.XLMForSequenceClassification,XLMForTokenClassification:()=>l.XLMForTokenClassification,XLMModel:()=>l.XLMModel,XLMPreTrainedModel:()=>l.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>l.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>l.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>l.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>l.XLMRobertaForTokenClassification,XLMRobertaModel:()=>l.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>l.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>M.XLMRobertaTokenizer,XLMTokenizer:()=>M.XLMTokenizer,XLMWithLMHeadModel:()=>l.XLMWithLMHeadModel,XVectorOutput:()=>l.XVectorOutput,YolosFeatureExtractor:()=>K.YolosFeatureExtractor,YolosForObjectDetection:()=>l.YolosForObjectDetection,YolosModel:()=>l.YolosModel,YolosObjectDetectionOutput:()=>l.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>l.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>fe.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>fe.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>fe.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>fe.ZeroShotObjectDetectionPipeline,bankers_round:()=>x.bankers_round,cat:()=>D.cat,cos_sim:()=>x.cos_sim,dot:()=>x.dot,dynamic_time_warping:()=>x.dynamic_time_warping,env:()=>bt.env,full:()=>D.full,full_like:()=>D.full_like,getKeyValueShapes:()=>ge.getKeyValueShapes,hamming:()=>Me.hamming,hanning:()=>Me.hanning,interpolate:()=>D.interpolate,interpolate_4d:()=>D.interpolate_4d,interpolate_data:()=>x.interpolate_data,is_chinese_char:()=>M.is_chinese_char,layer_norm:()=>D.layer_norm,log_softmax:()=>x.log_softmax,magnitude:()=>x.magnitude,matmul:()=>D.matmul,max:()=>x.max,mean:()=>D.mean,mean_pooling:()=>D.mean_pooling,medianFilter:()=>x.medianFilter,mel_filter_bank:()=>Me.mel_filter_bank,min:()=>x.min,ones:()=>D.ones,ones_like:()=>D.ones_like,permute:()=>D.permute,permute_data:()=>x.permute_data,pipeline:()=>fe.pipeline,quantize_embeddings:()=>D.quantize_embeddings,read_audio:()=>Me.read_audio,rfft:()=>D.rfft,round:()=>x.round,softmax:()=>x.softmax,spectrogram:()=>Me.spectrogram,stack:()=>D.stack,std_mean:()=>D.std_mean,topk:()=>D.topk,window_function:()=>Me.window_function,zeros:()=>D.zeros,zeros_like:()=>D.zeros_like});var bt=Nr("./src/env.js"),fe=Nr("./src/pipelines.js"),l=Nr("./src/models.js"),M=Nr("./src/tokenizers.js"),K=Nr("./src/processors.js"),ge=Nr("./src/configs.js"),Me=Nr("./src/utils/audio.js"),xe=Nr("./src/utils/image.js"),D=Nr("./src/utils/tensor.js"),x=Nr("./src/utils/maths.js"),V=Nr("./src/generation/streamers.js"),P=Nr("./src/generation/stopping_criteria.js")})(),h.ASTFeatureExtractor,h.ASTForAudioClassification,h.ASTModel,h.ASTPreTrainedModel,h.AlbertForMaskedLM,h.AlbertForQuestionAnswering,h.AlbertForSequenceClassification,h.AlbertModel,h.AlbertPreTrainedModel,h.AlbertTokenizer,h.AudioClassificationPipeline,h.AutoConfig,h.AutoModel,h.AutoModelForAudioClassification,h.AutoModelForAudioFrameClassification,h.AutoModelForCTC;var Kh=h.AutoModelForCausalLM;h.AutoModelForDepthEstimation,h.AutoModelForDocumentQuestionAnswering,h.AutoModelForImageClassification,h.AutoModelForImageFeatureExtraction,h.AutoModelForImageMatting,h.AutoModelForImageSegmentation,h.AutoModelForImageToImage,h.AutoModelForMaskGeneration,h.AutoModelForMaskedLM,h.AutoModelForObjectDetection,h.AutoModelForQuestionAnswering,h.AutoModelForSemanticSegmentation,h.AutoModelForSeq2SeqLM,h.AutoModelForSequenceClassification,h.AutoModelForSpeechSeq2Seq,h.AutoModelForTextToSpectrogram,h.AutoModelForTextToWaveform,h.AutoModelForTokenClassification,h.AutoModelForVision2Seq,h.AutoModelForXVector,h.AutoModelForZeroShotObjectDetection,h.AutoProcessor;var Xh=h.AutoTokenizer;h.AutomaticSpeechRecognitionPipeline,h.BartForConditionalGeneration,h.BartForSequenceClassification,h.BartModel,h.BartPretrainedModel,h.BartTokenizer,h.BaseModelOutput,h.BaseStreamer,h.BeitFeatureExtractor,h.BeitForImageClassification,h.BeitModel,h.BeitPreTrainedModel,h.BertForMaskedLM,h.BertForQuestionAnswering,h.BertForSequenceClassification,h.BertForTokenClassification,h.BertModel,h.BertPreTrainedModel,h.BertTokenizer,h.BitImageProcessor,h.BlenderbotForConditionalGeneration,h.BlenderbotModel,h.BlenderbotPreTrainedModel,h.BlenderbotSmallForConditionalGeneration,h.BlenderbotSmallModel,h.BlenderbotSmallPreTrainedModel,h.BlenderbotSmallTokenizer,h.BlenderbotTokenizer,h.BloomForCausalLM,h.BloomModel,h.BloomPreTrainedModel,h.BloomTokenizer,h.CLIPFeatureExtractor,h.CLIPImageProcessor,h.CLIPModel,h.CLIPPreTrainedModel,h.CLIPSegForImageSegmentation,h.CLIPSegModel,h.CLIPSegPreTrainedModel,h.CLIPTextModelWithProjection,h.CLIPTokenizer,h.CLIPVisionModelWithProjection,h.CamembertForMaskedLM,h.CamembertForQuestionAnswering,h.CamembertForSequenceClassification,h.CamembertForTokenClassification,h.CamembertModel,h.CamembertPreTrainedModel,h.CamembertTokenizer,h.CausalLMOutput,h.CausalLMOutputWithPast,h.ChineseCLIPFeatureExtractor,h.ChineseCLIPModel,h.ChineseCLIPPreTrainedModel,h.ClapAudioModelWithProjection,h.ClapFeatureExtractor,h.ClapModel,h.ClapPreTrainedModel,h.ClapTextModelWithProjection,h.CodeGenForCausalLM,h.CodeGenModel,h.CodeGenPreTrainedModel,h.CodeGenTokenizer,h.CodeLlamaTokenizer,h.CohereForCausalLM,h.CohereModel,h.CoherePreTrainedModel,h.CohereTokenizer,h.ConvBertForMaskedLM,h.ConvBertForQuestionAnswering,h.ConvBertForSequenceClassification,h.ConvBertForTokenClassification,h.ConvBertModel,h.ConvBertPreTrainedModel,h.ConvBertTokenizer,h.ConvNextFeatureExtractor,h.ConvNextForImageClassification,h.ConvNextImageProcessor,h.ConvNextModel,h.ConvNextPreTrainedModel,h.ConvNextV2ForImageClassification,h.ConvNextV2Model,h.ConvNextV2PreTrainedModel,h.DPTFeatureExtractor,h.DPTForDepthEstimation,h.DPTImageProcessor,h.DPTModel,h.DPTPreTrainedModel,h.DebertaForMaskedLM,h.DebertaForQuestionAnswering,h.DebertaForSequenceClassification,h.DebertaForTokenClassification,h.DebertaModel,h.DebertaPreTrainedModel,h.DebertaTokenizer,h.DebertaV2ForMaskedLM,h.DebertaV2ForQuestionAnswering,h.DebertaV2ForSequenceClassification,h.DebertaV2ForTokenClassification,h.DebertaV2Model,h.DebertaV2PreTrainedModel,h.DebertaV2Tokenizer,h.DeiTFeatureExtractor,h.DeiTForImageClassification,h.DeiTModel,h.DeiTPreTrainedModel,h.DepthAnythingForDepthEstimation,h.DepthAnythingPreTrainedModel,h.DepthEstimationPipeline,h.DetrFeatureExtractor,h.DetrForObjectDetection,h.DetrForSegmentation,h.DetrModel,h.DetrObjectDetectionOutput,h.DetrPreTrainedModel,h.DetrSegmentationOutput,h.Dinov2ForImageClassification,h.Dinov2Model,h.Dinov2PreTrainedModel,h.DistilBertForMaskedLM,h.DistilBertForQuestionAnswering,h.DistilBertForSequenceClassification,h.DistilBertForTokenClassification,h.DistilBertModel,h.DistilBertPreTrainedModel,h.DistilBertTokenizer,h.DocumentQuestionAnsweringPipeline,h.DonutFeatureExtractor,h.DonutSwinModel,h.DonutSwinPreTrainedModel,h.EfficientNetForImageClassification,h.EfficientNetImageProcessor,h.EfficientNetModel,h.EfficientNetPreTrainedModel,h.ElectraForMaskedLM,h.ElectraForQuestionAnswering,h.ElectraForSequenceClassification,h.ElectraForTokenClassification,h.ElectraModel,h.ElectraPreTrainedModel,h.ElectraTokenizer,h.EosTokenCriteria,h.EsmForMaskedLM,h.EsmForSequenceClassification,h.EsmForTokenClassification,h.EsmModel,h.EsmPreTrainedModel,h.EsmTokenizer,h.FFT,h.FalconForCausalLM,h.FalconModel,h.FalconPreTrainedModel,h.FalconTokenizer,h.FastViTForImageClassification,h.FastViTModel,h.FastViTPreTrainedModel,h.FeatureExtractionPipeline,h.FeatureExtractor,h.FillMaskPipeline,h.Florence2ForConditionalGeneration,h.Florence2PreTrainedModel,h.Florence2Processor,h.GLPNFeatureExtractor,h.GLPNForDepthEstimation,h.GLPNModel,h.GLPNPreTrainedModel,h.GPT2LMHeadModel,h.GPT2Model,h.GPT2PreTrainedModel,h.GPT2Tokenizer,h.GPTBigCodeForCausalLM,h.GPTBigCodeModel,h.GPTBigCodePreTrainedModel,h.GPTJForCausalLM,h.GPTJModel,h.GPTJPreTrainedModel,h.GPTNeoForCausalLM,h.GPTNeoModel,h.GPTNeoPreTrainedModel,h.GPTNeoXForCausalLM,h.GPTNeoXModel,h.GPTNeoXPreTrainedModel,h.GPTNeoXTokenizer,h.Gemma2ForCausalLM,h.Gemma2Model,h.Gemma2PreTrainedModel,h.GemmaForCausalLM,h.GemmaModel,h.GemmaPreTrainedModel,h.GemmaTokenizer,h.Grok1Tokenizer,h.HerbertTokenizer,h.HubertForCTC,h.HubertForSequenceClassification,h.HubertModel,h.HubertPreTrainedModel,h.ImageClassificationPipeline,h.ImageFeatureExtractionPipeline,h.ImageFeatureExtractor,h.ImageMattingOutput,h.ImageSegmentationPipeline,h.ImageToImagePipeline,h.ImageToTextPipeline;var Qh=h.InterruptableStoppingCriteria;h.LlamaForCausalLM,h.LlamaModel,h.LlamaPreTrainedModel,h.LlamaTokenizer,h.LlavaForConditionalGeneration,h.LlavaPreTrainedModel,h.LongT5ForConditionalGeneration,h.LongT5Model,h.LongT5PreTrainedModel,h.M2M100ForConditionalGeneration,h.M2M100Model,h.M2M100PreTrainedModel,h.M2M100Tokenizer,h.MBart50Tokenizer,h.MBartForCausalLM,h.MBartForConditionalGeneration,h.MBartForSequenceClassification,h.MBartModel,h.MBartPreTrainedModel,h.MBartTokenizer,h.MPNetForMaskedLM,h.MPNetForQuestionAnswering,h.MPNetForSequenceClassification,h.MPNetForTokenClassification,h.MPNetModel,h.MPNetPreTrainedModel,h.MPNetTokenizer,h.MT5ForConditionalGeneration,h.MT5Model,h.MT5PreTrainedModel,h.MarianMTModel,h.MarianModel,h.MarianPreTrainedModel,h.MarianTokenizer,h.MaskedLMOutput,h.MaxLengthCriteria,h.MistralForCausalLM,h.MistralModel,h.MistralPreTrainedModel,h.MobileBertForMaskedLM,h.MobileBertForQuestionAnswering,h.MobileBertForSequenceClassification,h.MobileBertModel,h.MobileBertPreTrainedModel,h.MobileBertTokenizer,h.MobileNetV1FeatureExtractor,h.MobileNetV1ForImageClassification,h.MobileNetV1Model,h.MobileNetV1PreTrainedModel,h.MobileNetV2FeatureExtractor,h.MobileNetV2ForImageClassification,h.MobileNetV2Model,h.MobileNetV2PreTrainedModel,h.MobileNetV3FeatureExtractor,h.MobileNetV3ForImageClassification,h.MobileNetV3Model,h.MobileNetV3PreTrainedModel,h.MobileNetV4FeatureExtractor,h.MobileNetV4ForImageClassification,h.MobileNetV4Model,h.MobileNetV4PreTrainedModel,h.MobileViTFeatureExtractor,h.MobileViTForImageClassification,h.MobileViTImageProcessor,h.MobileViTModel,h.MobileViTPreTrainedModel,h.MobileViTV2ForImageClassification,h.MobileViTV2Model,h.MobileViTV2PreTrainedModel,h.ModelOutput,h.Moondream1ForConditionalGeneration,h.MptForCausalLM,h.MptModel,h.MptPreTrainedModel,h.MusicgenForCausalLM,h.MusicgenForConditionalGeneration,h.MusicgenModel,h.MusicgenPreTrainedModel,h.NllbTokenizer,h.NomicBertModel,h.NomicBertPreTrainedModel,h.NougatImageProcessor,h.NougatTokenizer,h.OPTForCausalLM,h.OPTModel,h.OPTPreTrainedModel,h.ObjectDetectionPipeline,h.OpenELMForCausalLM,h.OpenELMModel,h.OpenELMPreTrainedModel,h.OwlViTFeatureExtractor,h.OwlViTForObjectDetection,h.OwlViTModel,h.OwlViTPreTrainedModel,h.OwlViTProcessor,h.Owlv2ForObjectDetection,h.Owlv2ImageProcessor,h.Owlv2Model,h.Owlv2PreTrainedModel,h.Phi3ForCausalLM,h.Phi3Model,h.Phi3PreTrainedModel,h.PhiForCausalLM,h.PhiModel,h.PhiPreTrainedModel,h.Pipeline,h.PreTrainedModel,h.PreTrainedTokenizer,h.PretrainedConfig,h.PretrainedMixin,h.Processor,h.PyAnnoteFeatureExtractor,h.PyAnnoteForAudioFrameClassification,h.PyAnnoteModel,h.PyAnnotePreTrainedModel,h.PyAnnoteProcessor,h.QuestionAnsweringModelOutput,h.QuestionAnsweringPipeline,h.Qwen2ForCausalLM,h.Qwen2Model,h.Qwen2PreTrainedModel,h.Qwen2Tokenizer,h.RTDetrForObjectDetection,h.RTDetrImageProcessor,h.RTDetrModel,h.RTDetrObjectDetectionOutput,h.RTDetrPreTrainedModel,h.RawImage,h.ResNetForImageClassification,h.ResNetModel,h.ResNetPreTrainedModel,h.RoFormerForMaskedLM,h.RoFormerForQuestionAnswering,h.RoFormerForSequenceClassification,h.RoFormerForTokenClassification,h.RoFormerModel,h.RoFormerPreTrainedModel,h.RoFormerTokenizer,h.RobertaForMaskedLM,h.RobertaForQuestionAnswering,h.RobertaForSequenceClassification,h.RobertaForTokenClassification,h.RobertaModel,h.RobertaPreTrainedModel,h.RobertaTokenizer,h.SamImageProcessor,h.SamImageSegmentationOutput,h.SamModel,h.SamPreTrainedModel,h.SamProcessor,h.SeamlessM4TFeatureExtractor,h.SegformerFeatureExtractor,h.SegformerForImageClassification,h.SegformerForSemanticSegmentation,h.SegformerModel,h.SegformerPreTrainedModel,h.Seq2SeqLMOutput,h.SequenceClassifierOutput,h.SiglipImageProcessor,h.SiglipModel,h.SiglipPreTrainedModel,h.SiglipTextModel,h.SiglipTokenizer,h.SiglipVisionModel,h.SpeechT5FeatureExtractor,h.SpeechT5ForSpeechToText,h.SpeechT5ForTextToSpeech,h.SpeechT5HifiGan,h.SpeechT5Model,h.SpeechT5PreTrainedModel,h.SpeechT5Processor,h.SpeechT5Tokenizer,h.SqueezeBertForMaskedLM,h.SqueezeBertForQuestionAnswering,h.SqueezeBertForSequenceClassification,h.SqueezeBertModel,h.SqueezeBertPreTrainedModel,h.SqueezeBertTokenizer,h.StableLmForCausalLM,h.StableLmModel,h.StableLmPreTrainedModel,h.Starcoder2ForCausalLM,h.Starcoder2Model,h.Starcoder2PreTrainedModel,h.StoppingCriteria,h.StoppingCriteriaList,h.SummarizationPipeline,h.Swin2SRForImageSuperResolution,h.Swin2SRImageProcessor,h.Swin2SRModel,h.Swin2SRPreTrainedModel,h.SwinForImageClassification,h.SwinModel,h.SwinPreTrainedModel,h.T5ForConditionalGeneration,h.T5Model,h.T5PreTrainedModel,h.T5Tokenizer,h.TableTransformerForObjectDetection,h.TableTransformerModel,h.TableTransformerObjectDetectionOutput,h.TableTransformerPreTrainedModel,h.Tensor,h.Text2TextGenerationPipeline,h.TextClassificationPipeline,h.TextGenerationPipeline;var Yh=h.TextStreamer;h.TextToAudioPipeline,h.TokenClassificationPipeline,h.TokenClassifierOutput,h.TokenizerModel,h.TrOCRForCausalLM,h.TrOCRPreTrainedModel,h.TranslationPipeline,h.UniSpeechForCTC,h.UniSpeechForSequenceClassification,h.UniSpeechModel,h.UniSpeechPreTrainedModel,h.UniSpeechSatForAudioFrameClassification,h.UniSpeechSatForCTC,h.UniSpeechSatForSequenceClassification,h.UniSpeechSatModel,h.UniSpeechSatPreTrainedModel,h.ViTFeatureExtractor,h.ViTForImageClassification,h.ViTImageProcessor,h.ViTModel,h.ViTPreTrainedModel,h.VisionEncoderDecoderModel,h.VitMatteForImageMatting,h.VitMatteImageProcessor,h.VitMattePreTrainedModel,h.VitsModel,h.VitsModelOutput,h.VitsPreTrainedModel,h.VitsTokenizer,h.Wav2Vec2BertForCTC,h.Wav2Vec2BertForSequenceClassification,h.Wav2Vec2BertModel,h.Wav2Vec2BertPreTrainedModel,h.Wav2Vec2CTCTokenizer,h.Wav2Vec2FeatureExtractor,h.Wav2Vec2ForAudioFrameClassification,h.Wav2Vec2ForCTC,h.Wav2Vec2ForSequenceClassification,h.Wav2Vec2Model,h.Wav2Vec2PreTrainedModel,h.Wav2Vec2ProcessorWithLM,h.WavLMForAudioFrameClassification,h.WavLMForCTC,h.WavLMForSequenceClassification,h.WavLMForXVector,h.WavLMModel,h.WavLMPreTrainedModel,h.WeSpeakerFeatureExtractor,h.WeSpeakerResNetModel,h.WeSpeakerResNetPreTrainedModel,h.WhisperFeatureExtractor,h.WhisperForConditionalGeneration,h.WhisperModel,h.WhisperPreTrainedModel,h.WhisperProcessor,h.WhisperTextStreamer,h.WhisperTokenizer,h.XLMForQuestionAnswering,h.XLMForSequenceClassification,h.XLMForTokenClassification,h.XLMModel,h.XLMPreTrainedModel,h.XLMRobertaForMaskedLM,h.XLMRobertaForQuestionAnswering,h.XLMRobertaForSequenceClassification,h.XLMRobertaForTokenClassification,h.XLMRobertaModel,h.XLMRobertaPreTrainedModel,h.XLMRobertaTokenizer,h.XLMTokenizer,h.XLMWithLMHeadModel,h.XVectorOutput,h.YolosFeatureExtractor,h.YolosForObjectDetection,h.YolosModel,h.YolosObjectDetectionOutput,h.YolosPreTrainedModel,h.ZeroShotAudioClassificationPipeline,h.ZeroShotClassificationPipeline,h.ZeroShotImageClassificationPipeline,h.ZeroShotObjectDetectionPipeline,h.bankers_round,h.cat,h.cos_sim,h.dot,h.dynamic_time_warping,h.env,h.full,h.full_like,h.getKeyValueShapes,h.hamming,h.hanning,h.interpolate,h.interpolate_4d,h.interpolate_data,h.is_chinese_char,h.layer_norm,h.log_softmax,h.magnitude,h.matmul,h.max,h.mean,h.mean_pooling,h.medianFilter,h.mel_filter_bank,h.min,h.ones,h.ones_like,h.permute,h.permute_data,h.pipeline,h.quantize_embeddings,h.read_audio,h.rfft,h.round,h.softmax,h.spectrogram,h.stack,h.std_mean,h.topk,h.window_function,h.zeros,h.zeros_like;class Td{static async getInstance(fe=null){return this.tokenizer??(this.tokenizer=Xh.from_pretrained(this.model_id,{progress_callback:fe})),this.model??(this.model=Kh.from_pretrained(this.model_id,{dtype:"q4f16",device:"webgpu",use_external_data_format:!0,progress_callback:fe})),Promise.all([this.tokenizer,this.model])}}Te(Td,"model_id","onnx-community/Phi-3.5-mini-instruct-onnx-web");const Au=new Qh;async function Zh(bt){const[fe,l]=await Td.getInstance(),M=fe.apply_chat_template(bt,{add_generation_prompt:!0,return_dict:!0});let K,ge=0,Me;const xe=()=>{K??(K=performance.now()),ge++>0&&(Me=ge/(performance.now()-K)*1e3)},D=te=>{self.postMessage({status:"update",output:te,tps:Me,numTokens:ge})},x=new Yh(fe,{skip_prompt:!0,skip_special_tokens:!0,callback_function:D,token_callback_function:xe});self.postMessage({status:"start"});const{past_key_values:V,sequences:P}=await l.generate({...M,do_sample:!0,top_k:3,temperature:.2,max_new_tokens:1024,streamer:x,stopping_criteria:Au,return_dict_in_generate:!0}),J=fe.batch_decode(P,{skip_special_tokens:!0});self.postMessage({status:"complete",output:J})}async function Jh(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(bt){self.postMessage({status:"error",data:bt.toString()})}}async function ef(){self.postMessage({status:"loading",data:"Loading model..."});const[bt,fe]=await Td.getInstance(M=>{self.postMessage(M)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const l=bt("a");await fe.generate({...l,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async bt=>{const{type:fe,data:l}=bt.data;switch(fe){case"check":Jh();break;case"load":ef();break;case"generate":Au.reset(),Zh(l);break;case"interrupt":Au.interrupt();break;case"reset":Au.reset();break}})})();