var Nm=Object.defineProperty;var jm=(wn,ns,js)=>ns in wn?Nm(wn,ns,{enumerable:!0,configurable:!0,writable:!0,value:js}):wn[ns]=js;var Te=(wn,ns,js)=>jm(wn,typeof ns!="symbol"?ns+"":ns,js);(function(){"use strict";var wn={},ns={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Mt,me,l)=>{Mt.exports=l.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Mt,me,l)=>{l.r(me),l.d(me,{Environment:()=>Ke,Interpreter:()=>ut,Template:()=>xt,parse:()=>$e,tokenize:()=>P});var x=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"}),H=Object.freeze({set:x.Set,for:x.For,in:x.In,is:x.Is,if:x.If,else:x.Else,endif:x.EndIf,elif:x.ElseIf,endfor:x.EndFor,and:x.And,or:x.Or,not:x.Not,"not in":x.NotIn,macro:x.Macro,endmacro:x.EndMacro,true:x.BooleanLiteral,false:x.BooleanLiteral,True:x.BooleanLiteral,False:x.BooleanLiteral}),ge=class{constructor(M,W){this.value=M,this.type=W}};function ve(M){return/\w/.test(M)}function xe(M){return/[0-9]/.test(M)}var D=[["{%",x.OpenStatement],["%}",x.CloseStatement],["{{",x.OpenExpression],["}}",x.CloseExpression],["(",x.OpenParen],[")",x.CloseParen],["{",x.OpenCurlyBracket],["}",x.CloseCurlyBracket],["[",x.OpenSquareBracket],["]",x.CloseSquareBracket],[",",x.Comma],[".",x.Dot],[":",x.Colon],["|",x.Pipe],["<=",x.ComparisonBinaryOperator],[">=",x.ComparisonBinaryOperator],["==",x.ComparisonBinaryOperator],["!=",x.ComparisonBinaryOperator],["<",x.ComparisonBinaryOperator],[">",x.ComparisonBinaryOperator],["+",x.AdditiveBinaryOperator],["-",x.AdditiveBinaryOperator],["*",x.MultiplicativeBinaryOperator],["/",x.MultiplicativeBinaryOperator],["%",x.MultiplicativeBinaryOperator],["=",x.Equals]],T=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function j(M,W={}){return M.endsWith(` `)&&(M=M.slice(0,-1)),M=M.replace(/{#.*?#}/gs,"{##}"),W.lstrip_blocks&&(M=M.replace(/^[ \t]*({[#%])/gm,"$1")),W.trim_blocks&&(M=M.replace(/([#%]})\n/g,"$1")),M.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function P(M,W={}){var Je,At,_t;const S=[],X=j(M,W);let fe=0;const Ye=Se=>{let $="";for(;Se(X[fe]);){if(X[fe]==="\\"){if(++fe,fe>=X.length)throw new SyntaxError("Unexpected end of input");const q=X[fe++],be=T.get(q);if(be===void 0)throw new SyntaxError(`Unexpected escaped character: ${q}`);$+=be;continue}if($+=X[fe++],fe>=X.length)throw new SyntaxError("Unexpected end of input")}return $};e:for(;fe0){S.push(new ge(q,x.Text));continue}}Ye(q=>/\s/.test(q));const $=X[fe];if($==="-"||$==="+"){const q=(At=S.at(-1))==null?void 0:At.type;if(q===x.Text||q===void 0)throw new SyntaxError(`Unexpected character: ${$}`);switch(q){case x.Identifier:case x.NumericLiteral:case x.BooleanLiteral:case x.StringLiteral:case x.CloseParen:case x.CloseSquareBracket:break;default:{++fe;const be=Ye(xe);S.push(new ge(`${$}${be}`,be.length>0?x.NumericLiteral:x.UnaryOperator));continue}}}for(const[q,be]of D)if(X.slice(fe,fe+q.length)===q){S.push(new ge(q,be)),fe+=q.length;continue e}if($==="'"||$==='"'){++fe;const q=Ye(be=>be!==$);S.push(new ge(q,x.StringLiteral)),++fe;continue}if(xe($)){const q=Ye(xe);S.push(new ge(q,x.NumericLiteral));continue}if(ve($)){const q=Ye(ve),be=Object.hasOwn(H,q)?H[q]:x.Identifier;be===x.In&&((_t=S.at(-1))==null?void 0:_t.type)===x.Not?(S.pop(),S.push(new ge("not in",x.NotIn))):S.push(new ge(q,be));continue}throw new SyntaxError(`Unexpected character: ${$}`)}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,X){super();Te(this,"type","If");this.test=W,this.body=S,this.alternate=X}},ie=class extends J{constructor(W,S,X,fe){super();Te(this,"type","For");this.loopvar=W,this.iterable=S,this.body=X,this.defaultBlock=fe}},R=class extends J{constructor(W,S){super();Te(this,"type","Set");this.assignee=W,this.value=S}},Y=class extends J{constructor(W,S,X){super();Te(this,"type","Macro");this.name=W,this.args=S,this.body=X}},se=class extends J{constructor(){super(...arguments);Te(this,"type","Expression")}},le=class extends se{constructor(W,S,X){super();Te(this,"type","MemberExpression");this.object=W,this.property=S,this.computed=X}},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}},I=class extends se{constructor(W){super();Te(this,"type","Literal");this.value=W}},B=class extends I{constructor(){super(...arguments);Te(this,"type","NumericLiteral")}},A=class extends I{constructor(){super(...arguments);Te(this,"type","StringLiteral")}},_e=class extends I{constructor(){super(...arguments);Te(this,"type","BooleanLiteral")}},ye=class extends I{constructor(){super(...arguments);Te(this,"type","ArrayLiteral")}},Ce=class extends I{constructor(){super(...arguments);Te(this,"type","TupleLiteral")}},ke=class extends I{constructor(){super(...arguments);Te(this,"type","ObjectLiteral")}},Ie=class extends se{constructor(W,S,X){super();Te(this,"type","BinaryExpression");this.operator=W,this.left=S,this.right=X}},tt=class extends se{constructor(W,S){super();Te(this,"type","FilterExpression");this.operand=W,this.filter=S}},Qe=class extends se{constructor(W,S){super();Te(this,"type","SelectExpression");this.iterable=W,this.test=S}},ht=class extends se{constructor(W,S,X){super();Te(this,"type","TestExpression");this.operand=W,this.negate=S,this.test=X}},we=class extends se{constructor(W,S){super();Te(this,"type","UnaryExpression");this.operator=W,this.argument=S}},V=class extends se{constructor(W=void 0,S=void 0,X=void 0){super();Te(this,"type","SliceExpression");this.start=W,this.stop=S,this.step=X}},he=class extends se{constructor(W,S){super();Te(this,"type","KeywordArgumentExpression");this.key=W,this.value=S}};function $e(M){const W=new te([]);let S=0;function X(Ze,St){const Dt=M[S++];if(!Dt||Dt.type!==Ze)throw new Error(`Parser Error: ${St}. ${Dt.type} !== ${Ze}.`);return Dt}function fe(){switch(M[S].type){case x.Text:return At();case x.OpenStatement:return _t();case x.OpenExpression:return Se();default:throw new SyntaxError(`Unexpected token type: ${M[S].type}`)}}function Ye(...Ze){return S+Ze.length<=M.length&&Ze.some((St,Dt)=>St!==M[S+Dt].type)}function Je(...Ze){return S+Ze.length<=M.length&&Ze.every((St,Dt)=>St===M[S+Dt].type)}function At(){return new A(X(x.Text,"Expected text token").value)}function _t(){X(x.OpenStatement,"Expected opening statement token");let Ze;switch(M[S].type){case x.Set:++S,Ze=$(),X(x.CloseStatement,"Expected closing statement token");break;case x.If:++S,Ze=q(),X(x.OpenStatement,"Expected {% token"),X(x.EndIf,"Expected endif token"),X(x.CloseStatement,"Expected %} token");break;case x.Macro:++S,Ze=be(),X(x.OpenStatement,"Expected {% token"),X(x.EndMacro,"Expected endmacro token"),X(x.CloseStatement,"Expected %} token");break;case x.For:++S,Ze=Ae(),X(x.OpenStatement,"Expected {% token"),X(x.EndFor,"Expected endfor token"),X(x.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${M[S].type}`)}return Ze}function Se(){X(x.OpenExpression,"Expected opening expression token");const Ze=Ne();return X(x.CloseExpression,"Expected closing expression token"),Ze}function $(){const Ze=Ne();if(Je(x.Equals)){++S;const St=$();return new R(Ze,St)}return Ze}function q(){var qr,Un,Fn,Lr,Zr,Nr,Sn,Pr;const Ze=Ne();X(x.CloseStatement,"Expected closing statement token");const St=[],Dt=[];for(;!(((qr=M[S])==null?void 0:qr.type)===x.OpenStatement&&(((Un=M[S+1])==null?void 0:Un.type)===x.ElseIf||((Fn=M[S+1])==null?void 0:Fn.type)===x.Else||((Lr=M[S+1])==null?void 0:Lr.type)===x.EndIf));)St.push(fe());if(((Zr=M[S])==null?void 0:Zr.type)===x.OpenStatement&&((Nr=M[S+1])==null?void 0:Nr.type)!==x.EndIf)if(++S,Je(x.ElseIf))X(x.ElseIf,"Expected elseif token"),Dt.push(q());else for(X(x.Else,"Expected else token"),X(x.CloseStatement,"Expected closing statement token");!(((Sn=M[S])==null?void 0:Sn.type)===x.OpenStatement&&((Pr=M[S+1])==null?void 0:Pr.type)===x.EndIf);)Dt.push(fe());return new ne(Ze,St,Dt)}function be(){const Ze=Cr();if(Ze.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const St=Rt();X(x.CloseStatement,"Expected closing statement token");const Dt=[];for(;Ye(x.OpenStatement,x.EndMacro);)Dt.push(fe());return new Y(Ze,St,Dt)}function Be(Ze=!1){const St=Ze?Cr:Ne,Dt=[St()],qr=Je(x.Comma);for(;qr&&(++S,Dt.push(St()),!!Je(x.Comma)););return qr?new Ce(Dt):Dt[0]}function Ae(){const Ze=Be(!0);if(!(Ze instanceof N||Ze instanceof Ce))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Ze.type} instead`);X(x.In,"Expected `in` keyword following loop variable");const St=Ne();X(x.CloseStatement,"Expected closing statement token");const Dt=[];for(;Ye(x.OpenStatement,x.EndFor)&&Ye(x.OpenStatement,x.Else);)Dt.push(fe());const qr=[];if(Je(x.OpenStatement,x.Else))for(++S,++S,X(x.CloseStatement,"Expected closing statement token");Ye(x.OpenStatement,x.EndFor);)qr.push(fe());return new ie(Ze,St,Dt,qr)}function Ne(){return dt()}function dt(){const Ze=nt();if(Je(x.If)){++S;const St=nt();if(Je(x.Else)){++S;const Dt=nt();return new ne(St,[Ze],[Dt])}else return new Qe(Ze,St)}return Ze}function nt(){let Ze=vt();for(;Je(x.Or);){const St=M[S];++S;const Dt=vt();Ze=new Ie(St,Ze,Dt)}return Ze}function vt(){let Ze=ft();for(;Je(x.And);){const St=M[S];++S;const Dt=ft();Ze=new Ie(St,Ze,Dt)}return Ze}function ft(){let Ze;for(;Je(x.Not);){const St=M[S];++S;const Dt=ft();Ze=new we(St,Dt)}return Ze??Ct()}function Ct(){let Ze=Lt();for(;Je(x.ComparisonBinaryOperator)||Je(x.In)||Je(x.NotIn);){const St=M[S];++S;const Dt=Lt();Ze=new Ie(St,Ze,Dt)}return Ze}function Lt(){let Ze=Wt();for(;Je(x.AdditiveBinaryOperator);){const St=M[S];++S;const Dt=Wt();Ze=new Ie(St,Ze,Dt)}return Ze}function Xe(){const Ze=er();return Je(x.OpenParen)?jt(Ze):Ze}function jt(Ze){let St=new ae(Ze,Rt());return Je(x.OpenParen)&&(St=jt(St)),St}function Rt(){X(x.OpenParen,"Expected opening parenthesis for arguments list");const Ze=Ht();return X(x.CloseParen,"Expected closing parenthesis for arguments list"),Ze}function Ht(){const Ze=[];for(;!Je(x.CloseParen);){let St=Ne();if(Je(x.Equals)){if(++S,!(St instanceof N))throw new SyntaxError("Expected identifier for keyword argument");const Dt=Ne();St=new he(St,Dt)}Ze.push(St),Je(x.Comma)&&++S}return Ze}function Xt(){const Ze=[];let St=!1;for(;!Je(x.CloseSquareBracket);)Je(x.Colon)?(Ze.push(void 0),++S,St=!0):(Ze.push(Ne()),Je(x.Colon)&&(++S,St=!0));if(Ze.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(St){if(Ze.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new V(...Ze)}return Ze[0]}function er(){let Ze=Cr();for(;Je(x.Dot)||Je(x.OpenSquareBracket);){const St=M[S];++S;let Dt;const qr=St.type!==x.Dot;if(qr)Dt=Xt(),X(x.CloseSquareBracket,"Expected closing square bracket");else if(Dt=Cr(),Dt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Ze=new le(Ze,Dt,qr)}return Ze}function Wt(){let Ze=Tr();for(;Je(x.MultiplicativeBinaryOperator);){const St=M[S];++S;const Dt=Tr();Ze=new Ie(St,Ze,Dt)}return Ze}function Tr(){let Ze=Ur();for(;Je(x.Is);){++S;const St=Je(x.Not);St&&++S;let Dt=Cr();if(Dt instanceof _e&&(Dt=new N(Dt.value.toString())),!(Dt instanceof N))throw new SyntaxError("Expected identifier for the test");Ze=new ht(Ze,St,Dt)}return Ze}function Ur(){let Ze=Xe();for(;Je(x.Pipe);){++S;let St=Cr();if(!(St instanceof N))throw new SyntaxError("Expected identifier for the filter");Je(x.OpenParen)&&(St=jt(St)),Ze=new tt(Ze,St)}return Ze}function Cr(){const Ze=M[S];switch(Ze.type){case x.NumericLiteral:return++S,new B(Number(Ze.value));case x.StringLiteral:return++S,new A(Ze.value);case x.BooleanLiteral:return++S,new _e(Ze.value.toLowerCase()==="true");case x.Identifier:return++S,new N(Ze.value);case x.OpenParen:{++S;const St=Be();if(M[S].type!==x.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${M[S].type} instead`);return++S,St}case x.OpenSquareBracket:{++S;const St=[];for(;!Je(x.CloseSquareBracket);)St.push(Ne()),Je(x.Comma)&&++S;return++S,new ye(St)}case x.OpenCurlyBracket:{++S;const St=new Map;for(;!Je(x.CloseCurlyBracket);){const Dt=Ne();X(x.Colon,"Expected colon between key and value in object literal");const qr=Ne();St.set(Dt,qr),Je(x.Comma)&&++S}return++S,new ke(St)}default:throw new SyntaxError(`Unexpected token: ${Ze.type}`)}}for(;S=0?(W=(W??(W=0))<0?Math.max(M.length+W,0):Math.min(W,M.length),S=(S??(S=M.length))<0?Math.max(M.length+S,0):Math.min(S,M.length)):(W=(W??(W=M.length-1))<0?Math.max(M.length+W,-1):Math.min(W,M.length-1),S=(S??(S=-1))<-1?Math.max(M.length+S,-1):Math.min(S,M.length-1));const Ye=[];for(let Je=W;fe*JeW.toUpperCase())}var rt=class{constructor(M=void 0){Te(this,"type","RuntimeValue");Te(this,"value");Te(this,"builtins",new Map);this.value=M}__bool__(){return new st(!!this.value)}},lt=class extends rt{constructor(){super(...arguments);Te(this,"type","NumericValue")}},Re=class extends rt{constructor(){super(...arguments);Te(this,"type","StringValue");Te(this,"builtins",new Map([["upper",new je(()=>new Re(this.value.toUpperCase()))],["lower",new je(()=>new Re(this.value.toLowerCase()))],["strip",new je(()=>new Re(this.value.trim()))],["title",new je(()=>new Re(pt(this.value)))],["length",new lt(this.value.length)]]))}},st=class extends rt{constructor(){super(...arguments);Te(this,"type","BooleanValue")}},Tt=class extends rt{constructor(){super(...arguments);Te(this,"type","ObjectValue");Te(this,"builtins",new Map([["get",new je(([W,S])=>{if(!(W instanceof Re))throw new Error(`Object key must be a string: got ${W.type}`);return this.value.get(W.value)??S??new Ge})],["items",new je(()=>new re(Array.from(this.value.entries()).map(([W,S])=>new re([new Re(W),S]))))]]))}__bool__(){return new st(this.value.size>0)}},ze=class extends Tt{constructor(){super(...arguments);Te(this,"type","KeywordArgumentsValue")}},re=class extends rt{constructor(){super(...arguments);Te(this,"type","ArrayValue");Te(this,"builtins",new Map([["length",new lt(this.value.length)]]))}__bool__(){return new st(this.value.length>0)}},Ee=class extends re{constructor(){super(...arguments);Te(this,"type","TupleValue")}},je=class extends rt{constructor(){super(...arguments);Te(this,"type","FunctionValue")}},Ge=class extends rt{constructor(){super(...arguments);Te(this,"type","NullValue")}},Ve=class extends rt{constructor(){super(...arguments);Te(this,"type","UndefinedValue")}},Ke=class{constructor(M){Te(this,"variables",new Map([["namespace",new je(M=>{if(M.length===0)return new Tt(new Map);if(M.length!==1||!(M[0]instanceof Tt))throw new Error("`namespace` expects either zero arguments or a single object argument");return M[0]})]]));Te(this,"tests",new Map([["boolean",M=>M.type==="BooleanValue"],["callable",M=>M instanceof je],["odd",M=>{if(M.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${M.type}`);return M.value%2!==0}],["even",M=>{if(M.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${M.type}`);return M.value%2===0}],["false",M=>M.type==="BooleanValue"&&!M.value],["true",M=>M.type==="BooleanValue"&&M.value],["string",M=>M.type==="StringValue"],["number",M=>M.type==="NumericValue"],["integer",M=>M.type==="NumericValue"&&Number.isInteger(M.value)],["iterable",M=>M instanceof re||M instanceof Re],["lower",M=>{const W=M.value;return M.type==="StringValue"&&W===W.toLowerCase()}],["upper",M=>{const W=M.value;return M.type==="StringValue"&&W===W.toUpperCase()}],["none",M=>M.type==="NullValue"],["defined",M=>M.type!=="UndefinedValue"],["undefined",M=>M.type==="UndefinedValue"],["equalto",(M,W)=>M.value===W.value],["eq",(M,W)=>M.value===W.value]]));this.parent=M}set(M,W){return this.declareVariable(M,mt(W))}declareVariable(M,W){if(this.variables.has(M))throw new SyntaxError(`Variable already declared: ${M}`);return this.variables.set(M,W),W}setVariable(M,W){return this.variables.set(M,W),W}resolve(M){if(this.variables.has(M))return this;if(this.parent)return this.parent.resolve(M);throw new Error(`Unknown variable: ${M}`)}lookupVariable(M){try{return this.resolve(M).variables.get(M)??new Ve}catch{return new Ve}}},ut=class{constructor(M){Te(this,"global");this.global=M??new Ke}run(M){return this.evaluate(M,this.global)}evaluateBinaryExpression(M,W){const S=this.evaluate(M.left,W);switch(M.operator.value){case"and":return S.__bool__().value?this.evaluate(M.right,W):S;case"or":return S.__bool__().value?S:this.evaluate(M.right,W)}const X=this.evaluate(M.right,W);switch(M.operator.value){case"==":return new st(S.value==X.value);case"!=":return new st(S.value!=X.value)}if(S instanceof Ve||X instanceof Ve)throw new Error("Cannot perform operation on undefined values");if(S instanceof Ge||X instanceof Ge)throw new Error("Cannot perform operation on null values");if(S instanceof lt&&X instanceof lt)switch(M.operator.value){case"+":return new lt(S.value+X.value);case"-":return new lt(S.value-X.value);case"*":return new lt(S.value*X.value);case"/":return new lt(S.value/X.value);case"%":return new lt(S.value%X.value);case"<":return new st(S.value":return new st(S.value>X.value);case">=":return new st(S.value>=X.value);case"<=":return new st(S.value<=X.value)}else if(S instanceof re&&X instanceof re)switch(M.operator.value){case"+":return new re(S.value.concat(X.value))}else if(X instanceof re){const fe=X.value.find(Ye=>Ye.value===S.value)!==void 0;switch(M.operator.value){case"in":return new st(fe);case"not in":return new st(!fe)}}if(S instanceof Re||X instanceof Re)switch(M.operator.value){case"+":return new Re(S.value.toString()+X.value.toString())}if(S instanceof Re&&X instanceof Re)switch(M.operator.value){case"in":return new st(X.value.includes(S.value));case"not in":return new st(!X.value.includes(S.value))}if(S instanceof Re&&X instanceof Tt)switch(M.operator.value){case"in":return new st(X.value.has(S.value));case"not in":return new st(!X.value.has(S.value))}throw new SyntaxError(`Unknown operator "${M.operator.value}" between ${S.type} and ${X.type}`)}evaluateArguments(M,W){const S=[],X=new Map;for(const fe of M)if(fe.type==="KeywordArgumentExpression"){const Ye=fe;X.set(Ye.key.value,this.evaluate(Ye.value,W))}else{if(X.size>0)throw new Error("Positional arguments must come before keyword arguments");S.push(this.evaluate(fe,W))}return[S,X]}evaluateFilterExpression(M,W){const S=this.evaluate(M.operand,W);if(M.filter.type==="Identifier"){const X=M.filter;if(X.value==="tojson")return new Re(wt(S));if(S instanceof re)switch(X.value){case"list":return S;case"first":return S.value[0];case"last":return S.value[S.value.length-1];case"length":return new lt(S.value.length);case"reverse":return new re(S.value.reverse());case"sort":return new re(S.value.sort((fe,Ye)=>{if(fe.type!==Ye.type)throw new Error(`Cannot compare different types: ${fe.type} and ${Ye.type}`);switch(fe.type){case"NumericValue":return fe.value-Ye.value;case"StringValue":return fe.value.localeCompare(Ye.value);default:throw new Error(`Cannot compare type: ${fe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${X.value}`)}else if(S instanceof Re)switch(X.value){case"length":return new lt(S.value.length);case"upper":return new Re(S.value.toUpperCase());case"lower":return new Re(S.value.toLowerCase());case"title":return new Re(pt(S.value));case"capitalize":return new Re(S.value.charAt(0).toUpperCase()+S.value.slice(1));case"trim":return new Re(S.value.trim());case"indent":return new Re(S.value.split(` `).map((fe,Ye)=>Ye===0||fe.length===0?fe:" "+fe).join(` `));case"string":return S;default:throw new Error(`Unknown StringValue filter: ${X.value}`)}else if(S instanceof lt)switch(X.value){case"abs":return new lt(Math.abs(S.value));default:throw new Error(`Unknown NumericValue filter: ${X.value}`)}else if(S instanceof Tt)switch(X.value){case"items":return new re(Array.from(S.value.entries()).map(([fe,Ye])=>new re([new Re(fe),Ye])));case"length":return new lt(S.value.size);default:throw new Error(`Unknown ObjectValue filter: ${X.value}`)}throw new Error(`Cannot apply filter "${X.value}" to type: ${S.type}`)}else if(M.filter.type==="CallExpression"){const X=M.filter;if(X.callee.type!=="Identifier")throw new Error(`Unknown filter: ${X.callee.type}`);const fe=X.callee.value;if(fe==="tojson"){const[,Ye]=this.evaluateArguments(X.args,W),Je=Ye.get("indent")??new Ge;if(!(Je instanceof lt||Je instanceof Ge))throw new Error("If set, indent must be a number");return new Re(wt(S,Je.value))}if(S instanceof re){switch(fe){case"selectattr":{if(S.value.some($=>!($ instanceof Tt)))throw new Error("`selectattr` can only be applied to array of objects");if(X.args.some($=>$.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Ye,Je,At]=X.args.map($=>this.evaluate($,W));let _t;if(Je){const $=W.tests.get(Je.value);if(!$)throw new Error(`Unknown test: ${Je.value}`);_t=$}else _t=(...$)=>$[0].__bool__().value;const Se=S.value.filter($=>{const q=$.value.get(Ye.value);return q?_t(q,At):!1});return new re(Se)}case"map":{const[,Ye]=this.evaluateArguments(X.args,W);if(Ye.has("attribute")){const Je=Ye.get("attribute");if(!(Je instanceof Re))throw new Error("attribute must be a string");const At=Ye.get("default"),_t=S.value.map(Se=>{if(!(Se instanceof Tt))throw new Error("items in map must be an object");return Se.value.get(Je.value)??At??new Ve});return new re(_t)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${fe}`)}else if(S instanceof Re){switch(fe){case"indent":{const[Ye,Je]=this.evaluateArguments(X.args,W),At=Ye.at(0)??Je.get("width")??new lt(4);if(!(At instanceof lt))throw new Error("width must be a number");const _t=Ye.at(1)??Je.get("first")??new st(!1),Se=Ye.at(2)??Je.get("blank")??new st(!1),$=S.value.split(` `),q=" ".repeat(At.value),be=$.map((Be,Ae)=>!_t.value&&Ae===0||!Se.value&&Be.length===0?Be:q+Be);return new Re(be.join(` `))}}throw new Error(`Unknown StringValue filter: ${fe}`)}else throw new Error(`Cannot apply filter "${fe}" to type: ${S.type}`)}throw new Error(`Unknown filter: ${M.filter.type}`)}evaluateTestExpression(M,W){const S=this.evaluate(M.operand,W),X=W.tests.get(M.test.value);if(!X)throw new Error(`Unknown test: ${M.test.value}`);const fe=X(S);return new st(M.negate?!fe:fe)}evaluateUnaryExpression(M,W){const S=this.evaluate(M.argument,W);switch(M.operator.value){case"not":return new st(!S.value);default:throw new SyntaxError(`Unknown operator: ${M.operator.value}`)}}evalProgram(M,W){return this.evaluateBlock(M.body,W)}evaluateBlock(M,W){let S="";for(const X of M){const fe=this.evaluate(X,W);fe.type!=="NullValue"&&fe.type!=="UndefinedValue"&&(S+=fe.value)}return new Re(S)}evaluateIdentifier(M,W){return W.lookupVariable(M.value)}evaluateCallExpression(M,W){const[S,X]=this.evaluateArguments(M.args,W);X.size>0&&S.push(new ze(X));const fe=this.evaluate(M.callee,W);if(fe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${fe.type}`);return fe.value(S,W)}evaluateSliceExpression(M,W,S){if(!(M instanceof re||M instanceof Re))throw new Error("Slice object must be an array or string");const X=this.evaluate(W.start,S),fe=this.evaluate(W.stop,S),Ye=this.evaluate(W.step,S);if(!(X instanceof lt||X instanceof Ve))throw new Error("Slice start must be numeric or undefined");if(!(fe instanceof lt||fe instanceof Ve))throw new Error("Slice stop must be numeric or undefined");if(!(Ye instanceof lt||Ye instanceof Ve))throw new Error("Slice step must be numeric or undefined");return M instanceof re?new re(He(M.value,X.value,fe.value,Ye.value)):new Re(He(Array.from(M.value),X.value,fe.value,Ye.value).join(""))}evaluateMemberExpression(M,W){const S=this.evaluate(M.object,W);let X;if(M.computed){if(M.property.type==="SliceExpression")return this.evaluateSliceExpression(S,M.property,W);X=this.evaluate(M.property,W)}else X=new Re(M.property.value);let fe;if(S instanceof Tt){if(!(X instanceof Re))throw new Error(`Cannot access property with non-string: got ${X.type}`);fe=S.value.get(X.value)??S.builtins.get(X.value)}else if(S instanceof re||S instanceof Re)if(X instanceof lt)fe=S.value.at(X.value),S instanceof Re&&(fe=new Re(S.value.at(X.value)));else if(X instanceof Re)fe=S.builtins.get(X.value);else throw new Error(`Cannot access property with non-string/non-number: got ${X.type}`);else{if(!(X instanceof Re))throw new Error(`Cannot access property with non-string: got ${X.type}`);fe=S.builtins.get(X.value)}return fe instanceof rt?fe:new Ve}evaluateSet(M,W){const S=this.evaluate(M.value,W);if(M.assignee.type==="Identifier"){const X=M.assignee.value;W.setVariable(X,S)}else if(M.assignee.type==="MemberExpression"){const X=M.assignee,fe=this.evaluate(X.object,W);if(!(fe instanceof Tt))throw new Error("Cannot assign to member of non-object");if(X.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");fe.value.set(X.property.value,S)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(M.assignee)}`);return new Ge}evaluateIf(M,W){const S=this.evaluate(M.test,W);return this.evaluateBlock(S.__bool__().value?M.body:M.alternate,W)}evaluateFor(M,W){const S=new Ke(W);let X,fe;if(M.iterable.type==="SelectExpression"){const Se=M.iterable;fe=this.evaluate(Se.iterable,S),X=Se.test}else fe=this.evaluate(M.iterable,S);if(!(fe instanceof re))throw new Error(`Expected iterable type in for loop: got ${fe.type}`);const Ye=[],Je=[];for(let Se=0;SeBe.setVariable(M.loopvar.value,q);else if(M.loopvar.type==="TupleLiteral"){const Be=M.loopvar;if(q.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${q.type}`);const Ae=q;if(Be.value.length!==Ae.value.length)throw new Error(`Too ${Be.value.length>Ae.value.length?"few":"many"} items to unpack`);be=Ne=>{for(let dt=0;dt0?Ye[Se-1]:new Ve],["nextitem",Se{var Je;const fe=new Ke(X);S=S.slice();let Ye;((Je=S.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(Ye=S.pop());for(let At=0;Atthis.evaluate(S,W)));case"TupleLiteral":return new Ee(M.value.map(S=>this.evaluate(S,W)));case"ObjectLiteral":{const S=new Map;for(const[X,fe]of M.value){const Ye=this.evaluate(X,W);if(!(Ye instanceof Re))throw new Error(`Object keys must be strings: got ${Ye.type}`);S.set(Ye.value,this.evaluate(fe,W))}return new Tt(S)}case"Identifier":return this.evaluateIdentifier(M,W);case"CallExpression":return this.evaluateCallExpression(M,W);case"MemberExpression":return this.evaluateMemberExpression(M,W);case"UnaryExpression":return this.evaluateUnaryExpression(M,W);case"BinaryExpression":return this.evaluateBinaryExpression(M,W);case"FilterExpression":return this.evaluateFilterExpression(M,W);case"TestExpression":return this.evaluateTestExpression(M,W);default:throw new SyntaxError(`Unknown node type: ${M.type}`)}}};function mt(M){switch(typeof M){case"number":return new lt(M);case"string":return new Re(M);case"boolean":return new st(M);case"undefined":return new Ve;case"object":return M===null?new Ge:Array.isArray(M)?new re(M.map(mt)):new Tt(new Map(Object.entries(M).map(([W,S])=>[W,mt(S)])));case"function":return new je((W,S)=>{const X=M(...W.map(fe=>fe.value))??null;return mt(X)});default:throw new Error(`Cannot convert to runtime value: ${M}`)}}function wt(M,W,S){const X=S??0;switch(M.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(M.value);case"ArrayValue":case"ObjectValue":{const fe=W?" ".repeat(W):"",Ye=` `+fe.repeat(X),Je=Ye+fe;if(M.type==="ArrayValue"){const At=M.value.map(_t=>wt(_t,W,X+1));return W?`[${Je}${At.join(`,${Je}`)}${Ye}]`:`[${At.join(", ")}]`}else{const At=Array.from(M.value.entries()).map(([_t,Se])=>{const $=`"${_t}": ${wt(Se,W,X+1)}`;return W?`${Je}${$}`:$});return W?`{${At.join(",")}${Ye}}`:`{${At.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${M.type}`)}}var xt=class{constructor(M){Te(this,"parsed");const W=P(M,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=$e(W)}render(M){const W=new Ke;W.set("false",!1),W.set("true",!0),W.set("raise_exception",fe=>{throw new Error(fe)}),W.set("range",ee);for(const[fe,Ye]of Object.entries(M))W.set(fe,Ye);return new ut(W).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Mt,me,l)=>{l.r(me),l.d(me,{registerBackend:()=>ge,resolveBackendAndExecutionProviders:()=>xe});const x=new Map,H=[],ge=(D,T,j)=>{if(T&&typeof T.init=="function"&&typeof T.createInferenceSessionHandler=="function"){const P=x.get(D);if(P===void 0)x.set(D,{backend:T,priority:j});else{if(P.priority>j)return;if(P.priority===j&&P.backend!==T)throw new Error(`cannot register backend "${D}" using priority ${j}`)}if(j>=0){const J=H.indexOf(D);J!==-1&&H.splice(J,1);for(let te=0;te{const T=x.get(D);if(!T)return"backend not found.";if(T.initialized)return T.backend;if(T.aborted)return T.error;{const j=!!T.initPromise;try{return j||(T.initPromise=T.backend.init(D)),await T.initPromise,T.initialized=!0,T.backend}catch(P){return j||(T.error=`${P}`,T.aborted=!0),T.error}finally{delete T.initPromise}}},xe=async D=>{const T=D.executionProviders||[],j=T.map(R=>typeof R=="string"?R:R.name),P=j.length===0?H:j;let J;const te=[],ne=new Set;for(const R of P){const Y=await ve(R);typeof Y=="string"?te.push({name:R,err:Y}):(J||(J=Y),J===Y&&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:Y}of te)j.includes(R)&&console.warn(`removing requested execution provider "${R}" from session options because it is not available: ${Y}`);const ie=T.filter(R=>ne.has(typeof R=="string"?R:R.name));return[J,new Proxy(D,{get:(R,Y)=>Y==="executionProviders"?ie:Reflect.get(R,Y)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Mt,me,l)=>{l.r(me),l.d(me,{registerBackend:()=>x.registerBackend});var x=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Mt,me,l)=>{l.r(me),l.d(me,{env:()=>ge});var x=l("./node_modules/onnxruntime-common/dist/esm/version.js");let H="warning";const ge={wasm:{},webgl:{},webgpu:{},versions:{common:x.version},set logLevel(ve){if(ve!==void 0){if(typeof ve!="string"||["verbose","info","warning","error","fatal"].indexOf(ve)===-1)throw new Error(`Unsupported logging level: ${ve}`);H=ve}},get logLevel(){return H}};Object.defineProperty(ge,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Mt,me,l)=>{l.r(me),l.d(me,{env:()=>H});var x=l("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const H=x.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Mt,me,l)=>{l.r(me),l.d(me,{InferenceSession:()=>ge.InferenceSession,TRACE:()=>xe.TRACE,TRACE_FUNC_BEGIN:()=>xe.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>xe.TRACE_FUNC_END,Tensor:()=>ve.Tensor,TrainingSession:()=>D.TrainingSession,env:()=>H.env,registerBackend:()=>x.registerBackend});var x=l("./node_modules/onnxruntime-common/dist/esm/backend.js"),H=l("./node_modules/onnxruntime-common/dist/esm/env.js"),ge=l("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),ve=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":(Mt,me,l)=>{l.r(me),l.d(me,{InferenceSession:()=>ve});var x=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),H=l("./node_modules/onnxruntime-common/dist/esm/tensor.js"),ge=l("./node_modules/onnxruntime-common/dist/esm/trace.js");class ve{constructor(D){this.handler=D}async run(D,T,j){(0,ge.TRACE_FUNC_BEGIN)();const P={};let J={};if(typeof D!="object"||D===null||D instanceof H.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 T=="object"){if(T===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(T instanceof H.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(T)){if(T.length===0)throw new TypeError("'fetches' cannot be an empty array.");te=!1;for(const R of T){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 j=="object"&&j!==null)J=j;else if(typeof j<"u")throw new TypeError("'options' must be an object.")}else{let R=!1;const Y=Object.getOwnPropertyNames(T);for(const se of this.outputNames)if(Y.indexOf(se)!==-1){const le=T[se];(le===null||le instanceof H.Tensor)&&(R=!0,te=!1,P[se]=le)}if(R){if(typeof j=="object"&&j!==null)J=j;else if(typeof j<"u")throw new TypeError("'options' must be an object.")}else J=T}}else if(typeof T<"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 Y=ne[R];Y instanceof H.Tensor?ie[R]=Y:ie[R]=new H.Tensor(Y.type,Y.data,Y.dims)}return(0,ge.TRACE_FUNC_END)(),ie}async release(){return this.handler.dispose()}static async create(D,T,j,P){(0,ge.TRACE_FUNC_BEGIN)();let J,te={};if(typeof D=="string"){if(J=D,typeof T=="object"&&T!==null)te=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else if(D instanceof Uint8Array){if(J=D,typeof T=="object"&&T!==null)te=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else if(D instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&D instanceof SharedArrayBuffer){const Y=D;let se=0,le=D.byteLength;if(typeof T=="object"&&T!==null)te=T;else if(typeof T=="number"){if(se=T,!Number.isSafeInteger(se))throw new RangeError("'byteOffset' must be an integer.");if(se<0||se>=Y.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${Y.byteLength}).`);if(le=D.byteLength-se,typeof j=="number"){if(le=j,!Number.isSafeInteger(le))throw new RangeError("'byteLength' must be an integer.");if(le<=0||se+le>Y.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${Y.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 j<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof T<"u")throw new TypeError("'options' must be an object.");J=new Uint8Array(Y,se,le)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[ne,ie]=await(0,x.resolveBackendAndExecutionProviders)(te),R=await ne.createInferenceSessionHandler(J,ie);return(0,ge.TRACE_FUNC_END)(),new ve(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":(Mt,me,l)=>{l.r(me),l.d(me,{InferenceSession:()=>H});var x=l("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const H=x.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Mt,me,l)=>{l.r(me)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Mt,me,l)=>{l.r(me)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Mt,me,l)=>{l.r(me),l.d(me,{tensorToDataURL:()=>x,tensorToImageData:()=>H});const x=(ge,ve)=>{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 T,j;(ve==null?void 0:ve.tensorLayout)!==void 0&&ve.tensorLayout==="NHWC"?(T=ge.dims[2],j=ge.dims[3]):(T=ge.dims[3],j=ge.dims[2]);const P=(ve==null?void 0:ve.format)!==void 0?ve.format:"RGB",J=ve==null?void 0:ve.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=j*T;let R=0,Y=ie,se=ie*2,le=-1;P==="RGBA"?(R=0,Y=ie,se=ie*2,le=ie*3):P==="RGB"?(R=0,Y=ie,se=ie*2):P==="RBG"&&(R=0,se=ie,Y=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 T,j,P;(ve==null?void 0:ve.tensorLayout)!==void 0&&ve.tensorLayout==="NHWC"?(T=ge.dims[2],j=ge.dims[1],P=ge.dims[3]):(T=ge.dims[3],j=ge.dims[2],P=ge.dims[1]);const J=ve!==void 0&&ve.format!==void 0?ve.format:"RGB",te=ve==null?void 0:ve.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=j*T;if(ve!==void 0&&(ve.format!==void 0&&P===4&&ve.format!=="RGBA"||P===3&&ve.format!=="RGB"&&ve.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const Y=4;let se=0,le=1,ae=2,N=3,I=0,B=R,A=R*2,_e=-1;J==="RGBA"?(I=0,B=R,A=R*2,_e=R*3):J==="RGB"?(I=0,B=R,A=R*2):J==="RBG"&&(I=0,A=R,B=R*2),D=xe.createImageData(T,j);for(let ye=0;ye{l.r(me)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Mt,me,l)=>{l.r(me),l.d(me,{bufferToTensor:()=>H,tensorFromGpuBuffer:()=>xe,tensorFromImage:()=>ge,tensorFromPinnedBuffer:()=>D,tensorFromTexture:()=>ve});var x=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const H=(T,j)=>{if(T===void 0)throw new Error("Image buffer must be defined");if(j.height===void 0||j.width===void 0)throw new Error("Image height and width must be defined");if(j.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:P,width:J}=j,te=j.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=j.format!==void 0?j.format:"RGBA",Y=j.tensorFormat!==void 0&&j.tensorFormat!==void 0?j.tensorFormat:"RGB",se=P*J,le=Y==="RGBA"?new Float32Array(se*4):new Float32Array(se*3);let ae=4,N=0,I=1,B=2,A=3,_e=0,ye=se,Ce=se*2,ke=-1;R==="RGB"&&(ae=3,N=0,I=1,B=2,A=-1),Y==="RGBA"?ke=se*3:Y==="RBG"?(_e=0,Ce=se,ye=se*2):Y==="BGR"&&(Ce=0,ye=se,_e=se*2);for(let tt=0;tt{const P=typeof HTMLImageElement<"u"&&T instanceof HTMLImageElement,J=typeof ImageData<"u"&&T instanceof ImageData,te=typeof ImageBitmap<"u"&&T instanceof ImageBitmap,ne=typeof T=="string";let ie,R=j??{};const Y=()=>{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=le=>le instanceof HTMLCanvasElement||le instanceof OffscreenCanvas?le.getContext("2d"):null;if(P){const le=Y();le.width=T.width,le.height=T.height;const ae=se(le);if(ae!=null){let N=T.height,I=T.width;if(j!==void 0&&j.resizedHeight!==void 0&&j.resizedWidth!==void 0&&(N=j.resizedHeight,I=j.resizedWidth),j!==void 0){if(R=j,j.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");R.tensorFormat="RGBA",R.height=N,R.width=I}else R.tensorFormat="RGBA",R.height=N,R.width=I;ae.drawImage(T,0,0),ie=ae.getImageData(0,0,I,N).data}else throw new Error("Can not access image data")}else if(J){let le,ae;if(j!==void 0&&j.resizedWidth!==void 0&&j.resizedHeight!==void 0?(le=j.resizedHeight,ae=j.resizedWidth):(le=T.height,ae=T.width),j!==void 0&&(R=j),R.format="RGBA",R.height=le,R.width=ae,j!==void 0){const N=Y();N.width=ae,N.height=le;const I=se(N);if(I!=null)I.putImageData(T,0,0),ie=I.getImageData(0,0,ae,le).data;else throw new Error("Can not access image data")}else ie=T.data}else if(te){if(j===void 0)throw new Error("Please provide image config with format for Imagebitmap");const le=Y();le.width=T.width,le.height=T.height;const ae=se(le);if(ae!=null){const N=T.height,I=T.width;return ae.drawImage(T,0,0,I,N),ie=ae.getImageData(0,0,I,N).data,R.height=N,R.width=I,H(ie,R)}else throw new Error("Can not access image data")}else{if(ne)return new Promise((le,ae)=>{const N=Y(),I=se(N);if(!T||!I)return ae();const B=new Image;B.crossOrigin="Anonymous",B.src=T,B.onload=()=>{N.width=B.width,N.height=B.height,I.drawImage(B,0,0,N.width,N.height);const A=I.getImageData(0,0,N.width,N.height);R.height=N.height,R.width=N.width,le(H(A.data,R))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ie!==void 0)return H(ie,R);throw new Error("Input data provided is not supported - aborted tensor creation")},ve=(T,j)=>{const{width:P,height:J,download:te,dispose:ne}=j,ie=[1,J,P,4];return new x.Tensor({location:"texture",type:"float32",texture:T,dims:ie,download:te,dispose:ne})},xe=(T,j)=>{const{dataType:P,dims:J,download:te,dispose:ne}=j;return new x.Tensor({location:"gpu-buffer",type:P??"float32",gpuBuffer:T,dims:J,download:te,dispose:ne})},D=(T,j,P)=>new x.Tensor({location:"cpu-pinned",type:T,data:j,dims:P??[j.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Mt,me,l)=>{l.r(me)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Mt,me,l)=>{l.r(me),l.d(me,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>H,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>x,checkTypedArray:()=>ve});const x=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),H=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ge=!1;const ve=()=>{if(!ge){ge=!0;const xe=typeof BigInt64Array<"u"&&BigInt64Array.from,D=typeof BigUint64Array<"u"&&BigUint64Array.from,T=typeof Float16Array<"u"&&Float16Array.from;xe&&(x.set("int64",BigInt64Array),H.set(BigInt64Array,"int64")),D&&(x.set("uint64",BigUint64Array),H.set(BigUint64Array,"uint64")),T?(x.set("float16",Float16Array),H.set(Float16Array,"float16")):x.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Mt,me,l)=>{l.r(me),l.d(me,{Tensor:()=>xe});var x=l("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),H=l("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),ge=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),ve=l("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class xe{constructor(T,j,P){(0,ge.checkTypedArray)();let J,te;if(typeof T=="object"&&"location"in T)switch(this.dataLocation=T.location,J=T.type,te=T.dims,T.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(!(T.data instanceof ie))throw new TypeError(`buffer should be of type ${ie.name}`);this.cpuData=T.data;break}case"texture":{if(J!=="float32")throw new TypeError(`unsupported type "${J}" to create tensor from texture`);this.gpuTextureData=T.texture,this.downloader=T.download,this.disposer=T.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=T.gpuBuffer,this.downloader=T.download,this.disposer=T.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ie,R;if(typeof T=="string")if(J=T,R=P,T==="string"){if(!Array.isArray(j))throw new TypeError("A string tensor's data must be a string array.");ie=j}else{const Y=ge.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(T);if(Y===void 0)throw new TypeError(`Unsupported tensor type: ${T}.`);if(Array.isArray(j)){if(T==="float16"&&Y===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");T==="uint64"||T==="int64"?ie=Y.from(j,BigInt):ie=Y.from(j)}else if(j instanceof Y)ie=j;else throw new TypeError(`A ${J} tensor's data must be type of ${Y}`)}else if(R=j,Array.isArray(T)){if(T.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const Y=typeof T[0];if(Y==="string")J="string",ie=T;else if(Y==="boolean")J="bool",ie=Uint8Array.from(T);else throw new TypeError(`Invalid element type of data array: ${Y}.`)}else{const Y=ge.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(T.constructor);if(Y===void 0)throw new TypeError(`Unsupported type for tensor data: ${T.constructor}.`);J=Y,ie=T}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,ve.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(T,j){return(0,H.tensorFromImage)(T,j)}static fromTexture(T,j){return(0,H.tensorFromTexture)(T,j)}static fromGpuBuffer(T,j){return(0,H.tensorFromGpuBuffer)(T,j)}static fromPinnedBuffer(T,j,P){return(0,H.tensorFromPinnedBuffer)(T,j,P)}toDataURL(T){return(0,x.tensorToDataURL)(this,T)}toImageData(T){return(0,x.tensorToImageData)(this,T)}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(T){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 j=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=j,T&&this.disposer&&(this.disposer(),this.disposer=void 0),j}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(T){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,ve.tensorReshape)(this,T)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Mt,me,l)=>{l.r(me),l.d(me,{calculateSize:()=>H,tensorReshape:()=>ge});var x=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const H=ve=>{let xe=1;for(let D=0;D{switch(ve.location){case"cpu":return new x.Tensor(ve.type,ve.data,xe);case"cpu-pinned":return new x.Tensor({location:"cpu-pinned",data:ve.data,type:ve.type,dims:xe});case"texture":return new x.Tensor({location:"texture",texture:ve.texture,type:ve.type,dims:xe});case"gpu-buffer":return new x.Tensor({location:"gpu-buffer",gpuBuffer:ve.gpuBuffer,type:ve.type,dims:xe});default:throw new Error(`tensorReshape: tensor location ${ve.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Mt,me,l)=>{l.r(me),l.d(me,{Tensor:()=>H});var x=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const H=x.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Mt,me,l)=>{l.r(me),l.d(me,{TRACE:()=>H,TRACE_FUNC_BEGIN:()=>ve,TRACE_FUNC_END:()=>xe});var x=l("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const H=(D,T)=>{(typeof x.env.trace>"u"?!x.env.wasm.trace:!x.env.trace)||console.timeStamp(`${D}::ORT::${T}`)},ge=(D,T)=>{var J;const j=((J=new Error().stack)==null?void 0:J.split(/\r\n|\r|\n/g))||[];let P=!1;for(let te=0;te{(typeof x.env.trace>"u"?!x.env.wasm.trace:!x.env.trace)||ge("BEGIN",D)},xe=D=>{(typeof x.env.trace>"u"?!x.env.wasm.trace:!x.env.trace)||ge("END",D)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Mt,me,l)=>{l.r(me),l.d(me,{TrainingSession:()=>ve});var x=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),H=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 ve{constructor(D,T,j){this.handler=D,this.hasOptimizerModel=T,this.hasEvalModel=j}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,T){const j=D.evalModel||"",P=D.optimizerModel||"",J=T||{},[te,ne]=await(0,x.resolveBackendAndExecutionProviders)(J);if(te.createTrainingSessionHandler){const ie=await te.createTrainingSessionHandler(D.checkpointState,D.trainModel,j,P,ne);return new ve(ie,!!D.optimizerModel,!!D.evalModel)}else throw new Error(ge)}typeNarrowingForRunStep(D,T,j,P,J){const te={};let ne={};if(typeof j!="object"||j===null||j instanceof H.Tensor||Array.isArray(j))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 H.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(T.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 Y=Object.getOwnPropertyNames(P);for(const se of T)if(Y.indexOf(se)!==-1){const le=P[se];(le===null||le instanceof H.Tensor)&&(R=!0,ie=!1,te[se]=le)}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 j[R]>"u")throw new Error(`input '${R}' is missing in 'feeds'.`);if(ie)for(const R of T)te[R]=null;return[te,ne]}convertHandlerReturnTypeToMapOfTensors(D){const T={};for(const j in D)if(Object.hasOwnProperty.call(D,j)){const P=D[j];P instanceof H.Tensor?T[j]=P:T[j]=new H.Tensor(P.type,P.data,P.dims)}return T}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(D,T,j){const[P,J]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,D,T,j),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,T,j){if(this.hasEvalModel){const[P,J]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,D,T,j),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,T=!0){const j=await this.getParametersSize(T);if(D.length!==4*j)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,T)}async getContiguousParameters(D=!0){return this.handler.getContiguousParameters(D)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Mt,me,l)=>{l.r(me),l.d(me,{TrainingSession:()=>H});var x=l("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const H=x.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Mt,me,l)=>{l.r(me),l.d(me,{version:()=>x});const x="1.18.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(Mt,me,l)=>{l.r(me),l.d(me,{InferenceSession:()=>wt,TRACE:()=>Ee,TRACE_FUNC_BEGIN:()=>Ge,TRACE_FUNC_END:()=>Ve,Tensor:()=>ze,TrainingSession:()=>At,default:()=>vf,env:()=>A,registerBackend:()=>ne});/*! * ONNX Runtime Web v1.19.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var x=Object.defineProperty,H=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyNames,ve=Object.prototype.hasOwnProperty,xe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),D=(e,t)=>()=>(e&&(t=e(e=0)),t),T=(e,t)=>{for(var r in t)x(e,r,{get:t[r],enumerable:!0})},j=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ge(t))!ve.call(e,s)&&s!==r&&x(e,s,{get:()=>t[s],enumerable:!(n=H(t,s))||n.enumerable});return e},P=e=>j(x({},"__esModule",{value:!0}),e),J,te,ne,ie,R,Y=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 h=await ie(c);typeof h=="string"?a.push({name:c,err:h}):(s||(s=h),s===h&&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:h}of a)r.includes(c)&&console.warn(`removing requested execution provider "${c}" from session options because it is not available: ${h}`);let d=t.filter(c=>i.has(typeof c=="string"?c:c.name));return[s,new Proxy(e,{get:(c,h)=>h==="executionProviders"?d:Reflect.get(c,h)})]}}),se=D(()=>{Y()}),le,ae=D(()=>{le="1.19.0"}),N,I,B=D(()=>{ae(),N="warning",I={wasm:{},webgl:{},webgpu:{},versions:{common:le},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(I,"logLevel",{enumerable:!0})}),A,_e=D(()=>{B(),A=I}),ye,Ce,ke=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,h;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?h=[0,0,0,0]:typeof d.bias=="number"?h=[d.bias,d.bias,d.bias,d.bias]:(h=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(h[3]=d.bias[3]));let w=a*s,y=0,u=w,k=w*2,C=-1;i==="RGBA"?(y=0,u=w,k=w*2,C=w*3):i==="RGB"?(y=0,u=w,k=w*2):i==="RBG"&&(y=0,k=w,u=w*2);for(let F=0;F{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,h,w;c===void 0||c.mean===void 0?h=[255,255,255,255]:typeof c.mean=="number"?h=[c.mean,c.mean,c.mean,c.mean]:(h=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(h[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,k=0,C=1,F=2,U=3,G=0,L=y,pe=y*2,Z=-1;d==="RGBA"?(G=0,L=y,pe=y*2,Z=y*3):d==="RGB"?(G=0,L=y,pe=y*2):d==="RBG"&&(G=0,pe=y,L=y*2),n=r.createImageData(s,a);for(let oe=0;oe{Tt(),Ie=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*n,w=c==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),y=4,u=0,k=1,C=2,F=3,U=0,G=h,L=h*2,pe=-1;d==="RGB"&&(y=3,u=0,k=1,C=2,F=-1),c==="RGBA"?pe=h*3:c==="RBG"?(U=0,L=h,G=h*2):c==="BGR"&&(L=0,G=h,U=h*2);for(let Z=0;Z{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,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")},h=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=h(w);if(y!=null){let u=e.height,k=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(u=t.resizedHeight,k=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=k}else d.tensorFormat="RGBA",d.height=u,d.width=k;y.drawImage(e,0,0),i=y.getImageData(0,0,k,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 k=h(u);if(k!=null)k.putImageData(e,0,0),i=k.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=h(w);if(y!=null){let u=e.height,k=e.width;return y.drawImage(e,0,0,k,u),i=y.getImageData(0,0,k,u).data,d.height=u,d.width=k,Ie(i,d)}else throw new Error("Can not access image data")}else{if(a)return new Promise((w,y)=>{let u=c(),k=h(u);if(!e||!k)return y();let C=new Image;C.crossOrigin="Anonymous",C.src=e,C.onload=()=>{u.width=C.width,u.height=C.height,k.drawImage(C,0,0,u.width,u.height);let F=k.getImageData(0,0,u.width,u.height);d.height=u.height,d.width=u.width,w(Ie(F.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ie(i,d);throw new Error("Input data provided is not supported - aborted tensor creation")},Qe=(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})},ht=(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]})}),he,$e,ee,He,pt=D(()=>{he=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),$e=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ee=!1,He=()=>{if(!ee){ee=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(he.set("int64",BigInt64Array),$e.set(BigInt64Array,"int64")),t&&(he.set("uint64",BigUint64Array),$e.set(BigUint64Array,"uint64")),r?(he.set("float16",Float16Array),$e.set(Float16Array,"float16")):he.set("float16",Uint16Array)}}}),rt,lt,Re=D(()=>{Tt(),rt=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,Tt=D(()=>{ke(),V(),pt(),Re(),st=class{constructor(e,t,r){He();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=he.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=he.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&c===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array 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=$e.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=rt(s);if(this.cpuData&&a!==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 tt(e,t)}static fromTexture(e,t){return Qe(e,t)}static fromGpuBuffer(e,t){return ht(e,t)}static fromPinnedBuffer(e,t,r){return we(e,t,r)}toDataURL(e){return ye(this,e)}toImageData(e){return Ce(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}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 lt(this,e)}}}),ze,re=D(()=>{Tt(),ze=st}),Ee,je,Ge,Ve,Ke=D(()=>{B(),Ee=(e,t)=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||console.timeStamp(`${e}::ORT::${t}`)},je=(e,t)=>{var s;let r=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||je("BEGIN",e)},Ve=e=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||je("END",e)}}),ut,mt=D(()=>{Y(),re(),Ke(),ut=class Qh{constructor(t){this.handler=t}async run(t,r,n){Ge();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 h of r){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);s[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!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)&&(h=!0,i=!1,s[y]=u)}if(h){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 h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(i)for(let h of this.outputNames)s[h]=null;let d=await this.handler.run(t,s,a),c={};for(let h in d)if(Object.hasOwnProperty.call(d,h)){let w=d[h];w instanceof ze?c[h]=w:c[h]=new ze(w.type,w.data,w.dims)}return Ve(),c}async release(){return this.handler.dispose()}static async create(t,r,n,s){Ge();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),h=await d.createInferenceSessionHandler(a,c);return Ve(),new Qh(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),wt,xt=D(()=>{mt(),wt=ut}),M=D(()=>{}),W=D(()=>{}),S=D(()=>{}),X=D(()=>{}),fe,Ye,Je=D(()=>{Y(),re(),fe="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Ye=class Yh{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 Yh(c,!!t.optimizerModel,!!t.evalModel)}else throw new Error(fe)}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 h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);i[h]=null}if(typeof a=="object"&&a!==null)d=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,w=Object.getOwnPropertyNames(s);for(let y of r)if(w.indexOf(y)!==-1){let u=s[y];(u===null||u instanceof ze)&&(h=!0,c=!1,i[y]=u)}if(h){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 h of t)if(typeof n[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(c)for(let h of r)i[h]=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()}}}),At,_t=D(()=>{Je(),At=Ye}),Se={};T(Se,{InferenceSession:()=>wt,TRACE:()=>Ee,TRACE_FUNC_BEGIN:()=>Ge,TRACE_FUNC_END:()=>Ve,Tensor:()=>ze,TrainingSession:()=>At,env:()=>A,registerBackend:()=>ne});var $=D(()=>{se(),_e(),xt(),re(),M(),W(),Ke(),S(),X(),_t()}),q=D(()=>{}),be={};T(be,{default:()=>Ne});var Be,Ae,Ne,dt=D(()=>{var e;_p(),Zr(),Ur(),Be="ort-wasm-proxy-worker",Ae=((e=globalThis.self)==null?void 0:e.name)===Be,Ae&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Fn(n.wasm).then(()=>{Dd(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;Bd(a,s).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})});break}case"copy-from":{let{buffer:s}=n,a=dd(s);postMessage({type:r,out:a});break}case"create":{let{model:s,options:a}=n;Ld(s,a).then(i=>{postMessage({type:r,out:i})},i=>{postMessage({type:r,err:i})});break}case"release":Rd(n),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:a,inputs:i,outputIndices:d,options:c}=n;jd(s,a,i,d,new Array(d.length).fill(null),c).then(h=>{h.some(w=>w[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:h},Ud([...i,...h]))},h=>{postMessage({type:r,err:h})});break}case"end-profiling":Vd(n),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),Ne=Ae?null:t=>new Worker(t??Xe,{type:"module",name:Be})}),nt={};T(nt,{default:()=>Ct});var vt,ft,Ct,Lt=D(()=>{var e;ft=(vt=self.location.href,async function(t={}){function r(){return cr.buffer!=Zt.buffer&&hn(),Zt}function n(){return cr.buffer!=Zt.buffer&&hn(),_r}function s(){return cr.buffer!=Zt.buffer&&hn(),Le}function a(){return cr.buffer!=Zt.buffer&&hn(),Nt}function i(){return cr.buffer!=Zt.buffer&&hn(),tr}function d(){return cr.buffer!=Zt.buffer&&hn(),Br}function c(){return cr.buffer!=Zt.buffer&&hn(),Xr}function h(){return cr.buffer!=Zt.buffer&&hn(),En}var w,y,u=Object.assign({},t),k=new Promise((o,f)=>{w=o,y=f}),C=typeof window=="object",F=typeof importScripts=="function",U=F&&self.name=="em-pthread";u.mountExternalData=(o,f)=>{(u.Fb||(u.Fb=new Map)).set(o,f)},u.unmountExternalData=()=>{delete u.Fb};var G=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let L=()=>{let o=(b,v,z)=>(...ce)=>{let Ue=ts,ot=v==null?void 0:v();ce=b(...ce);let Et=v==null?void 0:v();return ot!==Et&&(b=Et,z(ot),v=z=null),ts!=Ue?new Promise((It,Kt)=>{oc={resolve:It,reject:Kt}}):ce},f=b=>async(...v)=>{var z;try{if(u.Eb)throw Error("Session already started");let ce=u.Eb={bc:v[0],errors:[]},Ue=await b(...v);if(u.Eb!==ce)throw Error("Session mismatch");(z=u.Mb)==null||z.flush();let ot=ce.errors;if(0It),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.Mb,u.Tb,u.Xb,u.Nb,u.Wb,u.jb,u.Yb,u.$b,u.Ub,u.Vb,u.Zb]=f;let b=u.Mb;u.jsepRegisterBuffer=(v,z,ce,Ue)=>b.registerBuffer(v,z,ce,Ue),u.jsepGetBuffer=v=>b.getBuffer(v),u.jsepCreateDownloader=(v,z,ce)=>b.createDownloader(v,z,ce),u.jsepOnReleaseSession=v=>{b.onReleaseSession(v)},u.jsepOnRunStart=v=>b.onRunStart(v)}};var pe,Z,oe=Object.assign({},u),et="./this.program",We=(o,f)=>{throw f},ct="";(C||F)&&(F?ct=self.location.href:typeof document<"u"&&document.currentScript&&(ct=document.currentScript.src),vt&&(ct=vt),ct=ct.startsWith("blob:")?"":ct.substr(0,ct.replace(/[?#].*/,"").lastIndexOf("/")+1),F&&(Z=o=>{var f=new XMLHttpRequest;return f.open("GET",o,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),pe=(o,f,b)=>{var v=new XMLHttpRequest;v.open("GET",o,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?f(v.response):b()},v.onerror=b,v.send(null)});var Ot,zt=console.log.bind(console),hr=console.error.bind(console),br=zt,rr=hr;if(Object.assign(u,oe),oe=null,U){let o=function(f){try{var b=f.data,v=b.cmd;if(v==="load"){let z=[];self.onmessage=ce=>z.push(ce),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ce of z)o(ce);self.onmessage=o};for(let ce of b.handlers)u[ce]&&!u[ce].proxy||(u[ce]=(...Ue)=>{postMessage({Lb:"callHandler",kc:ce,args:Ue})},ce=="print"&&(br=u[ce]),ce=="printErr"&&(rr=u[ce]));cr=b.wasmMemory,hn(),Sr(b.wasmModule)}else if(v==="run"){cc(b.pthread_ptr,0,0,1,0,0),sc(b.pthread_ptr),Cf(),jp(),Wr||(Lh(),Wr=!0);try{$f(b.start_routine,b.arg)}catch(z){if(z!="unwind")throw z}}else v==="cancel"?Aa()&&Td(-1):b.target!=="setimmediate"&&(v==="checkMailbox"?Wr&&md():v&&(rr(`worker: received unknown command ${v}`),rr(b)))}catch(z){throw Rh(),z}};var Sr,Wr=!1;rr=function(...f){f=f.join(" "),console.error(f)},self.alert=function(...f){postMessage({Lb:"alert",text:f.join(" "),mc:Aa()})},u.instantiateWasm=(f,b)=>new Promise(v=>{Sr=z=>{z=new WebAssembly.Instance(z,Dp()),b(z),v()}}),self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=o}u.wasmBinary&&(Ot=u.wasmBinary);var cr,Rr,Bt,Zt,_r,Le,Nt,tr,Br,Xr,an,zs,En,In=!1;function hn(){var o=cr.buffer;u.HEAP8=Zt=new Int8Array(o),u.HEAP16=Le=new Int16Array(o),u.HEAPU8=_r=new Uint8Array(o),u.HEAPU16=Nt=new Uint16Array(o),u.HEAP32=tr=new Int32Array(o),u.HEAPU32=Br=new Uint32Array(o),u.HEAPF32=Xr=new Float32Array(o),u.HEAPF64=En=new Float64Array(o),u.HEAP64=an=new BigInt64Array(o),u.HEAPU64=zs=new BigUint64Array(o)}if(!U){if(!((cr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof G))throw rr("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");hn()}var Au=[],fn=[],Tn=[],Nn=0,Ds=null;function hd(){if(--Nn==0&&Ds){var o=Ds;Ds=null,o()}}function Sa(o){throw rr(o="Aborted("+o+")"),In=!0,Bt=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),y(o),o}var qd,Ip=o=>o.startsWith("data:application/octet-stream;base64,"),Fp=o=>o.startsWith("file://");function Op(o){if(o==qd&&Ot)return new Uint8Array(Ot);if(Z)return Z(o);throw"both async and sync fetching of the wasm failed"}function zp(o,f,b){return function(v){if(!Ot&&(C||F)){if(typeof fetch=="function"&&!Fp(v))return fetch(v,{credentials:"same-origin"}).then(z=>{if(!z.ok)throw`failed to load wasm binary file at '${v}'`;return z.arrayBuffer()}).catch(()=>Op(v));if(pe)return new Promise((z,ce)=>{pe(v,Ue=>z(new Uint8Array(Ue)),ce)})}return Promise.resolve().then(()=>Op(v))}(o).then(v=>WebAssembly.instantiate(v,f)).then(b,v=>{rr(`failed to asynchronously prepare wasm: ${v}`),Sa(v)})}function Dp(){return{a:{M:Tf,za:xf,b:Sf,$:Gp,z:Kp,pa:Xp,X:Yp,Z:Zp,qa:Jp,na:eh,ga:th,ma:rh,J:nh,Y:sh,V:ih,oa:ah,W:oh,va:kf,D:Pf,P:Af,O:Ff,C:zf,s:Df,p:Bf,E:Lf,y:Gf,Q:qf,ta:Hf,ja:Kf,T:Xf,aa:Qf,F:Yf,ia:sc,sa:Zf,u:Jf,B:rm,o:nm,m:im,c:rc,n:am,k:um,Aa:dm,r:cm,f:pm,v:hm,l:fm,g:mm,i:_m,j:gm,h:wm,e:ym,da:bm,ea:Mm,fa:vm,ba:Mh,ca:vh,S:xm,d:Tm,N:Cm,G:$m,K:Em,w:Sm,ra:km,U:Pm,t:Th,x:Am,L:Im,R:Fm,ya:Om,xa:zm,ka:Eh,la:Sh,_:Yd,A:kh,I:Ph,ha:Ah,H:Ih,a:cr,wa:Qd,ua:zh,q:Lm}}}var Hd={849460:(o,f,b,v)=>{if(u===void 0||!u.Fb)return 1;if((o=dn(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=u.Fb.get(o)))return 2;if(v>>>=0,(f>>>=0)+(b>>>=0)>o.byteLength)return 3;try{return n().set(o.subarray(f,f+b),v>>>0),0}catch{return 4}},849961:()=>{u.Ub()},849992:()=>{u.Vb()},850021:()=>{u.Zb()},850046:o=>u.Tb(o),850079:o=>u.Xb(o),850111:(o,f,b)=>{u.Nb(o,f,b,!0)},850150:(o,f,b)=>{u.Nb(o,f,b)},850183:()=>typeof wasmOffsetConverter<"u",850240:o=>{u.jb("Abs",o,void 0)},850291:o=>{u.jb("Neg",o,void 0)},850342:o=>{u.jb("Floor",o,void 0)},850395:o=>{u.jb("Ceil",o,void 0)},850447:o=>{u.jb("Reciprocal",o,void 0)},850505:o=>{u.jb("Sqrt",o,void 0)},850557:o=>{u.jb("Exp",o,void 0)},850608:o=>{u.jb("Erf",o,void 0)},850659:o=>{u.jb("Sigmoid",o,void 0)},850714:(o,f,b)=>{u.jb("HardSigmoid",o,{alpha:f,beta:b})},850793:o=>{u.jb("Log",o,void 0)},850844:o=>{u.jb("Sin",o,void 0)},850895:o=>{u.jb("Cos",o,void 0)},850946:o=>{u.jb("Tan",o,void 0)},850997:o=>{u.jb("Asin",o,void 0)},851049:o=>{u.jb("Acos",o,void 0)},851101:o=>{u.jb("Atan",o,void 0)},851153:o=>{u.jb("Sinh",o,void 0)},851205:o=>{u.jb("Cosh",o,void 0)},851257:o=>{u.jb("Asinh",o,void 0)},851310:o=>{u.jb("Acosh",o,void 0)},851363:o=>{u.jb("Atanh",o,void 0)},851416:o=>{u.jb("Tanh",o,void 0)},851468:o=>{u.jb("Not",o,void 0)},851519:(o,f,b)=>{u.jb("Clip",o,{min:f,max:b})},851588:o=>{u.jb("Clip",o,void 0)},851640:(o,f)=>{u.jb("Elu",o,{alpha:f})},851698:o=>{u.jb("Relu",o,void 0)},851750:(o,f)=>{u.jb("LeakyRelu",o,{alpha:f})},851814:(o,f)=>{u.jb("ThresholdedRelu",o,{alpha:f})},851884:(o,f)=>{u.jb("Cast",o,{to:f})},851942:o=>{u.jb("Add",o,void 0)},851993:o=>{u.jb("Sub",o,void 0)},852044:o=>{u.jb("Mul",o,void 0)},852095:o=>{u.jb("Div",o,void 0)},852146:o=>{u.jb("Pow",o,void 0)},852197:o=>{u.jb("Equal",o,void 0)},852250:o=>{u.jb("Greater",o,void 0)},852305:o=>{u.jb("GreaterOrEqual",o,void 0)},852367:o=>{u.jb("Less",o,void 0)},852419:o=>{u.jb("LessOrEqual",o,void 0)},852478:(o,f,b,v,z)=>{u.jb("ReduceMean",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852637:(o,f,b,v,z)=>{u.jb("ReduceMax",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852795:(o,f,b,v,z)=>{u.jb("ReduceMin",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852953:(o,f,b,v,z)=>{u.jb("ReduceProd",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},853112:(o,f,b,v,z)=>{u.jb("ReduceSum",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},853270:(o,f,b,v,z)=>{u.jb("ReduceL1",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},853427:(o,f,b,v,z)=>{u.jb("ReduceL2",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},853584:(o,f,b,v,z)=>{u.jb("ReduceLogSum",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},853745:(o,f,b,v,z)=>{u.jb("ReduceSumSquare",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},853909:(o,f,b,v,z)=>{u.jb("ReduceLogSumExp",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},854073:o=>{u.jb("Where",o,void 0)},854126:(o,f,b)=>{u.jb("Transpose",o,{perm:f?Array.from(i().subarray(f>>>0,b>>>0)):[]})},854234:(o,f,b,v)=>{u.jb("DepthToSpace",o,{blocksize:f,mode:dn(b),format:v?"NHWC":"NCHW"})},854367:(o,f,b,v)=>{u.jb("DepthToSpace",o,{blocksize:f,mode:dn(b),format:v?"NHWC":"NCHW"})},854500:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe,sr)=>{u.jb("ConvTranspose",o,{format:Et?"NHWC":"NCHW",autoPad:f,dilations:[b],group:v,kernelShape:[z],pads:[ce,Ue],strides:[ot],wIsConst:()=>!!r()[It>>>0],outputPadding:Kt?Array.from(i().subarray(Kt>>>0,kr>>>0)):[],outputShape:Fr?Array.from(i().subarray(Fr>>>0,Oe>>>0)):[],activation:dn(sr)})},854901:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe)=>{u.jb("ConvTranspose",o,{format:ot?"NHWC":"NCHW",autoPad:f,dilations:Array.from(i().subarray(b>>>0,2+(b>>>0)>>>0)),group:v,kernelShape:Array.from(i().subarray(z>>>0,2+(z>>>0)>>>0)),pads:Array.from(i().subarray(ce>>>0,4+(ce>>>0)>>>0)),strides:Array.from(i().subarray(Ue>>>0,2+(Ue>>>0)>>>0)),wIsConst:()=>!!r()[Et>>>0],outputPadding:It?Array.from(i().subarray(It>>>0,Kt>>>0)):[],outputShape:kr?Array.from(i().subarray(kr>>>0,Fr>>>0)):[],activation:dn(Oe)})},855466:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe,sr)=>{u.jb("ConvTranspose",o,{format:Et?"NHWC":"NCHW",autoPad:f,dilations:[b],group:v,kernelShape:[z],pads:[ce,Ue],strides:[ot],wIsConst:()=>!!r()[It>>>0],outputPadding:Kt?Array.from(i().subarray(Kt>>>0,kr>>>0)):[],outputShape:Fr?Array.from(i().subarray(Fr>>>0,Oe>>>0)):[],activation:dn(sr)})},855867:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe)=>{u.jb("ConvTranspose",o,{format:ot?"NHWC":"NCHW",autoPad:f,dilations:Array.from(i().subarray(b>>>0,2+(b>>>0)>>>0)),group:v,kernelShape:Array.from(i().subarray(z>>>0,2+(z>>>0)>>>0)),pads:Array.from(i().subarray(ce>>>0,4+(ce>>>0)>>>0)),strides:Array.from(i().subarray(Ue>>>0,2+(Ue>>>0)>>>0)),wIsConst:()=>!!r()[Et>>>0],outputPadding:It?Array.from(i().subarray(It>>>0,Kt>>>0)):[],outputShape:kr?Array.from(i().subarray(kr>>>0,Fr>>>0)):[],activation:dn(Oe)})},856432:(o,f)=>{u.jb("GlobalAveragePool",o,{format:f?"NHWC":"NCHW"})},856523:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe,sr,zr)=>{u.jb("AveragePool",o,{format:zr?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:v,storage_order:z,dilations:[ce,Ue],kernel_shape:[ot,Et],pads:[It,Kt,kr,Fr],strides:[Oe,sr]})},856807:(o,f)=>{u.jb("GlobalAveragePool",o,{format:f?"NHWC":"NCHW"})},856898:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe,sr,zr)=>{u.jb("AveragePool",o,{format:zr?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:v,storage_order:z,dilations:[ce,Ue],kernel_shape:[ot,Et],pads:[It,Kt,kr,Fr],strides:[Oe,sr]})},857182:(o,f)=>{u.jb("GlobalMaxPool",o,{format:f?"NHWC":"NCHW"})},857269:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe,sr,zr)=>{u.jb("MaxPool",o,{format:zr?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:v,storage_order:z,dilations:[ce,Ue],kernel_shape:[ot,Et],pads:[It,Kt,kr,Fr],strides:[Oe,sr]})},857549:(o,f)=>{u.jb("GlobalMaxPool",o,{format:f?"NHWC":"NCHW"})},857636:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe,sr,zr)=>{u.jb("MaxPool",o,{format:zr?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:v,storage_order:z,dilations:[ce,Ue],kernel_shape:[ot,Et],pads:[It,Kt,kr,Fr],strides:[Oe,sr]})},857916:(o,f,b,v,z)=>{u.jb("Gemm",o,{alpha:f,beta:b,transA:v,transB:z})},858020:o=>{u.jb("MatMul",o,void 0)},858074:(o,f,b,v)=>{u.jb("ArgMax",o,{keepDims:!!f,selectLastIndex:!!b,axis:v})},858182:(o,f,b,v)=>{u.jb("ArgMin",o,{keepDims:!!f,selectLastIndex:!!b,axis:v})},858290:(o,f)=>{u.jb("Softmax",o,{axis:f})},858353:(o,f)=>{u.jb("Concat",o,{axis:f})},858413:(o,f,b,v,z)=>{u.jb("Split",o,{axis:f,numOutputs:b,splitSizes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},858553:o=>{u.jb("Expand",o,void 0)},858607:(o,f)=>{u.jb("Gather",o,{axis:Number(f)})},858678:(o,f)=>{u.jb("GatherElements",o,{axis:Number(f)})},858757:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt)=>{u.jb("Resize",o,{antialias:f,axes:b?Array.from(i().subarray(b>>>0,v>>>0)):[],coordinateTransformMode:dn(z),cubicCoeffA:ce,excludeOutside:Ue,extrapolationValue:ot,keepAspectRatioPolicy:dn(Et),mode:dn(It),nearestMode:dn(Kt)})},859103:(o,f,b,v,z,ce,Ue)=>{u.jb("Slice",o,{starts:f?Array.from(i().subarray(f>>>0,b>>>0)):[],ends:v?Array.from(i().subarray(v>>>0,z>>>0)):[],axes:ce?Array.from(i().subarray(ce>>>0,Ue>>>0)):[]})},859319:o=>{u.jb("Tile",o,void 0)},859371:(o,f,b)=>{u.jb("InstanceNormalization",o,{epsilon:f,format:b?"NHWC":"NCHW"})},859485:(o,f,b)=>{u.jb("InstanceNormalization",o,{epsilon:f,format:b?"NHWC":"NCHW"})},859599:o=>{u.jb("Range",o,void 0)},859652:(o,f)=>{u.jb("Einsum",o,{equation:dn(f)})},859733:(o,f,b,v,z)=>{u.jb("Pad",o,{mode:f,value:b,pads:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},859860:(o,f,b,v,z,ce)=>{u.jb("BatchNormalization",o,{epsilon:f,momentum:b,spatial:!!z,trainingMode:!!v,format:ce?"NHWC":"NCHW"})},860029:(o,f,b,v,z,ce)=>{u.jb("BatchNormalization",o,{epsilon:f,momentum:b,spatial:!!z,trainingMode:!!v,format:ce?"NHWC":"NCHW"})},860198:(o,f,b)=>{u.jb("CumSum",o,{exclusive:Number(f),reverse:Number(b)})},860295:(o,f,b,v,z,ce,Ue,ot,Et)=>{u.jb("Attention",o,{numHeads:f,isUnidirectional:b,maskFilterValue:v,scale:z,doRotary:ce,qkvHiddenSizes:Ue?Array.from(i().subarray(Number(ot)>>>0,Number(ot)+Ue>>>0)):[],pastPresentShareBuffer:!!Et})},860567:o=>{u.jb("BiasAdd",o,void 0)},860622:o=>{u.jb("BiasSplitGelu",o,void 0)},860683:o=>{u.jb("FastGelu",o,void 0)},860739:(o,f,b,v,z,ce,Ue,ot,Et,It,Kt,kr,Fr,Oe,sr,zr)=>{u.jb("Conv",o,{format:kr?"NHWC":"NCHW",auto_pad:f,dilations:b?Array.from(i().subarray(b>>>0,v>>>0)):[],group:z,kernel_shape:ce?Array.from(i().subarray(ce>>>0,Ue>>>0)):[],pads:ot?Array.from(i().subarray(ot>>>0,Et>>>0)):[],strides:It?Array.from(i().subarray(It>>>0,Kt>>>0)):[],w_is_const:()=>!!r()[Fr>>>0],activation:dn(Oe),activation_params:sr?Array.from(c().subarray(sr>>>0,zr>>>0)):[]})},861235:o=>{u.jb("Gelu",o,void 0)},861287:(o,f,b,v)=>{u.jb("GroupQueryAttention",o,{numHeads:f,kvNumHeads:b,scale:v})},861400:(o,f,b,v)=>{u.jb("LayerNormalization",o,{axis:f,epsilon:b,simplified:!!v})},861511:(o,f,b,v)=>{u.jb("LayerNormalization",o,{axis:f,epsilon:b,simplified:!!v})},861622:(o,f,b,v,z,ce)=>{u.jb("MatMulNBits",o,{k:f,n:b,accuracyLevel:v,bits:z,blockSize:ce})},861749:(o,f,b,v,z,ce)=>{u.jb("MultiHeadAttention",o,{numHeads:f,isUnidirectional:b,maskFilterValue:v,scale:z,doRotary:ce})},861908:(o,f)=>{u.jb("QuickGelu",o,{alpha:f})},861972:(o,f,b,v,z)=>{u.jb("RotaryEmbedding",o,{interleaved:!!f,numHeads:b,rotaryEmbeddingDim:v,scale:z})},862111:(o,f,b)=>{u.jb("SkipLayerNormalization",o,{epsilon:f,simplified:!!b})},862213:o=>{u.Yb(o)},862247:(o,f)=>u.$b(o,f,u.Eb.bc,u.Eb.errors),862359:(o,f,b)=>{u.jb("SkipLayerNormalization",o,{epsilon:f,simplified:!!b})}};function xf(o,f,b){return _h(async()=>{await u.Wb(o,f,b)})}function Tf(){return typeof wasmOffsetConverter<"u"}function Kd(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var Xd=o=>{o.terminate(),o.onmessage=()=>{}},Bp=o=>{Bs.length==0&&(Up(),Vp(Bs[0]));var f=Bs.pop();if(!f)return 6;pi.push(f),Jn[o.Ab]=f,f.Ab=o.Ab;var b={cmd:"run",start_routine:o.cc,arg:o.Pb,pthread_ptr:o.Ab};return f.postMessage(b,o.ic),0},ci=0,Gr=(o,f,...b)=>{for(var v=2*b.length,z=fc(),ce=hc(8*v),Ue=ce>>>3,ot=0;ot>>0]=Et)}return o=Nh(o,0,v,ce,f),Cd(z),o};function Qd(o){if(U)return Gr(0,1,o);if(Bt=o,!(0{if(Bt=o,U)throw Lp(o),"unwind";Qd(o)},Bs=[],pi=[],Rp=[],Jn={},Np=o=>{var f=o.Ab;delete Jn[f],Bs.push(o),pi.splice(pi.indexOf(o),1),o.Ab=0,pc(f)};function jp(){Rp.forEach(o=>o())}var Vp=o=>new Promise(f=>{o.onmessage=z=>{var ce=(z=z.data).cmd;if(z.targetThread&&z.targetThread!=Aa()){var Ue=Jn[z.targetThread];Ue?Ue.postMessage(z,z.transferList):rr(`Internal error! Worker sent a message "${ce}" to target pthread ${z.targetThread}, but that thread no longer exists!`)}else ce==="checkMailbox"?md():ce==="spawnThread"?Bp(z):ce==="cleanupThread"?Np(Jn[z.thread]):ce==="killThread"?(z=z.thread,ce=Jn[z],delete Jn[z],Xd(ce),pc(z),pi.splice(pi.indexOf(ce),1),ce.Ab=0):ce==="cancelThread"?Jn[z.thread].postMessage({cmd:"cancel"}):ce==="loaded"?(o.loaded=!0,f(o)):ce==="alert"?alert(`Thread ${z.threadId}: ${z.text}`):z.target==="setimmediate"?o.postMessage(z):ce==="callHandler"?u[z.handler](...z.args):ce&&rr(`worker sent an unknown command ${ce}`)},o.onerror=z=>{throw rr(`worker sent an error! ${z.filename}:${z.lineno}: ${z.message}`),z};var b,v=[];for(b of[])u.hasOwnProperty(b)&&v.push(b);o.postMessage({cmd:"load",handlers:v,wasmMemory:cr,wasmModule:Rr})});function Up(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Bs.push(o)}var fd=o=>{for(;0{var o=Aa(),f=d()[o+52>>>2>>>0];o=d()[o+56>>>2>>>0],Vh(f,f-o),Cd(f)},$f=(o,f)=>{ci=0,o=Uh(o,f),0>>=0);throw f>>>=0,b>>>=0,d()[v.Ib+16>>>2>>>0]=0,d()[v.Ib+4>>>2>>>0]=f,d()[v.Ib+8>>>2>>>0]=b,o}function Wp(o,f,b,v){return U?Gr(2,1,o,f,b,v):Gp(o,f,b,v)}function Gp(o,f,b,v){if(o>>>=0,f>>>=0,b>>>=0,v>>>=0,G===void 0)return rr("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var z=[];return U&&z.length===0?Wp(o,f,b,v):(o={cc:b,Ab:o,Pb:v,ic:z},U?(o.Lb="spawnThread",postMessage(o,z),0):Bp(o))}var qp=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Hp=(o,f,b)=>{var v=(f>>>=0)+b;for(b=f;o[b]&&!(b>=v);)++b;if(16(z=(240&z)==224?(15&z)<<12|ce<<6|Ue:(7&z)<<18|ce<<12|Ue<<6|63&o[f++])?v+=String.fromCharCode(z):(z-=65536,v+=String.fromCharCode(55296|z>>10,56320|1023&z))}}else v+=String.fromCharCode(z)}return v},dn=(o,f)=>(o>>>=0)?Hp(n(),o,f):"";function Kp(o,f,b){return U?Gr(3,1,o,f,b):0}function Xp(o,f){if(U)return Gr(4,1,o,f)}var Zd=o=>{for(var f=0,b=0;b=v?f++:2047>=v?f+=2:55296<=v&&57343>=v?(f+=4,++b):f+=3}return f},Qp=(o,f,b,v)=>{if(!(0>>=0;v=b+v-1;for(var ce=0;ce=Ue&&(Ue=65536+((1023&Ue)<<10)|1023&o.charCodeAt(++ce)),127>=Ue){if(b>=v)break;f[b++>>>0]=Ue}else{if(2047>=Ue){if(b+1>=v)break;f[b++>>>0]=192|Ue>>6}else{if(65535>=Ue){if(b+2>=v)break;f[b++>>>0]=224|Ue>>12}else{if(b+3>=v)break;f[b++>>>0]=240|Ue>>18,f[b++>>>0]=128|Ue>>12&63}f[b++>>>0]=128|Ue>>6&63}f[b++>>>0]=128|63&Ue}}return f[b>>>0]=0,b-z},ka=(o,f,b)=>Qp(o,n(),f,b);function Yp(o,f){if(U)return Gr(5,1,o,f)}function Zp(o,f,b){if(U)return Gr(6,1,o,f,b)}function Jp(o,f,b){return U?Gr(7,1,o,f,b):0}function eh(o,f){if(U)return Gr(8,1,o,f)}function th(o,f,b){if(U)return Gr(9,1,o,f,b)}function rh(o,f,b,v){if(U)return Gr(10,1,o,f,b,v)}function nh(o,f,b,v){if(U)return Gr(11,1,o,f,b,v)}function sh(o,f,b,v){if(U)return Gr(12,1,o,f,b,v)}function ih(o){if(U)return Gr(13,1,o)}function ah(o,f){if(U)return Gr(14,1,o,f)}function oh(o,f,b){if(U)return Gr(15,1,o,f,b)}var lh,Ls,kf=()=>{Sa("")},es=o=>{for(var f="";n()[o>>>0];)f+=lh[n()[o++>>>0]];return f},Jd={},ec={};function fs(o,f,b={}){if(!("argPackAdvance"in f))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(v,z,ce={}){var Ue=z.name;if(!v)throw new Ls(`type "${Ue}" must have a positive integer typeid pointer`);if(ec.hasOwnProperty(v)){if(ce.Rb)return;throw new Ls(`Cannot register type '${Ue}' twice`)}ec[v]=z,Jd.hasOwnProperty(v)&&(z=Jd[v],delete Jd[v],z.forEach(ot=>ot()))}(o,f,b)}var uh=(o,f,b)=>{switch(f){case 1:return b?v=>r()[v>>>0]:v=>n()[v>>>0];case 2:return b?v=>s()[v>>>1>>>0]:v=>a()[v>>>1>>>0];case 4:return b?v=>i()[v>>>2>>>0]:v=>d()[v>>>2>>>0];case 8:return b?v=>an[v>>>3]:v=>zs[v>>>3];default:throw new TypeError(`invalid integer width (${f}): ${o}`)}};function Pf(o,f,b){b>>>=0,fs(o>>>=0,{name:f=es(f>>>0),fromWireType:v=>v,toWireType:function(v,z){if(typeof z!="bigint"&&typeof z!="number")throw z=z===null?"null":(v=typeof z)=="object"||v==="array"||v==="function"?z.toString():""+z,new TypeError(`Cannot convert "${z}" to ${this.name}`);return typeof z=="number"&&(z=BigInt(z)),z},argPackAdvance:Rs,readValueFromPointer:uh(f,b,f.indexOf("u")==-1),Db:null})}var Rs=8;function Af(o,f,b,v){fs(o>>>=0,{name:f=es(f>>>0),fromWireType:function(z){return!!z},toWireType:function(z,ce){return ce?b:v},argPackAdvance:Rs,readValueFromPointer:function(z){return this.fromWireType(n()[z>>>0])},Db:null})}var tc=[],ms=[];function rc(o){9<(o>>>=0)&&--ms[o+1]==0&&(ms[o]=void 0,tc.push(o))}var jn=o=>{if(!o)throw new Ls("Cannot use deleted val. handle = "+o);return ms[o]},Vn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=tc.pop()||ms.length;return ms[f]=o,ms[f+1]=1,f}};function nc(o){return this.fromWireType(d()[o>>>2>>>0])}var If={name:"emscripten::val",fromWireType:o=>{var f=jn(o);return rc(o),f},toWireType:(o,f)=>Vn(f),argPackAdvance:Rs,readValueFromPointer:nc,Db:null};function Ff(o){return fs(o>>>0,If)}var Of=(o,f)=>{switch(f){case 4:return function(b){return this.fromWireType(c()[b>>>2>>>0])};case 8:return function(b){return this.fromWireType(h()[b>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${o}`)}};function zf(o,f,b){b>>>=0,fs(o>>>=0,{name:f=es(f>>>0),fromWireType:v=>v,toWireType:(v,z)=>z,argPackAdvance:Rs,readValueFromPointer:Of(f,b),Db:null})}function Df(o,f,b,v,z){if(o>>>=0,b>>>=0,f=es(f>>>0),z===-1&&(z=4294967295),z=ot=>ot,v===0){var ce=32-8*b;z=ot=>ot<>>ce}var Ue=f.includes("unsigned")?function(ot,Et){return Et>>>0}:function(ot,Et){return Et};fs(o,{name:f,fromWireType:z,toWireType:Ue,argPackAdvance:Rs,readValueFromPointer:uh(f,b,v!==0),Db:null})}function Bf(o,f,b){function v(ce){var Ue=d()[ce>>>2>>>0];return ce=d()[ce+4>>>2>>>0],new z(r().buffer,ce,Ue)}var z=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];fs(o>>>=0,{name:b=es(b>>>0),fromWireType:v,argPackAdvance:Rs,readValueFromPointer:v},{Rb:!0})}function Lf(o,f){o>>>=0;var b=(f=es(f>>>0))==="std::string";fs(o,{name:f,fromWireType:function(v){var z=d()[v>>>2>>>0],ce=v+4;if(b)for(var Ue=ce,ot=0;ot<=z;++ot){var Et=ce+ot;if(ot==z||n()[Et>>>0]==0){if(Ue=dn(Ue,Et-Ue),It===void 0)var It=Ue;else It+="\0",It+=Ue;Ue=Et+1}}else{for(It=Array(z),ot=0;ot>>0]);It=It.join("")}return rs(v),It},toWireType:function(v,z){z instanceof ArrayBuffer&&(z=new Uint8Array(z));var ce=typeof z=="string";if(!(ce||z instanceof Uint8Array||z instanceof Uint8ClampedArray||z instanceof Int8Array))throw new Ls("Cannot pass non-string to std::string");var Ue=b&&ce?Zd(z):z.length,ot=xd(4+Ue+1),Et=ot+4;if(d()[ot>>>2>>>0]=Ue,b&&ce)ka(z,Et,Ue+1);else if(ce)for(ce=0;ce>>0]=It}else for(ce=0;ce>>0]=z[ce];return v!==null&&v.push(rs,ot),ot},argPackAdvance:Rs,readValueFromPointer:nc,Db(v){rs(v)}})}var dh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Rf=(o,f)=>{for(var b=o>>1,v=b+f/2;!(b>=v)&&a()[b>>>0];)++b;if(32<(b<<=1)-o&&dh)return dh.decode(n().slice(o,b));for(b="",v=0;!(v>=f/2);++v){var z=s()[o+2*v>>>1>>>0];if(z==0)break;b+=String.fromCharCode(z)}return b},Nf=(o,f,b)=>{if(b??(b=2147483647),2>b)return 0;var v=f;b=(b-=2)<2*o.length?b/2:o.length;for(var z=0;z>>1>>>0]=ce,f+=2}return s()[f>>>1>>>0]=0,f-v},jf=o=>2*o.length,Vf=(o,f)=>{for(var b=0,v="";!(b>=f/4);){var z=i()[o+4*b>>>2>>>0];if(z==0)break;++b,65536<=z?(z-=65536,v+=String.fromCharCode(55296|z>>10,56320|1023&z)):v+=String.fromCharCode(z)}return v},Uf=(o,f,b)=>{if(f>>>=0,b??(b=2147483647),4>b)return 0;var v=f;b=v+b-4;for(var z=0;z=ce&&(ce=65536+((1023&ce)<<10)|1023&o.charCodeAt(++z)),i()[f>>>2>>>0]=ce,(f+=4)+4>b)break}return i()[f>>>2>>>0]=0,f-v},Wf=o=>{for(var f=0,b=0;b=v&&++b,f+=4}return f};function Gf(o,f,b){if(o>>>=0,f>>>=0,b=es(b>>>=0),f===2)var v=Rf,z=Nf,ce=jf,Ue=ot=>a()[ot>>>1>>>0];else f===4&&(v=Vf,z=Uf,ce=Wf,Ue=ot=>d()[ot>>>2>>>0]);fs(o,{name:b,fromWireType:ot=>{for(var Et,It=d()[ot>>>2>>>0],Kt=ot+4,kr=0;kr<=It;++kr){var Fr=ot+4+kr*f;kr!=It&&Ue(Fr)!=0||(Kt=v(Kt,Fr-Kt),Et===void 0?Et=Kt:(Et+="\0",Et+=Kt),Kt=Fr+f)}return rs(ot),Et},toWireType:(ot,Et)=>{if(typeof Et!="string")throw new Ls(`Cannot pass non-string to C++ string type ${b}`);var It=ce(Et),Kt=xd(4+It+f);return d()[Kt>>>2>>>0]=It/f,z(Et,Kt+4,It+f),ot!==null&&ot.push(rs,Kt),Kt},argPackAdvance:Rs,readValueFromPointer:nc,Db(ot){rs(ot)}})}function qf(o,f){fs(o>>>=0,{Sb:!0,name:f=es(f>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Hf=()=>1;function Kf(o){cc(o>>>0,!F,1,!C,131072,!1),jp()}var ch=o=>{if(!In)try{if(o(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(i(),o>>>2,o).value.then(md),o+=128,Atomics.store(i(),o>>>2,1))}var md=()=>{var o=Aa();o&&(sc(o),ch(jh))};function Xf(o,f){(o>>>=0)==f>>>0?setTimeout(md):U?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=Jn[o])&&o.postMessage({cmd:"checkMailbox"})}var ic=[];function Qf(o,f,b,v,z){for(f>>>=0,v/=2,ic.length=v,b=z>>>0>>>3,z=0;z>>0];return(f?Hd[f]:Rm[o])(...ic)}function Yf(o){o>>>=0,U?postMessage({cmd:"cleanupThread",thread:o}):Np(Jn[o])}function Zf(o){}var ac=(o,f)=>{var b=ec[o];if(b===void 0)throw o=Bh(o),b=es(o),rs(o),new Ls(`${f} has unknown type ${b}`);return b},ph=(o,f,b)=>{var v=[];return o=o.toWireType(v,b),v.length&&(d()[f>>>2>>>0]=Vn(v)),o};function Jf(o,f,b){return f>>>=0,b>>>=0,o=jn(o>>>0),f=ac(f,"emval::as"),ph(f,b,o)}var _d=o=>{try{o()}catch(f){Sa(f)}},Ns=0,ts=null,hh=0,gd=[],fh={},mh={},em=0,oc=null,tm=[];function _h(o){return function(f){if(!In){if(Ns===0){var b=!1,v=!1;f((z=0)=>{if(!In&&(hh=z,b=!0,v)){Ns=2,_d(()=>qh(ts)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),z=!1;try{var ce=function(){var Et=i()[ts+8>>>2>>>0];return Et=qt[mh[Et]],--ci,Et()}()}catch(Et){ce=Et,z=!0}var Ue=!1;if(!ts){var ot=oc;ot&&(oc=null,(z?ot.reject:ot.resolve)(ce),Ue=!0)}if(z&&!Ue)throw ce}}),v=!0,b||(Ns=1,ts=function(){var z=xd(65548),ce=z+12;d()[z>>>2>>>0]=ce,d()[z+4>>>2>>>0]=ce+65536,ce=gd[0];var Ue=fh[ce];return Ue===void 0&&(Ue=em++,fh[ce]=Ue,mh[Ue]=ce),ce=Ue,i()[z+8>>>2>>>0]=ce,z}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),_d(()=>Wh(ts)))}else Ns===2?(Ns=0,_d(Hh),rs(ts),ts=null,tm.forEach(ch)):Sa(`invalid state: ${Ns}`);return hh}}(f=>{o().then(f)})}function rm(o){return o>>>=0,_h(()=>(o=jn(o)).then(Vn))}var wd=[];function nm(o,f,b,v){return b>>>=0,v>>>=0,(o=wd[o>>>0])(null,f=jn(f>>>0),b,v)}var sm={},yd=o=>{var f=sm[o];return f===void 0?es(o):f};function im(o,f,b,v,z){return b>>>=0,v>>>=0,z>>>=0,(o=wd[o>>>0])(f=jn(f>>>0),f[b=yd(b)],v,z)}var gh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function am(o){return(o>>>=0)==0?Vn(gh()):(o=yd(o),Vn(gh()[o]))}var om=o=>{var f=wd.length;return wd.push(o),f},lm=(o,f)=>{for(var b=Array(o),v=0;v>>2>>>0],"parameter "+v);return b},wh=(o,f)=>Object.defineProperty(f,"name",{value:o});function um(o,f,b){var v=(f=lm(o,f>>>0)).shift();o--;var z=`return function (obj, func, destructorsRef, args) { `,ce=0,Ue=[];b===0&&Ue.push("obj");for(var ot=["retType"],Et=[v],It=0;ItKt.name).join(", ")}) => ${v.name}>`,om(wh(b,o))}function dm(o){return o=yd(o>>>0),Vn(u[o])}function cm(o,f){return f>>>=0,o=jn(o>>>0),f=jn(f),Vn(o[f])}function pm(o){9<(o>>>=0)&&(ms[o+1]+=1)}function hm(){return Vn([])}function fm(o){o=jn(o>>>0);for(var f=Array(o.length),b=0;b>>0))}function _m(){return Vn({})}function gm(o){for(var f=jn(o>>>=0);f.length;){var b=f.pop();f.pop()(b)}rc(o)}function wm(o,f,b){f>>>=0,b>>>=0,o=jn(o>>>0),f=jn(f),b=jn(b),o[f]=b}function ym(o,f){return f>>>=0,o=(o=ac(o>>>0,"_emval_take_value")).readValueFromPointer(f),Vn(o)}function bm(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 Pa=o=>o%4==0&&(o%100!=0||o%400==0),yh=[0,31,60,91,121,152,182,213,244,274,305,335],bh=[0,31,59,90,120,151,181,212,243,273,304,334];function Mm(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=(Pa(o.getFullYear())?yh:bh)[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 v=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(b!=v&&o.getTimezoneOffset()==Math.min(v,b)),i()[f+32>>>2>>>0]=o}function vm(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],v=f.getTimezoneOffset(),z=new Date(f.getFullYear(),6,1).getTimezoneOffset(),ce=new Date(f.getFullYear(),0,1).getTimezoneOffset(),Ue=Math.min(ce,z);return 0>b?i()[o+32>>>2>>>0]=+(z!=ce&&Ue==v):0>>2>>>0]=f.getDay(),b=(Pa(f.getFullYear())?yh:bh)[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 Mh(o,f,b,v,z,ce,Ue){return U?Gr(16,1,o,f,b,v,z,ce,Ue):-52}function vh(o,f,b,v,z,ce){if(U)return Gr(17,1,o,f,b,v,z,ce)}function xm(o,f,b,v){o>>>=0,f>>>=0,b>>>=0,v>>>=0;var z=new Date().getFullYear(),ce=new Date(z,0,1),Ue=new Date(z,6,1);z=ce.getTimezoneOffset();var ot=Ue.getTimezoneOffset(),Et=Math.max(z,ot);d()[o>>>2>>>0]=60*Et,i()[f>>>2>>>0]=+(z!=ot),ce=(o=It=>It.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ce),Ue=o(Ue),ot{lc.length=0;for(var b;b=n()[o++>>>0];){var v=b!=105;f+=(v&=b!=112)&&f%8?4:0,lc.push(b==112?d()[f>>>2>>>0]:b==106?an[f>>>3]:b==105?i()[f>>>2>>>0]:h()[f>>>3>>>0]),f+=v?8:4}return lc};function Tm(o,f,b){return o>>>=0,f=xh(f>>>0,b>>>0),Hd[o](...f)}function Cm(o,f,b){return o>>>=0,f=xh(f>>>0,b>>>0),Hd[o](...f)}var $m=()=>{},Em=()=>Date.now();function Sm(o,f){return rr(dn(o>>>0,f>>>0))}var Th,km=()=>{throw ci+=1,"unwind"};function Pm(){return 4294901760}Th=()=>performance.timeOrigin+performance.now();var Am=()=>navigator.hardwareConcurrency;function Im(){return Sa("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Fm(o){o>>>=0;var f=n().length;if(o<=f||4294901760=b;b*=2){var v=f*(1+.2/b);v=Math.min(v,o+100663296);var z=Math;v=Math.max(o,v);e:{z=(z.min.call(z,4294901760,v+(65536-v%65536)%65536)-cr.buffer.byteLength+65535)/65536;try{cr.grow(z),hn();var ce=1;break e}catch{}ce=void 0}if(ce)return!0}return!1}var bd=()=>(Sa("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Iu={},Ch=o=>{o.forEach(f=>{bd()})};function Om(){var o=Error().stack.toString().split(` `);return o[0]=="Error"&&o.shift(),Ch(o),Iu.Ob=bd(),Iu.ac=o,Iu.Ob}function zm(o,f,b){if(o>>>=0,f>>>=0,Iu.Ob==o)var v=Iu.ac;else(v=Error().stack.toString().split(` `))[0]=="Error"&&v.shift(),Ch(v);for(var z=3;v[z]&&bd()!=o;)++z;for(o=0;o>>2>>>0]=bd();return o}var uc,dc={},$h=()=>{if(!uc){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",_:et};for(o in dc)dc[o]===void 0?delete f[o]:f[o]=dc[o];var b=[];for(o in f)b.push(`${o}=${f[o]}`);uc=b}return uc};function Eh(o,f){if(U)return Gr(18,1,o,f);o>>>=0,f>>>=0;var b=0;return $h().forEach((v,z)=>{var ce=f+b;for(z=d()[o+4*z>>>2>>>0]=ce,ce=0;ce>>0]=v.charCodeAt(ce);r()[z>>>0]=0,b+=v.length+1}),0}function Sh(o,f){if(U)return Gr(19,1,o,f);o>>>=0,f>>>=0;var b=$h();d()[o>>>2>>>0]=b.length;var v=0;return b.forEach(z=>v+=z.length+1),d()[f>>>2>>>0]=v,0}function kh(o){return U?Gr(20,1,o):52}function Ph(o,f,b,v){return U?Gr(21,1,o,f,b,v):52}function Ah(o,f,b,v){return U?Gr(22,1,o,f,b,v):70}var Dm=[null,[],[]];function Ih(o,f,b,v){if(U)return Gr(23,1,o,f,b,v);f>>>=0,b>>>=0,v>>>=0;for(var z=0,ce=0;ce>>2>>>0],ot=d()[f+4>>>2>>>0];f+=8;for(var Et=0;Et>>0],Kt=Dm[o];It===0||It===10?((o===1?br:rr)(Hp(Kt,0)),Kt.length=0):Kt.push(It)}z+=ot}return d()[v>>>2>>>0]=z,0}var Fh=[31,29,31,30,31,30,31,31,30,31,30,31],Oh=[31,28,31,30,31,30,31,31,30,31,30,31],Bm=(o,f)=>{r().set(o,f>>>0)};function zh(o,f,b,v){function z(Oe,sr,zr){for(Oe=typeof Oe=="number"?Oe.toString():Oe||"";Oe.lengthXh?-1:0hi-Oe.getDate())){Oe.setDate(Oe.getDate()+sr);break}sr-=hi-Oe.getDate()+1,Oe.setDate(1),11>zr?Oe.setMonth(zr+1):(Oe.setMonth(0),Oe.setFullYear(Oe.getFullYear()+1))}return zr=new Date(Oe.getFullYear()+1,0,4),sr=ot(new Date(Oe.getFullYear(),0,4)),zr=ot(zr),0>=Ue(sr,Oe)?0>=Ue(zr,Oe)?Oe.getFullYear()+1:Oe.getFullYear():Oe.getFullYear()-1}o>>>=0,f>>>=0,b>>>=0,v>>>=0;var It=d()[v+40>>>2>>>0];for(var Kt in v={fc:i()[v>>>2>>>0],ec:i()[v+4>>>2>>>0],Gb:i()[v+8>>>2>>>0],Kb:i()[v+12>>>2>>>0],Hb:i()[v+16>>>2>>>0],Cb:i()[v+20>>>2>>>0],ub:i()[v+24>>>2>>>0],Bb:i()[v+28>>>2>>>0],nc:i()[v+32>>>2>>>0],dc:i()[v+36>>>2>>>0],hc:It?dn(It):""},b=dn(b),It={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})b=b.replace(new RegExp(Kt,"g"),It[Kt]);var kr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Fr="January February March April May June July August September October November December".split(" ");for(Kt in It={"%a":Oe=>kr[Oe.ub].substring(0,3),"%A":Oe=>kr[Oe.ub],"%b":Oe=>Fr[Oe.Hb].substring(0,3),"%B":Oe=>Fr[Oe.Hb],"%C":Oe=>ce((Oe.Cb+1900)/100|0,2),"%d":Oe=>ce(Oe.Kb,2),"%e":Oe=>z(Oe.Kb,2," "),"%g":Oe=>Et(Oe).toString().substring(2),"%G":Et,"%H":Oe=>ce(Oe.Gb,2),"%I":Oe=>((Oe=Oe.Gb)==0?Oe=12:12{for(var sr=0,zr=0;zr<=Oe.Hb-1;sr+=(Pa(Oe.Cb+1900)?Fh:Oh)[zr++]);return ce(Oe.Kb+sr,3)},"%m":Oe=>ce(Oe.Hb+1,2),"%M":Oe=>ce(Oe.ec,2),"%n":()=>` `,"%p":Oe=>0<=Oe.Gb&&12>Oe.Gb?"AM":"PM","%S":Oe=>ce(Oe.fc,2),"%t":()=>" ","%u":Oe=>Oe.ub||7,"%U":Oe=>ce(Math.floor((Oe.Bb+7-Oe.ub)/7),2),"%V":Oe=>{var sr=Math.floor((Oe.Bb+7-(Oe.ub+6)%7)/7);if(2>=(Oe.ub+371-Oe.Bb-2)%7&&sr++,sr)sr==53&&((zr=(Oe.ub+371-Oe.Bb)%7)==4||zr==3&&Pa(Oe.Cb)||(sr=1));else{sr=52;var zr=(Oe.ub+7-Oe.Bb-1)%7;(zr==4||zr==5&&Pa(Oe.Cb%400-1))&&sr++}return ce(sr,2)},"%w":Oe=>Oe.ub,"%W":Oe=>ce(Math.floor((Oe.Bb+7-(Oe.ub+6)%7)/7),2),"%y":Oe=>(Oe.Cb+1900).toString().substring(2),"%Y":Oe=>Oe.Cb+1900,"%z":Oe=>{var sr=0<=(Oe=Oe.dc);return Oe=Math.abs(Oe)/60,(sr?"+":"-")+("0000"+(Oe/60*100+Oe%60)).slice(-4)},"%Z":Oe=>Oe.hc,"%%":()=>"%"},b=b.replace(/%%/g,"\0\0"),It)b.includes(Kt)&&(b=b.replace(new RegExp(Kt,"g"),It[Kt](v)));return Kt=function(Oe){var sr=Array(Zd(Oe)+1);return Qp(Oe,sr,0,sr.length),sr}(b=b.replace(/\0\0/g,"%")),Kt.length>f?0:(Bm(Kt,o),Kt.length-1)}function Lm(o,f,b,v){return zh(o>>>0,f>>>0,b>>>0,v>>>0)}U||function(){for(var o=u.numThreads-1;o--;)Up();Au.unshift(()=>{Nn++,function(f){U?f():Promise.all(Bs.map(Vp)).then(f)}(()=>hd())})}();for(var Dh=Array(256),Md=0;256>Md;++Md)Dh[Md]=String.fromCharCode(Md);lh=Dh,Ls=u.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},u.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},ms.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>ms.length/2-5-tc.length;var Rm=[Qd,Lp,Wp,Kp,Xp,Yp,Zp,Jp,eh,th,rh,nh,sh,ih,ah,oh,Mh,vh,Eh,Sh,kh,Ph,Ah,Ih],qt=function(){function o(b,v){return qt=b.exports,qt=function(){var z=qt,ce={};for(let[Ue,ot]of Object.entries(z))ce[Ue]=typeof ot=="function"?(...Et)=>{gd.push(Ue);try{return ot(...Et)}finally{In||(gd.pop(),ts&&Ns===1&&gd.length===0&&(Ns=0,ci+=1,_d(Gh),typeof Fibers<"u"&&Fibers.oc()))}}:ot;return ce}(),qt=function(){var z=qt,ce=ot=>Et=>ot(Et)>>>0,Ue=ot=>()=>ot()>>>0;return(z=Object.assign({},z)).Ca=ce(z.Ca),z.fb=Ue(z.fb),z.gb=ce(z.gb),z.emscripten_main_runtime_thread_id=Ue(z.emscripten_main_runtime_thread_id),z.sb=ce(z.sb),z.tb=Ue(z.tb),z}(),Rp.push(qt.ib),fn.unshift(qt.Ba),Rr=v,hd(),qt}var f=Dp();if(Nn++,u.instantiateWasm)try{return u.instantiateWasm(f,o)}catch(b){rr(`Module.instantiateWasm callback failed with error: ${b}`),y(b)}return qd||(qd=u.locateFile?Ip("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",ct):ct+"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,v){var z=qd;return Ot||typeof WebAssembly.instantiateStreaming!="function"||Ip(z)||Fp(z)||typeof fetch!="function"?zp(z,b,v):fetch(z,{credentials:"same-origin"}).then(ce=>WebAssembly.instantiateStreaming(ce,b).then(v,function(Ue){return rr(`wasm streaming compile failed: ${Ue}`),rr("falling back to ArrayBuffer instantiation"),zp(z,b,v)}))}(f,function(b){o(b.instance,b.module)}).catch(y),{}}(),Bh=o=>(Bh=qt.Ca)(o),Lh=()=>(Lh=qt.Da)();u._OrtInit=(o,f)=>(u._OrtInit=qt.Ea)(o,f),u._OrtGetLastError=(o,f)=>(u._OrtGetLastError=qt.Fa)(o,f),u._OrtCreateSessionOptions=(o,f,b,v,z,ce,Ue,ot,Et,It)=>(u._OrtCreateSessionOptions=qt.Ga)(o,f,b,v,z,ce,Ue,ot,Et,It),u._OrtAppendExecutionProvider=(o,f)=>(u._OrtAppendExecutionProvider=qt.Ha)(o,f),u._OrtAddFreeDimensionOverride=(o,f,b)=>(u._OrtAddFreeDimensionOverride=qt.Ia)(o,f,b),u._OrtAddSessionConfigEntry=(o,f,b)=>(u._OrtAddSessionConfigEntry=qt.Ja)(o,f,b),u._OrtReleaseSessionOptions=o=>(u._OrtReleaseSessionOptions=qt.Ka)(o),u._OrtCreateSession=(o,f,b)=>(u._OrtCreateSession=qt.La)(o,f,b),u._OrtReleaseSession=o=>(u._OrtReleaseSession=qt.Ma)(o),u._OrtGetInputOutputCount=(o,f,b)=>(u._OrtGetInputOutputCount=qt.Na)(o,f,b),u._OrtGetInputName=(o,f)=>(u._OrtGetInputName=qt.Oa)(o,f),u._OrtGetOutputName=(o,f)=>(u._OrtGetOutputName=qt.Pa)(o,f),u._OrtFree=o=>(u._OrtFree=qt.Qa)(o),u._OrtCreateTensor=(o,f,b,v,z,ce)=>(u._OrtCreateTensor=qt.Ra)(o,f,b,v,z,ce),u._OrtGetTensorData=(o,f,b,v,z)=>(u._OrtGetTensorData=qt.Sa)(o,f,b,v,z),u._OrtReleaseTensor=o=>(u._OrtReleaseTensor=qt.Ta)(o),u._OrtCreateRunOptions=(o,f,b,v)=>(u._OrtCreateRunOptions=qt.Ua)(o,f,b,v),u._OrtAddRunConfigEntry=(o,f,b)=>(u._OrtAddRunConfigEntry=qt.Va)(o,f,b),u._OrtReleaseRunOptions=o=>(u._OrtReleaseRunOptions=qt.Wa)(o),u._OrtCreateBinding=o=>(u._OrtCreateBinding=qt.Xa)(o),u._OrtBindInput=(o,f,b)=>(u._OrtBindInput=qt.Ya)(o,f,b),u._OrtBindOutput=(o,f,b,v)=>(u._OrtBindOutput=qt.Za)(o,f,b,v),u._OrtClearBoundOutputs=o=>(u._OrtClearBoundOutputs=qt._a)(o),u._OrtReleaseBinding=o=>(u._OrtReleaseBinding=qt.$a)(o),u._OrtRunWithBinding=(o,f,b,v,z)=>(u._OrtRunWithBinding=qt.ab)(o,f,b,v,z),u._OrtRun=(o,f,b,v,z,ce,Ue,ot)=>(u._OrtRun=qt.bb)(o,f,b,v,z,ce,Ue,ot),u._OrtEndProfiling=o=>(u._OrtEndProfiling=qt.cb)(o),u._JsepOutput=(o,f,b)=>(u._JsepOutput=qt.db)(o,f,b),u._JsepGetNodeName=o=>(u._JsepGetNodeName=qt.eb)(o);var vd,Aa=()=>(Aa=qt.fb)(),xd=u._malloc=o=>(xd=u._malloc=qt.gb)(o),rs=u._free=o=>(rs=u._free=qt.hb)(o),cc=(o,f,b,v,z,ce)=>(cc=qt.kb)(o,f,b,v,z,ce),Rh=()=>(Rh=qt.lb)(),Nh=(o,f,b,v,z)=>(Nh=qt.mb)(o,f,b,v,z),pc=o=>(pc=qt.nb)(o),Td=o=>(Td=qt.ob)(o),jh=()=>(jh=qt.pb)(),Vh=(o,f)=>(Vh=qt.qb)(o,f),Cd=o=>(Cd=qt.rb)(o),hc=o=>(hc=qt.sb)(o),fc=()=>(fc=qt.tb)(),Uh=u.dynCall_ii=(o,f)=>(Uh=u.dynCall_ii=qt.vb)(o,f),Wh=o=>(Wh=qt.wb)(o),Gh=()=>(Gh=qt.xb)(),qh=o=>(qh=qt.yb)(o),Hh=()=>(Hh=qt.zb)();function Kh(){0fc(),u.stackRestore=o=>Cd(o),u.stackAlloc=o=>hc(o),u.UTF8ToString=dn,u.stringToUTF8=ka,u.lengthBytesUTF8=Zd,Ds=function o(){vd||Kh(),vd||(Ds=o)},Kh(),k}),Ct=ft,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&ft()}),Xe,jt,Rt,Ht,Xt,er,Wt,Tr,Ur=D(()=>{var e,t;q(),Xe=self.location.href??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),jt=typeof location>"u"?void 0:location.origin,Rt=(r,n)=>{try{let s=n??Xe;return(s?new URL(r,s):new URL(r)).origin===jt}catch{return!1}},Ht=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Xt=(dt(),P(be)).default,er=async()=>{if(!Xe)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Rt(Xe))return[void 0,Xt()];let r=await Ht(Xe);return[r,Xt(r)]},Wt=(Lt(),P(nt)).default,Tr=async(r,n,s)=>[void 0,Wt]}),Cr,Ze,St,Dt,qr,Un,Fn,Lr,Zr=D(()=>{Ur(),Ze=!1,St=!1,Dt=!1,qr=()=>{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}},Un=()=>{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}},Fn=async e=>{if(Ze)return Promise.resolve();if(St)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Dt)throw new Error("previous call to 'initializeWebAssembly()' failed.");St=!0;let t=e.initTimeout,r=e.numThreads;if(!Un())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=qr();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,h=(c==null?void 0:c.href)??c,w=e.wasmBinary,[y,u]=await Tr(d,a,r>1),k=!1,C=[];if(t>0&&C.push(new Promise(F=>{setTimeout(()=>{k=!0,F()},t)})),C.push(new Promise((F,U)=>{let G={numThreads:r};w?G.wasmBinary=w:(h||a)&&(G.locateFile=(L,pe)=>h??(a??pe)+L),u(G).then(L=>{St=!1,Ze=!0,Cr=L,F(),y&&URL.revokeObjectURL(y)},L=>{St=!1,Dt=!0,U(L)})})),await Promise.race(C),k)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Lr=()=>{if(Ze&&Cr)return Cr;throw new Error("WebAssembly is not initialized yet.")}}),Nr,Sn,Pr,Wn=D(()=>{Zr(),Nr=(e,t)=>{let r=Lr(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Sn=(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")Sn(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}`)})},Pr=e=>{let t=Lr(),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)}}}),On,Vs=D(()=>{Zr(),Wn(),On=e=>{let t=Lr(),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=Nr(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Pr("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Sn(e.extra,"",new WeakSet,(i,d)=>{let c=Nr(i,n),h=Nr(d,n);t._OrtAddRunConfigEntry(r,c,h)!==0&&Pr(`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}}}),_s,gs,ws,ys,Gn,Us=D(()=>{Zr(),Wn(),_s=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},gs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ws=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)},ys=(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=Nr("deviceType",r),c=Nr(i,r);Lr()._OrtAddSessionConfigEntry(e,d,c)!==0&&Pr(`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=Nr("preferredLayout",r),c=Nr(i.preferredLayout,r);Lr()._OrtAddSessionConfigEntry(e,d,c)!==0&&Pr(`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=Nr(s,r);Lr()._OrtAppendExecutionProvider(e,a)!==0&&Pr(`Can't append execution provider: ${s}.`)}},Gn=e=>{let t=Lr(),r=0,n=[],s=e||{};ws(s);try{let a=_s(s.graphOptimizationLevel??"all"),i=gs(s.executionMode??"sequential"),d=typeof s.logId=="string"?Nr(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 h=s.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let w=typeof s.optimizedModelFilePath=="string"?Nr(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,d,c,h,w),r===0&&Pr("Can't create session options."),s.executionProviders&&ys(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=Nr("enableGraphCapture",n),u=Nr(s.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,y,u)!==0&&Pr(`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 k=Nr(y,n);t._OrtAddFreeDimensionOverride(r,k,u)!==0&&Pr(`Can't set a free dimension override: ${y} - ${u}.`)}return s.extra!==void 0&&Sn(s.extra,"",new WeakSet,(y,u)=>{let k=Nr(y,n),C=Nr(u,n);t._OrtAddSessionConfigEntry(r,k,C)!==0&&Pr(`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}}}),ss,kn,zn,Dn,Qn,is,as,Qt=D(()=>{ss=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;default:throw new Error(`unsupported data type: ${e}`)}},kn=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";default:throw new Error(`unsupported data type: ${e}`)}},zn=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],Dn=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}`)}},Qn=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}`)}},is=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",as=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}`)}}}),Yn,bs=D(()=>{q(),Yn=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 h=c.byteLength;new Uint8Array(a,i,h).set(c),i+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Ms,os,vs,xs,ls,Ts,Dr,mn=D(()=>{Qt(),Ms=["V","I","W","E","F"],os=(e,t)=>{console.log(`[${Ms[e]},${new Date().toISOString()}]${t}`)},ls=(e,t)=>{vs=e,xs=t},Ts=(e,t)=>{let r=Qn(e),n=Qn(vs);r>=n&&os(r,typeof t=="function"?t():t)},Dr=(...e)=>{xs&&Ts(...e)}}),Me,_=D(()=>{Qt(),Me=(e,t)=>new(Dn(t))(e)}),O=D(()=>{}),Q,ue,de,Fe,gt,bt,yt,Pt,Jt,$r=D(()=>{mn(),O(),Q=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]]),ue=[],de=e=>Math.ceil(e/16)*16,Fe=e=>{for(let t=0;tgt++,yt=async(e,t,r,n)=>{let s=de(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()}},Pt=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 Q)ue.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,s=t.byteLength,a=de(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 h=this.backend.getCommandEncoder();this.backend.endComputePass(),h.copyBufferToBuffer(d,0,i.gpuData.buffer,0,a),Dr("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=de(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 Dr("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=bt();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,n),Dr("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),Dr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=Fe(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:bt(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:e}),Dr("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 Dr("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("data does not exist");await yt(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Q.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))}},Jt=(...e)=>new Pt(...e)}),nr,Gt,fr=D(()=>{nr=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}},Gt=e=>new nr(e)}),on,Yr,qe,yn,Mr,Hr,cn,Yt=D(()=>{on=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Yr=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=on.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],h=s-d<0?1:t[s-d];if(c!==h&&c>1&&h>1)return;let w=Math.max(c,h);if(c&&h)i[a-d]=Math.max(c,h);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}},qe=class $d{static size(t){return $d.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 $d.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 $d.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])}},yn=class Fu{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{Qt(),Yt(),_n=64,Jr=(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}`)}},vr=(e,t=1)=>{let r=Jr(e,t);return typeof r=="string"?r:r[0]},xr=(e,t=1)=>{let r=Jr(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:qe.computeStrides(r)})}),t},gr=e=>e%4===0?4:e%2===0?2:1,Ar=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,jr=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,gn=(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,Ft=(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,Ws=(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`,h=Jr(t,s),w=typeof h=="string"?h:h[1],y=typeof h=="string"?h:h[0],u={indices:c,value:w,storage:y,tensor:t},k=Le=>typeof Le=="string"?Le:`${Le}u`,C={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},F=a?"uniforms.":"",U=`${F}${e}_shape`,G=`${F}${e}_strides`,L="";for(let Le=0;Le ${u.indices} { var indices: ${u.indices}; var current = offset; ${L} return indices; }`,Z=Le=>(C.offsetToIndices=!0,i<2?Le:`o2i_${e}(${Le})`),oe=[];if(i>=2)for(let Le=i-1;Le>=0;Le--)oe.push(`${Ft(G,Le,i)} * (indices[${Le}])`);let et=i<2?"":` fn i2o_${e}(indices: ${u.indices}) -> u32 { return ${oe.join("+")}; }`,We=Le=>(C.indicesToOffset=!0,i<2?Le:`i2o_${e}(${Le})`),ct=(...Le)=>i===0?"0u":`${u.indices}(${Le.map(k).join(",")})`,Ot=(Le,Nt)=>i<2?`${Le}`:`${Ft(Le,Nt,i)}`,zt=(Le,Nt,tr)=>i<2?`${Le}=${tr};`:`${Ft(Le,Nt,i)}=${tr};`,hr={},br=(Le,Nt)=>{C.broadcastedIndicesToOffset=!0;let tr=`${Nt.name}broadcastedIndicesTo${e}Offset`;if(tr in hr)return`${tr}(${Le})`;let Br=[];for(let Xr=i-1;Xr>=0;Xr--){let an=Nt.indicesGet("outputIndices",Xr+Nt.rank-i);Br.push(`${Ot(G,Xr)} * (${an} % ${Ot(U,Xr)})`)}return hr[tr]=`fn ${tr}(outputIndices: ${Nt.type.indices}) -> u32 { return ${Br.length>0?Br.join("+"):"0u"}; }`,`${tr}(${Le})`},rr=(Le,Nt)=>(()=>{if(u.storage===u.value)return`${e}[${Le}]=${Nt};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${Le}]=vec2(u32(${Nt}), select(0u, 0xFFFFFFFFu, ${Nt} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${Le}]=vec2(u32(${Nt}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${Le}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Nt}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Sr=Le=>(()=>{if(u.storage===u.value)return`${e}[${Le}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${Le}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${Le}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${Le}] & 0xFFu), bool(${e}[${Le}] & 0xFF00u), bool(${e}[${Le}] & 0xFF0000u), bool(${e}[${Le}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Wr=i<2?"":` fn get_${e}ByIndices(indices: ${u.indices}) -> ${w} { return ${Sr(`i2o_${e}(indices)`)}; }`,cr=i<2?"":(()=>{let Le=d.map(tr=>`d${tr}: u32`).join(", "),Nt=d.map(tr=>`d${tr}`).join(", ");return` fn get_${e}(${Le}) -> ${w} { return get_${e}ByIndices(${ct(Nt)}); }`})(),Rr=(...Le)=>{if(Le.length!==i)throw new Error(`indices length must be ${i}`);let Nt=Le.map(k).join(",");return i===0?Sr("0u"):i===1?Sr(Nt[0]):(C.get=!0,C.getByIndices=!0,C.indicesToOffset=!0,`get_${e}(${Nt})`)},Bt=Le=>i<2?Sr(Le):(C.getByIndices=!0,C.indicesToOffset=!0,`get_${e}ByIndices(${Le})`),Zt=i<2?"":` fn set_${e}ByIndices(indices: ${u.indices}, value: ${w}) { ${rr(`i2o_${e}(indices)`,"value")} }`,_r=i<2?"":(()=>{let Le=d.map(tr=>`d${tr}: u32`).join(", "),Nt=d.map(tr=>`d${tr}`).join(", ");return` fn set_${e}(${Le}, value: ${w}) { set_${e}ByIndices(${ct(Nt)}, value); }`})();return{impl:()=>{let Le=[],Nt=!1;return C.offsetToIndices&&(Le.push(pe),Nt=!0),C.indicesToOffset&&(Le.push(et),Nt=!0),C.broadcastedIndicesToOffset&&(Object.values(hr).forEach(tr=>Le.push(tr)),Nt=!0),C.set&&(Le.push(_r),Nt=!0),C.setByIndices&&(Le.push(Zt),Nt=!0),C.get&&(Le.push(cr),Nt=!0),C.getByIndices&&(Le.push(Wr),Nt=!0),!a&&Nt&&Le.unshift(`const ${U} = ${u.indices}(${r.join(",")});`,`const ${G} = ${u.indices}(${qe.computeStrides(r).join(",")});`),Le.join(` `)},type:u,offsetToIndices:Z,indicesToOffset:We,broadcastedIndicesToOffset:br,indices:ct,indicesGet:Ot,indicesSet:zt,set:(...Le)=>{if(Le.length!==i+1)throw new Error(`indices length must be ${i}`);let Nt=Le[i];if(typeof Nt!="string")throw new Error("value must be string");let tr=Le.slice(0,i).map(k).join(",");return i===0?rr("0u",Nt):i===1?rr(tr[0],Nt):(C.set=!0,C.setByIndices=!0,C.indicesToOffset=!0,`set_${e}(${tr}, ${Nt})`)},setByOffset:rr,setByIndices:(Le,Nt)=>i<2?rr(Le,Nt):(C.setByIndices=!0,C.indicesToOffset=!0,`set_${e}ByIndices(${Le}, ${Nt});`),get:Rr,getByOffset:Sr,getByIndices:Bt,usage:n,name:e,strides:G,shape:U,rank:i}},it=(e,t,r,n=1)=>Ws(e,t,r,"input",n),Ut=(e,t,r,n=1)=>Ws(e,t,r,"output",n),fi=(e,t,r,n=1)=>Ws(e,t,r,"internal",n),mi=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=_n){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])}},Ia=(e,t)=>new mi(e,t),us=(e,t)=>{let r=e.length,n=[];for(let s=0;s1&&i===1&&n.unshift(a)}return n}}),Fa,_i,Cs,Oa,Pn,za,gi,ds=D(()=>{Qt(),Yt(),fr(),ir(),Fa=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},_i=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Cs=(e,t)=>qe.sortBasedOnPerm(e,_i(e.length,t)),Oa=(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=_i(n,t),a=Cs(e.dims,s),i=Ut("output",r,a.length),d=it("a",r,n),c;if(s.length===2&&s[0]===1&&s[1]===0){let h=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=h=>` ${h.registerUniform("output_size","u32").declareVariables(d,i)} ${Oa(s,n,d,i)} ${h.mainStart()} ${h.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:h=>{let w=qe.size(a);return{outputs:[{dims:a,dataType:h[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},...kt(h[0].dims,a)]}},getShaderSource:c}},za=(e,t)=>{Fa(e.inputs),e.compute(Pn(e.inputs[0],t.perm))},gi=e=>Gt({perm:e.perm})}),Da,Ba,La,Ra,wi,Na,ja,yi,Va,Ua,bn,Wa,Ga,bi,qa,Ha,Mi,Ka,Xa,vi,Qa,zu=D(()=>{Qt(),Yt(),ir(),ki(),ds(),Da={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"},Ba={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"},La={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Ra={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},wi=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,s]},ja=(e,t)=>{let r=e.length+t.length,n=[],s=0;for(let a=0;a{for(let r=0;r{let r=[];if(!yi(e,t)){for(let n=0;nr.push(n))}return r},Ua=(e,t,r,n,s,a,i)=>{let d=r[0].dims,c=qe.size(a),h=qe.size(i),w=it("_A",r[0].dataType,d),y=Ut("output",s,a),u=32,k=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:C=>` ${C.registerUniform("reduceSize","u32").declareVariables(w,y)} ${k} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${C.mainStart(u)} let outputIndex = global_idx / ${u}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${La[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${u}) { let candidate = f32(${w.getByOffset("offset + k")}); bestValue = ${Da[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 = ${Ba[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}(${Ra[n]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:c},programUniforms:[{type:12,data:h}]})}},bn=(e,t,r,n)=>{let s=e.inputs.length===1?r:qs(e.inputs,r),a=s.axes;a.length===0&&!s.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((k,C)=>C));let i=qe.normalizeAxes(a,e.inputs[0].dims.length),d=i,c=e.inputs[0],h=Va(d,e.inputs[0].dims.length);h.length>0&&(c=e.compute(Pn(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],d=wi(d.length,c.dims.length));let[w,y]=Na(c.dims,d),u=w;s.keepDims&&(u=ja(w,i)),e.compute(Ua(t,{hint:s.cacheKey,inputDependencies:["type"]},[c],n,e.inputs[0].dataType,u,y),{inputs:[c]})},Wa=(e,t)=>{bn(e,"ReduceMeanShared",t,"mean")},Ga=(e,t)=>{bn(e,"ReduceL1Shared",t,"l1")},bi=(e,t)=>{bn(e,"ReduceL2Shared",t,"l2")},qa=(e,t)=>{bn(e,"ReduceLogSumExpShared",t,"logSumExp")},Ha=(e,t)=>{bn(e,"ReduceMaxShared",t,"max")},Mi=(e,t)=>{bn(e,"ReduceMinShared",t,"min")},Ka=(e,t)=>{bn(e,"ReduceProdShared",t,"prod")},Xa=(e,t)=>{bn(e,"ReduceSumShared",t,"sum")},vi=(e,t)=>{bn(e,"ReduceSumSquareShared",t,"sumSquare")},Qa=(e,t)=>{bn(e,"ReduceLogSumShared",t,"logSum")}}),Mn,Ya,Gs,qs,Cn,Za,xi,Ja,eo,Ti,to,ro,Ci,no,so,vn,io,ao,$i,oo,lo,Ei,uo,co,Si,po,ki=D(()=>{Qt(),Yt(),fr(),ir(),zu(),Mn=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.")},Ya=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Gs=(e,t,r,n,s,a,i=!1,d=!1)=>{let c=[],h=r[0].dims,w=h.length,y=qe.normalizeAxes(s,w),u=!d&&y.length===0;h.forEach((F,U)=>{u||y.indexOf(U)>=0?i&&c.push(1):c.push(F)});let k=c.length,C=qe.size(c);return{name:e,shaderCache:t,getShaderSource:F=>{let U=[],G=it("_A",r[0].dataType,w),L=Ut("output",a,k),pe=n(G,L,y),Z=pe[2];for(let oe=0,et=0;oe=0?(i&&et++,Z=`for(var j${oe}: u32 = 0; j${oe} < ${h[oe]}; j${oe}++) { ${pe[2].includes("last_index")?`let last_index = j${oe};`:""} ${G.indicesSet("input_indices",oe,`j${oe}`)} ${Z} }`):(U.push(`${G.indicesSet("input_indices",oe,L.indicesGet("output_indices",et))};`),et++);return` ${F.registerUniform("output_size","u32").declareVariables(G,L)} ${F.mainStart()} ${F.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${G.type.indices}; let output_indices = ${L.offsetToIndices("global_idx")}; ${U.join(` `)} ${pe[0]} // init ops for reduce max/min ${pe[1]} ${Z} ${pe[3]} ${pe.length===4?L.setByOffset("global_idx","value"):pe.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:c,dataType:a}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...kt(h,c)]})}},qs=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),Gt({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Cn=(e,t,r,n)=>{let s=e.inputs,a=s.length===1?r:qs(s,r);e.compute(Gs(t,{hint:a.cacheKey,inputDependencies:["rank"]},[s[0]],a.noopWithEmptyAxes&&a.axes.length===0?Ya:n,a.axes,s[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Za=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},xi=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Ja=(e,t)=>{Mn(e.inputs),Cn(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);"])},eo=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Ti=(e,t)=>{Mn(e.inputs),Cn(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")});`,""]})},to=(e,t)=>{Mn(e.inputs),Cn(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});`]})},ro=(e,t)=>{Mn(e.inputs),Cn(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")});`,""]})},Ci=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},no=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},so=(e,t)=>{Mn(e.inputs),Cn(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;`,""])},vn=(e,t,r)=>{if(t.length===0)return r;let n=1,s=1;for(let a=0;a1024},io=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?to(e,t):Wa(e,t)},ao=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xi(e,t):Ga(e,t)},$i=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ja(e,t):bi(e,t)},oo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?eo(e,t):qa(e,t)},lo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ti(e,t):Ha(e,t)},Ei=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ro(e,t):Mi(e,t)},uo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ci(e,t):Ka(e,t)},co=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?no(e,t):Xa(e,t)},Si=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?so(e,t):vi(e,t)},po=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Za(e,t):Qa(e,t)}}),Hs,ho,fo,Ks,Du=D(()=>{Qt(),fr(),ki(),Hs=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.")},ho=(e,t)=>{Hs(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(Gs("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},fo=(e,t)=>{Hs(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(Gs("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Ks=e=>Gt(e)}),mo,Pi,_o,go,cs,wo,yo,Xs=D(()=>{Qt(),O(),ir(),mo=(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 relative_position_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let c=r.dims[0],h=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,k=u;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let pe of t.qkvHiddenSizes)if(pe%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");y=t.qkvHiddenSizes[0],u=t.qkvHiddenSizes[1],k=t.qkvHiddenSizes[2]}let C=h;if(y!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==y+u+k)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let F=0;if(i){if(u!==k)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||(F=i.dims[3])}let U=C+F,G=-1,L=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");return{batchSize:c,sequenceLength:h,pastSequenceLength:F,kvSequenceLength:C,totalSequenceLength:U,maxSequenceLength:G,inputHiddenSize:w,hiddenSize:y,vHiddenSize:k,headSize:Math.floor(y/t.numHeads),vHeadSize:Math.floor(k/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:L,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Pi=(e,t,r,n)=>{let s=gr(n),a=64,i=n/s;i{let k=Ut("x",t.dataType,t.dims,s),C=[{name:"d_inv",type:xr(t.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${u.registerUniforms(C).declareVariables(k)} ${u.mainStart([a,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = workgroup_id.x * uniforms.d_comp + local_offset; var thread_max_vector = ${w}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${w}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(s){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: ${s}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${a}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${w}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${w}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(s){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: ${s}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${a}; 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] = ${k.type.value}(uniforms.d_inv); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${w}(x[offset + i]); x[offset + i] = ${k.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${a};${h};${s}`},getShaderSource:y,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:c})}},_o=(e,t,r,n,s,a,i,d)=>{let c=d+a.kvSequenceLength,h=[a.batchSize,a.numHeads,a.sequenceLength,c],w=a.kvNumHeads===void 0&&e.outputCount>1,y=w?[a.batchSize,a.numHeads,c,a.headSize]:void 0,u=i.scale===0?1/Math.sqrt(a.headSize):i.scale,k=gr(a.headSize),C=a.headSize/k,F=12,U={x:Math.ceil(c/F),y:Math.ceil(a.sequenceLength/F),z:a.batchSize*a.numHeads},G=[{type:12,data:a.sequenceLength},{type:12,data:C},{type:12,data:c},{type:12,data:a.numHeads},{type:1,data:u},{type:12,data:d},{type:12,data:a.kvSequenceLength}],L=["type","type"];n&&L.push("type"),s&&L.push("type");let pe=[{dims:h,dataType:t.dataType,gpuDataType:0}];w&&pe.push({dims:y,dataType:t.dataType,gpuDataType:0});let Z=oe=>{let et=it("q",t.dataType,t.dims,k),We=it("key",r.dataType,r.dims,k),ct=[et,We];if(n){let rr=it("past_key",n.dataType,n.dims,k);ct.push(rr)}s&&ct.push(it("relative_position_bias",s.dataType,s.dims));let Ot=Ut("output",t.dataType,h),zt=[Ot];w&&zt.push(Ut("present_key",t.dataType,y,k));let hr=xr(1,k),br=[{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 = ${F}u; var tileQ: array<${et.type.storage}, ${F*F}>; var tileK: array<${et.type.storage}, ${F*F}>; ${oe.registerUniforms(br).declareVariables(...ct,...zt)} ${oe.mainStart([F,F,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; ${n&&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 = ${hr}(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; ${n&&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 += ${hr}(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(k){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: ${k}`)}})()}; output[outputIdx] = ${Ot.type.value} (sum * uniforms.alpha) + ${s?"relative_position_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${s!==void 0};${n!==void 0};${e.outputCount}`,inputDependencies:L},getRunData:()=>({outputs:pe,dispatchGroup:U,programUniforms:G}),getShaderSource:Z}},go=(e,t,r,n,s,a)=>{let i=a+s.kvSequenceLength,d=s.nReps?s.nReps:1,c=s.vHiddenSize*d,h=s.kvNumHeads==null&&e.outputCount>1,w=h?[s.batchSize,s.numHeads,i,s.headSize]:void 0,y=[s.batchSize,s.sequenceLength,c],u=12,k={x:Math.ceil(s.vHeadSize/u),y:Math.ceil(s.sequenceLength/u),z:s.batchSize*s.numHeads},C=[{type:12,data:s.sequenceLength},{type:12,data:i},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:c},{type:12,data:a},{type:12,data:s.kvSequenceLength}],F=n?["type","type","type"]:["type","type"],U=[{dims:y,dataType:t.dataType,gpuDataType:0}];h&&U.push({dims:w,dataType:t.dataType,gpuDataType:0});let G=L=>{let pe=it("probs",t.dataType,t.dims),Z=it("v",r.dataType,r.dims),oe=[pe,Z];n&&oe.push(it("past_value",n.dataType,n.dims));let et=[Ut("output",t.dataType,y)];h&&et.push(Ut("present_value",t.dataType,w));let We=[{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<${pe.type.value}, ${u*u}>; var tileK: array<${pe.type.value}, ${u*u}>; ${L.registerUniforms(We).declareVariables(...oe,...et)} ${L.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; ${n&&h?` 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; `} ${h?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} var value = ${pe.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${n&&h?` 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]; `} ${h?"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.outputCount}`,inputDependencies:F},getRunData:()=>({outputs:U,dispatchGroup:k,programUniforms:C}),getShaderSource:G}},cs=(e,t,r,n,s,a,i,d,c,h,w)=>{let y=e.outputCount,u=h.kvNumHeads!==void 0||y>1?h.pastSequenceLength:0,k=u+h.kvSequenceLength,C=h.kvNumHeads===void 0&&y>1&&i?[t,r,i]:[t,r];c&&C.push(c);let F=e.compute(_o(e,t,r,y>1?i:void 0,c,h,w,u),{inputs:C,outputs:h.kvNumHeads===void 0&&y>1?[-1,1]:[-1]})[0];e.compute(Pi(e,F,h.batchSize*h.numHeads*h.sequenceLength,k),{inputs:[F],outputs:[]});let U=h.kvNumHeads===void 0&&y>1&&d?[F,n,d]:[F,n];e.compute(go(e,F,n,y>1&&d?d:void 0,h,u),{inputs:U,outputs:h.kvNumHeads===void 0&&y>1?[0,2]:[0]})},wo=(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]],h=[{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=Ut("output_q",c[0].dataType,r),k=Ut("output_k",c[0].dataType,r),C=Ut("output_v",c[0].dataType,r),F=it("input",c[0].dataType,c[0].dims),U=it("weight",c[1].dataType,c[1].dims),G=it("bias",c[2].dataType,c[2].dims),L=F.type.storage,pe=[{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(pe).declareVariables(F,U,G,u,k,C)} ${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:h}),getShaderSource:w},{inputs:c,outputs:[-1,-1,-1]})},yo=(e,t)=>{let r=mo(e.inputs,t),[n,s,a]=wo(e,r);return cs(e,n,s,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),bo,Mo,vo,xo,To=D(()=>{$(),Qt(),Yt(),fr(),ir(),bo=(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")},Mo=(e,t)=>{let{epsilon:r,spatial:n,format:s}=t,a=e[0].dims,i=n?gr(a[a.length-1]):1,d=s==="NHWC"&&a.length>1?i:1,c=qe.size(a)/i,h=n,w=h?a.length:a,y=it("x",e[0].dataType,e[0].dims,i),u=it("scale",e[1].dataType,e[1].dims,d),k=it("bias",e[2].dataType,e[2].dims,d),C=it("inputMean",e[3].dataType,e[3].dims,d),F=it("inputVar",e[4].dataType,e[4].dims,d),U=Ut("y",e[0].dataType,w,i),G=()=>{let pe="";if(n)pe=`let cOffset = ${a.length===1?"0u":s==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(s==="NCHW")pe=` ${U.indicesSet("outputIndices","0","0")} let cOffset = ${U.indicesToOffset("outputIndices")};`;else{pe=`var cIndices = ${u.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let Z=1;Z` const epsilon = ${r}; ${pe.registerUniform("outputSize","u32").declareVariables(y,u,k,C,F,U)} ${pe.mainStart()} ${pe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${U.offsetToIndices(`global_idx * ${i}`)}; ${G()} let scale = ${u.getByOffset("cOffset")}; let bias = ${k.getByOffset("cOffset")}; let inputMean = ${C.getByOffset("cOffset")}; let inputVar = ${F.getByOffset("cOffset")}; let x = ${y.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${U.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:h?["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:h?[{type:12,data:c},...kt(a)]:[{type:12,data:c}]})}},vo=e=>Gt(e),xo=(e,t)=>{let{inputs:r,outputCount:n}=e,s=vo({...t,outputCount:n});if(A.webgpu.validateInputContent&&bo(r,s),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Mo(r,s))}}),Co,$o,Ai,Bu=D(()=>{Yt(),ir(),Co=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")},$o=e=>{let t=e[0].dims,r=e[0].dims[2],n=qe.size(t)/4,s=e[0].dataType,a=it("input",s,t,4),i=it("bias",s,[r],4),d=it("residual",s,t,4),c=Ut("output",s,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` const channels = ${r}u / 4; ${h.declareVariables(a,i,d,c)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${a.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; ${c.setByOffset("global_idx","value")} }`}},Ai=e=>{Co(e.inputs),e.compute($o(e.inputs))}}),Eo,wr,So,ko,Ii,Po,Ao,Fi,Io,Fo,Qs,Oo,zo,Do,Oi,Bo,ps,Lo,Ys,Ro,zi,No,jo,Vo,Di,Uo,Wo,Bi,Go,qo,Li,Ho,Ko,Ri,Xo,Ni,ji,Vi,Ui,Qo,Yo,Wi,Zo,Jo,el,Gi=D(()=>{Qt(),Yt(),fr(),ir(),Eo=(e,t,r,n,s,a)=>{let i=Math.ceil(t/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let c=it("inputData",r,[i],4),h=Ut("outputData",n,[i],4);return` ${e.registerUniform("vec_size","u32").declareVariables(c,h)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${c.getByOffset("global_idx")}; ${h.setByOffset("global_idx",d)} }`},wr=(e,t,r,n,s,a=e.dataType)=>({name:t,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:i=>Eo(i,qe.size(e.dims),e.dataType,a,r,n),getRunData:i=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(qe.size(i[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(qe.size(e.dims)/4)}]})}),So=e=>{e.compute(wr(e.inputs[0],"Abs","abs"))},ko=e=>{e.compute(wr(e.inputs[0],"Acos","acos"))},Ii=e=>{e.compute(wr(e.inputs[0],"Acosh","acosh"))},Po=e=>{e.compute(wr(e.inputs[0],"Asin","asin"))},Ao=e=>{e.compute(wr(e.inputs[0],"Asinh","asinh"))},Fi=e=>{e.compute(wr(e.inputs[0],"Atan","atan"))},Io=e=>{e.compute(wr(e.inputs[0],"Atanh","atanh"))},Fo=e=>Gt(e),Qs=(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(wr(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Oo=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Hr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:cn;return Gt({min:t,max:r})},zo=(e,t)=>{let r=e.inputs.length===1?t:Oo(e.inputs),n=xr(e.inputs[0].dataType);e.compute(wr(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]})},Do=e=>{e.compute(wr(e.inputs[0],"Ceil","ceil"))},Oi=e=>{e.compute(wr(e.inputs[0],"Cos","cos"))},Bo=e=>{e.compute(wr(e.inputs[0],"Cosh","cosh"))},ps=e=>Gt(e),Lo=(e,t)=>{let r=xr(e.inputs[0].dataType);e.compute(wr(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))},Ys=(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)); }`,Ro=e=>{let t=xr(e.inputs[0].dataType);e.compute(wr(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Ys(t)))},zi=e=>{e.compute(wr(e.inputs[0],"Exp","exp"))},No=e=>{e.compute(wr(e.inputs[0],"Floor","floor"))},jo=e=>{let t=xr(e.inputs[0].dataType);e.compute(wr(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Ys(t)))},Vo=(e,t)=>{let r=xr(e.inputs[0].dataType);e.compute(wr(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))},Di=e=>{e.compute(wr(e.inputs[0],"Not",t=>`!${t}`))},Uo=e=>{e.compute(wr(e.inputs[0],"Neg",t=>`-${t}`))},Wo=e=>{e.compute(wr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Bi=e=>{let t=xr(e.inputs[0].dataType);e.compute(wr(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Go=e=>{e.compute(wr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},qo=e=>Gt(e),Li=(e,t)=>{let r=xr(e.inputs[0].dataType);e.compute(wr(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))},Ho=e=>{e.compute(wr(e.inputs[0],"Sin","sin"))},Ko=e=>{e.compute(wr(e.inputs[0],"Sinh","sinh"))},Ri=e=>{e.compute(wr(e.inputs[0],"Sqrt","sqrt"))},Xo=e=>{e.compute(wr(e.inputs[0],"Tan","tan"))},Ni=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,ji=e=>{e.compute(wr(e.inputs[0],"Tanh",Ni))},Vi=(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 ${Ni("v")}; } `,Ui=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Qo=e=>{let t=xr(e.inputs[0].dataType);e.compute(wr(e.inputs[0],"FastGelu",Ui,Vi(t),void 0,e.inputs[0].dataType))},Yo=(e,t)=>{let r=xr(e.inputs[0].dataType);return e.compute(wr(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},Wi=e=>{e.compute(wr(e.inputs[0],"Log","log"))},Zo=(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; } `,Jo=e=>`quick_gelu_impl(${e})`,el=(e,t)=>{let r=xr(e.inputs[0].dataType);e.compute(wr(e.inputs[0],"QuickGelu",Jo,Zo(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),qi,tl,rl,nl=D(()=>{Yt(),ir(),Gi(),qi=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")},tl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=it("input",e[0].dataType,e[0].dims,4),n=it("bias",e[0].dataType,[e[0].dims[2]],4),s=Ut("output",e[0].dataType,t,4),a=qe.size(t)/4,i=vr(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)} ${Ys(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")} }`}},rl=e=>{qi(e.inputs),e.compute(tl(e.inputs))}}),sl,il,xn,al,ol,Hi,ll,ul,dl,cl,pl,hl,Ki,Lu=D(()=>{Qt(),Yt(),ir(),sl=(e,t,r,n,s,a,i,d,c,h,w,y)=>{let u,k;typeof d=="string"?u=k=(L,pe)=>`${d}((${L}),(${pe}))`:typeof d=="function"?u=k=d:(u=d.scalar,k=d.vector);let C=Ut("outputData",w,n.length,4),F=it("aData",c,t.length,4),U=it("bData",h,r.length,4),G;if(s)if(a){let L=qe.size(t)===1,pe=qe.size(r)===1,Z=t.length>0&&t[t.length-1]%4===0,oe=r.length>0&&r[r.length-1]%4===0;L||pe?G=C.setByOffset("global_idx",k(L?`${F.type.value}(${F.getByOffset("0")}.x)`:F.getByOffset("global_idx"),pe?`${U.type.value}(${U.getByOffset("0")}.x)`:U.getByOffset("global_idx"))):G=` let outputIndices = ${C.offsetToIndices("global_idx * 4u")}; let offsetA = ${F.broadcastedIndicesToOffset("outputIndices",C)}; let offsetB = ${U.broadcastedIndicesToOffset("outputIndices",C)}; ${C.setByOffset("global_idx",k(i||Z?F.getByOffset("offsetA / 4u"):`${F.type.value}(${F.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||oe?U.getByOffset("offsetB / 4u"):`${U.type.value}(${U.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else G=C.setByOffset("global_idx",k(F.getByOffset("global_idx"),U.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let L=(pe,Z,oe="")=>{let et=`aData[indexA${Z}][componentA${Z}]`,We=`bData[indexB${Z}][componentB${Z}]`;return` let outputIndices${Z} = ${C.offsetToIndices(`global_idx * 4u + ${Z}u`)}; let offsetA${Z} = ${F.broadcastedIndicesToOffset(`outputIndices${Z}`,C)}; let offsetB${Z} = ${U.broadcastedIndicesToOffset(`outputIndices${Z}`,C)}; let indexA${Z} = offsetA${Z} / 4u; let indexB${Z} = offsetB${Z} / 4u; let componentA${Z} = offsetA${Z} % 4u; let componentB${Z} = offsetB${Z} % 4u; ${pe}[${Z}] = ${oe}(${u(et,We)}); `};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(F,U,C)} ${y??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${G} }`},il=(e,t,r,n,s,a,i=r.dataType)=>{let d=!qe.areEqual(r.dims,n.dims),c=r.dims,h=qe.size(r.dims),w=!1,y=!1,u=[d];if(d){let k=Yr.calcShape(r.dims,n.dims,!1);if(!k)throw new Error("Can't perform binary op on the given tensors");c=k,h=qe.size(c);let C=qe.size(r.dims)===1,F=qe.size(n.dims)===1,U=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(C),u.push(F),u.push(U),u.push(G);let L=1;for(let pe=1;pek.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:k=>sl(k,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(h/64/4)},programUniforms:[{type:12,data:Math.ceil(qe.size(c)/4)},...kt(r.dims,n.dims,c)]})}},xn=(e,t,r,n,s,a)=>{e.compute(il(t,s??"",e.inputs[0],e.inputs[1],r,n,a))},al=e=>{xn(e,"Add",(t,r)=>`${t}+${r}`)},ol=e=>{xn(e,"Div",(t,r)=>`${t}/${r}`)},Hi=e=>{xn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},ll=e=>{xn(e,"Mul",(t,r)=>`${t}*${r}`)},ul=e=>{let t=it("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;xn(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)); } `)},dl=e=>{xn(e,"Sub",(t,r)=>`${t}-${r}`)},cl=e=>{xn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},pl=e=>{xn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},hl=e=>{xn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Ki=e=>{xn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),fl,Xi,ml,_l,qn,gl,Ru=D(()=>{Qt(),Yt(),fr(),ir(),fl=(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,h)=>{if(h!==t&&c!==n.dims[h])throw new Error("non concat dimensions must match")})}})},Xi=(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; }`,ml=(e,t)=>{let r=e.length,n=[];for(let s=0;s{let s=qe.size(r),a=new Array(e.length),i=new Array(e.length),d=0,c=[],h=[],w=[{type:12,data:s}];for(let F=0;F`uniforms.sizeInConcatAxis${F}`).join(","),C=F=>` ${(()=>{F.registerUniform("outputSize","u32");for(let U=0;U(${k}); ${u} -= sizeInConcatAxis[inputIndex - 1u]; } ${ml(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:C}},qn=(e,t)=>{let r=e.inputs,n=r[0].dims,s=qe.normalizeAxis(t.axis,n.length);fl(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=>qe.size(d.dims)>0);e.compute(_l(i,s,a,r[0].dataType),{inputs:i})},gl=e=>Gt({axis:e.axis})}),Hn,Kn,Bn,Qi,Xn=D(()=>{Qt(),Yt(),Hn=(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}`)}},Kn=(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})},Bn=(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)||[Hr,cn];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}}}),en,Yi,hs=D(()=>{en=(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.`)}},Yi=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),Zi,wl=D(()=>{Zi=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)); } `}),yl,$s,Zs,Ji,bl,Js,ei,ea,ti=D(()=>{Qt(),Yt(),ir(),Xn(),hs(),yl=(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":""}); `,$s=(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];"} }`,Zs=(e,t,r="f32",n,s=!1,a=32,i=!1,d=32)=>{let c=t[1]*e[1],h=t[0]*e[0],w=s?c:a,y=s?a:c,u=w/t[0],k=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, ${h/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 * ${k}; 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; ${yl(s,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${k}; 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];"} ${$s(s,u)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Ji=(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":""}); `,bl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Js=(e,t,r="f32",n,s=!1,a=32,i=!1,d=32,c=!1)=>{let h=e[1]*t[1],w=e[0]*t[0],y=s?h:a,u=s?a:h;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 k=u/t[1],C=y/t[0],F=a/t[1],U=c?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${h}; 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]}) { ${Ji(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) * ${h}; let tileRowA = i32(localId.y) * ${k}; let tileColA = i32(localId.x) * ${C}; let tileRowB = i32(localId.y) * ${F}; // 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 < ${k}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${C}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Ji(s,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${F}; 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) { ${bl(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>; ${U} } `},ei=(e,t,r,n,s,a=!1)=>{let[i,d,c]=s,[h,w,y,u]=n,k=us(i,c),C=us(d,c),F=vr(n[0].type.tensor),U=()=>{let L=w.rank,pe=h.rank,Z=`var aIndices: ${w.type.indices};`;for(let oe=L-2-1,et=pe-1;oe>=0;oe--,et--)Z+=` aIndices[${oe}] = ${pe>1?`batchIndices[${et}]`:"batchIndices"};`;return k.forEach(oe=>{Z+=` aIndices[${oe}] = 0;`}),Z+=` aIndices[${L-2}] = u32(row); aIndices[${L-1}] = u32(colIn);`,Z},G=()=>{let L=y.rank,pe=h.rank,Z=`var bIndices: ${y.type.indices};`;for(let oe=L-2-1,et=pe-1;oe>=0;oe--,et--)Z+=` bIndices[${oe}] = ${pe>1?`batchIndices[${et}]`:"batchIndices"};`;return C.forEach(oe=>{Z+=` bIndices[${oe}] = 0;`}),Z+=` bIndices[${L-2}] = u32(row); bIndices[${L-1}] = u32(colIn);`,Z};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${en(e,F)} { var value = ${en(e,F)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${U()} value = ${w.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${en(e,F)} { var value = ${en(e,F)}(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: ${en(e,F)}) { 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]":`${en(e,F)}(bias[row])`};`:""} ${r} ${u.setByIndices("vec3(coords)","value")} } } `},ea=(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),h=n?n.slice(0,-2):r.slice(0,-2),w=qe.size(h),y=a[a.length-2],u=a[a.length-1],k=i[i.length-1],C=u%4===0&&k%4===0,F=y<=8?[4,1,1]:[4,4,1],U=[8,8,1],G=[Math.ceil(k/U[0]/F[0]),Math.ceil(y/U[1]/F[1]),Math.ceil(w/U[2]/F[2])],L=C?4:1,pe=[...d,y,u/L],Z=pe.length,oe=[...c,u,k/L],et=oe.length,We=[w,y,k/L],ct=[{type:6,data:y},{type:6,data:k},{type:6,data:u}];Kn(t,ct),ct.push(...kt(h,pe,oe));let Ot=["rank","rank"],zt=e.length>2;zt&&(ct.push(...kt(e[2].dims)),Ot.push("rank")),ct.push(...kt(We));let hr=br=>{let rr=h.length,Sr=fi("batchDims",e[0].dataType,rr,1),Wr=vr(e[0].dataType),cr=it("a",e[0].dataType,Z,L),Rr=it("b",e[1].dataType,et,L),Bt=Ut("result",e[0].dataType,We.length,L),Zt=[cr,Rr];if(zt){let Br=s?L:1;Zt.push(it("bias",e[2].dataType,e[2].dims.length,Br))}let _r=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Bn(t,_r);let Le=vr(Bt.type.tensor),Nt=Hn(t,Bt.type.value,Le),tr=ei(L,zt,Nt,[Sr,cr,Rr,Bt],[d,c,h],s);return` ${br.registerUniforms(_r).registerInternalVariables(Sr).declareVariables(...Zt,Bt)} ${tr} ${C?Zs(F,U,Wr,Sr):Js(F,U,Wr,Sr)} `};return{name:"MatMul",shaderCache:{hint:`${F};${t.activation};${C};${s}`,inputDependencies:Ot},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:G[0],y:G[1],z:G[2]},programUniforms:ct}),getShaderSource:hr}}}),Ml,Nu,ju=D(()=>{Qt(),mn(),ir(),Xn(),hs(),wl(),ti(),Ml=(e,t,r,n,s=!1,a,i=4,d=4,c=4,h="f32")=>{let w=Ot=>{switch(Ot){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Ot} is not supported.`)}},y=Ot=>{switch(Ot){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 ${Ot} is not supported.`)}},u=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,k=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])",F=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",U=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 = ${U} / outWidth; let outCol = ${U} % 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 = ${en(i,h)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${C} && xCol >= 0 && xCol < ${F}) { ${u} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${w(i)} } return resData;`,pe=e?t&&n?` let col = colIn * ${i}; ${L}`:` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${L} } return ${en(i,h)}(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 ${en(i,h)}(0.0);`,Z=`${y(d)}`,oe=en(c,h),et=en(e?i:d,h),We=en(e?d:i,h),ct=Hn(a,oe,h);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${et} { ${e?pe:Z} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${We} { ${e?Z:pe} } 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])"}; ${k} ${Yi(s)} ${ct} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Nu=(e,t,r,n,s,a,i,d)=>{let c=t.format==="NHWC",h=c?e[0].dims[3]:e[0].dims[1],w=r[0],y=c?r[2]:r[3],u=c?r[1]:r[2],k=c?r[3]:r[1],C=c&&(h%4===0||h%3===0)&&k%4===0,F=c?k:y*u,U=c?y*u:k,G=[8,8,1],L=n<=8?[4,1,1]:[4,4,1],pe=[Math.ceil(F/G[0]/L[0]),Math.ceil(U/G[1]/L[1]),Math.ceil(w/G[2]/L[2])];Dr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${pe}`);let Z=C?c&&h%4!==0?3:4:1,oe=G[1]*L[1],et=G[0]*L[0],We=Math.max(G[0]*Z,G[1]),ct=n%oe===0,Ot=s%et===0,zt=a%We===0,hr=C?[Z,4,4]:[1,1,1],br=[{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}];Kn(t,br),br.push(...kt(e[0].dims,e[1].dims));let rr=["rank","rank"];i&&(br.push(...kt(e[2].dims)),rr.push("rank")),br.push(...kt(r));let Sr=Wr=>{let cr=[{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}];Bn(t,cr);let Rr=C?4:1,Bt=vr(e[0].dataType),Zt=` fn setOutputAtIndex(flatIndex : i32, value : ${C?`vec4<${Bt}>`:Bt}) { result[flatIndex] = ${C?`vec4<${Bt}>`:Bt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${C?`vec4<${Bt}>`:Bt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${C?"/ 4":""}, value); }`,_r=it("x",e[0].dataType,e[0].dims.length,Z===3?1:Z),Le=it("w",e[1].dataType,e[1].dims.length,Rr),Nt=[_r,Le],tr=Ut("result",e[0].dataType,r.length,Rr);if(i){let Br=it("bias",e[2].dataType,e[2].dims.length,Rr);Nt.push(Br),Zt+=` fn getBiasByOutputCoords(coords : vec4) -> ${C?`vec4<${Bt}>`:Bt} { return bias[coords.${c?"w":"y"}${C?"/ 4":""}]; }`}return` ${Zi("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 }; ${Wr.registerUniforms(cr).declareVariables(...Nt,tr)} ${Zt} ${Ml(c,ct,Ot,zt,i,t,hr[0],hr[1],hr[2],Bt)} ${C?Zs(L,G,Bt,void 0,!c,We):Js(L,G,Bt,void 0,!c,We,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Z};${C};${ct};${Ot};${zt};${oe};${et};${We}`,inputDependencies:rr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:pe[0],y:pe[1],z:pe[2]},programUniforms:br}),getShaderSource:Sr}}}),vl,ta,Ln,xl,ra,Tl,Cl,$l,na=D(()=>{Qt(),mn(),Yt(),ir(),Xn(),hs(),vl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Ln=(e,t)=>t<=1?e:e+(e-1)*(t-1),xl=(e,t,r,n=1)=>{let s=Ln(t,n);return Math.floor((e[0]*(r-1)-r+s)/2)},ra=(e,t,r,n,s)=>{s==null&&(s=xl(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},Tl=(e,t,r,n,s,a,i,d,c,h)=>{let w,y,u,k;if(e==="VALID"&&(e=0),typeof e=="number"){w={top:e,bottom:e,left:e,right:e,front:e,back:e};let C=ra([t,r,n,1],[d,c,h],1,[s,a,i],e);y=C[0],u=C[1],k=C[2]}else if(Array.isArray(e)){if(!e.every((F,U,G)=>F===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 C=ra([t,r,n,1],[d,c,h],1,[s,a,i],e[0]);y=C[0],u=C[1],k=C[2]}else if(e==="SAME_UPPER"){y=Math.ceil(t/s),u=Math.ceil(r/a),k=Math.ceil(n/i);let C=(y-1)*s+d-t,F=(u-1)*a+c-r,U=(k-1)*i+h-n,G=Math.floor(C/2),L=C-G,pe=Math.floor(F/2),Z=F-pe,oe=Math.floor(U/2),et=U-oe;w={top:pe,bottom:Z,left:oe,right:et,front:G,back:L}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:w,outDepth:y,outHeight:u,outWidth:k}},Cl=(e,t,r,n,s,a=!1,i="channelsLast")=>{let d,c,h,w,y;if(i==="channelsLast")[d,c,h,w,y]=e;else if(i==="channelsFirst")[d,y,c,h,w]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,k,C,F]=t,[U,G,L]=ta(r),[pe,Z,oe]=ta(n),et=Ln(k,pe),We=Ln(C,Z),ct=Ln(F,oe),{padInfo:Ot,outDepth:zt,outHeight:hr,outWidth:br}=Tl(s,c,h,w,U,G,L,et,We,ct),rr=a?u*y:u,Sr=[0,0,0,0,0];return i==="channelsFirst"?Sr=[d,rr,zt,hr,br]:i==="channelsLast"&&(Sr=[d,zt,hr,br,rr]),{batchSize:d,dataFormat:i,inDepth:c,inHeight:h,inWidth:w,inChannels:y,outDepth:zt,outHeight:hr,outWidth:br,outChannels:rr,padInfo:Ot,strideDepth:U,strideHeight:G,strideWidth:L,filterDepth:k,filterHeight:C,filterWidth:F,effectiveFilterDepth:et,effectiveFilterHeight:We,effectiveFilterWidth:ct,dilationDepth:pe,dilationHeight:Z,dilationWidth:oe,inShape:e,outShape:Sr,filterShape:t}},$l=(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((U,G)=>G)},h=[Math.ceil(vl(c.x.map(U=>r[U]))/d[0]),1,1];Dr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let w=1,y=qe.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}];Kn(t,u),u.push(...kt(e[0].dims,e[1].dims));let k=["rank","rank"],C=e.length===3;C&&(u.push(...kt(e[2].dims)),k.push("rank")),u.push(...kt(r));let F=U=>{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}];Bn(t,G);let L=1,pe=vr(e[0].dataType),Z=it("x",e[0].dataType,e[0].dims.length,w),oe=it("W",e[1].dataType,e[1].dims.length,L),et=[Z,oe],We=Ut("result",e[0].dataType,r.length,L),ct="";if(C){let hr=it("bias",e[2].dataType,e[2].dims.length,L);et.push(hr),ct+=` fn getBiasByOutputCoords(coords : array) -> ${pe} { return bias[${i?Ft("coords",4,5):Ft("coords",1,5)}]; }`}let Ot=en(w,pe),zt=Hn(t,Ot,pe);return` ${ct} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${Z.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${oe.getByIndices("aIndices")}; } ${U.registerUniforms(G).declareVariables(...et,We)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${We.offsetToIndices("global_idx")}; let batch = ${Ft("coords",0,Z.rank)}; let d2 = ${i?Ft("coords",Z.rank-1,Z.rank):Ft("coords",1,Z.rank)}; let xFRCCorner = vec3(${i?Ft("coords",1,Z.rank):Ft("coords",2,Z.rank)}, ${i?Ft("coords",2,Z.rank):Ft("coords",3,Z.rank)}, ${i?Ft("coords",3,Z.rank):Ft("coords",4,Z.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${i?Ft("uniforms.x_shape",1,Z.rank):Ft("uniforms.x_shape",2,Z.rank)}; let xShapeZ = ${i?Ft("uniforms.x_shape",2,Z.rank):Ft("uniforms.x_shape",3,Z.rank)}; let xShapeW = ${i?Ft("uniforms.x_shape",3,Z.rank):Ft("uniforms.x_shape",4,Z.rank)}; let xShapeU = ${i?Ft("uniforms.x_shape",4,Z.rank):Ft("uniforms.x_shape",1,Z.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${i?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${i?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${i?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${C?"value = value + getBiasByOutputCoords(coords)":""}; ${zt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${w};${C}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:u}),getShaderSource:F}}}),El,Sl,Vu=D(()=>{Qt(),Yt(),ir(),Fl(),Xn(),El=(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",h=ri(a,i,t.dilations,t.pads,t.strides,c),w=qe.size(h),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}];Kn(t,y),y.push(...kt(a,i));let u=["rank","rank"];n&&(y.push(...kt(e[2].dims)),u.push("rank")),y.push(...kt(h));let k=C=>{let F=Ut("output",e[0].dataType,h.length),U=vr(F.type.tensor),G=Hn(t,F.type.value,U),L=it("x",e[0].dataType,a.length),pe=it("w",e[1].dataType,i.length),Z=[L,pe];n&&Z.push(it("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 Bn(t,oe),` ${C.registerUniforms(oe).declareVariables(...Z,F)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${F.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: ${F.type.value} = ${F.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 = ${pe.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${s} ${G} ${F.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:u},getRunData:()=>({outputs:[{dims:r?r(h):h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:y}),getShaderSource:k}},Sl=(e,t,r)=>{let n=e.length>2,s=gr(r[3]),a=gr(r[2]),i=qe.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],h=[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]]}];Kn(t,w),w.push(...kt(d,c,h));let y=(a-1)*t.strides[1]+c[1],u=k=>{let C=Ut("output",e[0].dataType,h.length,s),F=vr(C.type.tensor),U=Hn(t,C.type.value,F),G=it("x",e[0].dataType,d.length,s),L=it("w",e[1].dataType,c.length,s),pe=[G,L];n&&pe.push(it("b",e[2].dataType,e[2].dims,s));let Z=n?"value += b[output_channel];":"",oe=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Bn(t,oe),` ${k.registerUniforms(oe).declareVariables(...pe,C)} ${k.mainStart()} ${k.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<${C.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]; ${Z} ${U} ${C.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}}}),sa,kl,Pl,ia=D(()=>{Qt(),Yt(),ti(),ir(),Xn(),sa=(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],h=a[a.length-1],w=gr(c),y=gr(h),u=gr(d),k=qe.size(r)/w/u,C=e.length>2,F=n?n.slice(0,-2):r.slice(0,-2),U=[qe.size(F),d,c],G=[{type:12,data:k},{type:12,data:d},{type:12,data:c},{type:12,data:h}];Kn(t,G),G.push(...kt(F,a,i)),C&&G.push(...kt(e[2].dims)),G.push(...kt(U));let L=pe=>{let Z=fi("batch_dims",e[0].dataType,F.length),oe=it("a",e[0].dataType,a.length,y),et=it("b",e[1].dataType,i.length,w),We=Ut("output",e[0].dataType,U.length,w),ct=vr(We.type.tensor),Ot=Hn(t,We.type.value,ct),zt=[oe,et],hr="";if(C){let Zt=s?w:1;zt.push(it("bias",e[2].dataType,e[2].dims.length,Zt)),hr=`${s?`value += bias[col / ${Zt}];`:`value += ${We.type.value}(bias[row + i]);`}`}let br=a.slice(0,-2),rr=i.slice(0,-2),Sr=us(br,F),Wr=us(rr,F),cr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Bn(t,cr);let Rr=(Zt,_r)=>{let Le=Zt.rank,Nt=Zt.name;if(Le===2)return`var ${Nt}_indices = ${Zt.type.indices}(0u, 0u);`;let tr=Z.rank,Br=`var ${Nt}_indices: ${Zt.type.indices};`;for(let Xr=Le-2-1,an=tr-1;Xr>=0;Xr--,an--)Br+=` ${Nt}_indices[${Xr}] = ${tr>1?`batch_indices[${an}]`:"batch_indices"};`;return _r.forEach(Xr=>{Br+=` ${Nt}_indices[${Xr}] = 0;`}),Br+=`${Nt}_indices[${Le-2}] = 0u; ${Nt}_indices[${Le-1}] = 0u;`,Br},Bt=()=>{let Zt=`var a_data: ${oe.type.value};`;for(let _r=0;_r; for (var k: u32 = 0u; k < uniforms.K; k = k + ${y}) { ${Bt()} } for (var i = 0u; i < ${u}u; i++) { var value = values[i]; ${hr} ${Ot} let cur_indices = ${We.type.indices}(batch, row + i, col); let offset = ${We.indicesToOffset("cur_indices")}; ${We.setByOffset(`offset / ${w}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${w};${y};${u};${s}`,inputDependencies:C?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:G}),getShaderSource:L}},kl=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.")},Pl=e=>{kl(e.inputs);let t=Yr.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(sa(e.inputs,{activation:""},t)):e.compute(ea(e.inputs,{activation:""},t))}}),ri,ni,aa,si,oa,la,Al,Il,Es,Fl=D(()=>{Yt(),ju(),na(),ti(),Vu(),Xn(),ia(),ds(),ri=(e,t,r,n,s,a)=>{let i=e[0],d=e.slice(a?1:2,a?3:4),c=d.length,h=t[0],w=t.slice(2).map((u,k)=>u+(u-1)*(r[k]-1)),y=d.map((u,k)=>u+n[k]+n[k+c]).map((u,k)=>Math.floor((u-w[k]+s[k])/s[k]));return y.splice(0,0,i),y.splice(a?3:1,0,h),y},ni=[2,3,1,0],aa=(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")},si=(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,h=e.w_is_const();return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,pads:d,strides:c,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},la=(e,t,r)=>{let n=si(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 et=ri(t[0].dims,t[1].dims,r.dilations,n.pads,r.strides,s),We=e.kernelCustomData.wT??e.compute(Pn(t[1],ni),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=We);let ct=[t[0],We];t.length===3&&ct.push(t[2]),e.compute(Sl(ct,n,et),{inputs:ct})}else e.compute(El(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],h=t[1].dims[2],w=t[1].dims[3],y=ri(t[0].dims,t[1].dims,r.dilations,n.pads,r.strides,s),u=y[s?1:2],k=y[s?2:3],C=y[s?3:1],F=s&&h===i&&w===d&&r.pads[0]===0&&r.pads[1]===0;if(F||h===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 et=y[0],We,ct,Ot,zt=[];if(s){let rr=e.kernelCustomData.wT??e.compute(Pn(t[1],ni),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=rr),F){let Sr=i*d*c;We=t[0].reshape([1,et,Sr]),ct=rr.reshape([1,Sr,C]),Ot=[1,et,C]}else We=t[0].reshape([et,i*d,c]),ct=rr.reshape([1,c,C]),Ot=[et,u*k,C];zt.push(We),zt.push(ct)}else We=t[0].reshape([et,c,i*d]),ct=t[1].reshape([1,C,c]),Ot=[et,C,u*k],zt.push(ct),zt.push(We);a&&zt.push(t[2]);let hr=Ot[2],br=zt[0].dims[zt[0].dims.length-1];hr<8&&br<8?e.compute(sa(zt,n,y,Ot,s),{inputs:zt}):e.compute(ea(zt,n,y,Ot,s),{inputs:zt});return}let U=!0,G=e.kernelCustomData.wT??e.compute(Pn(t[1],ni),{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 pe=s?u*k:C,Z=s?C:u*k,oe=h*w*c;e.compute(Nu(L,n,y,pe,Z,oe,a,U),{inputs:L})},Al=(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=si({...t,pads:s,strides:a,dilations:i,kernelShape:d},n);e.compute(El(n,c,h=>r?[h[0],h[2],h[3]]:[]))},Il=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",s=si(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,i=Cl(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute($l(t,s,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},Es=(e,t)=>{aa(e.inputs,t),e.inputs[0].dims.length===3?Al(e,t):e.inputs[0].dims.length===5?Il(e,e.inputs,t):la(e,e.inputs,t)}}),Ol,zl,Uu=D(()=>{Qt(),mn(),ir(),Xn(),hs(),wl(),ti(),Ol=(e,t=!1,r,n,s=4)=>{let a=U=>{switch(U){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 ${U} 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])",h=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(${h}) || 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}];`,k=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);`,C=` let col = colIn * ${s}; let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${a(s)} } return ${n}(0.0); `,F=Hn(r,n);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?k:C} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?C:k} } 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} ${Yi(t)} ${F} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; } }`},zl=(e,t,r,n,s,a,i,d)=>{let c=t.format==="NHWC",h=c?e[0].dims[3]:e[0].dims[1],w=r[0],y=c?r[2]:r[3],u=c?r[1]:r[2],k=c?r[3]:r[1],C=c&&h%4===0&&h%3&&k%4===0,F=c?k:y*u,U=c?y*u:k,G=[8,8,1],L=n<=8?[4,1,1]:[4,4,1],pe=[Math.ceil(F/G[0]/L[0]),Math.ceil(U/G[1]/L[1]),Math.ceil(w/G[2]/L[2])];Dr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${pe}`);let Z=C?4:1,oe=Math.max(G[0]*Z,G[1]),et=C?4:1,We=[t.kernelShape[c?1:2],t.kernelShape[c?2:3]],ct=[We[0]+(t.dilations[0]<=1?0:(We[0]-1)*(t.dilations[0]-1)),We[1]+(t.dilations[1]<=1?0:(We[1]-1)*(t.dilations[1]-1))],Ot=[ct[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),ct[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:We},{type:6,data:Ot}];Kn(t,zt),zt.push(...kt(e[0].dims,e[1].dims));let hr=["rank","rank"];i&&(zt.push(...kt(e[2].dims)),hr.push("rank")),zt.push(...kt(r));let br=rr=>{let Sr=it("x",e[0].dataType,e[0].dims.length,et),Wr=it("w",e[1].dataType,e[1].dims.length,1),cr=Ut("result",e[0].dataType,r.length,et),Rr=[Sr,Wr],Bt="";if(i){let Le=it("bias",e[2].dataType,e[2].dims.length,et);Rr.push(Le),Bt+=` fn getBiasByOutputCoords(coords : vec4) -> ${Le.type.value} { return bias[coords.${c?"w":"y"}${C?"/ 4":""}]; }`}let Zt=[{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:We.length},{name:"pads",type:"i32",length:Ot.length}];Bn(t,Zt);let _r=vr(e[0].dataType,1);if(_r!=="f16"&&_r!=="f32")throw new Error(`elemType ${_r} is not supported.`);return` ${Zi("uniforms.result_strides")} ${rr.registerUniforms(Zt).declareVariables(...Rr,cr)}; ${Bt} ${Ol(c,i,t,Sr.type.value,Z)} ${C?Zs(L,G,_r,void 0,!c,oe):Js(L,G,_r,void 0,!c,oe,!1,void 0,d)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${L};${G};${C}`,inputDependencies:hr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:pe[0],y:pe[1],z:pe[2]},programUniforms:zt}),getShaderSource:br}}}),ua,Ss,kd=D(()=>{Qt(),mn(),Yt(),ir(),ua=(e,t,r,n,s,a=!1,i,d,c=!1)=>{let h=c?1:2,w=c?2:3,y=c?3:1,u=a?2:1,k=` fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${i}>`:i}) { result[flatIndex] = ${a?`vec4<${i}>`:i}(value); }`;n&&(k+=` fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${i}>`:i} { return bias[coords.${c?"w":"y"}${a?"/ 4":""}]; }`);let C=a?4:1,F=it("W",t[1].dataType,t[1].dims.length,C),U=it("Dy",t[0].dataType,t[0].dims.length,C),G=[U,F];n&&G.push(it("bias",t[2].dataType,[r[y]].length,C));let L=Ut("result",t[0].dataType,r.length,C),pe=`{ 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 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${U.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 = ${U.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 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${U.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 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${F.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${U.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")}; } }`,Z=` let outputIndices = ${L.offsetToIndices("global_idx")}; let batch = ${L.indicesGet("outputIndices",0)}; let d1 = ${L.indicesGet("outputIndices",y)}; let r = ${L.indicesGet("outputIndices",h)}; 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[${h}]) || 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?U.get("batch","idyR","idyC","inputChannel"):U.get("batch","inputChannel","idyR","idyC")}; let wValue = ${F.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)} ${k} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${a?pe:Z}}`},Ss=(e,t,r)=>{let n=e.length>2,s=t.outputShape,a=qe.size(s),i=[Math.ceil(a/64),1,1];Dr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let d=t.format==="NHWC",c=["rank","rank"],h=[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))],k=[u[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),u[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],C=!1,F=t.group,U=e[1].dims,G=U[0]/F,L=U[1],pe=[{type:12,data:a},{type:12,data:h},{type:12,data:w},{type:12,data:y},{type:12,data:u},{type:6,data:k},{type:12,data:G},{type:12,data:L},...kt(e[0].dims,e[1].dims)];n&&(pe.push(...kt(e[2].dims)),c.push("rank")),pe.push(...kt(s));let Z=i[1]===1&&i[2]===1,oe=et=>{let We=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:h.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:k.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],ct=vr(e[0].dataType);return`${ua(et,e,s,n,Z,C,ct,We,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:pe}),getShaderSource:oe}}}),Dl,Bl,da,ca,Ll,pa,Rl,Nl,ha,Wu,Pd=D(()=>{Uu(),kd(),Xn(),ds(),Dl=(e,t,r,n,s,a)=>(e-1)*t+r+(n-1)*s+1-a,Bl=(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)},da=(e,t,r,n,s,a,i,d,c,h)=>{let w=e.length-2,y=h.length===0;if(c.length===0)for(let C=0;C{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 h=e.strides.slice();if(h.reduce((y,u)=>y+u,0)===0){let y=t[0].dims.length-2;h=new Array(y).fill(1)}da(d,r,c,e.autoPad,e.group,s,h,n,i,a);let w=Object.assign({},e);return Object.assign(w,{kernelShape:r,pads:s,outputPadding:i,outputShape:a,dilations:c,strides:h}),w},Ll=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,h=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:h,...t,cacheKey:`${e.format};${t.activation};`}},pa=(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")},Rl=[2,3,1,0],Nl=(e,t,r)=>{let n=ca(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(Ss(t,n));return}let c=a[s?1:2],h=a[s?2:3],w=t[1].dims[2],y=t[1].dims[3],u=s?c*h:i,k=s?i:c*h,C=w*y*d,F=!0,U=e.kernelCustomData.wT??e.compute(Pn(t[1],Rl),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=U);let G=[t[0],U],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(zl(G,n,a,u,k,C,L,F),{inputs:G})},ha=(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=ca({...t,pads:d,strides:i,dilations:a,kernelShape:s},n);e.compute(Ss(n,c,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]]))},Wu=(e,t)=>{pa(e.inputs,t),e.inputs[0].dims.length===3?ha(e,t):Nl(e,e.inputs,t)}}),fa,ma,jl,Gu=D(()=>{Qt(),Yt(),fr(),ir(),fa=(e,t,r,n)=>{let s=qe.size(t),a=t.length,i=it("input",e,a),d=Ut("output",e,a),c=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=qe.normalizeAxis(c,a),w=y=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,k=Ft("uniforms.input_shape","uniforms.axis",a),C=n.reverse?u+(n.exclusive?" + 1":""):"0",F=n.reverse?k: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 = ${C}; let last : i32 = ${F}; 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:h},...kt(t,t)]}),getShaderSource:w}},ma=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,s=e.inputs[1];e.compute(fa(n,r,s,t),{inputs:[0]})},jl=e=>{let t=e.exclusive===1,r=e.reverse===1;return Gt({exclusive:t,reverse:r})}}),_a,Vl,Ul,ga,Wl,qu=D(()=>{Qt(),Yt(),fr(),ir(),_a=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.")},Vl=(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",h=t.blocksize,w=t.mode==="DCR";c?([r,n,s,a]=e.dims,i=w?[r,n,s,h,h,a/h**2]:[r,n,s,a/h**2,h,h],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,h,h,a/h**2,n,s]:[r,a/h**2,h,h,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,k=e.dataType,C=it("a",k,u),F=Ut("output",k,u),U=G=>` ${G.registerUniform("output_size","u32").declareVariables(C,F)} ${Vl(d,u,C,F)} ${G.mainStart()} ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${F.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${F.setByOffset("global_idx",C.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:G=>{let L=c?[r,n*h,s*h,a/h**2]:[r,a/h**2,n*h,s*h],pe=qe.size(L),Z=y.dims,oe=qe.sortBasedOnPerm(Z,d);return{outputs:[{dims:L,dataType:G[0].dataType}],dispatchGroup:{x:Math.ceil(pe/64)},programUniforms:[{type:12,data:pe},...kt(Z,oe)]}},getShaderSource:U}},ga=(e,t)=>{_a(e.inputs),e.compute(Ul(e.inputs[0],t))},Wl=e=>Gt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),ks,Ps,wa,Ir,Hu,Ku,Xu,ii,Gl,ql,Hl,Qu=D(()=>{Qt(),Yt(),fr(),ir(),ks="[a-zA-Z]|\\.\\.\\.",Ps="("+ks+")+",wa="^"+Ps+"$",Ir="("+Ps+",)*"+Ps,Hu="^"+Ir+"$",Ku=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)}},Xu=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(Hu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let d=e[i].dims.slice();if(!a.match(RegExp(wa)))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(Ps)))throw new Error("Invalid RHS");(s=n.match(RegExp(ks,"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(wa))&&!t&&e!=="")throw new Error("Invalid LHS term");let c=e.match(RegExp(ks,"g")),h=new Ku(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 k=0;ke+"_max",Gl=(e,t,r,n)=>{let s=e.map(h=>h.length).map((h,w)=>it(`input${w}`,t,h)),a=qe.size(n),i=Ut("output",t,n.length),d=[...r.symbolToInfo.keys()].filter(h=>!r.rhs.symbolToIndices.has(h)),c=h=>{let w=[],y="var prod = 1.0;",u="var sum = 0.0;",k="sum += prod;",C=[],F=[],U=[],G=[],L=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((Z,oe)=>{var et;if(r.rhs.symbolToIndices.has(oe)){let We=(et=r.rhs.symbolToIndices.get(oe))==null?void 0:et[0];We!==void 0&&r.lhs.forEach((ct,Ot)=>{if(Z.inputIndices.includes(Ot)){let zt=ct.symbolToIndices.get(oe);if(zt===void 0)throw new Error("Invalid symbol error");zt.forEach(hr=>{w.push(`${s[Ot].indicesSet(`input${Ot}Indices`,hr,i.indicesGet("outputIndices",We))}`)})}})}else r.lhs.forEach((We,ct)=>{if(Z.inputIndices.includes(ct)){let Ot=We.symbolToIndices.get(oe);if(Ot===void 0)throw new Error("Invalid symbol error");Ot.forEach(zt=>{C.push(`${s[ct].indicesSet(`input${ct}Indices`,zt,`${oe}`)}`)}),G.push(`prod *= ${s[ct].getByIndices(`input${ct}Indices`)};`)}}),F.push(`for(var ${oe}: u32 = 0; ${oe} < uniforms.${ii(oe)}; ${oe}++) {`),U.push("}")});let pe=L?[...w,`let sum = ${s.map((Z,oe)=>Z.getByIndices(`input${oe}Indices`)).join(" * ")};`]:[...w,u,...F,...C,y,...G,k,...U];return` ${h.registerUniforms(d.map(Z=>({name:`${ii(Z)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,i)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${i.offsetToIndices("global_idx")}; ${s.map((Z,oe)=>`var input${oe}Indices: ${s[oe].type.indices};`).join(` `)} ${pe.join(` `)}; ${i.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=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}});h.push({type:12,data:a});let w=e.map((y,u)=>[...kt(y)]).reduce((y,u)=>y.concat(u),h);return w.push(...kt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:w}},getShaderSource:c}},ql=(e,t)=>{let r=new Xu(e.inputs,t.equation),n=r.outputDims,s=e.inputs.map((a,i)=>a.dims);e.compute(Gl(s,e.inputs[0].dataType,r,n))},Hl=e=>{let t=e.equation.replace(/\s+/g,"");return Gt({equation:t})}}),ya,ai,Kl,Xl,ba,Ad=D(()=>{Qt(),Yt(),ir(),ya=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?ai(e,t):ai(t,e),Xl=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Kl(t,r),s=e[0].dataType,a=s===9?4:1,i=Math.ceil(qe.size(n)/a),d=h=>{let w=it("input",s,t.length,a),y=Ut("output",s,n.length,a),u;if(s===9){let k=(C,F,U="")=>` let outputIndices${F} = ${y.offsetToIndices(`outputOffset + ${F}u`)}; let offset${F} = ${w.broadcastedIndicesToOffset(`outputIndices${F}`,y)}; let index${F} = offset${F} / 4u; let component${F} = offset${F} % 4u; ${C}[${F}] = ${U}(${w.getByOffset(`index${F}`)}[component${F}]); `;u=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${k("data",0,"u32")} ${k("data",1,"u32")} ${k("data",2,"u32")} ${k("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` ${h.registerUniform("vec_size","u32").declareVariables(w,y)} ${h.mainStart()} ${h.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})}},ba=e=>{ya(e.inputs),e.compute(Xl(e.inputs),{inputs:[0]})}}),Yu,Ql,Zu=D(()=>{Qt(),Yt(),ir(),Gi(),Yu=e=>{let t=e[0].dataType,r=qe.size(e[0].dims),n=qe.size(e[1].dims),s=n%4===0,a=i=>{let d=it("x",t,[1],4),c=it("bias",t,[1],4),h=Ut("y",t,[1],4),w=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],y=k=>` let bias${k}_offset: u32 = (global_idx * 4 + ${k}) % uniforms.bias_size; let bias${k} = ${c.getByOffset(`bias${k}_offset / 4`)}[bias${k}_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,h)} ${Vi(xr(t))} ${i.mainStart(_n)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${d.getByOffset("global_idx")}; ${u} let x_in = x + bias; ${h.setByOffset("global_idx",Ui("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/_n/4)}})}},Ql=e=>{e.inputs.length<2||qe.size(e.inputs[1].dims)===0?Qo(e):e.compute(Yu(e.inputs))}}),Yl,Zl,Jl,eu,Ju=D(()=>{Qt(),Yt(),fr(),ir(),Yl=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Zl=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=qe.normalizeAxis(t.axis,s),i=r.slice(0);i.splice(a,1,...n);let d=r[a],c=e[0].dataType===9?4:1,h=Math.ceil(qe.size(i)/c),w=[{type:12,data:h},{type:6,data:d},{type:12,data:a},...kt(e[0].dims,e[1].dims,i)],y=u=>{let k=it("data",e[0].dataType,e[0].dims.length,c),C=it("inputIndices",e[1].dataType,e[1].dims.length),F=Ut("output",e[0].dataType,i.length,c),U=L=>{let pe=n.length,Z=`var indicesIndices${L} = ${C.type.indices}(0);`;for(let oe=0;oe1?`indicesIndices${L}[${oe}]`:`indicesIndices${L}`} = ${i.length>1?`outputIndices${L}[uniforms.axis + ${oe}]`:`outputIndices${L}`};`;Z+=` var idx${L} = ${C.getByIndices(`indicesIndices${L}`)}; if (idx${L} < 0) { idx${L} = idx${L} + uniforms.axisDimLimit; } var dataIndices${L} : ${k.type.indices}; `;for(let oe=0,et=0;oe1?`dataIndices${L}[${oe}]`:`dataIndices${L}`} = u32(idx${L});`,et+=pe):(Z+=`${s>1?`dataIndices${L}[${oe}]`:`dataIndices${L}`} = ${i.length>1?`outputIndices${L}[${et}]`:`outputIndices${L}`};`,et++);return Z},G;if(e[0].dataType===9){let L=(pe,Z,oe="")=>` let outputIndices${Z} = ${F.offsetToIndices(`outputOffset + ${Z}u`)}; ${U(Z)}; let offset${Z} = ${k.indicesToOffset(`dataIndices${Z}`)}; let index${Z} = offset${Z} / 4u; let component${Z} = offset${Z} % 4u; ${pe}[${Z}] = ${oe}(${k.getByOffset(`index${Z}`)}[component${Z}]); `;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")} ${F.setByOffset("global_idx","value")} `}else G=` let outputIndices = ${F.offsetToIndices("global_idx")}; ${U("")}; let value = ${k.getByIndices("dataIndices")}; ${F.setByOffset("global_idx","value")}; `;return` ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(k,C,F)} ${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(h/64)},programUniforms:w}),getShaderSource:y}},Jl=e=>Gt({axis:e.axis}),eu=(e,t)=>{let r=e.inputs;Yl(r),e.compute(Zl(e.inputs,t))}}),tu,ru,nu,su,ed=D(()=>{Qt(),Yt(),fr(),ir(),tu=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.`)},ru=(e,t)=>{let r=e[0].dims,n=e[0].dataType,s=r.length,a=e[1].dims,i=e[1].dataType,d=qe.normalizeAxis(t.axis,s),c=r[d],h=a.slice(0),w=qe.size(h),y=it("input",n,s),u=it("indicesInput",i,a.length),k=Ut("output",n,h.length),C=[{type:12,data:w},{type:6,data:c},{type:12,data:d}];return C.push(...kt(r,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:C}),getShaderSource:F=>` ${F.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(y,u,k)} ${F.mainStart()} ${F.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${k.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")}; ${k.setByOffset("global_idx","value")}; }`}},nu=e=>Gt({axis:e.axis}),su=(e,t)=>{let r=e.inputs;tu(r),e.compute(ru(e.inputs,t))}}),iu,au,ou,td,lu=D(()=>{Qt(),Yt(),ir(),iu=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")},au=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[s,a,i]=Mr.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=qe.size(d),h=[{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&&(h.push(...kt(e[2].dims)),w.push("rank")),h.push(...kt(d));let y=u=>{let k="";t.transA&&t.transB?k="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?k="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?k="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(k="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let C=t.alpha===1?"":"value *= uniforms.alpha;",F=it("a",e[0].dataType,e[0].dims),U=it("b",e[1].dataType,e[1].dims),G=F.type.value,L=null,pe=[F,U];e.length===3&&(L=it("c",e[2].dataType,e[2].dims.length),pe.push(L));let Z=Ut("output",e[0].dataType,d.length);pe.push(Z);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(...pe)} ${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++) { ${k} } ${C} ${L!=null?`let cOffset = ${L.broadcastedIndicesToOffset("vec2(m, n)",Z)}; 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:h}),getShaderSource:y}},ou=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}`}},td=(e,t)=>{iu(e.inputs),e.compute(au(e.inputs,t))}}),ln,uu,du,Ma,cu,As,pu,hu=D(()=>{Qt(),Yt(),fr(),O(),Xs(),ir(),ds(),ln=(e,t)=>e.length>t&&e[t].dims.length>0&&qe.size(e[t].dims)>0?e[t]:void 0,uu=(e,t)=>{let r=e[0],n=ln(e,1),s=ln(e,2),a=ln(e,3),i=ln(e,4),d=ln(e,5),c=ln(e,6),h=ln(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=!1,y=r.dims[0],u=r.dims[1],k=r.dims.length===3?w?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],C=u,F=0,U=0,G=Math.floor(k/t.numHeads);if(c&&h){if(c.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(c.dims[0]!==y||c.dims[1]!==t.numHeads||c.dims[3]!==G)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==y||h.dims[1]!==t.numHeads||h.dims[3]!==G)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');F=c.dims[2],U=c.dims[2]}else if(c||h)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(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');L=2,C=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==G)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,C=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==G)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');L=0,C=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}if(a){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let pe=0;if(i){pe=8;let ct=i.dims;throw ct.length===1?ct[0]===y?pe=1:ct[0]===3*y+2&&(pe=3):ct.length===2&&ct[0]===y&&ct[1]===C&&(pe=5),pe===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let Z=!1,oe=k;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(C!==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(C!==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],Z=!0}}let et=F+C,We=!1;if(i)throw new Error("Key padding mask is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(d.dims[0]!==y&&d.dims[0]!==1||d.dims[1]!==t.numHeads||d.dims[2]!==u||d.dims[3]!==et)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:y,sequenceLength:u,pastSequenceLength:F,kvSequenceLength:C,totalSequenceLength:et,maxSequenceLength:U,inputHiddenSize:0,hiddenSize:k,vHiddenSize:oe,headSize:G,vHeadSize:Math.floor(oe/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:pe,scale:t.scale,broadcastResPosBias:We,passPastInKv:Z,qkvFormat:L}},du=e=>Gt({...e}),Ma=Gt({perm:[0,2,1,3]}),cu=(e,t,r,n,s,a,i)=>{let d=[n,s,a],c=qe.size(d),h=[{type:12,data:c},{type:12,data:i},{type:12,data:a}],w=y=>{let u=Ut("qkv_with_bias",t.dataType,d),k=it("qkv",t.dataType,d),C=it("bias",r.dataType,d),F=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${y.registerUniforms(F).declareVariables(k,C,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:h}),getShaderSource:w},{inputs:[t,r],outputs:[-1]})[0]},As=(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=cu(e,a,i,t,n,r*s,d),c=c.reshape([t,n,r,s]),e.compute(Pn(c,Ma.perm),{inputs:[c],outputs:[-1]})[0]}else return a.dims.length===3&&(c=a.reshape([t,n,r,s])),e.compute(Pn(c,Ma.perm),{inputs:[c],outputs:[-1]})[0]},pu=(e,t)=>{let r=uu(e.inputs,t),n=e.inputs[0],s=ln(e.inputs,1),a=ln(e.inputs,2),i=ln(e.inputs,3),d=ln(e.inputs,4),c=ln(e.inputs,5),h=ln(e.inputs,6),w=ln(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=As(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(y)return cs(e,u,s,a,d,void 0,h,w,c,r,t);if(!s||!a)throw new Error("key and value must be provided");let k=As(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,s,i,r.hiddenSize),C=As(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,i,2*r.hiddenSize);cs(e,u,k,C,d,void 0,h,w,c,r,t)}}),va,fu,mu,xa,_u,gu=D(()=>{Qt(),Yt(),ir(),va=e=>Array.from(e.getBigInt64Array(),Number),fu=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(va(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")},mu=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??va(e[1]),s=mu(r,n),a=qe.size(s),i=e[0].dataType,d=it("input",i,r.length),c=Ut("output",i,s.length),h=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:h}},_u=e=>{fu(e.inputs),e.compute(xa(e.inputs),{inputs:[0]})}}),wu,Ta,yu,bu,Ca,Mu,rd=D(()=>{Qt(),Yt(),fr(),Xs(),ir(),hu(),gu(),ds(),wu=(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],h=r.dims[1],w=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],y=h,u=0,k=0,C=Math.floor(w/t.numHeads),F=a&&a.dims.length!==0,U=i&&i.dims.length!==0,G=!0;if(F&&U){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],k=a.dims[1]}else if(F||U)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]!==C)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');L=5,y=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==C)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');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 pe=0,Z=!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],Z=!0}}let et=u+y;return{batchSize:c,sequenceLength:h,pastSequenceLength:u,kvSequenceLength:y,totalSequenceLength:et,maxSequenceLength:k,inputHiddenSize:0,hiddenSize:w,vHiddenSize:oe,headSize:C,vHeadSize:Math.floor(oe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:pe,scale:t.scale,broadcastResPosBias:!1,passPastInKv:Z,qkvFormat:L,isPastkvBSNH:G}},Ta=(e,t,r,n)=>{let s=[n.batchSize,n.totalSequenceLength,n.kvNumHeads,n.headSize],a=4,i=qe.size(s)/a,d=n.totalSequenceLength,c=Ut("present_kv",r,s.length,a),h=it("new_kv",e.dataType,e.dims.length,a),w=t?it("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},k=t?["rank","rank"]:["rank"],C=[{type:12,data:i},{type:12,data:n.pastSequenceLength},{type:12,data:n.kvSequenceLength},{type:12,data:n.totalSequenceLength}],F=[h];w?(C.push(...kt(e.dims),...kt(t.dims),...kt(s)),F.push(w)):C.push(...kt(e.dims),...kt(s));let U=[{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];`,pe=t?`if (s < past_seqlen) { ${G} } else if (s < past_seqlen + uniforms.new_seqlen) { ${L} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${L} }`,Z=oe=>` ${oe.registerUniforms(U).declareVariables(...F,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; ${pe} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${n.kvNumHeads}${y}${!!t}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:u,programUniforms:C}),getShaderSource:Z}},yu=e=>Gt({...e}),bu=Gt({perm:[0,2,1,3]}),Ca=(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(Ta(a,r,a.dataType,n),{inputs:[a,r],outputs:[n.isPastkvBSNH?s:-1]})[0]:a=e.compute(Ta(a,void 0,a.dataType,n),{inputs:[a],outputs:[n.isPastkvBSNH?s:-1]})[0],d!==1&&(a=e.compute(xa([a],[1,1,1,d]),{inputs:[a],outputs:[-1]})[0],a=a.reshape([n.batchSize,n.totalSequenceLength,i*d,n.headSize])),e.compute(Pn(a,bu.perm),{inputs:[a],outputs:[-1]})[0]},Mu=(e,t)=>{var c;let r=wu(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=As(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=Ca(e,e.inputs[1],s,r,1),d=Ca(e,e.inputs[2],a,r,2);cs(e,n,i,d,void 0,void 0,void 0,void 0,void 0,r,t)}}),vu,xu,Tu,Cu,Id=D(()=>{Qt(),Yt(),ir(),vu=(e,t)=>{let r=e[0].dims,n=r,s=2,a=qe.sizeToDimension(r,s),i=qe.sizeFromDimension(r,s),d=gr(i),c=i/d,h=[r[0],r[1],c],w=["rank","type","type"],y=[{type:12,data:i},{type:12,data:c}];y.push(...kt(h,h));let u=k=>{let C=it("x",e[0].dataType,h.length,d),F=it("scale",e[1].dataType,e[1].dims),U=it("bias",e[2].dataType,e[2].dims),G=Ut("output",e[0].dataType,h.length,d),L=[C,F,U,G],pe=C.type.value,Z=d===1?"f32":`vec${d}`,oe=64,et=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${Z}, ${oe}>; const workgroupSize = ${oe}u; ${k.registerUniforms(et).declareVariables(...L)} ${k.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 = ${Z}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${Z}(${C.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 = ${gn("workgroupShared[0]",d)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${Z}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${Z}(${C.get("batch","channel","h")}) - ${Z}(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 = ${gn("workgroupShared[0]",d)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); let channelScale = invStdDev * f32(${F.getByOffset("channel")}); let channelShift = f32(${U.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${C.get("batch","channel","h")} * ${pe}(${Z}(channelScale)) + ${pe}(${Z}(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}},xu=(e,t,r,n,s,a,i,d)=>{let c=gr(i),h=64,w=c===1?"vec2f":`mat2x${c}f`,y=c===1?"f32":`vec${c}f`,u=(et,We)=>`${w}(${et}, ${We})`,k=s*i/c,C=Math.ceil(a/h),F=["type"],U=[{type:12,data:C},{type:12,data:a},{type:12,data:Math.floor(i/c)},{type:12,data:Math.floor(a*i/c)}],G=et=>{let We=it("input",t.dataType,t.dims,c);return` ${et.declareVariables(We)} @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; ${et.mainStart(h)} let currentImageNumber = global_idx / ${h} / uniforms.C; let currentChannelNumber = (global_idx / ${h}) % 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 = ${Ar("f32",c)}; var squaredSum = ${Ar("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:F},getRunData:()=>({outputs:[{dims:[s,i,h,2],dataType:1}],dispatchGroup:{x:s*i/c},programUniforms:U}),getShaderSource:G},{inputs:[t],outputs:[-1]})[0],pe=[{type:12,data:k},{type:12,data:a},{type:12,data:Math.floor(i/c)},{type:12,data:Math.floor(h*i/c)}],Z=["type","type","type"],oe=et=>{let We=it("scale",r.dataType,r.dims,c),ct=it("bias",n.dataType,n.dims,c);return` @group(0) @binding(0) var input : array<${w}>; @group(0) @binding(1) var scale : array<${We.type.storage}>; @group(0) @binding(2) var bias : array<${ct.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; ${et.mainStart()} ${et.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 = ${Ar("f32",c)}; var squaredSum = ${Ar("f32",c)}; for (var i: u32 = 0; i < min(${h}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${h}]; 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:Z},getRunData:()=>({outputs:[{dims:[s,i,2],dataType:1}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:pe}),getShaderSource:oe},{inputs:[L,r,n],outputs:[-1]})[0]},Tu=(e,t,r)=>{let n=t[0].dims,s=n,a=n[0],i=n[n.length-1],d=qe.sizeFromDimension(n,1)/i,c=gr(i),h=qe.size(s)/c,w=[{type:12,data:d},{type:12,data:Math.floor(i/c)}],y=["type","type"],u=xu(e,t[0],t[1],t[2],a,d,i,r.epsilon),k=C=>{let F=vr(t[0].dataType),U=c===1?"vec2f":`mat2x${c}f`,G=c===1?F:`vec${c}<${F}>`,L=it("input",t[0].dataType,t[0].dims,c),pe=Ut("output",t[0].dataType,s,c);return` @group(0) @binding(0) var input : array<${L.type.storage}>; @group(0) @binding(1) var scaleInput : array<${U}>; @group(0) @binding(2) var output : array<${pe.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${C.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(h/64)},programUniforms:w}),getShaderSource:k},{inputs:[t[0],u]})},Cu=(e,t)=>{t.format==="NHWC"?Tu(e,e.inputs,t):e.compute(vu(e.inputs,t))}}),or,$u,Qr,tn=D(()=>{Qt(),Yt(),ir(),or=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},$u=(e,t,r)=>{let n=t.simplified,s=e[0].dims,a=e[1],i=!n&&e[2],d=s,c=qe.normalizeAxis(t.axis,s.length),h=qe.sizeToDimension(s,c),w=qe.sizeFromDimension(s,c),y=qe.size(a.dims),u=i?qe.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 k=[];for(let oe=0;oe1,L=r>2,pe=oe=>{let et=vr(e[0].dataType),We=[it("x",e[0].dataType,e[0].dims,C),it("scale",a.dataType,a.dims,C)];i&&We.push(it("bias",i.dataType,i.dims,C)),We.push(Ut("output",e[0].dataType,d,C)),G&&We.push(Ut("mean_data_output",1,k)),L&&We.push(Ut("inv_std_output",1,k));let ct=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${oe.registerUniforms(ct).declareVariables(...We)} ${oe.mainStart()} ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Ar("f32",C)}; var mean_square_vector = ${Ar("f32",C)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${jr(et,C,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${gn("mean_vector",C)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${gn("mean_square_vector",C)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${jr(et,C,"x[j + offset]")}; let f32scale = ${jr(et,C,"scale[j]")}; output[j + offset] = ${We[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${i?`+ ${jr(et,C,"bias[j]")}`:""} ); } ${G?"mean_data_output[global_idx] = mean":""}; ${L?"inv_std_output[global_idx] = inv_std_dev":""}; }`},Z=[{dims:d,dataType:e[0].dataType}];return G&&Z.push({dims:k,dataType:1}),L&&Z.push({dims:k,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${C};${r};${n}`,inputDependencies:F},getRunData:()=>({outputs:Z,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:U}),getShaderSource:pe}},Qr=(e,t)=>{or(e.inputs),e.compute($u(e.inputs,t,e.outputCount))}}),rn,Zn,nd,Eu,sd=D(()=>{Qt(),Yt(),fr(),ir(),rn=(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(!qe.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(qe.size(d)!==t.n*s)throw new Error("scales input size error.");if(e.length===4){let c=e[3].dims,h=t.bits>4?t.n*s:t.n*Math.floor((s+1)/2);if(qe.size(c)!==h)throw new Error("zeroPoints input size error.")}},Zn=(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,h=t.n,w=s.slice(0,a-2),y=qe.size(w),u=t.blockSize/8*t.bits/4,k=e[0].dataType,C=gr(d),F=gr(t.k),U=gr(u),G=zn(k),L=d*i*G,pe=Math.floor(n/L),Z=i<=r[0]&&pe>0,oe=!Z||pe>=4?gr(h):pe>=2&&gr(h)>=2?2:1,et=w.concat([d,h]),We=qe.size(et)/oe/C,ct=Z?[]:[{type:12,data:We},{type:12,data:t.blockSize}],Ot=[y,d,c/F],zt=qe.convertShape(e[1].dims).slice();zt.splice(-1,1,u/U),ct.push(...kt(Ot)),ct.push(...kt(zt)),ct.push(...kt(e[2].dims)),e.length===4&&ct.push(...kt(qe.convertShape(e[3].dims)));let hr=[y,d,h/oe];ct.push(...kt(hr));let br=rr=>{let Sr=Ot.length,Wr=it("a",e[0].dataType,Sr,F),cr=it("b",12,zt.length,U),Rr=it("scales",e[2].dataType,e[2].dims.length),Bt=[Wr,cr,Rr],Zt=e.length===4?it("zero_points",12,e[3].dims.length):void 0;Zt&&Bt.push(Zt);let _r=hr.length,Le=Ut("output",e[0].dataType,_r,oe),Nt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],tr=vr(e[0].dataType),Br=(()=>{switch(F){case 1:return`array<${tr}, 8>`;case 2:return`mat4x2<${tr}>`;case 4:return`mat2x4<${tr}>`;default:throw new Error(`${F}-component is not supported.`)}})(),Xr=` for (var word: u32 = 0; word < ${u}; word += ${U}) { ${cr.indicesSet("b_indices","2","word")}; let b_data = ${cr.getByIndices("b_indices")}; for (var i: u32 = 0; i < ${U}; i++) { let b_value: u32 = ${U===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 = ${Br}(${Array.from({length:4},(zs,En)=>`${tr}(b_value_lower[${En}]), ${tr}(b_value_upper[${En}])`).join(", ")}); let b_dequantized_values = ${F===1?`${Br}(${Array.from({length:8},(zs,En)=>`(b_quantized_values[${En}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${Br}(${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 < ${Z?d:C}u; m++) { ${Wr.indicesSet("a_indices",Sr-2,Z?"m":`row * ${C} + m`)}; ${Wr.indicesSet("a_indices",Sr-1,"word_offset")}; var input_offset = ${Wr.indicesToOffset("a_indices")}; var a_data: ${Br}; for (var j: u32 = 0; j < ${8/F}; j++) { a_data[j] = ${Wr.getByOffset("input_offset")}; input_offset++; } ${Z?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${oe>1?"[c]":""} += ${Array.from({length:8/F},(zs,En)=>`${F===1?`a_data[${En}] * b_dequantized_values[${En}]`:`dot(a_data[${En}], b_dequantized_values[${En}])`}`).join(" + ")}; } word_offset += ${8/F}; } }`,an=Zt?` zero_point_offset += 4; if (zero_point_offset == 32) { zero_point_offset = 0; zero_point_index++; zero_point_word = ${Zt.getByOffset("zero_point_index")}; }`:"";return Z?` var workgroup_shared: array<${Le.type.value}, ${d*i}>; ${rr.declareVariables(...Bt,Le)} ${rr.mainStart([i,1,1])} var a_indices: ${Wr.type.indices}; var block = local_id.x; var col = workgroup_id.y; var batch = workgroup_id.z; ${Wr.indicesSet("a_indices","0","batch")}; // Two zero points are packed into one byte when uniforms.bits is 4. for (var c: u32 = 0; c < ${oe}; c++) { let col_times_components_plus_c = col * ${oe} + c; ${Zt?` 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 = ${Zt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} var b_indices: ${cr.type.indices}; ${cr.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 = ${Rr.getByOffset("scales_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${tr}(${Zt?"(zero_point_word) & 0xFu":8}); ${cr.indicesSet("b_indices","1","block")}; var word_offset: u32 = block * ${t.blockSize/F}; var workgroup_shared_offset: u32 = block * ${d}; ${Xr} } workgroupBarrier(); var output_indices: ${Le.type.indices}; var elements_per_thread: u32 = ${Math.ceil(d/i)}; ${Le.indicesSet("output_indices","0","batch")}; ${Le.indicesSet("output_indices",_r-1,"col")}; ${Le.indicesSet("output_indices",_r-2,"local_id.x * elements_per_thread")}; var output_offset = ${Le.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: ${Le.type.value} = ${Le.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}; } ${Le.setByOffset("output_offset","output_value")}; output_offset += ${h/oe}; } } }`:` ${rr.registerUniforms(Nt).declareVariables(...Bt,Le)} ${rr.mainStart()} ${rr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var output_values: array<${Le.type.value}, ${C}>; var output_indices = ${Le.offsetToIndices("global_idx")}; var col = ${Le.indicesGet("output_indices",_r-1)}; var row = ${Le.indicesGet("output_indices",_r-2)}; var a_indices: ${Wr.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 ${Zt?` var zero_point_abs_offset = col * ${oe} * ((${i} + 1) / 2); var zero_point_index: u32 = zero_point_abs_offset / 4; var zero_point_word: u32 = ${Zt.getByOffset("zero_point_index")}; var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} var scale_index = col * ${i*oe}; var b_indices: ${cr.type.indices}; for (var c: u32 = 0; c < ${oe}; c++) { ${cr.indicesSet("b_indices","0",`col * ${oe} + 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 = ${Rr.getByOffset("scale_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${tr}(${Zt?"extractBits(zero_point_word, zero_point_offset, 4)":8}); ${cr.indicesSet("b_indices","1","block")}; var word_offset: u32 = block_offset; ${Xr} scale_index++; ${an} block_offset += uniforms.block_size / ${F}; } // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. ${Zt?`if (zero_point_offset % 8 > 0) { ${an} }`:""} } for (var k: u32 = 0u; k < ${C}u; k++) { ${Le.indicesSet("output_indices",_r-2,`${C} * row + k`)}; ${Le.setByIndices("output_indices","output_values[k]")} } }`};return{name:Z?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${d};${k};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:et,dataType:k}],name:Z?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:Z?{x:1,y:Math.ceil(h/oe),z:y}:{x:Math.ceil(We/64)},programUniforms:ct}),getShaderSource:br}},nd=(e,t)=>{rn(e.inputs,t);let r=e.getMaxComputeWorkgroupSizes(),n=e.getMaxComputeWorkgroupStoragesize();e.compute(Zn(e.inputs,t,r,n))},Eu=e=>Gt(e)}),m,g,E,K,Pe,De,at,$t,Vt,lr=D(()=>{Qt(),Yt(),ir(),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)}) - ${Ft("uniforms.pads",s,r)}; if (k < 0) { break; } if (k >= i32(${Ft("uniforms.x_shape",s,t)})) { break; } offset += k * i32(${Ft("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]; } `},E=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Ft("uniforms.pads",s,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Ft("uniforms.x_shape",s,t)}) - 1); k = k % _2n_1; if(k >= i32(${Ft("uniforms.x_shape",s,t)})) { k = _2n_1 - k; } } offset += k * i32(${Ft("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},K=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Ft("uniforms.pads",s,r)}; if (k < 0) { k = 0; } if (k >= i32(${Ft("uniforms.x_shape",s,t)})) { k = i32(${Ft("uniforms.x_shape",s,t)}) - 1; } offset += k * i32(${Ft("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)}) - ${Ft("uniforms.pads",s,r)}; if (k < 0) { k += i32(${Ft("uniforms.x_shape",s,t)}]); } if (k >= i32(${Ft("uniforms.x_shape",s,t)})) { k -= i32(${Ft("uniforms.x_shape",s,t)}); } offset += k * i32(${Ft("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 E(e,t,r.pads.length);case 2:return K(e,t,r.pads.length);case 3:return Pe(e,t,r.pads.length);default:throw new Error("Invalid mode")}},at=(e,t)=>{let r=qe.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,s=qe.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 h=Ut("output",e[0].dataType,r.length),w=it("x",e[0].dataType,n.length),y=w.type.value,u=De(h,n.length,t),k=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&k.push({name:"constant_value",type:y}),` ${c.registerUniforms(k).declareVariables(w,h)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${h.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(qe.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},Vt=(e,t)=>{m(e.inputs);let r=$t(e.inputs,t);e.compute(at(e.inputs,r),{inputs:[0]})}}),ar,Er,ur,mr,dr,pr,yr,Or,un,pn,Rn,nn,Kr,sn,oi,li,$a,Fd,An,Is=D(()=>{$(),Qt(),Yt(),ir(),ar=e=>{if(A.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Er=(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():[],h=t.pads.slice();yn.adjustPoolAttributes(r,s,i,d,c,h);let w=yn.computePoolOutputShape(r,s,d,c,i,h,t.autoPad),y=Object.assign({},t);a?Object.assign(y,{kernelShape:i,strides:d,pads:h,dilations:c,cacheKey:t.cacheKey}):Object.assign(y,{kernelShape:i,strides:d,pads:h,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=qe.size(e),s=qe.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],h=t.pads[t.pads.length/2-1],w=t.pads[t.pads.length-1],y=!!(h+w);a.push({type:12,data:d},{type:12,data:c},{type:12,data:h},{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 k=t.kernelShape[t.kernelShape.length-2],C=t.strides[t.strides.length-2],F=t.pads[t.pads.length/2-2],U=t.pads[t.pads.length-2];u=!!(F+U),a.push({type:12,data:k},{type:12,data:C},{type:12,data:F},{type:12,data:U}),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=qe.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((h,w)=>h+w);return[a,i,!!c,!1,!1]}},mr=(e,t,r,n,s,a,i,d,c,h,w,y)=>{let u=s.format==="NHWC",k=t.type.value,C=Ut("output",t.type.tensor,n);if(s.kernelShape.length<=2){let F="",U="",G="",L=r-(u?2:1);if(w?F=` 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} }`:F=` 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 pe=r-(u?3:2);y?U=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${pe}] = indices[${pe}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${pe}] < 0 || xIndices[${pe}] >= uniforms.x_shape[${pe}]) { pad += i32(uniforms.kw); continue; } `:U=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${pe}] = indices[${pe}] * uniforms.sh - uniforms.phStart + j; `,G=` } `}return` ${e.registerUniforms(c).declareVariables(t,C)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${C.offsetToIndices("global_idx")}; var xIndices = ${C.offsetToIndices("global_idx")}; var value = ${k}(${d}); var pad = 0; ${U} ${F} ${G} ${i} output[global_idx] = value; }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let F=s.kernelShape.length,U=s.pads.length,G="";return h?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,C)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${C.offsetToIndices("global_idx")}; var xIndices = ${C.offsetToIndices("global_idx")}; var offsets: array; var value = ${k}(${d}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${F-1}u; j++) { offsets[j] = offset / ${Ft("uniforms.kernelStrides","j",F)}; offset -= offsets[j] * ${Ft("uniforms.kernelStrides","j",F)}; } offsets[${F-1}] = offset; isPad = false; for (var j = ${r-F}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${Ft("uniforms.strides",`j - ${r-F}u`,F)} + offsets[j - ${r-F}u] - ${Ft("uniforms.pads","j - 2u",U)}; ${G} } ${i} output[global_idx] = value; }`}},dr=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,pr=e=>`${dr(e)};${e.countIncludePad}`,yr=e=>`${dr(e)};${e.storageOrder};${e.dilations}`,Or=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}),un=(e,t,r,n)=>{let[s,a]=Er(t,n,r),i=it("x",t.dataType,t.dims.length),d=i.type.value,c="value += x_val;",h="";s.countIncludePad?h+=`value /= ${d}(uniforms.kernelSize);`:h+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[w,y,u,k,C]=ur(a,s);w.push(...kt(t.dims,a));let F=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${u};${k};${C}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(qe.size(a)/64)},programUniforms:w}),getShaderSource:U=>mr(U,i,t.dims.length,a.length,s,c,h,0,y,u,k,C)}},pn=e=>{let t=e.count_include_pad!==0,r=Or(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:pr(n)}},Rn=(e,t)=>{ar(e.inputs),e.compute(un("AveragePool",e.inputs[0],!1,t))},nn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Kr=e=>{let t=e.format;return{format:t,...nn,cacheKey:t}},sn=(e,t)=>{ar(e.inputs),e.compute(un("GlobalAveragePool",e.inputs[0],!0,t))},oi=(e,t,r,n)=>{let[s,a]=Er(t,n,r),i=` value = max(x_val, value); `,d="",c=it("x",t.dataType,t.dims.length),h=["rank"],[w,y,u,k,C]=ur(a,s);return w.push(...kt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${u};${k};${C}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(qe.size(a)/64)},programUniforms:w}),getShaderSource:F=>mr(F,c,t.dims.length,a.length,s,i,d,t.dataType===10?-65504:-1e5,y,u,k,C)}},li=(e,t)=>{ar(e.inputs),e.compute(oi("MaxPool",e.inputs[0],!1,t))},$a=e=>{let t=e.storage_order,r=e.dilations,n=Or(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:yr(s)}},Fd=e=>{let t=e.format;return{format:t,...nn,cacheKey:t}},An=(e,t)=>{ar(e.inputs),e.compute(oi("GlobalMaxPool",e.inputs[0],!0,t))}}),id,ad,od,ld=D(()=>{$(),Qt(),ir(),id=(e,t,r)=>{let n=e===t,s=et&&r>0;if(n||s||a)throw new Error("Range these inputs' contents are invalid.")},ad=(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=h=>{let w=Ut("output",n,a.length),y=w.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:y},{name:"delta",type:y}];return` ${h.registerUniforms(u).declareVariables(w)} ${h.mainStart()} ${h.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})}},od=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&&id(t,r,n),e.compute(ad(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),mc,_c,gc,wc,yc,bc,Mc,vc,xc,Tc,Cc,Od,$c,Ec,Sc,kc,Pc,Ac,Ic,of=D(()=>{Qt(),Yt(),fr(),ir(),mc=(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")}},_c=(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},gc=(e,t,r,n,s,a)=>{let[i,d,c]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=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!==h&&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");mc(n,t),t.axes.length>0&&_c(n,t.axes,h).forEach((w,y)=>n[y]=w)}if(c>0&&e.length>c&&(e[c].getBigInt64Array().forEach(w=>s.push(Number(w))),s.length!==h||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>h)throw new Error("Resize requires only of scales or sizes to be specified")},wc=(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`)}})()+"}",yc=(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`)}})()+"}",bc=(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},Mc=(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},vc=(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},xc=(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 = ${Ft("uniforms.scales","i",n)}; var roi_low = ${Ft("uniforms.roi","i",s)}; var roi_hi = ${Ft("uniforms.roi",`i + ${t.length}`,s)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Ft("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Ft("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; }`,Tc=(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 = ${Ft("uniforms.scales","i",s)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Ft("uniforms.roi","i",a)}; var roi_hi = ${Ft("uniforms.roi",`i + ${r.length}`,a)}; var input_shape_i = ${Ft("uniforms.input_shape","i",r.length)}; var output_shape_i = ${Ft("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; }`,Cc=(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 >= ${Ft("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,Od=(e,t,r,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",$c=(e,t,r,n,s)=>{let[a,i,d,c]=r.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { 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))`)}; ${Od(e,c,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${h} = originalIndices[${i}]; var col:${h} = 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: ${h} = getInputValue(batch, channel, row1, col1); var x12: ${h} = getInputValue(batch, channel, row1, col2); var x21: ${h} = getInputValue(batch, channel, row2, col1); var x22: ${h} = getInputValue(batch, channel, row2, col2); var dx1: ${h} = abs(row - ${h}(row1)); var dx2: ${h} = abs(${h}(row2) - row); var dy1: ${h} = abs(col - ${h}(col1)); var dy2: ${h} = abs(${h}(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); }`},Ec=(e,t,r,n,s,a,i,d,c,h)=>{let w=r.length===2,[y,u]=w?[0,1]:[2,3],k=e.type.value,C=F=>{let U=F===y?"row":"col";return` fn ${U}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${k} { var output_index = ${t.indicesGet("output_indices",F)}; var originalIdx: ${k} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[F]}, ${n[F]}, ${r[F]}, ${a[F]}, ${a[F]} + ${r.length}); var fractOriginalIdx: ${k} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${d} && (originalIdx < 0 || originalIdx > (${r[F]} - 1))) { return ${c}; } var data: array<${k}, 4> = array<${k}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${U}: ${k} = originalIdx + ${k}(i); if (${U} < 0 || ${U} >= ${r[F]}) { ${h?`coefs[i + 1] = 0.0; continue;`:d?`return ${c};`:`${U} = max(0, min(${U}, ${r[F]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",F,`u32(${U})`)}; data[i + 1] = ${F===y?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${C(y)}; ${C(u)}; fn getCubicInterpolationCoefs(s: ${k}) -> array<${k}, 4> { var absS = abs(s); var coeffs: array<${k}, 4> = array<${k}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${k} = 1.0 - absS; var twoMinusAbsS: ${k} = 2.0 - absS; var onePlusAbsS: ${k} = 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<${k}, 4>, coefs: array<${k}, 4>) -> ${k} { var coefsSum: ${k} = 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}) -> ${k} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},Sc=(e,t,r,n,s)=>{let[a,i,d,c,h]=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))`)}; ${Od(e,h,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[${h}])`:"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); }`},kc=(e,t,r,n,s,a)=>{let i=e.dims,d=bc(a,t.axes,i.length),c=Mc(i,n,s,t.axes),h=n.slice();n.length===0&&(h=i.map((L,pe)=>L===0?1:c[pe]/L),t.keepAspectRatioPolicy!=="stretch"&&(c=vc(i,h,t)));let w=Ut("output",e.dataType,c.length),y=it("input",e.dataType,i.length),u=qe.size(c),k=i.length===c.length&&i.every((L,pe)=>L===c[pe]),C=t.coordinateTransformMode==="tf_crop_and_resize",F=t.extrapolationValue,U=y.type.value,G=L=>` ${k?"":` ${wc(t.coordinateTransformMode,U)}; ${(()=>{switch(t.mode){case"nearest":return` ${Cc(y,i)}; ${yc(t.nearestMode,r,U)}; ${Tc(y,w,i,c,h.length,d.length,C)}; `;case"linear":return` ${xc(w,i,c,h.length,d.length)}; ${(()=>{if(i.length===2||i.length===4)return`${$c(y,w,i,C,F)}`;if(i.length===3||i.length===5)return`${Sc(y,w,i,C,F)}`;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`${Ec(y,w,i,c,h,d,t.cubicCoeffA,C,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${L.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",d.length).declareVariables(y,w)} ${L.mainStart()} ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${k?"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}|${h.length>0?h:""}|${s.length>0?s:""}|${d.length>0?d:""}|${k}|${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:h},{type:1,data:d},...kt(i,c)]})}},Pc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Ac=(e,t)=>{let r=[],n=[],s=[],a=Pc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");gc(e.inputs,t,a,r,n,s),e.compute(kc(e.inputs[0],t,a,r,n,s),{inputs:[0]})},Ic=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,h=e.nearestMode===""?"simple":e.nearestMode;return Gt({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:s,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:d,mode:c,nearestMode:h})}}),Fc,Oc,zc,lf=D(()=>{Qt(),Yt(),fr(),ir(),Fc=(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(!qe.areEqual(n.dims,[])&&!qe.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(!qe.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],h=r.dims[r.dims.length-2],w=s.dims[0],y=qe.sizeFromDimension(r.dims,1)/h,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(h!==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(h>w)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Oc=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:s,scale:a}=t,i=e[0].dims[0],d=qe.sizeFromDimension(e[0].dims,1),c=e[0].dims[e[0].dims.length-2],h=d/c,w=e[2].dims[1],y=s===0?w*2:h/n,u=new Array(i,c,h/y,y-w),k=qe.computeStrides(u),C=[{type:1,data:a},{type:12,data:u},{type:12,data:k},...e[0].dims.length===3?new Array({type:12,data:[d,h,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)],F=U=>{let G=it("input",e[0].dataType,e[0].dims.length),L=it("position_ids",e[1].dataType,e[1].dims.length),pe=it("cos_cache",e[2].dataType,e[2].dims.length),Z=it("sin_cache",e[3].dataType,e[3].dims.length),oe=Ut("output",e[0].dataType,e[0].dims.length);return U.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:k.length},{name:"input_output_strides",type:"u32",length:k.length}]),` ${U.declareVariables(G,L,pe,Z,oe)} ${U.mainStart(_n)} let half_rotary_emb_dim = uniforms.${pe.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${U.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${L.broadcastedIndicesToOffset("bsnh.xy",Ut("",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")} * ${pe.get("position_id","bsnh[3]")} - ${G.getByOffset("j")} * ${Z.get("position_id","bsnh[3]")}; ${oe.setByOffset("i","re")} let im = ${G.getByOffset("i")} * ${Z.get("position_id","bsnh[3]")} + ${G.getByOffset("j")} * ${pe.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:Gt({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:F,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(qe.size(u)/_n)},programUniforms:C})}},zc=(e,t)=>{Fc(e.inputs,t),e.compute(Oc(e.inputs,t))}}),Dc,Bc,Lc,uf=D(()=>{Qt(),Yt(),ir(),Dc=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")}},Bc=(e,t,r,n)=>{let s=t.simplified,a=e[0].dims,i=qe.size(a),d=a,c=i,h=a.slice(-1)[0],w=n?a.slice(0,-1).concat(1):[],y=!s&&e.length>3,u=e.length>4,k=n&&r>1,C=n&&r>2,F=r>3,U=64,G=gr(h),L=[{type:12,data:c},{type:12,data:G},{type:12,data:h},{type:1,data:t.epsilon}],pe=oe=>{let et=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],We=[it("x",e[0].dataType,e[0].dims,G),it("skip",e[1].dataType,e[1].dims,G),it("gamma",e[2].dataType,e[2].dims,G)];y&&We.push(it("beta",e[3].dataType,e[3].dims,G)),u&&We.push(it("bias",e[4].dataType,e[4].dims,G)),We.push(Ut("output",e[0].dataType,d,G)),k&&We.push(Ut("mean_output",1,w)),C&&We.push(Ut("inv_std_output",1,w)),F&&We.push(Ut("input_skip_bias_sum",e[0].dataType,d,G));let ct=vr(e[0].dataType),Ot=vr(1,G);return` ${oe.registerUniforms(et).declareVariables(...We)} var sum_shared : array<${Ot}, ${U}>; var sum_squared_shared : array<${Ot}, ${U}>; ${oe.mainStart([U,1,1])} let ix = local_id.x; let iy = global_id.x / ${U}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${U}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${U-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]":ct+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${F?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${jr(ct,G,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${U}; 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 = ${gn("sum",G)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${gn("square_sum",G)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); ${k?"mean_output[global_idx] = mean;":""} ${C?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${s?"":`- ${ct}(mean)`}) * ${ct}(inv_std_dev) * gamma[offset1d + i] ${y?"+ beta[offset1d + i]":""}; } }`},Z=[{dims:d,dataType:e[0].dataType}];return r>1&&Z.push({dims:w,dataType:1}),r>2&&Z.push({dims:w,dataType:1}),r>3&&Z.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${G};${k};${C};${F}`,inputDependencies:e.map((oe,et)=>"type")},getShaderSource:pe,getRunData:()=>({outputs:Z,dispatchGroup:{x:Math.ceil(c/h)},programUniforms:L})}},Lc=(e,t)=>{Dc(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(Bc(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Rc,Su,Nc,zd,jc,Vc,Uc,Wc,df=D(()=>{Qt(),Yt(),fr(),ir(),Rc=(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`)})},Su=(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},Nc=(e,t)=>{if(e.length>1){let r=Su(e,1),n=Su(e,2),s=Su(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),Gt({starts:r,ends:n,axes:s})}else return t},zd=(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]]))},jc=(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 = ${Ft("uniforms.input_shape","i",r.length)}; let steps_i = ${Ft("uniforms.steps","i",r.length)}; let signs_i = ${Ft("uniforms.signs","i",r.length)}; let starts_i = ${Ft("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; }`,Vc=(e,t)=>{let r=e[0].dims,n=qe.size(r),s=t.axes.length>0?qe.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=Su(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)=>zd(G,L,r,s,a)),d=t.ends.map((G,L)=>zd(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,pe)=>{if(G<0){let Z=(d[L]-i[L])/G,oe=i[L],et=oe+Z*a[L];i[L]=et,d[L]=oe,pe[L]=-G}});let h=r.slice(0);s.forEach((G,L)=>{h[G]=Math.ceil((d[G]-i[G])/a[G])});let w={dims:h,dataType:e[0].dataType},y=Ut("output",e[0].dataType,h.length),u=it("input",e[0].dataType,e[0].dims.length),k=qe.size(h),C=[{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}],F=[{type:12,data:k},{type:12,data:i},{type:6,data:c},{type:12,data:a},...kt(e[0].dims,h)],U=G=>` ${G.registerUniforms(C).declareVariables(u,y)} ${jc(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:U,getRunData:()=>({outputs:[w],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:F})}},Uc=(e,t)=>{Rc(e.inputs,t);let r=Nc(e.inputs,t);e.compute(Vc(e.inputs,r),{inputs:[0]})},Wc=e=>{let t=e.starts,r=e.ends,n=e.axes;return Gt({starts:t,ends:r,axes:n})}}),Gc,qc,Hc,Kc,cf=D(()=>{Qt(),Yt(),fr(),ir(),Gc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},qc=(e,t)=>{let r=e.dims,n=qe.size(r),s=64,a=t.axis;if(a<0&&(a=r.length+a),aG===4?`max(max(${U}.x, ${U}.y), max(${U}.z, ${U}.w))`:G===2?`max(${U}.x, ${U}.y)`:G===3?`max(max(${U}.x, ${U}.y), ${U}.z)`:U,y=it("x",e.dataType,e.dims,c),u=Ut("result",e.dataType,e.dims,c),k=y.type.value,C=vr(e.dataType)==="f32"?`var threadMax = ${k}(-3.402823e+38f);`:`var threadMax = ${k}(-65504.0h);`,F=U=>` var rowMaxShared : ${k}; var rowSumShared : ${k}; var threadShared : array<${k}, ${s}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${k} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${k}) { let index = row * row_stride + col; result[index] = value; } ${U.registerUniform("packedCols","i32").declareVariables(y,u)} ${U.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${s}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${C} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${k}(${w("threadShared[0]",c)}); } workgroupBarrier(); // find the rows sum var threadSum = ${k}(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 = ${k}(${gn("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:h}]}),getShaderSource:F}},Hc=(e,t)=>{Gc(e.inputs),e.compute(qc(e.inputs[0],t))},Kc=e=>Gt({axis:e.axis})}),Xc,Qc,Yc,Zc,Jc,ep,tp,pf=D(()=>{Qt(),Yt(),fr(),ir(),Xc=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Qc=(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),Gt({numOutputs:n,axis:t.axis,splitSizes:r})},Yc=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Ft("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Zc=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=qe.size(r),s=e[0].dataType,a=qe.normalizeAxis(t.axis,r.length),i=new Array(t.numOutputs),d=it("input",s,r.length),c=new Array(t.numOutputs),h=[],w=[],y=0,u=[{type:12,data:n}];for(let C=0;C` ${C.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",c.length).declareVariables(d,...i)} ${Yc(c.length)} ${Zc(i)} ${C.mainStart()} ${C.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 -= ${Ft("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:k,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u})}},ep=(e,t)=>{Xc(e.inputs);let r=e.inputs.length===1?t:Qc(e.inputs,t);e.compute(Jc(e.inputs,r),{inputs:[0]})},tp=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 Gt({axis:t,numOutputs:n,splitSizes:r})}}),rp,np,sp,hf=D(()=>{Qt(),Yt(),ir(),rp=(e,t,r,n,s)=>{let a=Ut("output_data",s,r.length,4),i=it("a_data",t[1].dataType,t[1].dims.length,4),d=it("b_data",t[2].dataType,t[2].dims.length,4),c=it("c_data",t[0].dataType,t[0].dims.length,4),h,w=(y,u,k)=>`select(${u}, ${y}, ${k})`;if(!n)h=a.setByOffset("global_idx",w(i.getByOffset("global_idx"),d.getByOffset("global_idx"),c.getByOffset("global_idx")));else{let y=(u,k,C="")=>{let F=`a_data[index_a${k}][component_a${k}]`,U=`b_data[index_b${k}][component_b${k}]`,G=`bool(c_data[index_c${k}] & (0xffu << (component_c${k} * 8)))`;return` let output_indices${k} = ${a.offsetToIndices(`global_idx * 4u + ${k}u`)}; let offset_a${k} = ${i.broadcastedIndicesToOffset(`output_indices${k}`,a)}; let offset_b${k} = ${d.broadcastedIndicesToOffset(`output_indices${k}`,a)}; let offset_c${k} = ${c.broadcastedIndicesToOffset(`output_indices${k}`,a)}; let index_a${k} = offset_a${k} / 4u; let index_b${k} = offset_b${k} / 4u; let index_c${k} = offset_c${k} / 4u; let component_a${k} = offset_a${k} % 4u; let component_b${k} = offset_b${k} % 4u; let component_c${k} = offset_c${k} % 4u; ${u}[${k}] = ${C}(${w(F,U,G)}); `};s===9?h=` 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));`:h=` ${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")} ${h} }`},np=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,s=e[1].dataType,a=!(qe.areEqual(t,r)&&qe.areEqual(r,n)),i=t,d=qe.size(t);if(a){let h=Yr.calcShape(Yr.calcShape(t,r,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");i=h,d=qe.size(i)}let c=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>rp(h,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)]})}},sp=e=>{e.compute(np(e.inputs))}}),ip,ff=D(()=>{Du(),Xs(),To(),Bu(),nl(),Lu(),Ru(),Fl(),Pd(),Gu(),qu(),Qu(),Ad(),Zu(),Ju(),ed(),lu(),rd(),Id(),tn(),ia(),sd(),hu(),lr(),Is(),ld(),ki(),of(),lf(),uf(),df(),cf(),pf(),gu(),ds(),Gi(),hf(),ip=new Map([["Abs",[So]],["Acos",[ko]],["Acosh",[Ii]],["Add",[al]],["ArgMax",[fo,Ks]],["ArgMin",[ho,Ks]],["Asin",[Po]],["Asinh",[Ao]],["Atan",[Fi]],["Atanh",[Io]],["Attention",[yo]],["AveragePool",[Rn,pn]],["BatchNormalization",[xo]],["BiasAdd",[Ai]],["BiasSplitGelu",[rl]],["Cast",[Qs,Fo]],["Ceil",[Do]],["Clip",[zo]],["Concat",[qn,gl]],["Conv",[Es,oa]],["ConvTranspose",[Wu,Ll]],["Cos",[Oi]],["Cosh",[Bo]],["CumSum",[ma,jl]],["DepthToSpace",[ga,Wl]],["Div",[ol]],["Einsum",[ql,Hl]],["Elu",[Lo,ps]],["Equal",[Hi]],["Erf",[Ro]],["Exp",[zi]],["Expand",[ba]],["FastGelu",[Ql]],["Floor",[No]],["FusedConv",[Es,oa]],["Gather",[eu,Jl]],["GatherElements",[su,nu]],["Gelu",[jo]],["Gemm",[td,ou]],["GlobalAveragePool",[sn,Kr]],["GlobalMaxPool",[An,Fd]],["Greater",[cl]],["GreaterOrEqual",[hl]],["GroupQueryAttention",[Mu,yu]],["HardSigmoid",[Li,qo]],["InstanceNormalization",[Cu]],["LayerNormalization",[Qr]],["LeakyRelu",[Vo,ps]],["Less",[pl]],["LessOrEqual",[Ki]],["Log",[Wi]],["MatMul",[Pl]],["MatMulNBits",[nd,Eu]],["MaxPool",[li,$a]],["Mul",[ll]],["MultiHeadAttention",[pu,du]],["Neg",[Uo]],["Not",[Di]],["Pad",[Vt]],["Pow",[ul]],["QuickGelu",[el,ps]],["Range",[od]],["Reciprocal",[Wo]],["ReduceMin",[Ei]],["ReduceMean",[io]],["ReduceMax",[lo]],["ReduceSum",[co]],["ReduceProd",[uo]],["ReduceL1",[ao]],["ReduceL2",[$i]],["ReduceLogSum",[po]],["ReduceLogSumExp",[oo]],["ReduceSumSquare",[Si]],["Relu",[Bi]],["Resize",[Ac,Ic]],["RotaryEmbedding",[zc]],["Sigmoid",[Go]],["Sin",[Ho]],["Sinh",[Ko]],["Slice",[Uc,Wc]],["SkipLayerNormalization",[Lc]],["Split",[ep,tp]],["Sqrt",[Ri]],["Softmax",[Hc,Kc]],["Sub",[dl]],["Tan",[Xo]],["Tanh",[ji]],["ThresholdedRelu",[Yo,ps]],["Tile",[_u]],["Transpose",[za,gi]],["Where",[sp]]])}),ap,mf=D(()=>{$(),mn(),ir(),ap=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){Ge(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let h of t)d.push({binding:d.length,resource:{buffer:h.buffer}});for(let h of r)d.push({binding:d.length,resource:{buffer:h.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 h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:c,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}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(),Ve(e.programInfo.name)}dispose(){}build(e,t){Ge(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let s=Ia(t,this.backend.device.limits),a=e.getShaderSource(s),i=`${n.join(` `)} ${s.additionalImplementations} ${a}`,d=r.createShaderModule({code:i,label:e.name});Dr("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let c=r.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return Ve(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]}}}),op,lp,up,dp,_f=D(()=>{$(),Qt(),mn(),_(),$r(),ff(),mf(),op=(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+`:${op(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},up=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},dp=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 up(t.info||await t.requestAdapterInfo()),this.gpuDataManager=Jt(this),this.programManager=new ap(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ls(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;Ge(),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=k);let F=Number(k-this.queryTimeBase),U=Number(C-this.queryTimeBase);if(!Number.isSafeInteger(F)||!Number.isSafeInteger(U))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:kn(G.dataType)})),outputsMetadata:u.map(G=>({dims:G.dims,dataType:kn(G.dataType)})),kernelId:i,kernelType:c,kernelName:h,programName:w,startTime:F,endTime:U});else{let G="";y.forEach((pe,Z)=>{G+=`input[${Z}]: [${pe.dims}] | ${kn(pe.dataType)}, `});let L="";u.forEach((pe,Z)=>{L+=`output[${Z}]: [${pe.dims}] | ${kn(pe.dataType)}, `}),console.log(`[profiling] kernel "${i}|${c}|${h}|${w}" ${G}${L}execution time: ${U-F} ns`)}Ee("GPU",`${w}::${k}::${C}`)}e.unmap(),this.pendingQueries.delete(e)}),Ve()}run(e,t,r,n,s,a){Ge(e.name);let i=[];for(let L=0;Lpe):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 pe=w[L]===-1,Z=w[L]===-2,oe=pe||Z?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 et=this.gpuDataManager.get(oe.data);if(!et)throw new Error(`no GPU data for output: ${oe.data}`);if(pe&&this.temporaryData.push(et),Z){let We=this.kernelPersistentData.get(this.currentKernelId);We||(We=[],this.kernelPersistentData.set(this.currentKernelId,We)),We.push(et)}u.push(et)}if(i.length!==t.length||u.length!==y.length){if(u.length===0)return Ve(e.name),y;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let k;if(h){let L=0,pe=[];h.forEach(We=>{let ct=typeof We.data=="number"?[We.data]:We.data;if(ct.length===0)return;let Ot=We.type===10?2:4,zt,hr;We.type===10?(hr=ct.length>4?16:ct.length>2?8:ct.length*Ot,zt=ct.length>4?16:Ot*ct.length):(hr=ct.length<=2?ct.length*Ot:16,zt=16),L=Math.ceil(L/hr)*hr,pe.push(L);let br=We.type===10?8:4;L+=ct.length>4?Math.ceil(ct.length/br)*zt:ct.length*Ot});let Z=16;L=Math.ceil(L/Z)*Z;let oe=new ArrayBuffer(L);h.forEach((We,ct)=>{let Ot=pe[ct],zt=typeof We.data=="number"?[We.data]:We.data;if(We.type===6)new Int32Array(oe,Ot,zt.length).set(zt);else if(We.type===12)new Uint32Array(oe,Ot,zt.length).set(zt);else if(We.type===10)new Uint16Array(oe,Ot,zt.length).set(zt);else if(We.type===1)new Float32Array(oe,Ot,zt.length).set(zt);else throw new Error(`Unsupported uniform type: ${kn(We.type)}`)});let et=this.gpuDataManager.create(L,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(et.buffer,0,oe,0,L),this.gpuDataManager.release(et.id),k={offset:0,size:L,buffer:et.buffer}}let C=this.programManager.normalizeDispatchGroupSize(c),F=C[1]===1&&C[2]===1,U=lp(e,t,F),G=this.programManager.getArtifact(U);if(G||(G=this.programManager.build(e,C),this.programManager.setArtifact(U,G),Dr("info",()=>`[artifact] key: ${U}, programName: ${e.name}`)),h&&G.uniformVariablesInfo){if(h.length!==G.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${G.uniformVariablesInfo.length}, got ${h.length} in program "${G.programInfo.name}".`);for(let L=0;L`[ProgramManager] run "${e.name}" (key=${U}) with ${C[0]}x${C[1]}x${C[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,C,k),Ve(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=ip.get(e);if(!s)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:s[0],attributes:[s[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let s=n.kernelType,a=n.kernelName,i=n.kernelEntry,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),Dr("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(h){return r.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${a}" failed. ${h}`)),1}finally{c&&r.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${s}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.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 yt(this,e,t);return Me(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(){Dr("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(){Dr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Dr("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()}}}),cp={};T(cp,{init:()=>hp});var ud,pp,hp,gf=D(()=>{Qt(),_f(),mn(),Yt(),ud=class Zh{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=qe.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=qe.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=qe.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(qe.size(t)!==qe.size(this.dims))throw new Error("Invalid new shape");return new Zh(this.module,this.dataType,this.data,t)}},pp=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,h)=>new ud(this.module,c,this.output(d,h),h),a=(d,c)=>{let h=zn(d);if(!h)throw new Error(`Unsupported data type: ${d}`);let w=h*qe.size(c),y=w>0?this.backend.gpuDataManager.create(w).id:0;return new ud(this.module,d,y,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 dp;await a.initialize(r,n),s("webgpu",[a,i=>a.alloc(i),i=>a.free(i),(i,d,c,h=!1)=>{if(h)Dr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${d}, size=${c}`),a.memcpy(i,d);else{Dr("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)=>{Dr("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,h)=>{Dr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${i}, contextDataOffset=${d}`);let w=new pp(t,a,d);return a.computeKernel(i,w,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else s("webnn")}}),fp,Dd,Bd,Fs,mp,dd,Ld,Rd,Nd,jd,Vd,Ud,_p=D(()=>{Vs(),Us(),Qt(),Zr(),Wn(),bs(),fp=(e,t)=>{Lr()._OrtInit(e,t)!==0&&Pr("Can't initialize onnxruntime.")},Dd=async e=>{fp(e.wasm.numThreads,Qn(e.logLevel))},Bd=async(e,t)=>{{let r=(gf(),P(cp)).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",Lr(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Lr(),e)}}},Fs=new Map,mp=e=>{let t=Lr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Pr("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},dd=e=>{let t=Lr(),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]},Ld=async(e,t)=>{var y,u;let r,n,s=Lr();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=dd(e);let a=0,i=0,d=0,c=[],h=[],w=[];try{if([i,c]=Gn(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let Z=[];for(let oe of t.externalData){let et=typeof oe=="string"?oe:oe.path;Z.push(Yn(typeof oe=="string"?oe:oe.data).then(We=>{s.mountExternalData(et,We)}))}await Promise.all(Z)}for(let Z of(t==null?void 0:t.executionProviders)??[])if((typeof Z=="string"?Z:Z.name)==="webnn"){if(s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof Z!="string"){let oe=Z,et=oe==null?void 0:oe.context,We=oe==null?void 0:oe.gpuDevice,ct=oe==null?void 0:oe.deviceType,Ot=oe==null?void 0:oe.numThreads,zt=oe==null?void 0:oe.powerPreference;et?s.currentContext=et:We?s.currentContext=await navigator.ml.createContext(We):s.currentContext=await navigator.ml.createContext({deviceType:ct,numThreads:Ot,powerPreference:zt})}else s.currentContext=await navigator.ml.createContext();break}a=await s._OrtCreateSession(r,n,i),a===0&&Pr("Can't create a session."),s.currentContext&&(s.currentContext=void 0);let[k,C]=mp(a),F=!!(t!=null&&t.enableGraphCapture),U=[],G=[],L=[];for(let Z=0;ZZ==="gpu-buffer")&&(d=s._OrtCreateBinding(a),d===0&&Pr("Can't create IO binding."),pe={handle:d,outputPreferredLocations:L,outputPreferredLocationsEncoded:L.map(Z=>as(Z))}),Fs.set(a,[a,h,w,pe,F,!1]),[a,U,G]}catch(k){throw h.forEach(C=>s._OrtFree(C)),w.forEach(C=>s._OrtFree(C)),d!==0&&s._OrtReleaseBinding(d),a!==0&&s._OrtReleaseSession(a),k}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i),c.forEach(k=>s._free(k)),(u=s.unmountExternalData)==null||u.call(s)}},Rd=e=>{var c;let t=Lr(),r=Fs.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(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n),Fs.delete(e)},Nd=(e,t,r,n,s,a=!1)=>{if(!e){t.push(0);return}let i=Lr(),d=e[0],c=e[1],h=e[3],w,y;if(d==="string"&&h==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let C=e[2].gpuBuffer,F=zn(ss(d));y=c.reduce((G,L)=>G*L,1)*F;let U=i.jsepRegisterBuffer;if(!U)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');w=U(n,s,C,y)}else{let C=e[2];if(Array.isArray(C)){y=4*C.length,w=i._malloc(y),r.push(w);let F=w/4;for(let U=0;Ui.HEAP32[C++]=U);let F=i._OrtCreateTensor(ss(d),w,y,k,c.length,as(h));F===0&&Pr(`Can't create tensor for input/output. session=${n}, index=${s}.`),t.push(F)}finally{i.stackRestore(u)}},jd=async(e,t,r,n,s,a)=>{var zt,hr;let i=Lr(),d=Fs.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=d[0],h=d[1],w=d[2],y=d[3],u=d[4],k=d[5],C=t.length,F=n.length,U=0,G=[],L=[],pe=[],Z=[],oe=i.stackSave(),et=i.stackAlloc(C*4),We=i.stackAlloc(C*4),ct=i.stackAlloc(F*4),Ot=i.stackAlloc(F*4);try{[U,G]=On(a);for(let Bt=0;Btfn*Tn,1);tr=kn(an);let Au=y==null?void 0:y.outputPreferredLocations[n[Bt]];if(tr==="string"){if(Au==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let fn=[],Tn=Br/4;for(let Nn=0;Nn0){let fn=i.jsepGetBuffer;if(!fn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Tn=fn(Br),Nn=zn(an);if(Nn===void 0||!is(tr))throw new Error(`Unsupported data type: ${tr}`);Nt=!0,Rr.push([tr,In,{gpuBuffer:Tn,download:i.jsepCreateDownloader(Tn,hn*Nn,tr),dispose:()=>{i._OrtReleaseTensor(Zt)}},"gpu-buffer"])}else{let fn=Dn(tr),Tn=new fn(hn);new Uint8Array(Tn.buffer,Tn.byteOffset,Tn.byteLength).set(i.HEAPU8.subarray(Br,Br+Tn.byteLength)),Rr.push([tr,In,Tn,"cpu"])}}finally{i.stackRestore(_r),tr==="string"&&Br&&i._free(Br),Nt||i._OrtReleaseTensor(Zt)}}return y&&!u&&(i._OrtClearBoundOutputs(y.handle),Fs.set(e,[c,h,w,y,u,!1])),Rr}finally{i.stackRestore(oe),L.forEach(br=>i._OrtReleaseTensor(br)),pe.forEach(br=>i._OrtReleaseTensor(br)),Z.forEach(br=>i._free(br)),U!==0&&i._OrtReleaseRunOptions(U),G.forEach(br=>i._free(br))}},Vd=e=>{let t=Lr(),r=Fs.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Pr("Can't get an profile file name."),t._OrtFree(s)},Ud=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Os,$n,Ea,ku,Pu,cd,Wd,pd,ui,di,gp,wp,yp,bp,Mp,vp,xp,Tp,Cp=D(()=>{$(),_p(),Zr(),Ur(),Os=()=>!!A.wasm.proxy&&typeof document<"u",Ea=!1,ku=!1,Pu=!1,pd=new Map,ui=(e,t)=>{let r=pd.get(e);r?r.push(t):pd.set(e,[t])},di=()=>{if(Ea||!ku||Pu||!$n)throw new Error("worker not ready")},gp=e=>{switch(e.data.type){case"init-wasm":Ea=!1,e.data.err?(Pu=!0,Wd[1](e.data.err)):(ku=!0,Wd[0]()),cd&&(URL.revokeObjectURL(cd),cd=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=pd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},wp=async()=>{if(!ku){if(Ea)throw new Error("multiple calls to 'initWasm()' detected.");if(Pu)throw new Error("previous call to 'initWasm()' failed.");if(Ea=!0,Os())return new Promise((e,t)=>{$n==null||$n.terminate(),er().then(([r,n])=>{try{$n=n,$n.onerror=a=>t(a),$n.onmessage=gp,Wd=[e,t];let s={type:"init-wasm",in:A};$n.postMessage(s),cd=r}catch(s){t(s)}},t)});try{await Fn(A.wasm),await Dd(A),ku=!0}catch(e){throw Pu=!0,e}finally{Ea=!1}}},yp=async e=>{if(Os())return di(),new Promise((t,r)=>{ui("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:A}};$n.postMessage(n)});await Bd(A,e)},bp=async e=>Os()?(di(),new Promise((t,r)=>{ui("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};$n.postMessage(n,[e.buffer])})):dd(e),Mp=async(e,t)=>{if(Os()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return di(),new Promise((r,n)=>{ui("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 Ld(e,t)},vp=async e=>{if(Os())return di(),new Promise((t,r)=>{ui("release",[t,r]);let n={type:"release",in:e};$n.postMessage(n)});Rd(e)},xp=async(e,t,r,n,s,a)=>{if(Os()){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 di(),new Promise((i,d)=>{ui("run",[i,d]);let c=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:c,outputIndices:n,options:a}};$n.postMessage(h,Ud(c))})}else return jd(e,t,r,n,s,a)},Tp=async e=>{if(Os())return di(),new Promise((t,r)=>{ui("end-profiling",[t,r]);let n={type:"end-profiling",in:e};$n.postMessage(n)});Vd(e)}}),Gd,$p,Ep,wf=D(()=>{$(),Cp(),Qt(),q(),bs(),Gd=(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()}`)}},$p=e=>{switch(e[3]){case"cpu":return new ze(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!is(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]}`)}},Ep=class{async fetchModelAndCopyToWasmMemory(e){return bp(await Yn(e))}async loadModel(e,t){Ge();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await Mp(r,t),Ve()}async dispose(){return vp(this.sessionId)}async run(e,t,r){Ge();let n=[],s=[];Object.entries(e).forEach(y=>{let u=y[0],k=y[1],C=this.inputNames.indexOf(u);if(C===-1)throw new Error(`invalid input '${u}'`);n.push(k),s.push(C)});let a=[],i=[];Object.entries(t).forEach(y=>{let u=y[0],k=y[1],C=this.outputNames.indexOf(u);if(C===-1)throw new Error(`invalid output '${u}'`);a.push(k),i.push(C)});let d=n.map((y,u)=>Gd(y,()=>`input "${this.inputNames[s[u]]}"`)),c=a.map((y,u)=>y?Gd(y,()=>`output "${this.outputNames[i[u]]}"`):null),h=await xp(this.sessionId,s,d,i,c,r),w={};for(let y=0;y{$(),Cp(),wf(),Ur(),Sp=()=>{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))}},kp=class{async init(e){Sp(),await wp(),await yp(e)}async createInferenceSessionHandler(e,t){let r=new Ep;return await r.loadModel(e,t),Promise.resolve(r)}}}),Pp={};T(Pp,{wasmBackend:()=>Ap});var Ap,bf=D(()=>{yf(),Ap=new kp});$(),$(),$();var Mf="1.19.0",vf=Se;{let e=(bf(),P(Pp)).wasmBackend;ne("webgpu",e,5),ne("webnn",e,5),ne("cpu",e,10),ne("wasm",e,10)}Object.defineProperty(A.versions,"web",{value:Mf,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":(Mt,me,l)=>{var x;l.r(me),l.d(me,{Tensor:()=>xe.Tensor,createInferenceSession:()=>ie,deviceToExecutionProviders:()=>te,isONNXProxy:()=>se,isONNXTensor:()=>R});var H=l("./src/env.js"),ge=l("?2ce3"),ve=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"}}),T=[];let j,P;if(H.apis.IS_NODE_ENV){switch(P=ge??(x||(x=l.t(ge,2))),process.platform){case"win32":T.push("dml");break;case"linux":process.arch==="x64"&&T.push("cuda");break}T.push("cpu"),j=["cpu"]}else P=ve,H.apis.IS_WEBNN_AVAILABLE&&T.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),H.apis.IS_WEBGPU_AVAILABLE&&T.push("webgpu"),T.push("wasm"),j=["wasm"];const J=P.InferenceSession;function te(le=null){if(!le)return j;switch(le){case"auto":return T;case"gpu":return T.filter(ae=>["webgpu","cuda","dml","webnn-gpu"].includes(ae))}if(T.includes(le))return[D[le]??le];throw new Error(`Unsupported device: "${le}". Should be one of: ${T.join(", ")}.`)}let ne=null;async function ie(le,ae){ne&&await ne;const N=J.create(le,ae);return ne??(ne=N),await N}function R(le){return le instanceof P.Tensor}const Y=P==null?void 0:P.env;Y!=null&&Y.wasm&&(Y.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${H.env.version}/dist/`,Y.wasm.proxy=!H.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(Y.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(Y.wasm.simd=!1)),Y!=null&&Y.webgpu&&(Y.webgpu.powerPreference="high-performance");function se(){var le;return(le=Y==null?void 0:Y.wasm)==null?void 0:le.proxy}H.env.backends.onnx=Y},"./src/configs.js":(Mt,me,l)=>{l.r(me),l.d(me,{AutoConfig:()=>T,PretrainedConfig:()=>D,getKeyValueShapes:()=>xe});var x=l("./src/utils/core.js"),H=l("./src/utils/hub.js");async function ge(j,P){return await(0,H.getModelJSON)(j,"config.json",!0,P)}function ve(j){const P={};let J={};switch(j.model_type){case"llava":case"paligemma":case"florence2":J=ve(j.text_config);break;case"moondream1":J=ve(j.phi_config);break;case"musicgen":J=ve(j.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=ve(j.decoder),ie="num_decoder_layers"in ne,R=(0,x.pick)(j,["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,x.pick)(j,["model_type","multi_query","is_encoder_decoder"])};for(const ne in P)te[ne]=j[P[ne]];return te}function xe(j,{prefix:P="past_key_values"}={}){const J={},te=j.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,Y=[ne,te.num_encoder_heads,0,ie],se=[ne,te.num_decoder_heads,0,R];for(let le=0;le{var A;l.r(me),l.d(me,{apis:()=>R,env:()=>I});var x=l("?569f"),H=l("?3f59"),ge=l("?154a");const ve="3.0.0-alpha.7",xe=typeof self<"u",D=xe&&self.constructor.name==="DedicatedWorkerGlobalScope",T=xe&&"caches"in self,j=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(x),ie=!B(H),R=Object.freeze({IS_BROWSER_ENV:xe,IS_WEBWORKER_ENV:D,IS_WEB_CACHE_AVAILABLE:T,IS_WEBGPU_AVAILABLE:j,IS_WEBNN_AVAILABLE:P,IS_PROCESS_AVAILABLE:J,IS_NODE_ENV:te,IS_FS_AVAILABLE:ne,IS_PATH_AVAILABLE:ie}),Y=ne&&ie,se=Y?H.dirname(H.dirname(ge.fileURLToPath(self.location.href))):"./",le=Y?H.join(se,"/.cache/"):null,ae="/models/",N=Y?H.join(se,ae):ae,I={version:ve,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!xe,localModelPath:N,useFS:ne,useBrowserCache:T,useFSCache:ne,cacheDir:le,useCustomCache:!1,customCache:null};function B(_e){return Object.keys(_e).length===0}},"./src/generation/configuration_utils.js":(Mt,me,l)=>{l.r(me),l.d(me,{GenerationConfig:()=>H});var x=l("./src/utils/core.js");class H{constructor(ve){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,x.pick)(ve,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Mt,me,l)=>{l.r(me),l.d(me,{ClassifierFreeGuidanceLogitsProcessor:()=>Y,ForcedBOSTokenLogitsProcessor:()=>D,ForcedEOSTokenLogitsProcessor:()=>T,LogitsProcessor:()=>ge,LogitsProcessorList:()=>xe,LogitsWarper:()=>ve,MinLengthLogitsProcessor:()=>ne,MinNewTokensLengthLogitsProcessor:()=>ie,NoBadWordsLogitsProcessor:()=>R,NoRepeatNGramLogitsProcessor:()=>J,RepetitionPenaltyLogitsProcessor:()=>te,SuppressTokensAtBeginLogitsProcessor:()=>j,TemperatureLogitsWarper:()=>se,TopKLogitsWarper:()=>ae,TopPLogitsWarper:()=>le,WhisperTimeStampLogitsProcessor:()=>P});var x=l("./src/utils/generic.js");l("./src/utils/tensor.js");var H=l("./src/utils/maths.js");class ge extends x.Callable{_call(I,B){throw Error("`_call` should be implemented in a subclass")}}class ve extends x.Callable{_call(I,B){throw Error("`_call` should be implemented in a subclass")}}class xe extends x.Callable{constructor(){super(),this.processors=[]}push(I){this.processors.push(I)}extend(I){this.processors.push(...I)}_call(I,B){let A=B;for(const _e of this.processors)A=_e(I,A);return A}[Symbol.iterator](){return this.processors.values()}}class D extends ge{constructor(I){super(),this.bos_token_id=I}_call(I,B){for(let A=0;A=1&&Ce[Ce.length-1]>=this.timestamp_begin,Ie=Ce.length<2||Ce[Ce.length-2]>=this.timestamp_begin;if(ke&&(Ie?ye.subarray(this.timestamp_begin).fill(-1/0):ye.subarray(0,this.eos_token_id).fill(-1/0)),I[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 tt=(0,H.log_softmax)(ye),Qe=Math.log(tt.subarray(this.timestamp_begin).map(Math.exp).reduce((we,V)=>we+V)),ht=(0,H.max)(tt.subarray(0,this.timestamp_begin))[0];Qe>ht&&ye.subarray(0,this.timestamp_begin).fill(-1/0)}return B}}class J extends ge{constructor(I){super(),this.no_repeat_ngram_size=I}getNgrams(I){const B=I.length,A=[];for(let ye=0;ye1 to use the classifier free guidance processor, got guidance scale ${I}.`);this.guidance_scale=I}_call(I,B){if(B.dims[0]!==2*I.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${B.dims[0]} for the logits and ${I.length} for the input ids.`);const A=I.length,_e=B.slice([0,A],null),ye=B.slice([A,B.dims[0]],null);for(let Ce=0;Ce1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${I}`);if(!Number.isInteger(A)||A<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${A}`);this.top_p=I,this.filter_value=B,this.min_tokens_to_keep=A}}class ae extends ve{constructor(I,{filter_value:B=-1/0,min_tokens_to_keep:A=1}={}){if(super(),!Number.isInteger(I)||I<0)throw new Error(`\`top_k\` must be a positive integer, but is ${I}`);this.top_k=Math.max(I,A),this.filter_value=B}}},"./src/generation/logits_sampler.js":(Mt,me,l)=>{l.r(me),l.d(me,{LogitsSampler:()=>ve});var x=l("./src/utils/generic.js"),H=l("./src/utils/tensor.js"),ge=l("./src/utils/maths.js");l("./src/generation/configuration_utils.js");class ve extends x.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 T(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 ve{async sample(P){const J=(0,ge.max)(P.data)[1];return[[BigInt(J),0]]}}class D extends ve{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,H.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 T extends ve{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,H.topk)(P,J),ie=(0,ge.softmax)(te.data);return Array.from({length:this.generation_config.num_beams},(R,Y)=>[ne.data[Y],Math.log(ie[Y])])}}},"./src/generation/stopping_criteria.js":(Mt,me,l)=>{l.r(me),l.d(me,{EosTokenCriteria:()=>xe,InterruptableStoppingCriteria:()=>D,MaxLengthCriteria:()=>ve,StoppingCriteria:()=>H,StoppingCriteriaList:()=>ge});var x=l("./src/utils/generic.js");class H extends x.Callable{_call(j,P){throw Error("StoppingCriteria needs to be subclassed")}}class ge extends x.Callable{constructor(){super(),this.criteria=[]}push(j){this.criteria.push(j)}extend(j){j instanceof ge?j=j.criteria:j instanceof H&&(j=[j]),this.criteria.push(...j)}_call(j,P){const J=new Array(j.length).fill(!1);for(const te of this.criteria){const ne=te(j,P);for(let ie=0;ieP.length>=this.max_length)}}class xe extends H{constructor(j){super(),Array.isArray(j)||(j=[j]),this.eos_token_id=j}_call(j,P){return j.map(J=>{const te=J.at(-1);return this.eos_token_id.some(ne=>te==ne)})}}class D extends H{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(j,P){return new Array(j.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Mt,me,l)=>{l.r(me),l.d(me,{BaseStreamer:()=>ve,TextStreamer:()=>D,WhisperTextStreamer:()=>T});var x=l("./src/utils/core.js"),H=l("./src/tokenizers.js"),ge=l("./src/env.js");class ve{put(P){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const xe=ge.apis.IS_PROCESS_AVAILABLE?j=>process.stdout.write(j):j=>console.log(j);class D extends ve{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,x.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,H.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 T 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:Y=null,time_precision:se=.02,skip_special_tokens:le=!0,decode_kwargs:ae={}}={}){super(P,{skip_prompt:J,callback_function:te,token_callback_function:ne,decode_kwargs:{skip_special_tokens:le,...ae}}),this.timestamp_begin=P.timestamp_begin,this.on_chunk_start=ie,this.on_chunk_end=R,this.on_finalize=Y,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":(Mt,me,l)=>{l.r(me),l.d(me,{ASTForAudioClassification:()=>Ws,ASTModel:()=>Ft,ASTPreTrainedModel:()=>gn,AlbertForMaskedLM:()=>Qt,AlbertForQuestionAnswering:()=>as,AlbertForSequenceClassification:()=>is,AlbertModel:()=>Qn,AlbertPreTrainedModel:()=>Dn,AutoModel:()=>lu,AutoModelForAudioClassification:()=>bu,AutoModelForAudioFrameClassification:()=>Mu,AutoModelForCTC:()=>yu,AutoModelForCausalLM:()=>pu,AutoModelForDepthEstimation:()=>Tu,AutoModelForDocumentQuestionAnswering:()=>rd,AutoModelForImageClassification:()=>mu,AutoModelForImageFeatureExtraction:()=>Cu,AutoModelForImageMatting:()=>vu,AutoModelForImageSegmentation:()=>xa,AutoModelForImageToImage:()=>xu,AutoModelForMaskGeneration:()=>Ta,AutoModelForMaskedLM:()=>hu,AutoModelForObjectDetection:()=>gu,AutoModelForQuestionAnswering:()=>va,AutoModelForSemanticSegmentation:()=>_u,AutoModelForSeq2SeqLM:()=>du,AutoModelForSequenceClassification:()=>ln,AutoModelForSpeechSeq2Seq:()=>Ma,AutoModelForTextToSpectrogram:()=>cu,AutoModelForTextToWaveform:()=>As,AutoModelForTokenClassification:()=>uu,AutoModelForVision2Seq:()=>fu,AutoModelForXVector:()=>Ca,AutoModelForZeroShotObjectDetection:()=>wu,BartForConditionalGeneration:()=>_,BartForSequenceClassification:()=>O,BartModel:()=>Me,BartPretrainedModel:()=>mn,BaseModelOutput:()=>pt,BeitForImageClassification:()=>Fo,BeitModel:()=>Io,BeitPreTrainedModel:()=>Fi,BertForMaskedLM:()=>Re,BertForQuestionAnswering:()=>ze,BertForSequenceClassification:()=>st,BertForTokenClassification:()=>Tt,BertModel:()=>lt,BertPreTrainedModel:()=>rt,BlenderbotForConditionalGeneration:()=>Pt,BlenderbotModel:()=>yt,BlenderbotPreTrainedModel:()=>bt,BlenderbotSmallForConditionalGeneration:()=>nr,BlenderbotSmallModel:()=>$r,BlenderbotSmallPreTrainedModel:()=>Jt,BloomForCausalLM:()=>fo,BloomModel:()=>ho,BloomPreTrainedModel:()=>Hs,CLIPModel:()=>Oa,CLIPPreTrainedModel:()=>Cs,CLIPSegForImageSegmentation:()=>ja,CLIPSegModel:()=>Na,CLIPSegPreTrainedModel:()=>wi,CLIPTextModelWithProjection:()=>Pn,CLIPVisionModelWithProjection:()=>za,CamembertForMaskedLM:()=>be,CamembertForQuestionAnswering:()=>Ne,CamembertForSequenceClassification:()=>Be,CamembertForTokenClassification:()=>Ae,CamembertModel:()=>q,CamembertPreTrainedModel:()=>$,CausalLMOutput:()=>Zn,CausalLMOutputWithPast:()=>nd,ChineseCLIPModel:()=>Ra,ChineseCLIPPreTrainedModel:()=>La,ClapAudioModelWithProjection:()=>zl,ClapModel:()=>Fl,ClapPreTrainedModel:()=>Es,ClapTextModelWithProjection:()=>Ol,CodeGenForCausalLM:()=>Gs,CodeGenModel:()=>Ya,CodeGenPreTrainedModel:()=>Mn,CohereForCausalLM:()=>eo,CohereModel:()=>Ja,CoherePreTrainedModel:()=>xi,ConvBertForMaskedLM:()=>M,ConvBertForQuestionAnswering:()=>X,ConvBertForSequenceClassification:()=>W,ConvBertForTokenClassification:()=>S,ConvBertModel:()=>xt,ConvBertPreTrainedModel:()=>wt,ConvNextForImageClassification:()=>rl,ConvNextModel:()=>tl,ConvNextPreTrainedModel:()=>qi,ConvNextV2ForImageClassification:()=>il,ConvNextV2Model:()=>sl,ConvNextV2PreTrainedModel:()=>nl,DPTForDepthEstimation:()=>Ui,DPTModel:()=>Vi,DPTPreTrainedModel:()=>ji,DebertaForMaskedLM:()=>vt,DebertaForQuestionAnswering:()=>Lt,DebertaForSequenceClassification:()=>ft,DebertaForTokenClassification:()=>Ct,DebertaModel:()=>nt,DebertaPreTrainedModel:()=>dt,DebertaV2ForMaskedLM:()=>Rt,DebertaV2ForQuestionAnswering:()=>er,DebertaV2ForSequenceClassification:()=>Ht,DebertaV2ForTokenClassification:()=>Xt,DebertaV2Model:()=>jt,DebertaV2PreTrainedModel:()=>Xe,DeiTForImageClassification:()=>Wo,DeiTModel:()=>Uo,DeiTPreTrainedModel:()=>Di,DepthAnythingForDepthEstimation:()=>Yo,DepthAnythingPreTrainedModel:()=>Qo,DetrForObjectDetection:()=>zo,DetrForSegmentation:()=>Do,DetrModel:()=>Oo,DetrObjectDetectionOutput:()=>Oi,DetrPreTrainedModel:()=>Qs,DetrSegmentationOutput:()=>Bo,Dinov2ForImageClassification:()=>ol,Dinov2Model:()=>al,Dinov2PreTrainedModel:()=>xn,DistilBertForMaskedLM:()=>St,DistilBertForQuestionAnswering:()=>Ze,DistilBertForSequenceClassification:()=>Ur,DistilBertForTokenClassification:()=>Cr,DistilBertModel:()=>Tr,DistilBertPreTrainedModel:()=>Wt,DonutSwinModel:()=>Gi,DonutSwinPreTrainedModel:()=>el,EfficientNetForImageClassification:()=>Nl,EfficientNetModel:()=>Rl,EfficientNetPreTrainedModel:()=>pa,ElectraForMaskedLM:()=>Je,ElectraForQuestionAnswering:()=>Se,ElectraForSequenceClassification:()=>At,ElectraForTokenClassification:()=>_t,ElectraModel:()=>Ye,ElectraPreTrainedModel:()=>fe,EsmForMaskedLM:()=>Un,EsmForSequenceClassification:()=>Fn,EsmForTokenClassification:()=>Lr,EsmModel:()=>qr,EsmPreTrainedModel:()=>Dt,FalconForCausalLM:()=>Il,FalconModel:()=>Al,FalconPreTrainedModel:()=>la,FastViTForImageClassification:()=>Mo,FastViTModel:()=>bo,FastViTPreTrainedModel:()=>Xs,Florence2ForConditionalGeneration:()=>_i,Florence2PreTrainedModel:()=>Fa,GLPNForDepthEstimation:()=>Jo,GLPNModel:()=>Zo,GLPNPreTrainedModel:()=>Wi,GPT2LMHeadModel:()=>Ua,GPT2Model:()=>Va,GPT2PreTrainedModel:()=>yi,GPTBigCodeForCausalLM:()=>zu,GPTBigCodeModel:()=>Qa,GPTBigCodePreTrainedModel:()=>vi,GPTJForCausalLM:()=>Xa,GPTJModel:()=>Ka,GPTJPreTrainedModel:()=>Mi,GPTNeoForCausalLM:()=>Ga,GPTNeoModel:()=>Wa,GPTNeoPreTrainedModel:()=>bn,GPTNeoXForCausalLM:()=>Ha,GPTNeoXModel:()=>qa,GPTNeoXPreTrainedModel:()=>bi,Gemma2ForCausalLM:()=>so,Gemma2Model:()=>no,Gemma2PreTrainedModel:()=>Ci,GemmaForCausalLM:()=>ro,GemmaModel:()=>to,GemmaPreTrainedModel:()=>Ti,HubertForCTC:()=>vl,HubertForSequenceClassification:()=>ta,HubertModel:()=>ju,HubertPreTrainedModel:()=>Nu,ImageMattingOutput:()=>Eu,LlamaForCausalLM:()=>Za,LlamaModel:()=>Cn,LlamaPreTrainedModel:()=>qs,LlavaForConditionalGeneration:()=>us,LlavaPreTrainedModel:()=>Ia,LongT5ForConditionalGeneration:()=>xs,LongT5Model:()=>vs,LongT5PreTrainedModel:()=>os,M2M100ForConditionalGeneration:()=>_l,M2M100Model:()=>ml,M2M100PreTrainedModel:()=>Xi,MBartForCausalLM:()=>gt,MBartForConditionalGeneration:()=>de,MBartForSequenceClassification:()=>Fe,MBartModel:()=>ue,MBartPreTrainedModel:()=>Q,MPNetForMaskedLM:()=>_s,MPNetForQuestionAnswering:()=>ys,MPNetForSequenceClassification:()=>gs,MPNetForTokenClassification:()=>ws,MPNetModel:()=>Vs,MPNetPreTrainedModel:()=>On,MT5ForConditionalGeneration:()=>Dr,MT5Model:()=>Ts,MT5PreTrainedModel:()=>ls,MarianMTModel:()=>fl,MarianModel:()=>Lu,MarianPreTrainedModel:()=>Ki,MaskedLMOutput:()=>tn,MistralForCausalLM:()=>ni,MistralModel:()=>ri,MistralPreTrainedModel:()=>ia,MobileBertForMaskedLM:()=>Sn,MobileBertForQuestionAnswering:()=>Wn,MobileBertForSequenceClassification:()=>Pr,MobileBertModel:()=>Nr,MobileBertPreTrainedModel:()=>Zr,MobileNetV1ForImageClassification:()=>Gu,MobileNetV1Model:()=>jl,MobileNetV1PreTrainedModel:()=>ma,MobileNetV2ForImageClassification:()=>Ul,MobileNetV2Model:()=>Vl,MobileNetV2PreTrainedModel:()=>_a,MobileNetV3ForImageClassification:()=>qu,MobileNetV3Model:()=>Wl,MobileNetV3PreTrainedModel:()=>ga,MobileNetV4ForImageClassification:()=>wa,MobileNetV4Model:()=>Ps,MobileNetV4PreTrainedModel:()=>ks,MobileViTForImageClassification:()=>$o,MobileViTModel:()=>Co,MobileViTPreTrainedModel:()=>To,MobileViTV2ForImageClassification:()=>Eo,MobileViTV2Model:()=>Bu,MobileViTV2PreTrainedModel:()=>Ai,ModelOutput:()=>He,Moondream1ForConditionalGeneration:()=>ir,MptForCausalLM:()=>mo,MptModel:()=>Du,MptPreTrainedModel:()=>Ks,MusicgenForCausalLM:()=>Pd,MusicgenForConditionalGeneration:()=>fa,MusicgenModel:()=>Wu,MusicgenPreTrainedModel:()=>ha,NomicBertModel:()=>Ee,NomicBertPreTrainedModel:()=>re,OPTForCausalLM:()=>go,OPTModel:()=>_o,OPTPreTrainedModel:()=>Pi,OpenELMForCausalLM:()=>ao,OpenELMModel:()=>io,OpenELMPreTrainedModel:()=>vn,OwlViTForObjectDetection:()=>ko,OwlViTModel:()=>So,OwlViTPreTrainedModel:()=>wr,Owlv2ForObjectDetection:()=>Ao,Owlv2Model:()=>Po,Owlv2PreTrainedModel:()=>Ii,Phi3ForCausalLM:()=>ki,Phi3Model:()=>po,Phi3PreTrainedModel:()=>Si,PhiForCausalLM:()=>co,PhiModel:()=>uo,PhiPreTrainedModel:()=>Ei,PreTrainedModel:()=>ee,PretrainedMixin:()=>Ir,PyAnnoteForAudioFrameClassification:()=>Xn,PyAnnoteModel:()=>Qi,PyAnnotePreTrainedModel:()=>Bn,QuestionAnsweringModelOutput:()=>rn,Qwen2ForCausalLM:()=>lo,Qwen2Model:()=>oo,Qwen2PreTrainedModel:()=>$i,RTDetrForObjectDetection:()=>Ys,RTDetrModel:()=>Lo,RTDetrObjectDetectionOutput:()=>Ro,RTDetrPreTrainedModel:()=>ps,ResNetForImageClassification:()=>qo,ResNetModel:()=>Go,ResNetPreTrainedModel:()=>Bi,RoFormerForMaskedLM:()=>Ve,RoFormerForQuestionAnswering:()=>mt,RoFormerForSequenceClassification:()=>Ke,RoFormerForTokenClassification:()=>ut,RoFormerModel:()=>Ge,RoFormerPreTrainedModel:()=>je,RobertaForMaskedLM:()=>on,RobertaForQuestionAnswering:()=>yn,RobertaForSequenceClassification:()=>Yr,RobertaForTokenClassification:()=>qe,RobertaModel:()=>fr,RobertaPreTrainedModel:()=>Gt,SamImageSegmentationOutput:()=>hl,SamModel:()=>pl,SamPreTrainedModel:()=>cl,SegformerForImageClassification:()=>Dl,SegformerForSemanticSegmentation:()=>Bl,SegformerModel:()=>kd,SegformerPreTrainedModel:()=>Ss,Seq2SeqLMOutput:()=>Id,SequenceClassifierOutput:()=>or,SiglipModel:()=>ds,SiglipPreTrainedModel:()=>gi,SiglipTextModel:()=>Da,SiglipVisionModel:()=>Ba,SpeechT5ForSpeechToText:()=>Sl,SpeechT5ForTextToSpeech:()=>Vu,SpeechT5HifiGan:()=>sa,SpeechT5Model:()=>El,SpeechT5PreTrainedModel:()=>na,SqueezeBertForMaskedLM:()=>ss,SqueezeBertForQuestionAnswering:()=>zn,SqueezeBertForSequenceClassification:()=>kn,SqueezeBertModel:()=>Us,SqueezeBertPreTrainedModel:()=>Gn,StableLmForCausalLM:()=>Ll,StableLmModel:()=>ca,StableLmPreTrainedModel:()=>da,Starcoder2ForCausalLM:()=>oa,Starcoder2Model:()=>si,Starcoder2PreTrainedModel:()=>aa,Swin2SRForImageSuperResolution:()=>Ni,Swin2SRModel:()=>Xo,Swin2SRPreTrainedModel:()=>Ri,SwinForImageClassification:()=>Ko,SwinModel:()=>Ho,SwinPreTrainedModel:()=>Li,T5ForConditionalGeneration:()=>Ms,T5Model:()=>bs,T5PreTrainedModel:()=>Yn,TableTransformerForObjectDetection:()=>jo,TableTransformerModel:()=>No,TableTransformerObjectDetectionOutput:()=>Vo,TableTransformerPreTrainedModel:()=>zi,TokenClassifierOutput:()=>Qr,TrOCRForCausalLM:()=>Pl,TrOCRPreTrainedModel:()=>kl,UniSpeechForCTC:()=>wl,UniSpeechForSequenceClassification:()=>yl,UniSpeechModel:()=>Zi,UniSpeechPreTrainedModel:()=>hs,UniSpeechSatForAudioFrameClassification:()=>Js,UniSpeechSatForCTC:()=>Ji,UniSpeechSatForSequenceClassification:()=>bl,UniSpeechSatModel:()=>Zs,UniSpeechSatPreTrainedModel:()=>$s,ViTForImageClassification:()=>yo,ViTModel:()=>wo,ViTPreTrainedModel:()=>cs,VisionEncoderDecoderModel:()=>mi,VitMatteForImageMatting:()=>xo,VitMattePreTrainedModel:()=>vo,VitsModel:()=>ua,VitsModelOutput:()=>sd,VitsPreTrainedModel:()=>Uu,Wav2Vec2BertForCTC:()=>ti,Wav2Vec2BertForSequenceClassification:()=>Ml,Wav2Vec2BertModel:()=>ea,Wav2Vec2BertPreTrainedModel:()=>ei,Wav2Vec2ForAudioFrameClassification:()=>Kn,Wav2Vec2ForCTC:()=>Ru,Wav2Vec2ForSequenceClassification:()=>Hn,Wav2Vec2Model:()=>gl,Wav2Vec2PreTrainedModel:()=>qn,WavLMForAudioFrameClassification:()=>$l,WavLMForCTC:()=>ra,WavLMForSequenceClassification:()=>Tl,WavLMForXVector:()=>Cl,WavLMModel:()=>xl,WavLMPreTrainedModel:()=>Ln,WeSpeakerResNetModel:()=>Yi,WeSpeakerResNetPreTrainedModel:()=>en,WhisperForConditionalGeneration:()=>fi,WhisperModel:()=>Ut,WhisperPreTrainedModel:()=>it,XLMForQuestionAnswering:()=>Jr,XLMForSequenceClassification:()=>Yt,XLMForTokenClassification:()=>_n,XLMModel:()=>Hr,XLMPreTrainedModel:()=>Mr,XLMRobertaForMaskedLM:()=>kt,XLMRobertaForQuestionAnswering:()=>jr,XLMRobertaForSequenceClassification:()=>gr,XLMRobertaForTokenClassification:()=>Ar,XLMRobertaModel:()=>xr,XLMRobertaPreTrainedModel:()=>vr,XLMWithLMHeadModel:()=>cn,XVectorOutput:()=>$u,YolosForObjectDetection:()=>ul,YolosModel:()=>ll,YolosObjectDetectionOutput:()=>dl,YolosPreTrainedModel:()=>Hi});var x=l("./src/configs.js"),H=l("./src/backends/onnx.js"),ge=l("./src/utils/dtypes.js"),ve=l("./src/utils/generic.js"),xe=l("./src/utils/core.js"),D=l("./src/utils/hub.js"),T=l("./src/generation/logits_process.js"),j=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"),Y=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},le=new Map,ae=new Map,N=new Map;async function I(m,g,E){let K=E.device;K&&typeof K!="string"&&(K.hasOwnProperty(g)?K=K[g]:(console.warn(`device not specified for "${g}". Using the default device.`),K=null));const Pe=K??(ie.apis.IS_NODE_ENV?"cpu":"wasm"),De=(0,H.deviceToExecutionProviders)(Pe);let at=E.dtype;typeof at!="string"&&(at&&at.hasOwnProperty(g)?at=at[g]:(at=ge.DEFAULT_DEVICE_DTYPE_MAPPING[Pe]??ge.DATA_TYPES.fp32,console.warn(`dtype not specified for "${g}". Using the default dtype (${at}) for this device (${Pe}).`)));const $t=at;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 Vt=ge.DEFAULT_DTYPE_SUFFIX_MAPPING[$t],lr=`${E.subfolder??""}/${g}${Vt}.onnx`,ar={...E.session_options};ar.executionProviders??(ar.executionProviders=De);const Er=(0,D.getModelFile)(m,lr,!0,E);let ur=[];if(E.use_external_data_format&&(E.use_external_data_format===!0||typeof E.use_external_data_format=="object"&&E.use_external_data_format.hasOwnProperty(g)&&E.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}${Vt}.onnx_data`,pr=`${E.subfolder??""}/${dr}`;ur.push(new Promise(async(yr,Or)=>{const un=await(0,D.getModelFile)(m,pr,!0,E);yr({path:dr,data:un})}))}else ar.externalData!==void 0&&(ur=ar.externalData.map(async dr=>{if(typeof dr.data=="string"){const pr=await(0,D.getModelFile)(m,dr.data,!0,E);return{...dr,data:pr}}return dr}));if(ur.length>0&&(ar.externalData=await Promise.all(ur)),Pe==="webgpu"){const dr=(0,x.getKeyValueShapes)(E.config,{prefix:"present"});if(Object.keys(dr).length>0&&!(0,H.isONNXProxy)()){const pr={};for(const yr in dr)pr[yr]="gpu-buffer";ar.preferredOutputLocation=pr}}return{buffer:await Er,session_options:ar}}async function B(m,g,E){return Object.fromEntries(await Promise.all(Object.keys(g).map(async K=>{const{buffer:Pe,session_options:De}=await I(m,g[K],E),at=await(0,H.createInferenceSession)(Pe,De);return[K,at]})))}function A(m,g){const E=Object.create(null),K=[];for(const at of m.inputNames){const $t=g[at];if(!($t instanceof P.Tensor)){K.push(at);continue}E[at]=(0,H.isONNXProxy)()?$t.clone():$t}if(K.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${K.join(", ")}.`);const Pe=Object.keys(g).length,De=m.inputNames.length;if(Pe>De){let at=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: "${at.join(", ")}".`)}return E}async function _e(m,g){const E=A(m,g);try{const K=Object.fromEntries(Object.entries(E).map(([De,at])=>[De,at.ort_tensor]));let Pe=await m.run(K);return Pe=ye(Pe),Pe}catch(K){throw console.error(`An error occurred during model execution: "${K}".`),console.error("Inputs given to model:",E),K}}function ye(m){for(let g in m)(0,H.isONNXTensor)(m[g])?m[g]=new P.Tensor(m[g]):typeof m[g]=="object"&&ye(m[g]);return m}function Ce(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 ke(m){return new P.Tensor("bool",[m],[1])}async function Ie(m,g){let{encoder_outputs:E,input_ids:K,decoder_input_ids:Pe,...De}=g;if(!E){const $t=(0,xe.pick)(g,m.sessions.model.inputNames);E=(await tt(m,$t)).last_hidden_state}return De.input_ids=Pe,De.encoder_hidden_states=E,m.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(De.encoder_attention_mask=g.attention_mask),await Qe(m,De,!0)}async function tt(m,g){const E=m.sessions.model,K=(0,xe.pick)(g,E.inputNames);if(E.inputNames.includes("inputs_embeds")&&!K.inputs_embeds){if(!g.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");K.inputs_embeds=await m.encode_text({input_ids:g.input_ids})}return E.inputNames.includes("token_type_ids")&&!K.token_type_ids&&(K.token_type_ids=new P.Tensor("int64",new BigInt64Array(K.input_ids.data.length),K.input_ids.dims)),await _e(E,K)}async function Qe(m,g,E=!1){const K=m.sessions[E?"decoder_model_merged":"model"],{past_key_values:Pe,...De}=g;K.inputNames.includes("use_cache_branch")&&(De.use_cache_branch=ke(!!Pe)),K.inputNames.includes("position_ids")&&De.attention_mask&&!De.position_ids&&(De.position_ids=we(De,Pe)),m.addPastKeyValues(De,Pe);const at=(0,xe.pick)(De,K.inputNames);return await _e(K,at)}async function ht(m,{input_ids:g=null,attention_mask:E=null,pixel_values:K=null,position_ids:Pe=null,inputs_embeds:De=null,past_key_values:at=null,generation_config:$t=null,logits_processor:Vt=null,...lr}){if(!De){if(De=await m.encode_text({input_ids:g}),K&&g.dims[1]!==1){const Er=await m.encode_image({pixel_values:K});({inputs_embeds:De,attention_mask:E}=m._merge_input_ids_with_image_features({image_features:Er,inputs_embeds:De,input_ids:g,attention_mask:E}))}else if(at&&K&&g.dims[1]===1){const Er=g.dims[1],ur=Object.values(at)[0].dims.at(-2);E=(0,P.cat)([(0,P.ones)([g.dims[0],ur]),E.slice(null,[E.dims[1]-Er,E.dims[1]])],1)}}return await Qe(m,{inputs_embeds:De,past_key_values:at,attention_mask:E,position_ids:Pe,generation_config:$t,logits_processor:Vt},!0)}function we(m,g=null){const{input_ids:E,inputs_embeds:K,attention_mask:Pe}=m,[De,at]=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 Vt=De.dims[1]-(Pe-$t);E.input_ids=De.slice(null,[-Vt,null]),E.attention_mask=(0,P.ones)([1,Pe+Vt])}}}return E}function he(m,g,E,K){return E.past_key_values&&(g=g.map(Pe=>[Pe.at(-1)])),{...E,decoder_input_ids:Ce(g)}}function $e(m,...g){return m.config.is_encoder_decoder?he(m,...g):V(m,...g)}class ee extends ve.Callable{constructor(E,K){super();Te(this,"main_input_name","input_ids");Te(this,"forward_params",["input_ids","attention_mask"]);this.config=E,this.sessions=K;const Pe=N.get(this.constructor),De=le.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=Qe,this._prepare_inputs_for_generation=V;break;case se.Seq2Seq:case se.Vision2Seq:case se.Musicgen:this.can_generate=!0,this._forward=Ie,this._prepare_inputs_for_generation=he;break;case se.EncoderDecoder:this._forward=Ie;break;case se.ImageTextToText:this.can_generate=!0,this._forward=ht,this._prepare_inputs_for_generation=$e;break;default:this._forward=tt;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var K;const E=[];for(const Pe of Object.values(this.sessions))(K=Pe==null?void 0:Pe.handler)!=null&&K.dispose&&E.push(Pe.handler.dispose());return await Promise.all(E)}static async from_pretrained(E,{progress_callback:K=null,config:Pe=null,cache_dir:De=null,local_files_only:at=!1,revision:$t="main",model_file_name:Vt=null,subfolder:lr="onnx",device:ar=null,dtype:Er=null,use_external_data_format:ur=null,session_options:mr={}}={}){let dr={progress_callback:K,config:Pe,cache_dir:De,local_files_only:at,revision:$t,model_file_name:Vt,subfolder:lr,device:ar,dtype:Er,use_external_data_format:ur,session_options:mr};const pr=N.get(this),yr=le.get(pr);Pe=dr.config=await x.AutoConfig.from_pretrained(E,dr);let Or;if(yr===se.DecoderOnly)Or=await Promise.all([B(E,{model:dr.model_file_name??"model"},dr),(0,D.getModelJSON)(E,"generation_config.json",!1,dr)]);else if(yr===se.Seq2Seq||yr===se.Vision2Seq)Or=await Promise.all([B(E,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},dr),(0,D.getModelJSON)(E,"generation_config.json",!1,dr)]);else if(yr===se.MaskGeneration)Or=await Promise.all([B(E,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},dr)]);else if(yr===se.EncoderDecoder)Or=await Promise.all([B(E,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},dr)]);else if(yr===se.ImageTextToText){const un={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Pe.is_encoder_decoder&&(un.model="encoder_model"),Or=await Promise.all([B(E,un,dr),(0,D.getModelJSON)(E,"generation_config.json",!1,dr)])}else yr===se.Musicgen?Or=await Promise.all([B(E,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},dr),(0,D.getModelJSON)(E,"generation_config.json",!1,dr)]):(yr!==se.EncoderOnly&&console.warn(`Model type for '${pr??(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.`),Or=await Promise.all([B(E,{model:dr.model_file_name??"model"},dr)]));return new this(Pe,...Or)}async _call(E){return await this.forward(E)}async forward(E){return await this._forward(this,E)}_get_logits_warper(E){const K=new T.LogitsProcessorList;return E.temperature!==null&&E.temperature!==1&&K.push(new T.TemperatureLogitsWarper(E.temperature)),E.top_k!==null&&E.top_k!==0&&K.push(new T.TopKLogitsWarper(E.top_k)),E.top_p!==null&&E.top_p<1&&K.push(new T.TopPLogitsWarper(E.top_p)),K}_get_logits_processor(E,K,Pe=null){const De=new T.LogitsProcessorList;if(E.repetition_penalty!==null&&E.repetition_penalty!==1&&De.push(new T.RepetitionPenaltyLogitsProcessor(E.repetition_penalty)),E.no_repeat_ngram_size!==null&&E.no_repeat_ngram_size>0&&De.push(new T.NoRepeatNGramLogitsProcessor(E.no_repeat_ngram_size)),E.bad_words_ids!==null&&De.push(new T.NoBadWordsLogitsProcessor(E.bad_words_ids,E.eos_token_id)),E.min_length!==null&&E.eos_token_id!==null&&E.min_length>0&&De.push(new T.MinLengthLogitsProcessor(E.min_length,E.eos_token_id)),E.min_new_tokens!==null&&E.eos_token_id!==null&&E.min_new_tokens>0&&De.push(new T.MinNewTokensLengthLogitsProcessor(K,E.min_new_tokens,E.eos_token_id)),E.forced_bos_token_id!==null&&De.push(new T.ForcedBOSTokenLogitsProcessor(E.forced_bos_token_id)),E.forced_eos_token_id!==null&&De.push(new T.ForcedEOSTokenLogitsProcessor(E.max_length,E.forced_eos_token_id)),E.begin_suppress_tokens!==null){const at=K>1||E.forced_bos_token_id===null?K:K+1;De.push(new T.SuppressTokensAtBeginLogitsProcessor(E.begin_suppress_tokens,at))}return E.guidance_scale!==null&&E.guidance_scale>1&&De.push(new T.ClassifierFreeGuidanceLogitsProcessor(E.guidance_scale)),Pe!==null&&De.extend(Pe),De}_prepare_generation_config(E,K,Pe=j.GenerationConfig){const De={...this.config};for(const $t of["decoder","generator","text_config"])$t in De&&Object.assign(De,De[$t]);const at=new Pe(De);return"generation_config"in this&&Object.assign(at,this.generation_config),E&&Object.assign(at,E),K&&Object.assign(at,(0,xe.pick)(K,Object.getOwnPropertyNames(at))),at}_get_stopping_criteria(E,K=null){const Pe=new te.StoppingCriteriaList;return E.max_length!==null&&Pe.push(new te.MaxLengthCriteria(E.max_length,this.config.max_position_embeddings??null)),E.eos_token_id!==null&&Pe.push(new te.EosTokenCriteria(E.eos_token_id)),K&&Pe.extend(K),Pe}_validate_model_class(){if(!this.can_generate){const E=[ai,ba,ya,ii],K=N.get(this.constructor),Pe=new Set,De=this.config.model_type;for(const $t of E){const Vt=$t.get(De);Vt&&Pe.add(Vt[0])}let at=`The current model class (${K}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Pe.size>0&&(at+=` Please use the following class instead: ${[...Pe].join(", ")}`),Error(at)}}prepare_inputs_for_generation(...E){return this._prepare_inputs_for_generation(this,...E)}_update_model_kwargs_for_generation({generated_input_ids:E,outputs:K,model_inputs:Pe,is_encoder_decoder:De}){return Pe.past_key_values=this.getPastKeyValues(K,Pe.past_key_values),Pe.input_ids=new P.Tensor("int64",E.flat(),[E.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:E,bos_token_id:K,model_kwargs:Pe}){const De=(0,xe.pick)(Pe,this.forward_params),at=this.main_input_name;if(at in De){if(E)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[at]=E;return{inputs_tensor:De[at],model_inputs:De,model_input_name:at}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:E,model_inputs:K,model_input_name:Pe,generation_config:De}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!K.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:$t,pixel_values:Vt,attention_mask:lr,...ar}=K,Er=await this._prepare_inputs_embeds(K);K={...ar,...(0,xe.pick)(Er,["inputs_embeds","attention_mask"])}}let{last_hidden_state:at}=await tt(this,K);if(De.guidance_scale!==null&&De.guidance_scale>1)at=(0,P.cat)([at,(0,P.full_like)(at,0)],0),"attention_mask"in K&&(K.attention_mask=(0,P.cat)([K.attention_mask,(0,P.zeros_like)(K.attention_mask)],0));else if(K.decoder_input_ids){const $t=Ce(K.decoder_input_ids).dims[0];if($t!==at.dims[0]){if(at.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${at.dims[0]}) than the decoder inputs (${$t}).`);at=(0,P.cat)(Array.from({length:$t},()=>at),0)}}return K.encoder_outputs=at,K}_prepare_decoder_input_ids_for_generation({batch_size:E,model_input_name:K,model_kwargs:Pe,decoder_start_token_id:De,bos_token_id:at,generation_config:$t}){let{decoder_input_ids:Vt,...lr}=Pe;if(Vt)Array.isArray(Vt[0])||(Vt=Array.from({length:E},()=>Vt));else if(De??(De=at),this.config.model_type==="musicgen")Vt=Array.from({length:E*this.config.decoder.num_codebooks},()=>[De]);else if(Array.isArray(De)){if(De.length!==E)throw new Error(`\`decoder_start_token_id\` expcted to have length ${E} but got ${De.length}`);Vt=De}else Vt=Array.from({length:E},()=>[De]);return Vt=Ce(Vt),Pe.decoder_attention_mask=(0,P.ones_like)(Vt),{input_ids:Vt,model_inputs:lr}}async generate({inputs:E=null,generation_config:K=null,logits_processor:Pe=null,stopping_criteria:De=null,streamer:at=null,...$t}){this._validate_model_class(),K=this._prepare_generation_config(K,$t);let{inputs_tensor:Vt,model_inputs:lr,model_input_name:ar}=this._prepare_model_inputs({inputs:E,model_kwargs:$t});const Er=this.config.is_encoder_decoder;Er&&("encoder_outputs"in lr||(lr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Vt,model_inputs:lr,model_input_name:ar,generation_config:K})));let ur;Er?{input_ids:ur,model_inputs:lr}=this._prepare_decoder_input_ids_for_generation({batch_size:lr[ar].dims.at(0),model_input_name:ar,model_kwargs:lr,decoder_start_token_id:K.decoder_start_token_id,bos_token_id:K.bos_token_id,generation_config:K}):ur=lr[ar];let mr=ur.dims.at(-1);K.max_new_tokens!==null&&(K.max_length=mr+K.max_new_tokens);const dr=this._get_logits_processor(K,mr,Pe),pr=this._get_stopping_criteria(K,De),yr=lr[ar].dims.at(0),Or=ne.LogitsSampler.getSampler(K),un=new Array(yr).fill(0),pn=ur.tolist();at&&at.put(pn);let Rn=null,nn={};for(;;){lr=this.prepare_inputs_for_generation(pn,lr,K);const sn=await this.forward(lr);if(K.output_attentions&&K.return_dict_in_generate){const An=this.getAttentions(sn);for(const Is in An)Is in nn||(nn[Is]=[]),nn[Is].push(An[Is])}const oi=sn.logits.slice(null,-1,null),li=dr(pn,oi),$a=[];for(let An=0;AnAn)){K.return_dict_in_generate&&(Rn=this.getPastKeyValues(sn,lr.past_key_values,!1));break}lr=this._update_model_kwargs_for_generation({generated_input_ids:$a,outputs:sn,model_inputs:lr,is_encoder_decoder:Er})}at&&at.end();const Kr=new P.Tensor("int64",pn.flat(),[pn.length,pn[0].length]);return K.return_dict_in_generate?{sequences:Kr,past_key_values:Rn,...nn}:Kr}getPastKeyValues(E,K,Pe=!0){const De=Object.create(null);for(const at in E)if(at.startsWith("present")){const $t=at.replace("present","past_key_values");if(K&&at.includes("encoder"))De[$t]=K[$t];else{if(Pe&&K){const Vt=K[$t];Vt.location==="gpu-buffer"&&Vt.dispose()}De[$t]=E[at]}}return De}getAttentions(E){const K={};for(const Pe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const De in E)De.startsWith(Pe)&&(Pe in K||(K[Pe]=[]),K[Pe].push(E[De]));return K}addPastKeyValues(E,K){if(K)Object.assign(E,K);else{const Pe=this.custom_config.kv_cache_dtype??"float32",De=Pe==="float16"?new Uint16Array:[],at=(0,x.getKeyValueShapes)(this.config);for(const $t in at)E[$t]=new P.Tensor(Pe,De,at[$t])}}async encode_image({pixel_values:E}){const K=(await _e(this.sessions.vision_encoder,{pixel_values:E})).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 (${K.dims[1]}).`),this.config.num_image_tokens=K.dims[1]),K}async encode_text({input_ids:E}){return(await _e(this.sessions.embed_tokens,{input_ids:E})).inputs_embeds}}class He{}class pt extends He{constructor({last_hidden_state:g,hidden_states:E=null,attentions:K=null}){super(),this.last_hidden_state=g,this.hidden_states=E,this.attentions=K}}class rt extends ee{}class lt extends rt{}class Re extends rt{async _call(g){return new tn(await super._call(g))}}class st extends rt{async _call(g){return new or(await super._call(g))}}class Tt extends rt{async _call(g){return new Qr(await super._call(g))}}class ze extends rt{async _call(g){return new rn(await super._call(g))}}class re extends ee{}class Ee extends re{}class je extends ee{}class Ge extends je{}class Ve extends je{async _call(g){return new tn(await super._call(g))}}class Ke extends je{async _call(g){return new or(await super._call(g))}}class ut extends je{async _call(g){return new Qr(await super._call(g))}}class mt extends je{async _call(g){return new rn(await super._call(g))}}class wt extends ee{}class xt extends wt{}class M extends wt{async _call(g){return new tn(await super._call(g))}}class W extends wt{async _call(g){return new or(await super._call(g))}}class S extends wt{async _call(g){return new Qr(await super._call(g))}}class X extends wt{async _call(g){return new rn(await super._call(g))}}class fe extends ee{}class Ye extends fe{}class Je extends fe{async _call(g){return new tn(await super._call(g))}}class At extends fe{async _call(g){return new or(await super._call(g))}}class _t extends fe{async _call(g){return new Qr(await super._call(g))}}class Se extends fe{async _call(g){return new rn(await super._call(g))}}class $ extends ee{}class q extends ${}class be extends ${async _call(g){return new tn(await super._call(g))}}class Be extends ${async _call(g){return new or(await super._call(g))}}class Ae extends ${async _call(g){return new Qr(await super._call(g))}}class Ne extends ${async _call(g){return new rn(await super._call(g))}}class dt extends ee{}class nt extends dt{}class vt extends dt{async _call(g){return new tn(await super._call(g))}}class ft extends dt{async _call(g){return new or(await super._call(g))}}class Ct extends dt{async _call(g){return new Qr(await super._call(g))}}class Lt extends dt{async _call(g){return new rn(await super._call(g))}}class Xe extends ee{}class jt extends Xe{}class Rt extends Xe{async _call(g){return new tn(await super._call(g))}}class Ht extends Xe{async _call(g){return new or(await super._call(g))}}class Xt extends Xe{async _call(g){return new Qr(await super._call(g))}}class er extends Xe{async _call(g){return new rn(await super._call(g))}}class Wt extends ee{}class Tr extends Wt{}class Ur extends Wt{async _call(g){return new or(await super._call(g))}}class Cr extends Wt{async _call(g){return new Qr(await super._call(g))}}class Ze extends Wt{async _call(g){return new rn(await super._call(g))}}class St extends Wt{async _call(g){return new tn(await super._call(g))}}class Dt extends ee{}class qr extends Dt{}class Un extends Dt{async _call(g){return new tn(await super._call(g))}}class Fn extends Dt{async _call(g){return new or(await super._call(g))}}class Lr extends Dt{async _call(g){return new Qr(await super._call(g))}}class Zr extends ee{}class Nr extends Zr{}class Sn extends Zr{async _call(g){return new tn(await super._call(g))}}class Pr extends Zr{async _call(g){return new or(await super._call(g))}}class Wn extends Zr{async _call(g){return new rn(await super._call(g))}}class On extends ee{}class Vs extends On{}class _s extends On{async _call(g){return new tn(await super._call(g))}}class gs extends On{async _call(g){return new or(await super._call(g))}}class ws extends On{async _call(g){return new Qr(await super._call(g))}}class ys extends On{async _call(g){return new rn(await super._call(g))}}class Gn extends ee{}class Us extends Gn{}class ss extends Gn{async _call(g){return new tn(await super._call(g))}}class kn extends Gn{async _call(g){return new or(await super._call(g))}}class zn extends Gn{async _call(g){return new rn(await super._call(g))}}class Dn extends ee{}class Qn extends Dn{}class is extends Dn{async _call(g){return new or(await super._call(g))}}class as extends Dn{async _call(g){return new rn(await super._call(g))}}class Qt extends Dn{async _call(g){return new tn(await super._call(g))}}class Yn extends ee{constructor(E,K,Pe){super(E,K);Te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Pe}}class bs extends Yn{}class Ms extends Yn{}class os extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class vs extends os{}class xs extends os{}class ls extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Ts extends ls{}class Dr extends ls{}class mn extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Me extends mn{}class _ extends mn{}class O extends mn{async _call(g){return new or(await super._call(g))}}class Q extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class ue extends Q{}class de extends Q{}class Fe extends Q{async _call(g){return new or(await super._call(g))}}class gt extends Q{}class bt extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class yt extends bt{}class Pt extends bt{}class Jt extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class $r extends Jt{}class nr extends Jt{}class Gt extends ee{}class fr extends Gt{}class on extends Gt{async _call(g){return new tn(await super._call(g))}}class Yr extends Gt{async _call(g){return new or(await super._call(g))}}class qe extends Gt{async _call(g){return new Qr(await super._call(g))}}class yn extends Gt{async _call(g){return new rn(await super._call(g))}}class Mr extends ee{}class Hr extends Mr{}class cn extends Mr{async _call(g){return new tn(await super._call(g))}}class Yt extends Mr{async _call(g){return new or(await super._call(g))}}class _n extends Mr{async _call(g){return new Qr(await super._call(g))}}class Jr extends Mr{async _call(g){return new rn(await super._call(g))}}class vr extends ee{}class xr extends vr{}class kt extends vr{async _call(g){return new tn(await super._call(g))}}class gr extends vr{async _call(g){return new or(await super._call(g))}}class Ar extends vr{async _call(g){return new Qr(await super._call(g))}}class jr extends vr{async _call(g){return new rn(await super._call(g))}}class gn extends ee{}class Ft extends gn{}class Ws extends gn{}class it extends ee{constructor(E,K,Pe){super(E,K);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 Ut extends it{}class fi extends it{_prepare_generation_config(g,E){return super._prepare_generation_config(g,E,R.WhisperGenerationConfig)}_retrieve_init_tokens(g){const E=[g.decoder_start_token_id];let K=g.language;const Pe=g.task;if(g.is_multilingual){K||(console.warn("No language specified - defaulting to English (en)."),K="en");const at=`<|${(0,Y.whisper_language_to_code)(K)}|>`;E.push(g.lang_to_id[at]),E.push(g.task_to_id[Pe??"transcribe"])}else if(K||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&&E.at(-1)!==g.no_timestamps_token_id?E.push(g.no_timestamps_token_id):g.return_timestamps&&E.at(-1)===g.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),E.pop()),E.filter(De=>De!=null)}async generate({inputs:g=null,generation_config:E=null,logits_processor:K=null,stopping_criteria:Pe=null,...De}){E=this._prepare_generation_config(E,De);const at=De.decoder_input_ids??this._retrieve_init_tokens(E);if(E.return_timestamps&&(K??(K=new T.LogitsProcessorList),K.push(new T.WhisperTimeStampLogitsProcessor(E,at))),E.begin_suppress_tokens&&(K??(K=new T.LogitsProcessorList),K.push(new T.SuppressTokensAtBeginLogitsProcessor(E.begin_suppress_tokens,at.length))),E.return_token_timestamps){if(!E.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.");E.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),E.output_attentions=!0,E.return_dict_in_generate=!0}const $t=await super.generate({inputs:g,generation_config:E,logits_processor:K,decoder_input_ids:at,...De});return E.return_token_timestamps&&($t.token_timestamps=this._extract_token_timestamps($t,E.alignment_heads,E.num_frames)),$t}_extract_token_timestamps(g,E,K=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`.");K==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 at=g.cross_attentions,$t=Array.from({length:this.config.decoder_layers},(pr,yr)=>(0,P.cat)(at.map(Or=>Or[yr]),2)),Vt=(0,P.stack)(E.map(([pr,yr])=>{if(pr>=$t.length)throw new Error(`Layer index ${pr} is out of bounds for cross attentions (length ${$t.length}).`);return K?$t[pr].slice(null,yr,null,[0,K]):$t[pr].slice(null,yr)})).transpose(1,0,2,3),[lr,ar]=(0,P.std_mean)(Vt,-2,0,!0),Er=Vt.clone();for(let pr=0;prOr[sn+1]-Or[sn]),Rn=(0,xe.mergeArrays)([1],pn).map(Kr=>!!Kr),nn=[];for(let Kr=0;Krur.findIndex(mr=>mr==De)),Vt=$t.every(ur=>ur===-1),lr=$t.every(ur=>ur!==-1);if(!Vt&&!lr)throw new Error("Every input should contain either 0 or 1 image token.");if(Vt)return{inputs_embeds:g,attention_mask:Pe};const ar=[],Er=[];for(let ur=0;ur<$t.length;++ur){const mr=$t[ur],dr=g[ur],pr=E[ur],yr=Pe[ur];ar.push((0,P.cat)([dr.slice([0,mr]),pr,dr.slice([mr+1,dr.dims[0]])],0)),Er.push((0,P.cat)([yr.slice([0,mr]),(0,P.ones)([pr.dims[0]]),yr.slice([mr+1,yr.dims[0]])],0))}return{inputs_embeds:(0,P.stack)(ar,0),attention_mask:(0,P.stack)(Er,0)}}}class ir extends us{}class Fa extends ee{constructor(E,K,Pe){super(E,K);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 _i extends Fa{_merge_input_ids_with_image_features({inputs_embeds:g,image_features:E,input_ids:K,attention_mask:Pe}){return{inputs_embeds:(0,P.cat)([E,g],1),attention_mask:(0,P.cat)([(0,P.ones)(E.dims.slice(0,2)),Pe],1)}}async _prepare_inputs_embeds({input_ids:g,pixel_values:E,inputs_embeds:K,attention_mask:Pe}){if(!g&&!E)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let De,at;return g&&(De=await this.encode_text({input_ids:g})),E&&(at=await this.encode_image({pixel_values:E})),De&&at?{inputs_embeds:K,attention_mask:Pe}=this._merge_input_ids_with_image_features({inputs_embeds:De,image_features:at,input_ids:g,attention_mask:Pe}):K=De||at,{inputs_embeds:K,attention_mask:Pe}}async forward({input_ids:g,pixel_values:E,attention_mask:K,decoder_input_ids:Pe,decoder_attention_mask:De,encoder_outputs:at,past_key_values:$t,inputs_embeds:Vt,decoder_inputs_embeds:lr}){if(Vt||({inputs_embeds:Vt,attention_mask:K}=await this._prepare_inputs_embeds({input_ids:g,pixel_values:E,inputs_embeds:Vt,attention_mask:K})),!at){let{last_hidden_state:ur}=await tt(this,{inputs_embeds:Vt,attention_mask:K});at=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 Qe(this,{inputs_embeds:lr,attention_mask:De,encoder_attention_mask:K,encoder_hidden_states:at,past_key_values:$t},!0)}}class Cs extends ee{}class Oa extends Cs{}class Pn extends Cs{static async from_pretrained(g,E={}){return E.model_file_name??(E.model_file_name="text_model"),super.from_pretrained(g,E)}}class za extends Cs{static async from_pretrained(g,E={}){return E.model_file_name??(E.model_file_name="vision_model"),super.from_pretrained(g,E)}}class gi extends ee{}class ds extends gi{}class Da extends gi{static async from_pretrained(g,E={}){return E.model_file_name??(E.model_file_name="text_model"),super.from_pretrained(g,E)}}class Ba extends Cs{static async from_pretrained(g,E={}){return E.model_file_name??(E.model_file_name="vision_model"),super.from_pretrained(g,E)}}class La extends ee{}class Ra extends La{}class wi extends ee{}class Na extends wi{}class ja extends wi{}class yi extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Va extends yi{}class Ua extends yi{}class bn extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Wa extends bn{}class Ga extends bn{}class bi extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class qa extends bi{}class Ha extends bi{}class Mi extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Ka extends Mi{}class Xa extends Mi{}class vi extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Qa extends vi{}class zu extends vi{}class Mn extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Ya extends Mn{}class Gs extends Mn{}class qs extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Cn extends qs{}class Za extends qs{}class xi extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Ja extends xi{}class eo extends xi{}class Ti extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class to extends Ti{}class ro extends Ti{}class Ci extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class no extends Ci{}class so extends Ci{}class vn extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class io extends vn{}class ao extends vn{}class $i extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class oo extends $i{}class lo extends $i{}class Ei extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class uo extends Ei{}class co extends Ei{}class Si extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class po extends Si{}class ki extends Si{}class Hs extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class ho extends Hs{}class fo extends Hs{}class Ks extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Du extends Ks{}class mo extends Ks{}class Pi extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class _o extends Pi{}class go extends Pi{}class cs extends ee{}class wo extends cs{}class yo extends cs{async _call(g){return new or(await super._call(g))}}class Xs extends ee{}class bo extends Xs{}class Mo extends Xs{async _call(g){return new or(await super._call(g))}}class vo extends ee{}class xo extends vo{async _call(g){return new Eu(await super._call(g))}}class To extends ee{}class Co extends To{}class $o extends To{async _call(g){return new or(await super._call(g))}}class Ai extends ee{}class Bu extends Ai{}class Eo extends Ai{async _call(g){return new or(await super._call(g))}}class wr extends ee{}class So extends wr{}class ko extends wr{}class Ii extends ee{}class Po extends Ii{}class Ao extends Ii{}class Fi extends ee{}class Io extends Fi{}class Fo extends Fi{async _call(g){return new or(await super._call(g))}}class Qs extends ee{}class Oo extends Qs{}class zo extends Qs{async _call(g){return new Oi(await super._call(g))}}class Do extends Qs{async _call(g){return new Bo(await super._call(g))}}class Oi extends He{constructor({logits:g,pred_boxes:E}){super(),this.logits=g,this.pred_boxes=E}}class Bo extends He{constructor({logits:g,pred_boxes:E,pred_masks:K}){super(),this.logits=g,this.pred_boxes=E,this.pred_masks=K}}class ps extends ee{}class Lo extends ps{}class Ys extends ps{async _call(g){return new Ro(await super._call(g))}}class Ro extends He{constructor({logits:g,pred_boxes:E}){super(),this.logits=g,this.pred_boxes=E}}class zi extends ee{}class No extends zi{}class jo extends zi{async _call(g){return new Vo(await super._call(g))}}class Vo extends Oi{}class Di extends ee{}class Uo extends Di{}class Wo extends Di{async _call(g){return new or(await super._call(g))}}class Bi extends ee{}class Go extends Bi{}class qo extends Bi{async _call(g){return new or(await super._call(g))}}class Li extends ee{}class Ho extends Li{}class Ko extends Li{async _call(g){return new or(await super._call(g))}}class Ri extends ee{}class Xo extends Ri{}class Ni extends Ri{}class ji extends ee{}class Vi extends ji{}class Ui extends ji{}class Qo extends ee{}class Yo extends Qo{}class Wi extends ee{}class Zo extends Wi{}class Jo extends Wi{}class el extends ee{}class Gi extends el{}class qi extends ee{}class tl extends qi{}class rl extends qi{async _call(g){return new or(await super._call(g))}}class nl extends ee{}class sl extends nl{}class il extends nl{async _call(g){return new or(await super._call(g))}}class xn extends ee{}class al extends xn{}class ol extends xn{async _call(g){return new or(await super._call(g))}}class Hi extends ee{}class ll extends Hi{}class ul extends Hi{async _call(g){return new dl(await super._call(g))}}class dl extends He{constructor({logits:g,pred_boxes:E}){super(),this.logits=g,this.pred_boxes=E}}class cl extends ee{}class pl extends cl{async get_image_embeddings({pixel_values:g}){return await tt(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 K=g.input_points.dims.slice(0,-1),Pe=K.reduce((De,at)=>De*at,1);g.input_labels=new P.Tensor("int64",new BigInt64Array(Pe).fill(1n),K)}const E={image_embeddings:g.image_embeddings,image_positional_embeddings:g.image_positional_embeddings};return g.input_points&&(E.input_points=g.input_points),g.input_labels&&(E.input_labels=g.input_labels),g.input_boxes&&(E.input_boxes=g.input_boxes),await _e(this.sessions.prompt_encoder_mask_decoder,E)}async _call(g){return new hl(await super._call(g))}}class hl extends He{constructor({iou_scores:g,pred_masks:E}){super(),this.iou_scores=g,this.pred_masks=E}}class Ki extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Lu extends Ki{}class fl extends Ki{}class Xi extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class ml extends Xi{}class _l extends Xi{}class qn extends ee{}class gl extends qn{}class Ru extends qn{async _call(g){return new Zn(await super._call(g))}}class Hn extends qn{async _call(g){return new or(await super._call(g))}}class Kn extends qn{async _call(g){return new Qr(await super._call(g))}}class Bn extends ee{}class Qi extends Bn{}class Xn extends Bn{async _call(g){return new Qr(await super._call(g))}}class en extends ee{}class Yi extends en{}class hs extends ee{}class Zi extends hs{}class wl extends hs{async _call(g){return new Zn(await super._call(g))}}class yl extends hs{async _call(g){return new or(await super._call(g))}}class $s extends ee{}class Zs extends $s{}class Ji extends $s{async _call(g){return new Zn(await super._call(g))}}class bl extends $s{async _call(g){return new or(await super._call(g))}}class Js extends $s{async _call(g){return new Qr(await super._call(g))}}class ei extends ee{}class ea extends ei{}class ti extends ei{async _call(g){return new Zn(await super._call(g))}}class Ml extends ei{async _call(g){return new or(await super._call(g))}}class Nu extends ee{}class ju extends qn{}class vl extends qn{async _call(g){return new Zn(await super._call(g))}}class ta extends qn{async _call(g){return new or(await super._call(g))}}class Ln extends ee{}class xl extends Ln{}class ra extends Ln{async _call(g){return new Zn(await super._call(g))}}class Tl extends Ln{async _call(g){return new or(await super._call(g))}}class Cl extends Ln{async _call(g){return new $u(await super._call(g))}}class $l extends Ln{async _call(g){return new Qr(await super._call(g))}}class na extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class El extends na{}class Sl extends na{}class Vu extends na{async generate_speech(g,E,{threshold:K=.5,minlenratio:Pe=0,maxlenratio:De=20,vocoder:at=null}={}){const $t={input_ids:g},{encoder_outputs:Vt,encoder_attention_mask:lr}=await tt(this,$t),ar=Vt.dims[1]/this.config.reduction_factor,Er=Math.floor(ar*De),ur=Math.floor(ar*Pe),mr=this.config.num_mel_bins;let dr=[],pr=null,yr=null,Or=0;for(;;){++Or;const Rn=ke(!!yr);let nn;yr?nn=yr.output_sequence_out:nn=new P.Tensor("float32",new Float32Array(mr),[1,1,mr]);let Kr={use_cache_branch:Rn,output_sequence:nn,encoder_attention_mask:lr,speaker_embeddings:E,encoder_hidden_states:Vt};this.addPastKeyValues(Kr,pr),yr=await _e(this.sessions.decoder_model_merged,Kr),pr=this.getPastKeyValues(yr,pr);const{prob:sn,spectrum:oi}=yr;if(dr.push(oi),Or>=ur&&(Array.from(sn.data).filter(li=>li>=K).length>0||Or>=Er))break}const un=(0,P.cat)(dr),{waveform:pn}=await _e(at.sessions.model,{spectrogram:un});return{spectrogram:un,waveform:pn}}}class sa extends ee{constructor(){super(...arguments);Te(this,"main_input_name","spectrogram")}}class kl extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Pl extends kl{}class ia extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class ri extends ia{}class ni extends ia{}class aa extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class si extends aa{}class oa extends aa{}class la extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class Al extends la{}class Il extends la{}class Es extends ee{}class Fl extends Es{}class Ol extends Es{static async from_pretrained(g,E={}){return E.model_file_name??(E.model_file_name="text_model"),super.from_pretrained(g,E)}}class zl extends Es{static async from_pretrained(g,E={}){return E.model_file_name??(E.model_file_name="audio_model"),super.from_pretrained(g,E)}}class Uu extends ee{}class ua extends Uu{async _call(g){return new sd(await super._call(g))}}class Ss extends ee{}class kd extends Ss{}class Dl extends Ss{}class Bl extends Ss{}class da extends ee{constructor(g,E,K){super(g,E),this.generation_config=K}}class ca extends da{}class Ll extends da{}class pa extends ee{}class Rl extends pa{}class Nl extends pa{async _call(g){return new or(await super._call(g))}}class ha extends ee{}class Wu extends ha{}class Pd extends ha{}class fa extends ee{constructor(E,K,Pe){super(E,K);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(E){const[K,Pe]=E.dims,De=this.config.decoder.num_codebooks,at=Pe-De;let $t=0;for(let ar=0;ar0&&mr<=at&&(E.data[$t++]=E.data[ar])}const Vt=Math.floor(K/De),lr=$t/(Vt*De);return new P.Tensor(E.type,E.data.slice(0,$t),[Vt,De,lr])}prepare_inputs_for_generation(E,K,Pe){let De=structuredClone(E);for(let $t=0;$t=Vt&&(De[$t][Vt]=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,K,Pe)}async generate(E){const K=await super.generate(E),Pe=this._apply_and_filter_by_delay_pattern_mask(K).unsqueeze_(0),{audio_values:De}=await _e(this.sessions.encodec_decode,{audio_codes:Pe});return De}}class ma extends ee{}class jl extends ma{}class Gu extends ma{async _call(g){return new or(await super._call(g))}}class _a extends ee{}class Vl extends _a{}class Ul extends _a{async _call(g){return new or(await super._call(g))}}class ga extends ee{}class Wl extends ga{}class qu extends ga{async _call(g){return new or(await super._call(g))}}class ks extends ee{}class Ps extends ks{}class wa extends ks{async _call(g){return new or(await super._call(g))}}class Ir{static async from_pretrained(g,{progress_callback:E=null,config:K=null,cache_dir:Pe=null,local_files_only:De=!1,revision:at="main",model_file_name:$t=null,subfolder:Vt="onnx",device:lr=null,dtype:ar=null,use_external_data_format:Er=null,session_options:ur={}}={}){let mr={progress_callback:E,config:K,cache_dir:Pe,local_files_only:De,revision:at,model_file_name:$t,subfolder:Vt,device:lr,dtype:ar,use_external_data_format:Er,session_options:ur};if(mr.config=await x.AutoConfig.from_pretrained(g,mr),!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 pr=dr.get(mr.config.model_type);if(pr)return await pr[1].from_pretrained(g,mr)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${mr.config.model_type}", attempting to construct from base class.`),await ee.from_pretrained(g,mr);throw Error(`Unsupported model type: ${mr.config.model_type}`)}}Te(Ir,"MODEL_CLASS_MAPPINGS",null),Te(Ir,"BASE_IF_FAIL",!1);const Hu=new Map([["bert",["BertModel",lt]],["nomic_bert",["NomicBertModel",Ee]],["roformer",["RoFormerModel",Ge]],["electra",["ElectraModel",Ye]],["esm",["EsmModel",qr]],["convbert",["ConvBertModel",xt]],["camembert",["CamembertModel",q]],["deberta",["DebertaModel",nt]],["deberta-v2",["DebertaV2Model",jt]],["mpnet",["MPNetModel",Vs]],["albert",["AlbertModel",Qn]],["distilbert",["DistilBertModel",Tr]],["roberta",["RobertaModel",fr]],["xlm",["XLMModel",Hr]],["xlm-roberta",["XLMRobertaModel",xr]],["clap",["ClapModel",Fl]],["clip",["CLIPModel",Oa]],["clipseg",["CLIPSegModel",Na]],["chinese_clip",["ChineseCLIPModel",Ra]],["siglip",["SiglipModel",ds]],["mobilebert",["MobileBertModel",Nr]],["squeezebert",["SqueezeBertModel",Us]],["wav2vec2",["Wav2Vec2Model",gl]],["wav2vec2-bert",["Wav2Vec2BertModel",ea]],["unispeech",["UniSpeechModel",Zi]],["unispeech-sat",["UniSpeechSatModel",Zs]],["hubert",["HubertModel",ju]],["wavlm",["WavLMModel",xl]],["audio-spectrogram-transformer",["ASTModel",Ft]],["vits",["VitsModel",ua]],["pyannote",["PyAnnoteModel",Qi]],["wespeaker-resnet",["WeSpeakerResNetModel",Yi]],["detr",["DetrModel",Oo]],["rt_detr",["RTDetrModel",Lo]],["table-transformer",["TableTransformerModel",No]],["vit",["ViTModel",wo]],["fastvit",["FastViTModel",bo]],["mobilevit",["MobileViTModel",Co]],["mobilevitv2",["MobileViTV2Model",Bu]],["owlvit",["OwlViTModel",So]],["owlv2",["Owlv2Model",Po]],["beit",["BeitModel",Io]],["deit",["DeiTModel",Uo]],["convnext",["ConvNextModel",tl]],["convnextv2",["ConvNextV2Model",sl]],["dinov2",["Dinov2Model",al]],["resnet",["ResNetModel",Go]],["swin",["SwinModel",Ho]],["swin2sr",["Swin2SRModel",Xo]],["donut-swin",["DonutSwinModel",Gi]],["yolos",["YolosModel",ll]],["dpt",["DPTModel",Vi]],["glpn",["GLPNModel",Zo]],["hifigan",["SpeechT5HifiGan",sa]],["efficientnet",["EfficientNetModel",Rl]],["mobilenet_v1",["MobileNetV1Model",jl]],["mobilenet_v2",["MobileNetV2Model",Vl]],["mobilenet_v3",["MobileNetV3Model",Wl]],["mobilenet_v4",["MobileNetV4Model",Ps]]]),Ku=new Map([["t5",["T5Model",bs]],["longt5",["LongT5Model",vs]],["mt5",["MT5Model",Ts]],["bart",["BartModel",Me]],["mbart",["MBartModel",ue]],["marian",["MarianModel",Lu]],["whisper",["WhisperModel",Ut]],["m2m_100",["M2M100Model",ml]],["blenderbot",["BlenderbotModel",yt]],["blenderbot-small",["BlenderbotSmallModel",$r]]]),Xu=new Map([["bloom",["BloomModel",ho]],["gpt2",["GPT2Model",Va]],["gptj",["GPTJModel",Ka]],["gpt_bigcode",["GPTBigCodeModel",Qa]],["gpt_neo",["GPTNeoModel",Wa]],["gpt_neox",["GPTNeoXModel",qa]],["codegen",["CodeGenModel",Ya]],["llama",["LlamaModel",Cn]],["cohere",["CohereModel",Ja]],["gemma",["GemmaModel",to]],["gemma2",["Gemma2Model",no]],["openelm",["OpenELMModel",io]],["qwen2",["Qwen2Model",oo]],["phi",["PhiModel",uo]],["phi3",["Phi3Model",po]],["mpt",["MptModel",Du]],["opt",["OPTModel",_o]],["mistral",["MistralModel",ri]],["starcoder2",["Starcoder2Model",si]],["falcon",["FalconModel",Al]],["stablelm",["StableLmModel",ca]]]),ii=new Map([["speecht5",["SpeechT5ForSpeechToText",Sl]],["whisper",["WhisperForConditionalGeneration",fi]]]),Gl=new Map([["speecht5",["SpeechT5ForTextToSpeech",Vu]]]),ql=new Map([["vits",["VitsModel",ua]],["musicgen",["MusicgenForConditionalGeneration",fa]]]),Hl=new Map([["bert",["BertForSequenceClassification",st]],["roformer",["RoFormerForSequenceClassification",Ke]],["electra",["ElectraForSequenceClassification",At]],["esm",["EsmForSequenceClassification",Fn]],["convbert",["ConvBertForSequenceClassification",W]],["camembert",["CamembertForSequenceClassification",Be]],["deberta",["DebertaForSequenceClassification",ft]],["deberta-v2",["DebertaV2ForSequenceClassification",Ht]],["mpnet",["MPNetForSequenceClassification",gs]],["albert",["AlbertForSequenceClassification",is]],["distilbert",["DistilBertForSequenceClassification",Ur]],["roberta",["RobertaForSequenceClassification",Yr]],["xlm",["XLMForSequenceClassification",Yt]],["xlm-roberta",["XLMRobertaForSequenceClassification",gr]],["bart",["BartForSequenceClassification",O]],["mbart",["MBartForSequenceClassification",Fe]],["mobilebert",["MobileBertForSequenceClassification",Pr]],["squeezebert",["SqueezeBertForSequenceClassification",kn]]]),Qu=new Map([["bert",["BertForTokenClassification",Tt]],["roformer",["RoFormerForTokenClassification",ut]],["electra",["ElectraForTokenClassification",_t]],["esm",["EsmForTokenClassification",Lr]],["convbert",["ConvBertForTokenClassification",S]],["camembert",["CamembertForTokenClassification",Ae]],["deberta",["DebertaForTokenClassification",Ct]],["deberta-v2",["DebertaV2ForTokenClassification",Xt]],["mpnet",["MPNetForTokenClassification",ws]],["distilbert",["DistilBertForTokenClassification",Cr]],["roberta",["RobertaForTokenClassification",qe]],["xlm",["XLMForTokenClassification",_n]],["xlm-roberta",["XLMRobertaForTokenClassification",Ar]]]),ya=new Map([["t5",["T5ForConditionalGeneration",Ms]],["longt5",["LongT5ForConditionalGeneration",xs]],["mt5",["MT5ForConditionalGeneration",Dr]],["bart",["BartForConditionalGeneration",_]],["mbart",["MBartForConditionalGeneration",de]],["marian",["MarianMTModel",fl]],["m2m_100",["M2M100ForConditionalGeneration",_l]],["blenderbot",["BlenderbotForConditionalGeneration",Pt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",nr]]]),ai=new Map([["bloom",["BloomForCausalLM",fo]],["gpt2",["GPT2LMHeadModel",Ua]],["gptj",["GPTJForCausalLM",Xa]],["gpt_bigcode",["GPTBigCodeForCausalLM",zu]],["gpt_neo",["GPTNeoForCausalLM",Ga]],["gpt_neox",["GPTNeoXForCausalLM",Ha]],["codegen",["CodeGenForCausalLM",Gs]],["llama",["LlamaForCausalLM",Za]],["cohere",["CohereForCausalLM",eo]],["gemma",["GemmaForCausalLM",ro]],["gemma2",["Gemma2ForCausalLM",so]],["openelm",["OpenELMForCausalLM",ao]],["qwen2",["Qwen2ForCausalLM",lo]],["phi",["PhiForCausalLM",co]],["phi3",["Phi3ForCausalLM",ki]],["mpt",["MptForCausalLM",mo]],["opt",["OPTForCausalLM",go]],["mbart",["MBartForCausalLM",gt]],["mistral",["MistralForCausalLM",ni]],["starcoder2",["Starcoder2ForCausalLM",oa]],["falcon",["FalconForCausalLM",Il]],["trocr",["TrOCRForCausalLM",Pl]],["stablelm",["StableLmForCausalLM",Ll]]]),Kl=new Map([["bert",["BertForMaskedLM",Re]],["roformer",["RoFormerForMaskedLM",Ve]],["electra",["ElectraForMaskedLM",Je]],["esm",["EsmForMaskedLM",Un]],["convbert",["ConvBertForMaskedLM",M]],["camembert",["CamembertForMaskedLM",be]],["deberta",["DebertaForMaskedLM",vt]],["deberta-v2",["DebertaV2ForMaskedLM",Rt]],["mpnet",["MPNetForMaskedLM",_s]],["albert",["AlbertForMaskedLM",Qt]],["distilbert",["DistilBertForMaskedLM",St]],["roberta",["RobertaForMaskedLM",on]],["xlm",["XLMWithLMHeadModel",cn]],["xlm-roberta",["XLMRobertaForMaskedLM",kt]],["mobilebert",["MobileBertForMaskedLM",Sn]],["squeezebert",["SqueezeBertForMaskedLM",ss]]]),Xl=new Map([["bert",["BertForQuestionAnswering",ze]],["roformer",["RoFormerForQuestionAnswering",mt]],["electra",["ElectraForQuestionAnswering",Se]],["convbert",["ConvBertForQuestionAnswering",X]],["camembert",["CamembertForQuestionAnswering",Ne]],["deberta",["DebertaForQuestionAnswering",Lt]],["deberta-v2",["DebertaV2ForQuestionAnswering",er]],["mpnet",["MPNetForQuestionAnswering",ys]],["albert",["AlbertForQuestionAnswering",as]],["distilbert",["DistilBertForQuestionAnswering",Ze]],["roberta",["RobertaForQuestionAnswering",yn]],["xlm",["XLMForQuestionAnswering",Jr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",jr]],["mobilebert",["MobileBertForQuestionAnswering",Wn]],["squeezebert",["SqueezeBertForQuestionAnswering",zn]]]),ba=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",mi]]]),Ad=new Map([["llava",["LlavaForConditionalGeneration",us]],["moondream1",["Moondream1ForConditionalGeneration",ir]],["florence2",["Florence2ForConditionalGeneration",_i]]]),Yu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",mi]]]),Ql=new Map([["vit",["ViTForImageClassification",yo]],["fastvit",["FastViTForImageClassification",Mo]],["mobilevit",["MobileViTForImageClassification",$o]],["mobilevitv2",["MobileViTV2ForImageClassification",Eo]],["beit",["BeitForImageClassification",Fo]],["deit",["DeiTForImageClassification",Wo]],["convnext",["ConvNextForImageClassification",rl]],["convnextv2",["ConvNextV2ForImageClassification",il]],["dinov2",["Dinov2ForImageClassification",ol]],["resnet",["ResNetForImageClassification",qo]],["swin",["SwinForImageClassification",Ko]],["segformer",["SegformerForImageClassification",Dl]],["efficientnet",["EfficientNetForImageClassification",Nl]],["mobilenet_v1",["MobileNetV1ForImageClassification",Gu]],["mobilenet_v2",["MobileNetV2ForImageClassification",Ul]],["mobilenet_v3",["MobileNetV3ForImageClassification",qu]],["mobilenet_v4",["MobileNetV4ForImageClassification",wa]]]),Zu=new Map([["detr",["DetrForObjectDetection",zo]],["rt_detr",["RTDetrForObjectDetection",Ys]],["table-transformer",["TableTransformerForObjectDetection",jo]],["yolos",["YolosForObjectDetection",ul]]]),Yl=new Map([["owlvit",["OwlViTForObjectDetection",ko]],["owlv2",["Owlv2ForObjectDetection",Ao]]]),Zl=new Map([["detr",["DetrForSegmentation",Do]],["clipseg",["CLIPSegForImageSegmentation",ja]]]),Jl=new Map([["segformer",["SegformerForSemanticSegmentation",Bl]]]),eu=new Map([["sam",["SamModel",pl]]]),Ju=new Map([["wav2vec2",["Wav2Vec2ForCTC",Ru]],["wav2vec2-bert",["Wav2Vec2BertForCTC",ti]],["unispeech",["UniSpeechForCTC",wl]],["unispeech-sat",["UniSpeechSatForCTC",Ji]],["wavlm",["WavLMForCTC",ra]],["hubert",["HubertForCTC",vl]]]),tu=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Hn]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Ml]],["unispeech",["UniSpeechForSequenceClassification",yl]],["unispeech-sat",["UniSpeechSatForSequenceClassification",bl]],["wavlm",["WavLMForSequenceClassification",Tl]],["hubert",["HubertForSequenceClassification",ta]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ws]]]),ru=new Map([["wavlm",["WavLMForXVector",Cl]]]),nu=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Js]],["wavlm",["WavLMForAudioFrameClassification",$l]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Kn]],["pyannote",["PyAnnoteForAudioFrameClassification",Xn]]]),su=new Map([["vitmatte",["VitMatteForImageMatting",xo]]]),ed=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ni]]]),iu=new Map([["dpt",["DPTForDepthEstimation",Ui]],["depth_anything",["DepthAnythingForDepthEstimation",Yo]],["glpn",["GLPNForDepthEstimation",Jo]]]),au=new Map([["clip",["CLIPVisionModelWithProjection",za]],["siglip",["SiglipVisionModel",Ba]]]),ou=[[Hu,se.EncoderOnly],[Ku,se.EncoderDecoder],[Xu,se.DecoderOnly],[Hl,se.EncoderOnly],[Qu,se.EncoderOnly],[ya,se.Seq2Seq],[ii,se.Seq2Seq],[ai,se.DecoderOnly],[Kl,se.EncoderOnly],[Xl,se.EncoderOnly],[ba,se.Vision2Seq],[Ad,se.ImageTextToText],[Ql,se.EncoderOnly],[Zl,se.EncoderOnly],[Jl,se.EncoderOnly],[su,se.EncoderOnly],[ed,se.EncoderOnly],[iu,se.EncoderOnly],[Zu,se.EncoderOnly],[Yl,se.EncoderOnly],[eu,se.MaskGeneration],[Ju,se.EncoderOnly],[tu,se.EncoderOnly],[Gl,se.Seq2Seq],[ql,se.EncoderOnly],[ru,se.EncoderOnly],[nu,se.EncoderOnly],[au,se.EncoderOnly]];for(const[m,g]of ou)for(const[E,K]of m.values())le.set(E,g),N.set(K,E),ae.set(E,K);const td=[["MusicgenForConditionalGeneration",fa,se.Musicgen],["CLIPTextModelWithProjection",Pn,se.EncoderOnly],["SiglipTextModel",Da,se.EncoderOnly],["ClapTextModelWithProjection",Ol,se.EncoderOnly],["ClapAudioModelWithProjection",zl,se.EncoderOnly]];for(const[m,g,E]of td)le.set(m,E),N.set(g,m),ae.set(m,g);class lu extends Ir{}Te(lu,"MODEL_CLASS_MAPPINGS",ou.map(g=>g[0])),Te(lu,"BASE_IF_FAIL",!0);class ln extends Ir{}Te(ln,"MODEL_CLASS_MAPPINGS",[Hl]);class uu extends Ir{}Te(uu,"MODEL_CLASS_MAPPINGS",[Qu]);class du extends Ir{}Te(du,"MODEL_CLASS_MAPPINGS",[ya]);class Ma extends Ir{}Te(Ma,"MODEL_CLASS_MAPPINGS",[ii]);class cu extends Ir{}Te(cu,"MODEL_CLASS_MAPPINGS",[Gl]);class As extends Ir{}Te(As,"MODEL_CLASS_MAPPINGS",[ql]);class pu extends Ir{}Te(pu,"MODEL_CLASS_MAPPINGS",[ai]);class hu extends Ir{}Te(hu,"MODEL_CLASS_MAPPINGS",[Kl]);class va extends Ir{}Te(va,"MODEL_CLASS_MAPPINGS",[Xl]);class fu extends Ir{}Te(fu,"MODEL_CLASS_MAPPINGS",[ba]);class mu extends Ir{}Te(mu,"MODEL_CLASS_MAPPINGS",[Ql]);class xa extends Ir{}Te(xa,"MODEL_CLASS_MAPPINGS",[Zl]);class _u extends Ir{}Te(_u,"MODEL_CLASS_MAPPINGS",[Jl]);class gu extends Ir{}Te(gu,"MODEL_CLASS_MAPPINGS",[Zu]);class wu extends Ir{}Te(wu,"MODEL_CLASS_MAPPINGS",[Yl]);class Ta extends Ir{}Te(Ta,"MODEL_CLASS_MAPPINGS",[eu]);class yu extends Ir{}Te(yu,"MODEL_CLASS_MAPPINGS",[Ju]);class bu extends Ir{}Te(bu,"MODEL_CLASS_MAPPINGS",[tu]);class Ca extends Ir{}Te(Ca,"MODEL_CLASS_MAPPINGS",[ru]);class Mu extends Ir{}Te(Mu,"MODEL_CLASS_MAPPINGS",[nu]);class rd extends Ir{}Te(rd,"MODEL_CLASS_MAPPINGS",[Yu]);class vu extends Ir{}Te(vu,"MODEL_CLASS_MAPPINGS",[su]);class xu extends Ir{}Te(xu,"MODEL_CLASS_MAPPINGS",[ed]);class Tu extends Ir{}Te(Tu,"MODEL_CLASS_MAPPINGS",[iu]);class Cu extends Ir{}Te(Cu,"MODEL_CLASS_MAPPINGS",[au]);class Id extends He{constructor({logits:g,past_key_values:E,encoder_outputs:K,decoder_attentions:Pe=null,cross_attentions:De=null}){super(),this.logits=g,this.past_key_values=E,this.encoder_outputs=K,this.decoder_attentions=Pe,this.cross_attentions=De}}class or extends He{constructor({logits:g}){super(),this.logits=g}}class $u extends He{constructor({logits:g,embeddings:E}){super(),this.logits=g,this.embeddings=E}}class Qr extends He{constructor({logits:g}){super(),this.logits=g}}class tn extends He{constructor({logits:g}){super(),this.logits=g}}class rn extends He{constructor({start_logits:g,end_logits:E}){super(),this.start_logits=g,this.end_logits=E}}class Zn extends He{constructor({logits:g}){super(),this.logits=g}}class nd extends He{constructor({logits:g,past_key_values:E}){super(),this.logits=g,this.past_key_values=E}}class Eu extends He{constructor({alphas:g}){super(),this.alphas=g}}class sd extends He{constructor({waveform:g,spectrogram:E}){super(),this.waveform=g,this.spectrogram=E}}},"./src/models/whisper/common_whisper.js":(Mt,me,l)=>{l.r(me),l.d(me,{WHISPER_LANGUAGE_MAPPING:()=>H,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>ge,whisper_language_to_code:()=>ve});const x=[["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"]],H=new Map(x),ge=new Map([...x.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 ve(xe){xe=xe.toLowerCase();let D=ge.get(xe);if(D===void 0)if(H.has(xe))D=xe;else{const j=xe.length===2?H.keys():H.values();throw new Error(`Language "${xe}" is not supported. Must be one of: ${JSON.stringify(j)}`)}return D}},"./src/models/whisper/generation_whisper.js":(Mt,me,l)=>{l.r(me),l.d(me,{WhisperGenerationConfig:()=>H});var x=l("./src/generation/configuration_utils.js");class H extends x.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":(Mt,me,l)=>{l.r(me),l.d(me,{TensorOpRegistry:()=>ve});var x=l("./src/backends/onnx.js"),H=l("./src/utils/tensor.js");const ge=async(xe,D,T)=>{const j=await(0,x.createInferenceSession)(new Uint8Array(xe),D);return async P=>{const J=Object.fromEntries(Object.entries(P).map(([ne,ie])=>[ne,ie.ort_tensor])),te=await j.run(J);return Array.isArray(T)?T.map(ne=>new H.Tensor(te[ne])):new H.Tensor(te[T])}};class ve{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(ve,"session_options",{})},"./src/pipelines.js":(Mt,me,l)=>{l.r(me),l.d(me,{AudioClassificationPipeline:()=>ke,AutomaticSpeechRecognitionPipeline:()=>tt,DepthEstimationPipeline:()=>rt,DocumentQuestionAnsweringPipeline:()=>ee,FeatureExtractionPipeline:()=>ye,FillMaskPipeline:()=>le,ImageClassificationPipeline:()=>ht,ImageFeatureExtractionPipeline:()=>Ce,ImageSegmentationPipeline:()=>we,ImageToImagePipeline:()=>pt,ImageToTextPipeline:()=>Qe,ObjectDetectionPipeline:()=>he,Pipeline:()=>ie,QuestionAnsweringPipeline:()=>se,SummarizationPipeline:()=>N,Text2TextGenerationPipeline:()=>ae,TextClassificationPipeline:()=>R,TextGenerationPipeline:()=>A,TextToAudioPipeline:()=>He,TokenClassificationPipeline:()=>Y,TranslationPipeline:()=>I,ZeroShotAudioClassificationPipeline:()=>Ie,ZeroShotClassificationPipeline:()=>_e,ZeroShotImageClassificationPipeline:()=>V,ZeroShotObjectDetectionPipeline:()=>$e,pipeline:()=>st});var x=l("./src/tokenizers.js"),H=l("./src/models.js"),ge=l("./src/processors.js"),ve=l("./src/utils/generic.js"),xe=l("./src/utils/core.js"),D=l("./src/utils/maths.js"),T=l("./src/utils/audio.js"),j=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(Ee=>typeof Ee=="string"||Ee instanceof URL?(0,T.read_audio)(Ee,re):Ee instanceof Float64Array?new Float32Array(Ee):Ee))}function ne(ze,re){re&&(ze=ze.map(Ke=>Ke|0));const[Ee,je,Ge,Ve]=ze;return{xmin:Ee,ymin:je,xmax:Ge,ymax:Ve}}class ie extends ve.Callable{constructor({task:re,model:Ee,tokenizer:je=null,processor:Ge=null}){super(),this.task=re,this.model=Ee,this.tokenizer=je,this.processor=Ge}async dispose(){await this.model.dispose()}}class R extends ie{constructor(re){super(re)}async _call(re,{top_k:Ee=1}={}){const je=this.tokenizer(re,{padding:!0,truncation:!0}),Ge=await this.model(je),Ve=this.model.config.problem_type==="multi_label_classification"?mt=>mt.sigmoid():mt=>new j.Tensor("float32",(0,D.softmax)(mt.data),mt.dims),Ke=this.model.config.id2label,ut=[];for(const mt of Ge.logits){const wt=Ve(mt),xt=await(0,j.topk)(wt,Ee),M=xt[0].tolist(),S=xt[1].tolist().map((X,fe)=>({label:Ke?Ke[X]:`LABEL_${X}`,score:M[fe]}));Ee===1?ut.push(...S):ut.push(S)}return Array.isArray(re)||Ee===1?ut:ut[0]}}class Y extends ie{constructor(re){super(re)}async _call(re,{ignore_labels:Ee=["O"]}={}){const je=Array.isArray(re),Ge=this.tokenizer(je?re:[re],{padding:!0,truncation:!0}),Ke=(await this.model(Ge)).logits,ut=this.model.config.id2label,mt=[];for(let wt=0;wt_t==this.tokenizer.sep_token_id);mt[M].map((_t,Se)=>_t==1&&(Se===0||Se>S&&wt.findIndex($=>$==W[Se])===-1));const X=Ve[M].tolist(),fe=Ke[M].tolist();for(let _t=1;_tSe==W[_t])!==-1)&&(X[_t]=-1/0,fe[_t]=-1/0);const Ye=(0,D.softmax)(X).map((_t,Se)=>[_t,Se]),Je=(0,D.softmax)(fe).map((_t,Se)=>[_t,Se]);Ye[0][0]=0,Je[0][0]=0;const At=(0,xe.product)(Ye,Je).filter(_t=>_t[0][1]<=_t[1][1]).map(_t=>[_t[0][1],_t[1][1],_t[0][0]*_t[1][0]]).sort((_t,Se)=>Se[2]-_t[2]);for(let _t=0;_tX==this.tokenizer.mask_token_id);if(wt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const xt=Ge[ut][wt],M=await(0,j.topk)(new j.Tensor("float32",(0,D.softmax)(xt.data),xt.dims),Ee),W=M[0].tolist(),S=M[1].tolist();Ve.push(S.map((X,fe)=>{const Ye=mt.slice();return Ye[wt]=X,{score:W[fe],token:Number(X),token_str:this.tokenizer.model.vocab[X],sequence:this.tokenizer.decode(Ye,{skip_special_tokens:!0})}}))}return Array.isArray(re)?Ve:Ve[0]}}class ae extends ie{constructor(Ee){super(Ee);Te(this,"_key","generated_text")}async _call(Ee,je={}){Array.isArray(Ee)||(Ee=[Ee]),this.model.config.prefix&&(Ee=Ee.map(wt=>this.model.config.prefix+wt));const Ge=this.model.config.task_specific_params;Ge&&Ge[this.task]&&Ge[this.task].prefix&&(Ee=Ee.map(wt=>Ge[this.task].prefix+wt));const Ve=this.tokenizer,Ke={padding:!0,truncation:!0};let ut;this instanceof I&&"_build_translation_inputs"in Ve?ut=Ve._build_translation_inputs(Ee,Ke,je):ut=Ve(Ee,Ke);const mt=await this.model.generate({...ut,...je});return Ve.batch_decode(mt,{skip_special_tokens:!0}).map(wt=>({[this._key]:wt}))}}class N extends ae{constructor(Ee){super(Ee);Te(this,"_key","summary_text")}}class I extends ae{constructor(Ee){super(Ee);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,Ee={}){let je=!1,Ge=!1,Ve;if(typeof re=="string")Ve=re=[re];else if(Array.isArray(re)&&re.every(S=>typeof S=="string"))je=!0,Ve=re;else{if(B(re))re=[re];else if(Array.isArray(re)&&re.every(B))je=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Ge=!0,Ve=re.map(S=>this.tokenizer.apply_chat_template(S,{tokenize:!1,add_generation_prompt:!0}))}const Ke=Ee.add_special_tokens??!1,ut=Ge?!1:Ee.return_full_text??!0;this.tokenizer.padding_side="left";const mt=this.tokenizer(Ve,{add_special_tokens:Ke,padding:!0,truncation:!0}),wt=await this.model.generate({...mt,...Ee}),xt=this.tokenizer.batch_decode(wt,{skip_special_tokens:!0});let M;!ut&&mt.input_ids.dims.at(-1)>0&&(M=this.tokenizer.batch_decode(mt.input_ids,{skip_special_tokens:!0}).map(S=>S.length));const W=Array.from({length:re.length},S=>[]);for(let S=0;S[Ee.toLowerCase(),je])),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,Ee,{hypothesis_template:je="This example is {}.",multi_label:Ge=!1}={}){const Ve=Array.isArray(re);Ve||(re=[re]),Array.isArray(Ee)||(Ee=[Ee]);const Ke=Ee.map(wt=>je.replace("{}",wt)),ut=Ge||Ee.length===1,mt=[];for(const wt of re){const xt=[];for(const S of Ke){const X=this.tokenizer(wt,{text_pair:S,padding:!0,truncation:!0}),fe=await this.model(X);ut?xt.push([fe.logits.data[this.contradiction_id],fe.logits.data[this.entailment_id]]):xt.push(fe.logits.data[this.entailment_id])}const W=(ut?xt.map(S=>(0,D.softmax)(S)[1]):(0,D.softmax)(xt)).map((S,X)=>[S,X]).sort((S,X)=>X[0]-S[0]);mt.push({sequence:wt,labels:W.map(S=>Ee[S[1]]),scores:W.map(S=>S[0])})}return Ve?mt:mt[0]}}class ye extends ie{constructor(re){super(re)}async _call(re,{pooling:Ee="none",normalize:je=!1,quantize:Ge=!1,precision:Ve="binary"}={}){const Ke=this.tokenizer(re,{padding:!0,truncation:!0}),ut=await this.model(Ke);let mt=ut.last_hidden_state??ut.logits??ut.token_embeddings;if(Ee!=="none")if(Ee==="mean")mt=(0,j.mean_pooling)(mt,Ke.attention_mask);else if(Ee==="cls")mt=mt.slice(null,0);else throw Error(`Pooling method '${Ee}' not supported.`);return je&&(mt=mt.normalize(2,-1)),Ge&&(mt=(0,j.quantize_embeddings)(mt,Ve)),mt}}class Ce extends ie{constructor(re){super(re)}async _call(re,{pool:Ee=null}={}){const je=await J(re),{pixel_values:Ge}=await this.processor(je),Ve=await this.model({pixel_values:Ge});let Ke;if(Ee){if(!("pooler_output"in Ve))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ke=Ve.pooler_output}else Ke=Ve.last_hidden_state??Ve.logits??Ve.image_embeds;return Ke}}class ke extends ie{constructor(re){super(re)}async _call(re,{top_k:Ee=5}={}){const je=this.processor.feature_extractor.config.sampling_rate,Ge=await te(re,je),Ve=this.model.config.id2label,Ke=[];for(const ut of Ge){const mt=await this.processor(ut),xt=(await this.model(mt)).logits[0],M=await(0,j.topk)(new j.Tensor("float32",(0,D.softmax)(xt.data),xt.dims),Ee),W=M[0].tolist(),X=M[1].tolist().map((fe,Ye)=>({label:Ve?Ve[fe]:`LABEL_${fe}`,score:W[Ye]}));Ke.push(X)}return Array.isArray(re)?Ke:Ke[0]}}class Ie extends ie{constructor(re){super(re)}async _call(re,Ee,{hypothesis_template:je="This is a sound of {}."}={}){const Ge=!Array.isArray(re);Ge&&(re=[re]);const Ve=Ee.map(xt=>je.replace("{}",xt)),Ke=this.tokenizer(Ve,{padding:!0,truncation:!0}),ut=this.processor.feature_extractor.config.sampling_rate,mt=await te(re,ut),wt=[];for(const xt of mt){const M=await this.processor(xt),W=await this.model({...Ke,...M}),S=(0,D.softmax)(W.logits_per_audio.data);wt.push([...S].map((X,fe)=>({score:X,label:Ee[fe]})))}return Ge?wt[0]:wt}}class tt extends ie{constructor(re){super(re)}async _call(re,Ee={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(re,Ee);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(re,Ee);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(re,Ee){Ee.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Ee.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const je=!Array.isArray(re);je&&(re=[re]);const Ge=this.processor.feature_extractor.config.sampling_rate,Ve=await te(re,Ge),Ke=[];for(const ut of Ve){const mt=await this.processor(ut),xt=(await this.model(mt)).logits[0],M=[];for(const S of xt)M.push((0,D.max)(S.data)[1]);const W=this.tokenizer.decode(M);Ke.push({text:W})}return je?Ke[0]:Ke}async _call_whisper(re,Ee){const je=Ee.return_timestamps??!1,Ge=Ee.chunk_length_s??0,Ve=Ee.force_full_sequences??!1;let Ke=Ee.stride_length_s??null;const ut={...Ee};je==="word"&&(ut.return_token_timestamps=!0,ut.return_timestamps=!1);const mt=!Array.isArray(re);mt&&(re=[re]);const wt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,xt=this.processor.feature_extractor.config.hop_length,M=this.processor.feature_extractor.config.sampling_rate,W=await te(re,M),S=[];for(const X of W){let fe=[];if(Ge>0){if(Ke===null)Ke=Ge/6;else if(Ge<=Ke)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const At=M*Ge,_t=M*Ke,Se=At-2*_t;let $=0;for(;;){const q=$+At,be=X.subarray($,q),Be=await this.processor(be),Ae=$===0,Ne=q>=X.length;if(fe.push({stride:[be.length,Ae?0:_t,Ne?0:_t],input_features:Be.input_features,is_last:Ne}),Ne)break;$+=Se}}else fe=[{stride:[X.length,0,0],input_features:(await this.processor(X)).input_features,is_last:!0}];for(const At of fe){ut.num_frames=Math.floor(At.stride[0]/xt);const _t=await this.model.generate({inputs:At.input_features,...ut});je==="word"?(At.tokens=_t.sequences.tolist()[0],At.token_timestamps=_t.token_timestamps.tolist()[0].map(Se=>(0,D.round)(Se,2))):At.tokens=_t[0].tolist(),At.stride=At.stride.map(Se=>Se/M)}const[Ye,Je]=this.tokenizer._decode_asr(fe,{time_precision:wt,return_timestamps:je,force_full_sequences:Ve});S.push({text:Ye,...Je})}return mt?S[0]:S}}class Qe extends ie{constructor(re){super(re)}async _call(re,Ee={}){const je=Array.isArray(re),Ge=await J(re),{pixel_values:Ve}=await this.processor(Ge),Ke=[];for(const ut of Ve){ut.dims=[1,...ut.dims];const mt=await this.model.generate({inputs:ut,...Ee}),wt=this.tokenizer.batch_decode(mt,{skip_special_tokens:!0}).map(xt=>({generated_text:xt.trim()}));Ke.push(wt)}return je?Ke:Ke[0]}}class ht extends ie{constructor(re){super(re)}async _call(re,{top_k:Ee=5}={}){const je=await J(re),{pixel_values:Ge}=await this.processor(je),Ve=await this.model({pixel_values:Ge}),Ke=this.model.config.id2label,ut=[];for(const mt of Ve.logits){const wt=await(0,j.topk)(new j.Tensor("float32",(0,D.softmax)(mt.data),mt.dims),Ee),xt=wt[0].tolist(),W=wt[1].tolist().map((S,X)=>({label:Ke?Ke[S]:`LABEL_${S}`,score:xt[X]}));ut.push(W)}return Array.isArray(re)?ut:ut[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:Ee=.5,mask_threshold:je=.5,overlap_mask_area_threshold:Ge=.8,label_ids_to_fuse:Ve=null,target_sizes:Ke=null,subtask:ut=null}={}){if(Array.isArray(re)&&re.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const wt=await J(re),xt=wt.map(Je=>[Je.height,Je.width]),{pixel_values:M,pixel_mask:W}=await this.processor(wt),S=await this.model({pixel_values:M,pixel_mask:W});let X=null;if(ut!==null)X=this.subtasks_mapping[ut];else for(let[Je,At]of Object.entries(this.subtasks_mapping))if(At in this.processor.feature_extractor){X=this.processor.feature_extractor[At].bind(this.processor.feature_extractor),ut=Je;break}const fe=this.model.config.id2label,Ye=[];if(ut==="panoptic"||ut==="instance"){const Je=X(S,Ee,je,Ge,Ve,Ke??xt)[0],At=Je.segmentation;for(const _t of Je.segments_info){const Se=new Uint8ClampedArray(At.data.length);for(let q=0;qje.replace("{}",W)),ut=this.tokenizer(Ke,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:mt}=await this.processor(Ve),wt=await this.model({...ut,pixel_values:mt}),xt=this.model.config.model_type==="siglip"?W=>W.sigmoid().data:W=>(0,D.softmax)(W.data),M=[];for(const W of wt.logits_per_image){const X=[...xt(W)].map((fe,Ye)=>({score:fe,label:Ee[Ye]}));X.sort((fe,Ye)=>Ye.score-fe.score),M.push(X)}return Ge?M:M[0]}}class he extends ie{constructor(re){super(re)}async _call(re,{threshold:Ee=.9,percentage:je=!1}={}){const Ge=Array.isArray(re);if(Ge&&re.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ve=await J(re),Ke=je?null:Ve.map(S=>[S.height,S.width]),{pixel_values:ut,pixel_mask:mt}=await this.processor(Ve),wt=await this.model({pixel_values:ut,pixel_mask:mt}),xt=this.processor.feature_extractor.post_process_object_detection(wt,Ee,Ke),M=this.model.config.id2label,W=xt.map(S=>S.boxes.map((X,fe)=>({score:S.scores[fe],label:M[S.classes[fe]],box:ne(X,!je)})));return Ge?W:W[0]}}class $e extends ie{constructor(re){super(re)}async _call(re,Ee,{threshold:je=.1,top_k:Ge=null,percentage:Ve=!1}={}){const Ke=Array.isArray(re),ut=await J(re),mt=this.tokenizer(Ee,{padding:!0,truncation:!0}),wt=await this.processor(ut),xt=[];for(let M=0;M({score:Ye.scores[_t],label:Ee[Ye.classes[_t]],box:ne(At,!Ve)})).sort((At,_t)=>_t.score-At.score);Ge!==null&&(Je=Je.slice(0,Ge)),xt.push(Je)}return Ke?xt:xt[0]}}class ee extends ie{constructor(re){super(re)}async _call(re,Ee,je={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class He extends ie{constructor(Ee){super(Ee);Te(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Ee.vocoder??null}async _call(Ee,{speaker_embeddings:je=null}={}){return this.processor?this._call_text_to_spectrogram(Ee,{speaker_embeddings:je}):this._call_text_to_waveform(Ee)}async _call_text_to_waveform(Ee){const je=this.tokenizer(Ee,{padding:!0,truncation:!0}),{waveform:Ge}=await this.model(je),Ve=this.model.config.sampling_rate;return{audio:Ge.data,sampling_rate:Ve}}async _call_text_to_spectrogram(Ee,{speaker_embeddings:je}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await H.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof je=="string"||je instanceof URL)&&(je=new Float32Array(await(await fetch(je)).arrayBuffer())),je instanceof Float32Array)je=new j.Tensor("float32",je,[1,je.length]);else if(!(je instanceof j.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Ge}=this.tokenizer(Ee,{padding:!0,truncation:!0}),{waveform:Ve}=await this.model.generate_speech(Ge,je,{vocoder:this.vocoder}),Ke=this.processor.feature_extractor.config.sampling_rate;return{audio:Ve.data,sampling_rate:Ke}}}class pt extends ie{constructor(re){super(re)}async _call(re){const Ee=await J(re),je=await this.processor(Ee),Ge=await this.model(je),Ve=[];for(const Ke of Ge.reconstruction){const ut=Ke.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ve.push(P.RawImage.fromTensor(ut))}return Ve.length>1?Ve:Ve[0]}}class rt extends ie{constructor(re){super(re)}async _call(re){const Ee=await J(re),je=await this.processor(Ee),{predicted_depth:Ge}=await this.model(je),Ve=[];for(let Ke=0;Ke1?Ve:Ve[0]}}const lt=Object.freeze({"text-classification":{tokenizer:x.AutoTokenizer,pipeline:R,model:H.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:x.AutoTokenizer,pipeline:Y,model:H.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:x.AutoTokenizer,pipeline:se,model:H.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:x.AutoTokenizer,pipeline:le,model:H.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:x.AutoTokenizer,pipeline:N,model:H.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:x.AutoTokenizer,pipeline:I,model:H.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:x.AutoTokenizer,pipeline:ae,model:H.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:x.AutoTokenizer,pipeline:A,model:H.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:x.AutoTokenizer,pipeline:_e,model:H.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ke,model:H.AutoModelForAudioClassification,processor:ge.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:x.AutoTokenizer,pipeline:Ie,model:H.AutoModel,processor:ge.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:x.AutoTokenizer,pipeline:tt,model:[H.AutoModelForSpeechSeq2Seq,H.AutoModelForCTC],processor:ge.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:x.AutoTokenizer,pipeline:He,model:[H.AutoModelForTextToWaveform,H.AutoModelForTextToSpectrogram],processor:[ge.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:x.AutoTokenizer,pipeline:Qe,model:H.AutoModelForVision2Seq,processor:ge.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ht,model:H.AutoModelForImageClassification,processor:ge.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:we,model:[H.AutoModelForImageSegmentation,H.AutoModelForSemanticSegmentation],processor:ge.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:x.AutoTokenizer,pipeline:V,model:H.AutoModel,processor:ge.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:he,model:H.AutoModelForObjectDetection,processor:ge.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:x.AutoTokenizer,pipeline:$e,model:H.AutoModelForZeroShotObjectDetection,processor:ge.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:x.AutoTokenizer,pipeline:ee,model:H.AutoModelForDocumentQuestionAnswering,processor:ge.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:pt,model:H.AutoModelForImageToImage,processor:ge.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:rt,model:H.AutoModelForDepthEstimation,processor:ge.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:x.AutoTokenizer,pipeline:ye,model:H.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:ge.AutoProcessor,pipeline:Ce,model:[H.AutoModelForImageFeatureExtraction,H.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Re=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function st(ze,re=null,{progress_callback:Ee=null,config:je=null,cache_dir:Ge=null,local_files_only:Ve=!1,revision:Ke="main",device:ut=null,dtype:mt=null,model_file_name:wt=null,session_options:xt={}}={}){ze=Re[ze]??ze;const M=lt[ze.split("_",1)[0]];if(!M)throw Error(`Unsupported pipeline: ${ze}. Must be one of [${Object.keys(lt)}]`);re||(re=M.default.model,console.log(`No model specified. Using default model: "${re}".`));const W={progress_callback:Ee,config:je,cache_dir:Ge,local_files_only:Ve,revision:Ke,device:ut,dtype:mt,model_file_name:wt,session_options:xt},S=new Map([["tokenizer",M.tokenizer],["model",M.model],["processor",M.processor]]),X=await Tt(S,re,W);X.task=ze,(0,xe.dispatchCallback)(Ee,{status:"ready",task:ze,model:re});const fe=M.pipeline;return new fe(X)}async function Tt(ze,re,Ee){const je=Object.create(null),Ge=[];for(let[Ve,Ke]of ze.entries()){if(!Ke)continue;let ut;Array.isArray(Ke)?ut=new Promise(async(mt,wt)=>{var M,W;let xt;for(let S of Ke){if(S===null){mt(null);return}try{mt(await S.from_pretrained(re,Ee));return}catch(X){if((M=X.message)!=null&&M.includes("Unsupported model type"))xt=X;else if((W=X.message)!=null&&W.includes("Could not locate file"))xt=X;else{wt(X);return}}}wt(xt)}):ut=Ke.from_pretrained(re,Ee),je[Ve]=ut,Ge.push(ut)}await Promise.all(Ge);for(let[Ve,Ke]of Object.entries(je))je[Ve]=await Ke;return je}},"./src/processors.js":(Mt,me,l)=>{l.r(me),l.d(me,{ASTFeatureExtractor:()=>Ke,AutoProcessor:()=>_t,BeitFeatureExtractor:()=>rt,BitImageProcessor:()=>le,CLIPFeatureExtractor:()=>N,CLIPImageProcessor:()=>I,ChineseCLIPFeatureExtractor:()=>B,ClapFeatureExtractor:()=>ut,ConvNextFeatureExtractor:()=>_e,ConvNextImageProcessor:()=>ye,DPTFeatureExtractor:()=>Y,DPTImageProcessor:()=>se,DeiTFeatureExtractor:()=>pt,DetrFeatureExtractor:()=>st,DonutFeatureExtractor:()=>lt,EfficientNetImageProcessor:()=>Ie,FeatureExtractor:()=>ne,Florence2Processor:()=>At,GLPNFeatureExtractor:()=>ae,ImageFeatureExtractor:()=>ie,MobileNetV1FeatureExtractor:()=>tt,MobileNetV2FeatureExtractor:()=>Qe,MobileNetV3FeatureExtractor:()=>ht,MobileNetV4FeatureExtractor:()=>we,MobileViTFeatureExtractor:()=>V,MobileViTImageProcessor:()=>he,NougatImageProcessor:()=>Re,OwlViTFeatureExtractor:()=>$e,OwlViTProcessor:()=>Je,Owlv2ImageProcessor:()=>ee,Processor:()=>M,PyAnnoteFeatureExtractor:()=>mt,PyAnnoteProcessor:()=>fe,RTDetrImageProcessor:()=>He,SamImageProcessor:()=>ze,SamProcessor:()=>W,SeamlessM4TFeatureExtractor:()=>Ve,SegformerFeatureExtractor:()=>R,SiglipImageProcessor:()=>A,SpeechT5FeatureExtractor:()=>xt,SpeechT5Processor:()=>Ye,Swin2SRImageProcessor:()=>re,ViTFeatureExtractor:()=>Ce,ViTImageProcessor:()=>ke,VitMatteImageProcessor:()=>Ee,Wav2Vec2FeatureExtractor:()=>Ge,Wav2Vec2ProcessorWithLM:()=>X,WeSpeakerFeatureExtractor:()=>wt,WhisperFeatureExtractor:()=>je,WhisperProcessor:()=>S,YolosFeatureExtractor:()=>Tt});var x=l("./src/utils/generic.js"),H=l("./src/utils/core.js"),ge=l("./src/utils/hub.js"),ve=l("./src/utils/maths.js"),xe=l("./src/utils/tensor.js");l("./src/utils/image.js");var D=l("./src/utils/audio.js");function T([Se,$,q,be]){return[Se-q/2,$-be/2,Se+q/2,$+be/2]}function j(Se,$=.5,q=null,be=!1){const Be=Se.logits,Ae=Se.pred_boxes,[Ne,dt,nt]=Be.dims;if(q!==null&&q.length!==Ne)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let vt=[];for(let ft=0;ft$&&Xt.push(Wt)}else{let Wt=(0,ve.max)(Ht.data)[1];if(Wt===nt-1||(er=(0,ve.softmax)(Ht.data),er[Wt]<$))continue;Xt.push(Wt)}for(const Wt of Xt){let Tr=jt[Rt].data;Tr=T(Tr),Ct!==null&&(Tr=Tr.map((Ur,Cr)=>Ur*Ct[(Cr+1)%2])),Lt.boxes.push(Tr),Lt.classes.push(Wt),Lt.scores.push(er[Wt])}}vt.push(Lt)}return vt}function P(Se,$){var q;if(!(Se instanceof Float32Array||Se instanceof Float64Array))throw new Error(`${$} expects input to be a Float32Array or a Float64Array, but got ${((q=Se==null?void 0:Se.constructor)==null?void 0:q.name)??typeof Se} 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(Se,$,q=0,be=null){const Be=Se/$;let Ae=(0,ve.bankers_round)(Be)*$;return be!==null&&Ae>be&&(Ae=Math.floor(Be)*$),AeAe?vt=Math.floor(Ae*nt/Be):Ae>Be&&(nt=Math.floor(Be*vt/Ae)),await $.resize(vt,nt,{resample:be}))}async crop_margin($,q=200){const be=$.clone().grayscale(),Be=(0,ve.min)(be.data)[0],Ne=(0,ve.max)(be.data)[0]-Be;if(Ne===0)return $;const dt=q/255;let nt=be.width,vt=be.height,ft=0,Ct=0;const Lt=be.data;for(let Xe=0;Xethis.preprocess(Ae)));return{pixel_values:(0,xe.stack)(be.map(Ae=>Ae.pixel_values),0),original_sizes:be.map(Ae=>Ae.original_size),reshaped_input_sizes:be.map(Ae=>Ae.reshaped_input_size)}}}class R extends ie{post_process_semantic_segmentation($,q=null){const be=$.logits,Be=be.dims[0];if(q!==null&&q.length!==Be)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Ae=[];for(let Ne=0;NeLt[Wt]&&(Lt[Wt]=er[Wt],Xe[Wt]=Xt)}const jt=new Array(nt.dims[0]),Rt=Ct.data;for(let Xt=0;XtXt!==void 0);Ae.push({segmentation:Ct,labels:Ht})}return Ae}}class Y extends ie{}class se extends Y{}class le extends ie{}class ae extends ie{}class N extends ie{}class I extends N{}class B extends ie{}class A extends ie{}class _e extends ie{constructor($){super($),this.crop_pct=this.config.crop_pct??.875}async resize($){var be;const q=(be=this.size)==null?void 0:be.shortest_edge;if(q===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(q<384){const Be=Math.floor(q/this.crop_pct),[Ae,Ne]=this.get_resize_output_image_size($,{shortest_edge:Be});$=await $.resize(Ae,Ne,{resample:this.resample}),$=await $.center_crop(q,q)}else $=await $.resize(q,q,{resample:this.resample});return $}}class ye extends _e{}class Ce extends ie{}class ke extends ie{}class Ie extends ie{constructor($){super($),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(q=>q*q))}}class tt extends ie{}class Qe extends ie{}class ht extends ie{}class we extends ie{}class V extends ie{}class he extends V{}class $e extends ie{post_process_object_detection(...$){return j(...$)}}class ee extends $e{}class He extends ie{post_process_object_detection(...$){return j(...$)}}class pt extends ie{}class rt extends ie{}class lt extends ie{pad_image($,q,be,Be={}){const[Ae,Ne,dt]=q;let nt=this.image_mean;Array.isArray(this.image_mean)||(nt=new Array(dt).fill(nt));let vt=this.image_std;Array.isArray(vt)||(vt=new Array(dt).fill(nt));const ft=nt.map((Ct,Lt)=>-Ct/vt[Lt]);return super.pad_image($,q,be,{center:!0,constant_values:ft,...Be})}}class Re extends lt{}class st extends ie{async _call($){const q=await super._call($),be=[q.pixel_values.dims[0],64,64],Be=new xe.Tensor("int64",new BigInt64Array(be.reduce((Ae,Ne)=>Ae*Ne)).fill(1n),be);return{...q,pixel_mask:Be}}post_process_object_detection(...$){return j(...$)}remove_low_and_no_objects($,q,be,Be){let Ae=[],Ne=[],dt=[];for(let nt=0;nt<$.dims[0];++nt){let vt=$[nt],ft=q[nt],Ct=(0,ve.max)(vt.data)[1];if(Ct===Be)continue;let Xe=(0,ve.softmax)(vt.data)[Ct];Xe>be&&(Ae.push(ft),Ne.push(Xe),dt.push(Ct))}return[Ae,Ne,dt]}check_segment_validity($,q,be,Be=.5,Ae=.8){let Ne=[],dt=0,nt=0;const vt=q[be].data;for(let Ct=0;Ct<$.length;++Ct)$[Ct]===be&&(Ne.push(Ct),++dt),vt[Ct]>=Be&&++nt;let ft=dt>0&&nt>0;return ft&&(ft=dt/nt>Ae),[ft,Ne]}compute_segments($,q,be,Be,Ae,Ne=null,dt=null){let[nt,vt]=dt??$[0].dims,ft=new xe.Tensor("int32",new Int32Array(nt*vt),[nt,vt]),Ct=[];if(dt!==null)for(let Ht=0;Ht<$.length;++Ht)$[Ht]=(0,xe.interpolate)($[Ht],dt,"bilinear",!1);let Lt=new Int32Array($[0].data.length),Xe=new Float32Array($[0].data.length);for(let Ht=0;Ht<$.length;++Ht){let Xt=q[Ht];const er=$[Ht].data;for(let Wt=0;WtXe[Wt]&&(Lt[Wt]=Ht,Xe[Wt]=er[Wt])}let jt=0;const Rt=ft.data;for(let Ht=0;HtBe!==q.dims[Ae]))throw Error(`The first ${be.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new xe.Tensor("int64",$.flat(1/0).map(BigInt),be)}async _call($,{input_points:q=null,input_labels:be=null,input_boxes:Be=null}={}){const Ae=await super._call($);if(q&&(Ae.input_points=this.reshape_input_points(q,Ae.original_sizes,Ae.reshaped_input_sizes)),be){if(!Ae.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Ae.input_labels=this.add_input_labels(be,Ae.input_points)}return Be&&(Ae.input_boxes=this.reshape_input_points(Be,Ae.original_sizes,Ae.reshaped_input_sizes,!0)),Ae}async post_process_masks($,q,be,{mask_threshold:Be=0,binarize:Ae=!0,pad_size:Ne=null}={}){const dt=[];Ne=Ne??this.pad_size;const nt=[Ne.height,Ne.width];for(let vt=0;vtBe&&(jt[Rt]=1);Lt=new xe.Tensor("bool",jt,Lt.dims)}dt.push(Lt)}return dt}generate_crop_boxes($,q,{crop_n_layers:be=0,overlap_ratio:Be=.3413333333333333,points_per_crop:Ae=32,crop_n_points_downscale_factor:Ne=1}={}){}}class re extends ie{pad_image($,q,be,Be={}){const[Ae,Ne,dt]=q;return super.pad_image($,q,{width:Ne+(be-Ne%be)%be,height:Ae+(be-Ae%be)%be},{mode:"symmetric",center:!1,constant_values:-1,...Be})}}class Ee extends ie{async _call($,q){Array.isArray($)||($=[$]),Array.isArray(q)||(q=[q]);const be=await Promise.all($.map(Ne=>this.preprocess(Ne))),Be=await Promise.all(q.map(Ne=>this.preprocess(Ne,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,xe.stack)(be.map((Ne,dt)=>(0,xe.cat)([Ne.pixel_values,Be[dt].pixel_values],0)),0),original_sizes:be.map(Ne=>Ne.original_size),reshaped_input_sizes:be.map(Ne=>Ne.reshaped_input_size)}}}class je extends ne{constructor($){var q;super($),(q=this.config).mel_filters??(q.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($){const q=await(0,D.spectrogram)($,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=q.data,Be=(0,ve.max)(be)[0];for(let Ae=0;Aethis.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`."),q=$.slice(0,this.config.n_samples)):(q=new Float32Array(this.config.n_samples),q.set($)),{input_features:(await this._extract_fbank_features(q)).unsqueeze_(0)}}}class Ge extends ne{_zero_mean_unit_var_norm($){const be=$.reduce((Ae,Ne)=>Ae+Ne,0)/$.length,Be=$.reduce((Ae,Ne)=>Ae+(Ne-be)**2,0)/$.length;return $.map(Ae=>(Ae-be)/Math.sqrt(Be+1e-7))}async _call($){P($,"Wav2Vec2FeatureExtractor"),$ instanceof Float64Array&&($=new Float32Array($));let q=$;this.config.do_normalize&&(q=this._zero_mean_unit_var_norm(q));const be=[1,q.length];return{input_values:new xe.Tensor("float32",q,be),attention_mask:new xe.Tensor("int64",new BigInt64Array(q.length).fill(1n),be)}}}class Ve extends ne{constructor($){super($);const q=this.config.sampling_rate,be=(0,D.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(q/2),q,null,"kaldi",!0);for(let Be=0;Bebe*32768),(0,D.spectrogram)($,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:q,transpose:!0})}async _call($,{padding:q=!0,pad_to_multiple_of:be=2,do_normalize_per_mel_bins:Be=!0,return_attention_mask:Ae=!0}={}){P($,"SeamlessM4TFeatureExtractor");let Ne=await this._extract_fbank_features($,this.config.max_length);if(Be){const[jt,Rt]=Ne.dims,Ht=Ne.data;for(let Xt=0;Xt0){const er=new Float32Array(Rt*(jt+Xt));er.set(Ht),er.fill(this.config.padding_value,Ht.length);const Wt=jt+Xt;Ne=new xe.Tensor(Ne.type,er,[Wt,Rt]),Ae&&(dt=new xe.Tensor("int64",new BigInt64Array(Wt),[1,Wt]),dt.data.fill(1n,0,jt))}}const[nt,vt]=Ne.dims,ft=this.config.stride;if(nt%ft!==0)throw new Error(`The number of frames (${nt}) must be a multiple of the stride (${ft}).`);const Lt=Ne.view(1,Math.floor(nt/ft),vt*ft),Xe={input_features:Lt};if(Ae){const jt=Lt.dims[1],Rt=new BigInt64Array(jt);if(dt){const Ht=dt.data;for(let Xt=1,er=0;Xt0)if(be==="rand_trunc"){const dt=Math.floor(Math.random()*(Ne+1));$=$.subarray(dt,dt+q),Ae=await this._extract_fbank_features($,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${be}" not implemented`);else{if(Ne<0){let dt=new Float64Array(q);if(dt.set($),Be==="repeat")for(let nt=$.length;nt({id:nt,start:vt*be,end:ft*be,confidence:Ct/(ft-vt)})))}return Be}}class wt extends ne{constructor($){super($);const q=this.config.sampling_rate,be=(0,D.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(q/2),q,null,"kaldi",!0);for(let Be=0;Beq*32768),(0,D.spectrogram)($,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($){P($,"WeSpeakerFeatureExtractor");const q=(await this._extract_fbank_features($)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const be=q.mean(1).data,Be=q.data,[Ae,Ne,dt]=q.dims;for(let nt=0;nt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts($){typeof $=="string"&&($=[$]);const q=[];for(const be of $)if(this.task_prompts_without_inputs.has(be))q.push(this.task_prompts_without_inputs.get(be));else{for(const[Be,Ae]of this.task_prompts_with_input)if(be.includes(Be)){q.push(Ae.replaceAll("{input}",be).replaceAll(Be,""));break}q.length!==$.length&&q.push(be)}return q}post_process_generation($,q,be){const Be=this.tasks_answer_post_processing_type.get(q)??"pure_text";$=$.replaceAll("","").replaceAll("","");let Ae;switch(Be){case"pure_text":Ae=$;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Ne=Be==="ocr"?"quad_boxes":"bboxes",dt=$.matchAll(this.regexes[Ne]),nt=[],vt=[];for(const[ft,Ct,...Lt]of dt)nt.push(Ct?Ct.trim():nt.at(-1)??""),vt.push(Lt.map((Xe,jt)=>(Number(Xe)+.5)/this.size_per_bin*be[jt%2]));Ae={labels:nt,[Ne]:vt};break;default:throw new Error(`Task "${q}" (of type "${Be}") not yet implemented.`)}return{[q]:Ae}}}class _t{static async from_pretrained($,{progress_callback:q=null,config:be=null,cache_dir:Be=null,local_files_only:Ae=!1,revision:Ne="main"}={}){let dt=be??await(0,ge.getModelJSON)($,"preprocessor_config.json",!0,{progress_callback:q,config:be,cache_dir:Be,local_files_only:Ae,revision:Ne}),nt=dt.feature_extractor_type??dt.image_processor_type,vt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[nt];if(!vt)if(dt.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 ft=this.PROCESSOR_CLASS_MAPPING[dt.processor_class]??M,Ct=new vt(dt);return new ft(Ct)}}Te(_t,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:ie,WhisperFeatureExtractor:je,ViTFeatureExtractor:Ce,MobileViTFeatureExtractor:V,MobileViTImageProcessor:he,MobileNetV1FeatureExtractor:tt,MobileNetV2FeatureExtractor:Qe,MobileNetV3FeatureExtractor:ht,MobileNetV4FeatureExtractor:we,OwlViTFeatureExtractor:$e,Owlv2ImageProcessor:ee,CLIPFeatureExtractor:N,CLIPImageProcessor:I,Florence2Processor:At,ChineseCLIPFeatureExtractor:B,SiglipImageProcessor:A,ConvNextFeatureExtractor:_e,ConvNextImageProcessor:ye,SegformerFeatureExtractor:R,BitImageProcessor:le,DPTImageProcessor:se,DPTFeatureExtractor:Y,GLPNFeatureExtractor:ae,BeitFeatureExtractor:rt,DeiTFeatureExtractor:pt,DetrFeatureExtractor:st,RTDetrImageProcessor:He,YolosFeatureExtractor:Tt,DonutFeatureExtractor:lt,NougatImageProcessor:Re,EfficientNetImageProcessor:Ie,ViTImageProcessor:ke,VitMatteImageProcessor:Ee,SamImageProcessor:ze,Swin2SRImageProcessor:re,Wav2Vec2FeatureExtractor:Ge,SeamlessM4TFeatureExtractor:Ve,SpeechT5FeatureExtractor:xt,ASTFeatureExtractor:Ke,ClapFeatureExtractor:ut,PyAnnoteFeatureExtractor:mt,WeSpeakerFeatureExtractor:wt}),Te(_t,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:S,Wav2Vec2ProcessorWithLM:X,PyAnnoteProcessor:fe,SamProcessor:W,SpeechT5Processor:Ye,OwlViTProcessor:Je,Florence2Processor:At})},"./src/tokenizers.js":(Mt,me,l)=>{l.r(me),l.d(me,{AlbertTokenizer:()=>Rt,AutoTokenizer:()=>mn,BartTokenizer:()=>Lr,BertTokenizer:()=>jt,BlenderbotSmallTokenizer:()=>vs,BlenderbotTokenizer:()=>os,BloomTokenizer:()=>Pr,CLIPTokenizer:()=>Qt,CamembertTokenizer:()=>St,CodeGenTokenizer:()=>as,CodeLlamaTokenizer:()=>Vs,CohereTokenizer:()=>Dr,ConvBertTokenizer:()=>Ur,DebertaTokenizer:()=>er,DebertaV2Tokenizer:()=>Wt,DistilBertTokenizer:()=>Ze,ElectraTokenizer:()=>qr,EsmTokenizer:()=>Gn,FalconTokenizer:()=>ws,GPT2Tokenizer:()=>Fn,GPTNeoXTokenizer:()=>ys,GemmaTokenizer:()=>ss,Grok1Tokenizer:()=>kn,HerbertTokenizer:()=>Tr,LlamaTokenizer:()=>On,M2M100Tokenizer:()=>Qn,MBart50Tokenizer:()=>Nr,MBartTokenizer:()=>Zr,MPNetTokenizer:()=>gs,MarianTokenizer:()=>bs,MobileBertTokenizer:()=>Ht,NllbTokenizer:()=>Dn,NougatTokenizer:()=>ls,PreTrainedTokenizer:()=>Xe,Qwen2Tokenizer:()=>Us,RoFormerTokenizer:()=>Cr,RobertaTokenizer:()=>Sn,SiglipTokenizer:()=>Yn,SpeechT5Tokenizer:()=>xs,SqueezeBertTokenizer:()=>Xt,T5Tokenizer:()=>Un,TokenizerModel:()=>Ce,VitsTokenizer:()=>Ts,Wav2Vec2CTCTokenizer:()=>Ms,WhisperTokenizer:()=>is,XLMRobertaTokenizer:()=>_s,XLMTokenizer:()=>Dt,is_chinese_char:()=>ae});var x=l("./src/utils/generic.js"),H=l("./src/utils/core.js"),ge=l("./src/utils/hub.js"),ve=l("./src/utils/maths.js"),xe=l("./src/utils/tensor.js"),D=l("./src/utils/data-structures.js"),T=l("./node_modules/@huggingface/jinja/dist/index.js"),j=l("./src/models/whisper/common_whisper.js"),P=l("./src/utils/constants.js");async function J(Me,_){const O=await Promise.all([(0,ge.getModelJSON)(Me,"tokenizer.json",!0,_),(0,ge.getModelJSON)(Me,"tokenizer_config.json",!0,_)]);return _.legacy!==null&&(O[1].legacy=_.legacy),O}function te(Me,_){const O=[];let Q=0;for(const ue of Me.matchAll(_)){const de=ue[0];Q0&&O.push(de),Q=ue.index+de.length}return Q=19968&&Me<=40959||Me>=13312&&Me<=19903||Me>=131072&&Me<=173791||Me>=173824&&Me<=177983||Me>=177984&&Me<=178207||Me>=178208&&Me<=183983||Me>=63744&&Me<=64255||Me>=194560&&Me<=195103}function N(Me,_,O){const Q=[];let ue=0;for(;uethis.tokens_to_ids.get(O)??this.unk_token_id)}convert_ids_to_tokens(_){return _.map(O=>this.vocab[O]??this.unk_token)}}class ke extends Ce{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,Q]of this.tokens_to_ids)this.vocab[Q]=O}encode(_){const O=[];for(const Q of _){const ue=[...Q];if(ue.length>this.max_input_chars_per_word){O.push(this.unk_token);continue}let de=!1,Fe=0;const gt=[];for(;Fe0&&(Pt=this.config.continuing_subword_prefix+Pt),this.tokens_to_ids.has(Pt)){yt=Pt;break}--bt}if(yt===null){de=!0;break}gt.push(yt),Fe=bt}de?O.push(this.unk_token):O.push(...gt)}return O}}class Ie extends Ce{constructor(_,O){super(_);const Q=_.vocab.length;this.vocab=new Array(Q),this.scores=new Array(Q);for(let ue=0;ue[ue,de])),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,ve.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,Q=O.length;let ue=0;for(;ue{const Me=[...Array.from({length:94},(ue,de)=>de+33),...Array.from({length:12},(ue,de)=>de+161),...Array.from({length:82},(ue,de)=>de+174)],_=Me.slice();let O=0;for(let ue=0;ue<256;++ue)Me.includes(ue)||(Me.push(ue),_.push(256+O),O+=1);const Q=_.map(ue=>String.fromCharCode(ue));return Object.fromEntries(Me.map((ue,de)=>[ue,Q[de]]))})(),Qe=(0,H.reverseDictionary)(tt);class ht extends Ce{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,Q]of this.tokens_to_ids)this.vocab[Q]=O;this.bpe_ranks=new Map(_.merges.map((O,Q)=>[O,Q])),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 Q=Array.from(_);this.end_of_word_suffix&&(Q[Q.length-1]+=this.end_of_word_suffix);let ue=[];if(Q.length>1){const de=new D.PriorityQueue((bt,yt)=>bt.score`<0x${Fe.toString(16).toUpperCase().padStart(2,"0")}>`)):O.push(this.unk_token)}return O}}class we extends Ce{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[Q,ue]of this.tokens_to_ids)this.vocab[ue]=Q}encode(_){return _}}class V extends x.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"BertNormalizer":return new Tt(_);case"Precompiled":return new Ae(_);case"Sequence":return new st(_);case"Replace":return new he(_);case"NFC":return new $e(_);case"NFKC":return new ee(_);case"NFKD":return new He(_);case"Strip":return new pt(_);case"StripAccents":return new rt(_);case"Lowercase":return new lt(_);case"Prepend":return new Re(_);default:throw new Error(`Unknown Normalizer type: ${_.type}`)}}normalize(_){throw Error("normalize should be implemented in subclass.")}_call(_){return this.normalize(_)}}class he extends V{normalize(_){const O=ne(this.config.pattern);return O===null?_:_.replaceAll(O,this.config.content)}}class $e extends V{normalize(_){return _=_.normalize("NFC"),_}}class ee extends V{normalize(_){return _=_.normalize("NFKC"),_}}class He extends V{normalize(_){return _=_.normalize("NFKD"),_}}class pt extends V{normalize(_){return this.config.strip_left&&this.config.strip_right?_=_.trim():(this.config.strip_left&&(_=_.trimStart()),this.config.strip_right&&(_=_.trimEnd())),_}}class rt extends V{normalize(_){return _=se(_),_}}class lt extends V{normalize(_){return _=_.toLowerCase(),_}}class Re extends V{normalize(_){return _=this.config.prepend+_,_}}class st extends V{constructor(_){super(_),this.normalizers=_.normalizers.map(O=>V.fromConfig(O))}normalize(_){return this.normalizers.reduce((O,Q)=>Q.normalize(O),_)}}class Tt extends V{_tokenize_chinese_chars(_){const O=[];for(let Q=0;Q<_.length;++Q){const ue=_[Q],de=ue.charCodeAt(0);ae(de)?(O.push(" "),O.push(ue),O.push(" ")):O.push(ue)}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 Q of _){const ue=Q.charCodeAt(0);ue===0||ue===65533||this._is_control(Q)||(/^\s$/.test(Q)?O.push(" "):O.push(Q))}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 x.Callable{static fromConfig(_){if(_===null)return null;switch(_.type){case"BertPreTokenizer":return new re(_);case"Sequence":return new Ne(_);case"Whitespace":return new dt(_);case"WhitespaceSplit":return new nt(_);case"Metaspace":return new be(_);case"ByteLevel":return new Ee(_);case"Split":return new je(_);case"Punctuation":return new Ge(_);case"Digits":return new Ve(_);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(Q=>this.pre_tokenize_text(Q,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 Ee 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=tt,this.text_encoder=new TextEncoder}pre_tokenize_text(_,O){return this.add_prefix_space&&!_.startsWith(" ")&&(_=" "+_),(this.use_regex?_.match(this.pattern)||[]:[_]).map(ue=>Array.from(this.text_encoder.encode(ue),de=>this.byte_encoder[de]).join(""))}}class je 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 Ge extends ze{constructor(_){super(),this.config=_,this.pattern=new RegExp(`[^${B}]+|[${B}]+`,"gu")}pre_tokenize_text(_,O){return _.match(this.pattern)||[]}}class Ve 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 Ke extends x.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"TemplateProcessing":return new wt(_);case"ByteLevel":return new xt(_);case"RobertaProcessing":return new mt(_);case"BertProcessing":return new ut(_);case"Sequence":return new M(_);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 ut extends Ke{constructor(_){super(_),this.cls=_.cls[0],this.sep=_.sep[0]}post_process(_,O=null,{add_special_tokens:Q=!0}={}){Q&&(_=(0,H.mergeArrays)([this.cls],_,[this.sep]));let ue=new Array(_.length).fill(0);if(O!==null){const de=Q&&this instanceof mt?[this.sep]:[],Fe=Q?[this.sep]:[];_=(0,H.mergeArrays)(_,de,O,Fe),ue=(0,H.mergeArrays)(ue,new Array(O.length+de.length+Fe.length).fill(1))}return{tokens:_,token_type_ids:ue}}}class mt extends ut{}class wt extends Ke{constructor(_){super(_),this.single=_.single,this.pair=_.pair}post_process(_,O=null,{add_special_tokens:Q=!0}={}){const ue=O===null?this.single:this.pair;let de=[],Fe=[];for(const gt of ue)"SpecialToken"in gt?Q&&(de.push(gt.SpecialToken.id),Fe.push(gt.SpecialToken.type_id)):"Sequence"in gt&&(gt.Sequence.id==="A"?(de=(0,H.mergeArrays)(de,_),Fe=(0,H.mergeArrays)(Fe,new Array(_.length).fill(gt.Sequence.type_id))):gt.Sequence.id==="B"&&(de=(0,H.mergeArrays)(de,O),Fe=(0,H.mergeArrays)(Fe,new Array(O.length).fill(gt.Sequence.type_id))));return{tokens:de,token_type_ids:Fe}}}class xt extends Ke{post_process(_,O=null){return O&&(_=(0,H.mergeArrays)(_,O)),{tokens:_}}}class M extends Ke{constructor(_){super(_),this.processors=_.processors.map(O=>Ke.fromConfig(O))}post_process(_,O=null,Q={}){let ue;for(const de of this.processors)if(de instanceof xt)_=de.post_process(_).tokens,O&&(O=de.post_process(O).tokens);else{const Fe=de.post_process(_,O,Q);_=Fe.tokens,ue=Fe.token_type_ids}return{tokens:_,token_type_ids:ue}}}class W extends x.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 At(_);case"Replace":return new S(_);case"ByteFallback":return new X(_);case"Fuse":return new fe(_);case"Strip":return new Ye(_);case"Sequence":return new Se(_);case"CTC":return new _t(_);case"BPEDecoder":return new $(_);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(Q=>Q.replaceAll(O,this.config.content))}}class X extends W{constructor(_){super(_),this.text_decoder=new TextDecoder}decode_chain(_){const O=[];let Q=[];for(const ue of _){let de=null;if(ue.length===6&&ue.startsWith("<0x")&&ue.endsWith(">")){const Fe=parseInt(ue.slice(3,5),16);isNaN(Fe)||(de=Fe)}if(de!==null)Q.push(de);else{if(Q.length>0){const Fe=this.text_decoder.decode(Uint8Array.from(Q));O.push(Fe),Q=[]}O.push(ue)}}if(Q.length>0){const ue=this.text_decoder.decode(Uint8Array.from(Q));O.push(ue),Q=[]}return O}}class fe 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 Q=0;for(let de=0;de(Q!==0&&(O.startsWith(this.config.prefix)?O=O.replace(this.config.prefix,""):O=" "+O),this.cleanup&&(O=Y(O)),O))}}class At extends W{constructor(_){super(_),this.byte_decoder=Qe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(_){const O=_.join(""),Q=new Uint8Array([...O].map(de=>this.byte_decoder[de]));return this.text_decoder.decode(Q)}decode_chain(_){const O=[];let Q=[];for(const ue of _)this.added_tokens.find(de=>de.content===ue)!==void 0?(Q.length>0&&(O.push(this.convert_tokens_to_string(Q)),Q=[]),O.push(ue)):Q.push(ue);return Q.length>0&&O.push(this.convert_tokens_to_string(Q)),O}}class _t 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 de=1;de<_.length;++de)_[de]!==O.at(-1)&&O.push(_[de]);let ue=O.filter(de=>de!==this.pad_token).join("");return this.cleanup&&(ue=Y(ue).replaceAll(this.word_delimiter_token," ").trim()),ue}decode_chain(_){return[this.convert_tokens_to_string(_)]}}class Se extends W{constructor(_){super(_),this.decoders=_.decoders.map(O=>W.fromConfig(O))}decode_chain(_){return this.decoders.reduce((O,Q)=>Q.decode_chain(O),_)}}class $ extends W{constructor(_){super(_),this.suffix=this.config.suffix}decode_chain(_){return _.map((O,Q)=>O.replaceAll(this.suffix,Q===_.length-1?"":" "))}}class q extends W{decode_chain(_){let O="";for(let Q=1;Q<_.length;Q+=2)O+=_[Q];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 Q=_.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Q.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&O===0)&&(Q=this.strRep+Q),[Q]}}class Be extends W{constructor(_){super(_),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement}decode_chain(_){const O=[];for(let Q=0;Q<_.length;++Q){let ue=_[Q].replaceAll(this.replacement," ");this.addPrefixSpace&&Q==0&&ue.startsWith(" ")&&(ue=ue.substring(1)),O.push(ue)}return O}}class Ae extends V{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(Q=>Q.normalize("NFKC")).join("~"):_=_.normalize("NFKC"),_}}class Ne extends ze{constructor(_){super(),this.tokenizers=_.pretokenizers.map(O=>ze.fromConfig(O))}pre_tokenize_text(_,O){return this.tokenizers.reduce((Q,ue)=>ue.pre_tokenize(Q,O),[_])}}class dt 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 I(_)}}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 ft=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ct(Me,_,O,Q){for(const ue of Object.keys(Me)){const de=_-Me[ue].length,Fe=O(ue),gt=new Array(de).fill(Fe);Me[ue]=Q==="right"?(0,H.mergeArrays)(Me[ue],gt):(0,H.mergeArrays)(gt,Me[ue])}}function Lt(Me,_){for(const O of Object.keys(Me))Me[O].length=_}class Xe extends x.Callable{constructor(O,Q){super();Te(this,"return_token_type_ids",!1);Te(this,"padding_side","right");this._tokenizer_config=Q,this.normalizer=V.fromConfig(O.normalizer),this.pre_tokenizer=ze.fromConfig(O.pre_tokenizer),this.model=Ce.fromConfig(O.model,Q),this.post_processor=Ke.fromConfig(O.post_processor),this.decoder=W.fromConfig(O.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ue of O.added_tokens){const de=new ye(ue);this.added_tokens.push(de),this.model.tokens_to_ids.set(de.content,de.id),this.model.vocab[de.id]=de.content,de.special&&(this.special_tokens.push(de.content),this.all_special_ids.push(de.id))}if(this.additional_special_tokens=Q.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.toSorted((ue,de)=>de.content.length-ue.content.length).map(ue=>`${ue.lstrip?"\\s*":""}(${(0,H.escapeRegExp)(ue.content)})${ue.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=Q.model_max_length,this.remove_space=Q.remove_space,this.clean_up_tokenization_spaces=Q.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Q.do_lowercase_and_remove_accent??!1,Q.padding_side&&(this.padding_side=Q.padding_side),this.legacy=!1,this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){const ue=Object.create(null);for(const{name:de,template:Fe}of this.chat_template){if(typeof de!="string"||typeof Fe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ue[de]=Fe}this.chat_template=ue}this._compiled_template_cache=new Map}getToken(...O){for(const Q of O){const ue=this._tokenizer_config[Q];if(ue)if(typeof ue=="object"){if(ue.__type==="AddedToken")return ue.content;throw Error(`Unknown token: ${ue}`)}else return ue}return null}static async from_pretrained(O,{progress_callback:Q=null,config:ue=null,cache_dir:de=null,local_files_only:Fe=!1,revision:gt="main",legacy:bt=null}={}){const yt=await J(O,{progress_callback:Q,config:ue,cache_dir:de,local_files_only:Fe,revision:gt,legacy:bt});return new this(...yt)}_call(O,{text_pair:Q=null,add_special_tokens:ue=!0,padding:de=!1,truncation:Fe=null,max_length:gt=null,return_tensor:bt=!0,return_token_type_ids:yt=null}={}){const Pt=Array.isArray(O);let Jt;if(Pt){if(O.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(O.length!==Q.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Jt=O.map((nr,Gt)=>this._encode_plus(nr,{text_pair:Q[Gt],add_special_tokens:ue,return_token_type_ids:yt}))}else Jt=O.map(nr=>this._encode_plus(nr,{add_special_tokens:ue,return_token_type_ids:yt}))}else{if(O==null)throw Error("text may not be null or undefined");if(Array.isArray(Q))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Jt=[this._encode_plus(O,{text_pair:Q,add_special_tokens:ue,return_token_type_ids:yt})]}if(gt===null?de==="max_length"?gt=this.model_max_length:gt=(0,ve.max)(Jt.map(nr=>nr.input_ids.length))[0]:Fe||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),gt=Math.min(gt,this.model_max_length??1/0),de||Fe)for(let nr=0;nrgt?Fe&&Lt(Jt[nr],gt):de&&Ct(Jt[nr],gt,Gt=>Gt==="input_ids"?this.pad_token_id:0,this.padding_side));const $r={};if(bt){if(!(de&&Fe)&&Jt.some(Gt=>{var fr;for(const on of Object.keys(Gt))if(Gt[on].length!==((fr=Jt[0][on])==null?void 0:fr.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 nr=[Jt.length,Jt[0].input_ids.length];for(const Gt of Object.keys(Jt[0]))$r[Gt]=new xe.Tensor("int64",BigInt64Array.from(Jt.flatMap(fr=>fr[Gt]).map(BigInt)),nr)}else{for(const nr of Object.keys(Jt[0]))$r[nr]=Jt.map(Gt=>Gt[nr]);if(!Pt)for(const nr of Object.keys($r))$r[nr]=$r[nr][0]}return $r}_encode_text(O){return O===null?null:(this.added_tokens_regex?O.split(this.added_tokens_regex).filter(de=>de):[O]).map((de,Fe)=>{if(this.added_tokens.find(bt=>bt.content===de)!==void 0)return de;{if(this.remove_space===!0&&(de=de.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(de=le(de)),this.normalizer!==null&&(de=this.normalizer(de)),de.length===0)return[];const bt=this.pre_tokenizer!==null?this.pre_tokenizer(de,{section_index:Fe}):[de];return this.model(bt)}}).flat()}_encode_plus(O,{text_pair:Q=null,add_special_tokens:ue=!0,return_token_type_ids:de=null}={}){const{tokens:Fe,token_type_ids:gt}=this._tokenize_helper(O,{pair:Q,add_special_tokens:ue}),bt=this.model.convert_tokens_to_ids(Fe),yt={input_ids:bt,attention_mask:new Array(bt.length).fill(1)};return(de??this.return_token_type_ids)&>&&(yt.token_type_ids=gt),yt}_tokenize_helper(O,{pair:Q=null,add_special_tokens:ue=!1}={}){const de=this._encode_text(O),Fe=this._encode_text(Q);return this.post_processor?this.post_processor(de,Fe,{add_special_tokens:ue}):{tokens:(0,H.mergeArrays)(de??[],Fe??[])}}tokenize(O,{pair:Q=null,add_special_tokens:ue=!1}={}){return this._tokenize_helper(O,{pair:Q,add_special_tokens:ue}).tokens}encode(O,{text_pair:Q=null,add_special_tokens:ue=!0,return_token_type_ids:de=null}={}){return this._encode_plus(O,{text_pair:Q,add_special_tokens:ue,return_token_type_ids:de}).input_ids}batch_decode(O,Q={}){return O instanceof xe.Tensor&&(O=O.tolist()),O.map(ue=>this.decode(ue,Q))}decode(O,Q={}){if(O instanceof xe.Tensor&&(O=R(O)),!Array.isArray(O)||O.length===0||!(0,H.isIntegralNumber)(O[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(O,Q)}decode_single(O,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:ue=null}){let de=this.model.convert_ids_to_tokens(O);Q&&(de=de.filter(gt=>!this.special_tokens.includes(gt)));let Fe=this.decoder?this.decoder(de):de.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Fe=Fe.replaceAll(this.decoder.end_of_word_suffix," "),Q&&(Fe=Fe.trim())),(ue??this.clean_up_tokenization_spaces)&&(Fe=Y(Fe)),Fe}apply_chat_template(O,{tools:Q=null,documents:ue=null,chat_template:de=null,add_generation_prompt:Fe=!1,tokenize:gt=!0,padding:bt=!1,truncation:yt=!1,max_length:Pt=null,return_tensor:Jt=!0,return_dict:$r=!1,tokenizer_kwargs:nr={},...Gt}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const qe=this.chat_template;if(de!==null&&Object.hasOwn(qe,de))de=qe[de];else if(de===null&&"default"in qe)de=qe.default;else if(de===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(qe).sort()}.`)}else if(this.chat_template)de=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 de!="string")throw Error(`chat_template must be a string, but got ${typeof de}`);let fr=this._compiled_template_cache.get(de);fr===void 0&&(fr=new T.Template(de),this._compiled_template_cache.set(de,fr));const on=Object.create(null);for(const qe of ft){const yn=this.getToken(qe);yn&&(on[qe]=yn)}const Yr=fr.render({messages:O,add_generation_prompt:Fe,tools:Q,documents:ue,...on,...Gt});if(gt){const qe=this._call(Yr,{add_special_tokens:!1,padding:bt,truncation:yt,max_length:Pt,return_tensor:Jt,...nr});return $r?qe:qe.input_ids}return Yr}}class jt extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Rt extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Ht extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Xt extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class er extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Wt extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Tr extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Ur extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Cr extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Ze extends Xe{}class St extends Xe{}class Dt extends Xe{constructor(O,Q){super(O,Q);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 qr extends Xe{constructor(){super(...arguments);Te(this,"return_token_type_ids",!0)}}class Un extends Xe{}class Fn extends Xe{}class Lr extends Xe{}class Zr extends Xe{constructor(_,O){super(_,O),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(_,O,Q){return zn(this,_,O,Q)}}class Nr extends Zr{}class Sn extends Xe{}class Pr extends Xe{constructor(_,O){var de,Fe;const Q=".,!?…。,、।۔،",ue=(Fe=(de=_.pre_tokenizer)==null?void 0:de.pretokenizers[0])==null?void 0:Fe.pattern;ue&&ue.Regex===` ?[^(\\s|[${Q}])]+`&&(ue.Regex=` ?[^\\s${Q}]+`),super(_,O)}}const Wn="▁";class On extends Xe{constructor(O,Q){super(O,Q);Te(this,"padding_side","left");this.legacy=Q.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new be({replacement:Wn,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 Q=super._encode_text(Wn+O.replaceAll(Wn," "));return Q.length>1&&Q[0]===Wn&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class Vs extends Xe{}class _s extends Xe{}class gs extends Xe{}class ws extends Xe{}class ys extends Xe{}class Gn extends Xe{}class Us extends Xe{}class ss extends Xe{}class kn extends Xe{}function zn(Me,_,O,Q){if(!("language_codes"in Me)||!Array.isArray(Me.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Me)||!(Me.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Me)||typeof Me.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ue=Q.src_lang,de=Q.tgt_lang;if(!Me.language_codes.includes(de))throw new Error(`Target language code "${de}" is not valid. Must be one of: {${Me.language_codes.join(", ")}}`);if(ue!==void 0){if(!Me.language_codes.includes(ue))throw new Error(`Source language code "${ue}" is not valid. Must be one of: {${Me.language_codes.join(", ")}}`);for(const Fe of Me.post_processor.config.single)if("SpecialToken"in Fe&&Me.languageRegex.test(Fe.SpecialToken.id)){Fe.SpecialToken.id=Me.lang_to_token(ue);break}}return Q.forced_bos_token_id=Me.model.convert_tokens_to_ids([Me.lang_to_token(de)])[0],Me._call(_,O)}class Dn extends Xe{constructor(_,O){super(_,O),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(_,O,Q){return zn(this,_,O,Q)}}class Qn extends Xe{constructor(_,O){super(_,O),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)).map(Q=>Q.slice(2,-2)),this.lang_to_token=Q=>`__${Q}__`}_build_translation_inputs(_,O,Q){return zn(this,_,O,Q)}}class is extends Xe{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(_,{return_timestamps:O=!1,return_language:Q=!1,time_precision:ue=null,force_full_sequences:de=!0}={}){if(ue===null)throw Error("Must specify time_precision");let Fe=null;const gt=O==="word";function bt(){return{language:Fe,timestamp:[null,null],text:""}}const yt=[];let Pt=bt(),Jt=0;const $r=this.timestamp_begin;let nr=[],Gt=[],fr=!1,on=null;const Yr=new Set(this.all_special_ids);for(const Mr of _){const Hr=Mr.tokens,cn=gt?Mr.token_timestamps:null;let Yt=null,_n=$r;if("stride"in Mr){const[xr,kt,gr]=Mr.stride;if(Jt-=kt,on=xr-gr,kt&&(_n=kt/ue+$r),gr)for(let Ar=Hr.length-1;Ar>=0;--Ar){const jr=Number(Hr[Ar]);if(jr>=$r){if(Yt!==null&&(jr-$r)*ue=$r){const gr=(kt-$r)*ue+Jt,Ar=(0,ve.round)(gr,2);if(Yt!==null&&kt>=Yt)fr=!0;else if(fr||nr.length>0&&kt<_n)fr=!1;else if(Pt.timestamp[0]===null)Pt.timestamp[0]=Ar;else if(Ar!==Pt.timestamp[0]){Pt.timestamp[1]=Ar,nr.push(Jr),gt&&Gt.push(vr);const[jr,gn]=this.findLongestCommonSequence(nr,Gt),Ft=this.decode(jr);Pt.text=Ft,gt&&(Pt.words=this.collateWordTimestamps(jr,gn,Fe)),yt.push(Pt),nr=[],Jr=[],Gt=[],vr=[],Pt=bt()}}else if(Jr.push(kt),gt){let gr=(0,ve.round)(cn[xr]+Jt,2),Ar;if(xr+10?(nr.push(Jr),gt&&Gt.push(vr)):nr.every(xr=>xr.length===0)&&(Pt=bt(),nr=[],Jr=[],Gt=[],vr=[])}if(nr.length>0){if(de&&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[Mr,Hr]=this.findLongestCommonSequence(nr,Gt),cn=this.decode(Mr);Pt.text=cn,gt&&(Pt.words=this.collateWordTimestamps(Mr,Hr,Fe)),yt.push(Pt)}let qe=Object.create(null);const yn=yt.map(Mr=>Mr.text).join("");if(O||Q){for(let Mr=0;Mr0;let gt=Fe?[]:null,bt=Fe?O[0]:null;for(let yt=1;yt<_.length;++yt){const Pt=_[yt];let Jt=0,$r=[ue,ue,0,0];const nr=Pt.length;for(let Mr=1;MrAr===vr[jr]&&bt[Hr+jr]<=O[yt][_n+jr]).length:xr=Yt.filter((Ar,jr)=>Ar===vr[jr]).length;const kt=Mr/1e4,gr=xr/Mr+kt;xr>1&&gr>Jt&&(Jt=gr,$r=[Hr,cn,_n,Jr])}const[Gt,fr,on,Yr]=$r,qe=Math.floor((fr+Gt)/2),yn=Math.floor((Yr+on)/2);de.push(...Q.slice(0,qe)),Q=Pt.slice(yn),ue=Q.length,Fe&&(gt.push(...bt.slice(0,qe)),bt=O[yt].slice(yn))}return de.push(...Q),Fe?(gt.push(...bt),[de,gt]):[de,[]]}collateWordTimestamps(_,O,Q){const[ue,de,Fe]=this.combineTokensIntoWords(_,Q),gt=[];for(let bt=0;bt=ue){const gt=((Fe-ue)*Q).toFixed(2);de.push(`<|${gt}|>`),de.push([])}else de[de.length-1].push(Fe);return de=de.map(Fe=>typeof Fe=="string"?Fe:super.decode(Fe,O)),de.join("")}splitTokensOnUnicode(_){const O=this.decode(_,{decode_with_timestamps:!0}),Q="�",ue=[],de=[],Fe=[];let gt=[],bt=[],yt=0;for(let Pt=0;Pt<_.length;++Pt){const Jt=_[Pt];gt.push(Jt),bt.push(Pt);const $r=this.decode(gt,{decode_with_timestamps:!0});(!$r.includes(Q)||O[yt+$r.indexOf(Q)]===Q)&&(ue.push($r),de.push(gt),Fe.push(bt),gt=[],bt=[],yt+=$r.length)}return[ue,de,Fe]}splitTokensOnSpaces(_){const[O,Q,ue]=this.splitTokensOnUnicode(_),de=[],Fe=[],gt=[],bt=new RegExp(`^[${B}]$`,"gu");for(let yt=0;yt=this.model.tokens_to_ids.get("<|endoftext|>"),Gt=Pt.startsWith(" "),fr=Pt.trim(),on=bt.test(fr);if(nr||Gt||on||de.length===0)de.push(Pt),Fe.push(Jt),gt.push($r);else{const Yr=de.length-1;de[Yr]+=Pt,Fe[Yr].push(...Jt),gt[Yr].push(...$r)}}return[de,Fe,gt]}mergePunctuations(_,O,Q,ue,de){const Fe=structuredClone(_),gt=structuredClone(O),bt=structuredClone(Q);let yt=Fe.length-2,Pt=Fe.length-1;for(;yt>=0;)Fe[yt].startsWith(" ")&&ue.includes(Fe[yt].trim())?(Fe[Pt]=Fe[yt]+Fe[Pt],gt[Pt]=(0,H.mergeArrays)(gt[yt],gt[Pt]),bt[Pt]=(0,H.mergeArrays)(bt[yt],bt[Pt]),Fe[yt]="",gt[yt]=[],bt[yt]=[]):Pt=yt,--yt;for(yt=0,Pt=1;PtJt),gt.filter(Jt=>Jt.length>0),bt.filter(Jt=>Jt.length>0)]}get_decoder_prompt_ids({language:_=null,task:O=null,no_timestamps:Q=!0}={}){const ue=[];if(_){const de=(0,j.whisper_language_to_code)(_),Fe=this.model.tokens_to_ids.get(`<|${de}|>`);if(Fe===void 0)throw new Error(`Unable to find language "${de}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);ue.push(Fe)}else ue.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 de=this.model.tokens_to_ids.get(`<|${O}|>`);if(de===void 0)throw new Error(`Unable to find task "${O}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);ue.push(de)}else ue.push(null);if(Q){const de=this.model.tokens_to_ids.get("<|notimestamps|>");if(de===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);ue.push(de)}return ue.map((de,Fe)=>[Fe+1,de]).filter(de=>de[1]!==null)}}class as extends Xe{}class Qt extends Xe{}class Yn extends Xe{}class bs extends Xe{constructor(_,O){super(_,O),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Q=>this.languageRegex.test(Q)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(_){if(_===null)return null;const[O,...Q]=_.trim().split(this.languageRegex);if(Q.length===0)return super._encode_text(O);if(Q.length===2){const[ue,de]=Q;return this.supported_language_codes.includes(ue)||console.warn(`Unsupported language code "${ue}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,H.mergeArrays)([ue],super._encode_text(de))}}}class Ms extends Xe{}class os extends Xe{}class vs extends Xe{}class xs extends Xe{}class ls extends Xe{}class Ts extends Xe{constructor(_,O){super(_,O),this.decoder=new q({})}}class Dr extends Xe{}class mn{static async from_pretrained(_,{progress_callback:O=null,config:Q=null,cache_dir:ue=null,local_files_only:de=!1,revision:Fe="main",legacy:gt=null}={}){var $r;const[bt,yt]=await J(_,{progress_callback:O,config:Q,cache_dir:ue,local_files_only:de,revision:Fe,legacy:gt}),Pt=(($r=yt.tokenizer_class)==null?void 0:$r.replace(/Fast$/,""))??"PreTrainedTokenizer";let Jt=this.TOKENIZER_CLASS_MAPPING[Pt];return Jt||(console.warn(`Unknown tokenizer class "${Pt}", attempting to construct from base class.`),Jt=Xe),new Jt(bt,yt)}}Te(mn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Un,DistilBertTokenizer:Ze,CamembertTokenizer:St,DebertaTokenizer:er,DebertaV2Tokenizer:Wt,BertTokenizer:jt,HerbertTokenizer:Tr,ConvBertTokenizer:Ur,RoFormerTokenizer:Cr,XLMTokenizer:Dt,ElectraTokenizer:qr,MobileBertTokenizer:Ht,SqueezeBertTokenizer:Xt,AlbertTokenizer:Rt,GPT2Tokenizer:Fn,BartTokenizer:Lr,MBartTokenizer:Zr,MBart50Tokenizer:Nr,RobertaTokenizer:Sn,WhisperTokenizer:is,CodeGenTokenizer:as,CLIPTokenizer:Qt,SiglipTokenizer:Yn,MarianTokenizer:bs,BloomTokenizer:Pr,NllbTokenizer:Dn,M2M100Tokenizer:Qn,LlamaTokenizer:On,CodeLlamaTokenizer:Vs,XLMRobertaTokenizer:_s,MPNetTokenizer:gs,FalconTokenizer:ws,GPTNeoXTokenizer:ys,EsmTokenizer:Gn,Wav2Vec2CTCTokenizer:Ms,BlenderbotTokenizer:os,BlenderbotSmallTokenizer:vs,SpeechT5Tokenizer:xs,NougatTokenizer:ls,VitsTokenizer:Ts,Qwen2Tokenizer:Us,GemmaTokenizer:ss,Grok1Tokenizer:kn,CohereTokenizer:Dr,PreTrainedTokenizer:Xe})},"./src/utils/audio.js":(Mt,me,l)=>{l.r(me),l.d(me,{hamming:()=>j,hanning:()=>T,mel_filter_bank:()=>Y,read_audio:()=>xe,spectrogram:()=>I,window_function:()=>B});var x=l("./src/utils/hub.js"),H=l("./src/utils/maths.js"),ge=l("./src/utils/core.js"),ve=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,x.getFile)(A)).arrayBuffer(),Ce=new AudioContext({sampleRate:_e});typeof _e>"u"&&console.warn(`No sampling rate provided, using default of ${Ce.sampleRate}Hz.`);const ke=await Ce.decodeAudioData(ye);let Ie;if(ke.numberOfChannels===2){const tt=Math.sqrt(2),Qe=ke.getChannelData(0),ht=ke.getChannelData(1);Ie=new Float32Array(Qe.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,Ce=27/Math.log(6.4))=>A>=_e?ye+Math.log(A/_e)*Ce: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(Ce=>ye(Ce))}const te={htk:A=>700*(10**(A/2595)-1),kaldi:A=>700*(Math.exp(A/1127)-1),slaney:(A,_e=1e3,ye=15,Ce=Math.log(6.4)/27)=>A>=ye?_e*Math.exp(Ce*(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(Ce=>ye(Ce))}function ie(A,_e){const ye=Float64Array.from({length:_e.length-1},(tt,Qe)=>_e[Qe+1]-_e[Qe]),Ce=Array.from({length:A.length},()=>new Array(_e.length));for(let tt=0;ttnew Array(A.length));for(let tt=0;ttA+Ce*Ie)}function Y(A,_e,ye,Ce,ke,Ie=null,tt="htk",Qe=!1){if(Ie!==null&&Ie!=="slaney")throw new Error('norm must be one of null or "slaney"');const ht=J(ye,tt),we=J(Ce,tt),V=R(ht,we,_e+2);let he=ne(V,tt),$e;if(Qe){const He=ke/(A*2);$e=J(Float64Array.from({length:A},(pt,rt)=>rt*He),tt),he=V}else $e=R(0,Math.floor(ke/2),A);const ee=ie($e,he);if(Ie!==null&&Ie==="slaney")for(let He=0;He<_e;++He){const pt=ee[He],rt=2/(he[He+2]-he[He]);for(let lt=0;ltke)throw Error(`frame_length (${ye}) may not be larger than fft_length (${ke})`);if(ze!==ye)throw new Error(`Length of the window (${ze}) must equal frame_length (${ye})`);if(Ce<=0)throw new Error("hop_length must be greater than zero");if(Ie===null&&V!==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(tt){if(Qe!=="reflect")throw new Error(`pad_mode="${Qe}" not implemented yet.`);const W=Math.floor((ke-1)/2)+1;A=se(A,W,W)}let re=Math.floor(1+Math.floor((A.length-ye)/Ce));lt!==null&&rere?st&&(Ge=Re):Ge=je=Re);const Ve=new H.FFT(ke),Ke=new Float64Array(ke),ut=new Float64Array(Ve.outputBufferSize),mt=new Float32Array(Ee*Ge);for(let W=0;W=1;--fe)Ke[fe]-=we*Ke[fe-1];Ke[0]*=1-we}for(let fe=0;fe<_e.length;++fe)Ke[fe]*=_e[fe];Ve.realTransform(ut,Ke);for(let fe=0;feMath.pow(Qe,.85));break;default:throw new Error(`Unknown window type ${_e}.`)}if(ye&&(tt=tt.subarray(0,A)),Ce===null)return tt;if(A>Ce)throw new Error(`Length of the window (${A}) may not be larger than frame_length (${Ce})`);return tt}},"./src/utils/constants.js":(Mt,me,l)=>{l.r(me),l.d(me,{GITHUB_ISSUE_URL:()=>x});const x="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(Mt,me,l)=>{l.r(me),l.d(me,{calculateDimensions:()=>D,calculateReflectOffset:()=>J,dispatchCallback:()=>x,escapeRegExp:()=>ge,isIntegralNumber:()=>xe,isTypedArray:()=>ve,mergeArrays:()=>j,pick:()=>te,pop:()=>T,product:()=>P,reverseDictionary:()=>H});function x(ne,ie){ne&&ne(ie)}function H(ne){return Object.fromEntries(Object.entries(ne).map(([ie,R])=>[R,ie]))}function ge(ne){return ne.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ve(ne){var ie,R,Y;return((Y=(R=(ie=ne==null?void 0:ne.prototype)==null?void 0:ie.__proto__)==null?void 0:R.constructor)==null?void 0:Y.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 T(ne,ie,R=void 0){const Y=ne[ie];if(Y!==void 0)return delete ne[ie],Y;if(R===void 0)throw Error(`Key ${ie} does not exist in object.`);return R}function j(...ne){return Array.prototype.concat.apply([],ne)}function P(...ne){return ne.reduce((ie,R)=>ie.flatMap(Y=>R.map(se=>[Y,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":(Mt,me,l)=>{l.r(me),l.d(me,{CharTrie:()=>H,PriorityQueue:()=>x,TokenLattice:()=>ve});class x{constructor(T=(P,J)=>P>J,j=1/0){this._heap=[],this._comparator=T,this._maxSize=j}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...T){return this.extend(T)}extend(T){for(const j of T)if(this.size0&&this._swap(0,j),this._heap.pop(),this._siftDown(),T}replace(T){const j=this.peek();return this._heap[0]=T,this._siftDown(),j}_parent(T){return(T+1>>>1)-1}_left(T){return(T<<1)+1}_right(T){return T+1<<1}_greater(T,j){return this._comparator(this._heap[T],this._heap[j])}_swap(T,j){const P=this._heap[T];this._heap[T]=this._heap[j],this._heap[j]=P}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(T){for(;T>0&&this._greater(T,this._parent(T));)this._swap(T,this._parent(T)),T=this._parent(T)}_siftDown(){let T=0;for(;this._left(T)[]),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(T,j,P,J){const te=this.nodes.length,ne=new xe(J,te,T,j,P);this.beginNodes[T].push(ne),this.endNodes[T+j].push(ne),this.nodes.push(ne)}viterbi(){const T=this.len;let j=0;for(;j<=T;){if(this.beginNodes[j].length==0)return[];for(let ie of this.beginNodes[j]){ie.prev=null;let R=0,Y=null;for(let se of this.endNodes[j]){const le=se.backtraceScore+ie.score;(Y===null||le>R)&&(Y=se.clone(),R=le)}if(Y!==null)ie.prev=Y,ie.backtraceScore=R;else return[]}++j}const P=[],te=this.beginNodes[T][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(T){return this.sentence.slice(T.pos,T.pos+T.length)}tokens(){return this.viterbi().map(j=>this.piece(j))}tokenIds(){return this.viterbi().map(j=>j.tokenId)}}class xe{constructor(T,j,P,J,te){this.tokenId=T,this.nodeId=j,this.pos=P,this.length=J,this.score=te,this.prev=null,this.backtraceScore=0}clone(){const T=new xe(this.tokenId,this.nodeId,this.pos,this.length,this.score);return T.prev=this.prev,T.backtraceScore=this.backtraceScore,T}}},"./src/utils/devices.js":(Mt,me,l)=>{l.r(me),l.d(me,{DEVICE_TYPES:()=>x});const x=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":(Mt,me,l)=>{l.r(me),l.d(me,{DATA_TYPES:()=>ve,DEFAULT_DEVICE_DTYPE_MAPPING:()=>xe,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>D,isWebGpuFp16Supported:()=>ge});var x=l("./src/env.js"),H=l("./src/utils/devices.js");const ge=function(){let T;return async function(){if(T===void 0)if(!x.apis.IS_WEBGPU_AVAILABLE)T=!1;else try{T=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{T=!1}return T}}(),ve=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),xe=Object.freeze({[H.DEVICE_TYPES.wasm]:ve.q8}),D=Object.freeze({[ve.fp32]:"",[ve.fp16]:"_fp16",[ve.int8]:"_int8",[ve.uint8]:"_uint8",[ve.q8]:"_quantized",[ve.q4]:"_q4",[ve.q4f16]:"_q4f16",[ve.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Mt,me,l)=>{l.r(me),l.d(me,{Callable:()=>x});const x=class{constructor(){let H=function(...ge){return H._call(...ge)};return Object.setPrototypeOf(H,new.target.prototype)}_call(...H){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Mt,me,l)=>{l.r(me),l.d(me,{getFile:()=>j,getModelFile:()=>ie,getModelJSON:()=>R});var x=l("?7a2c"),H=l("?a42a"),ge=l("./src/env.js"),ve=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=x.existsSync(ae),this.exists){this.status=200,this.statusText="OK";let N=x.statSync(ae);this.headers.set("content-length",N.size.toString()),this.updateContentType();let I=this;this.body=new ReadableStream({start(B){I.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 x.promises.readFile(this.filePath)).buffer}async blob(){const ae=await x.promises.readFile(this.filePath);return new Blob([ae],{type:this.headers.get("content-type")})}async text(){return await x.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function T(le,ae=null,N=null){let I;try{I=new URL(le)}catch{return!1}return!(ae&&!ae.includes(I.protocol)||N&&!N.includes(I.hostname))}async function j(le){var ae;if(ge.env.useFS&&!T(le,["http:","https:","blob:"]))return new D(le);if(typeof process<"u"&&((ae=process==null?void 0:process.release)==null?void 0:ae.name)==="node"){const N=!!(wn!=null&&wn.TESTING_REMOTELY),I=ge.env.version,B=new Headers;if(B.set("User-Agent",`transformers.js/${I}; is_ci/${N};`),T(le,["http:","https:"],["huggingface.co","hf.co"])){const _e=(wn==null?void 0:wn.HF_TOKEN)??(wn==null?void 0:wn.HF_ACCESS_TOKEN);_e&&B.set("Authorization",`Bearer ${_e}`)}return fetch(le,{headers:B})}else return fetch(le)}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(le,ae,N){if(!N)return null;const I=P[le]??`Error (${le}) occurred while trying to load file`;throw Error(`${I}: "${ae}".`)}class te{constructor(ae){this.path=ae}async match(ae){let N=H.join(this.path,ae),I=new D(N);if(I.exists)return I}async put(ae,N){const I=Buffer.from(await N.arrayBuffer());let B=H.join(this.path,ae);try{await x.promises.mkdir(H.dirname(B),{recursive:!0}),await x.promises.writeFile(B,I)}catch(A){console.warn("An error occurred while writing the file to cache:",A)}}}async function ne(le,...ae){for(let N of ae)try{let I=await le.match(N);if(I)return I}catch{continue}}async function ie(le,ae,N=!0,I={}){if(!ge.env.allowLocalModels){if(I.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!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,ve.dispatchCallback)(I.progress_callback,{status:"initiate",name:le,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($e){console.warn("An error occurred while opening the browser cache:",$e)}}if(!B&&ge.env.useFSCache&&(B=new te(I.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=I.revision??"main";let _e=se(le,ae),ye=se(ge.env.localModelPath,_e),Ce=se(ge.env.remoteHost,ge.env.remotePathTemplate.replaceAll("{model}",le).replaceAll("{revision}",encodeURIComponent(A)),ae),ke=A==="main"?_e:se(le,A,ae),Ie,tt=B instanceof te?ke:Ce,Qe=!1,ht;B&&(ht=await ne(B,ye,tt));const we=ht!==void 0;if(ht===void 0){if(ge.env.allowLocalModels)if(T(_e,["http:","https:"])){if(I.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{ht=await j(ye),Ie=ye}catch(ee){console.warn(`Unable to load from local path "${ye}": "${ee}"`)}if(ht===void 0||ht.status===404){if(I.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(ht=await j(Ce),ht.status!==200)return J(ht.status,Ce,N);Ie=tt}Qe=B&&typeof Response<"u"&&ht instanceof Response&&ht.status===200}(0,ve.dispatchCallback)(I.progress_callback,{status:"download",name:le,file:ae});const V={status:"progress",name:le,file:ae};let he;return I.progress_callback?we&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(he=new Uint8Array(await ht.arrayBuffer()),(0,ve.dispatchCallback)(I.progress_callback,{...V,progress:100,loaded:he.length,total:he.length})):he=await Y(ht,$e=>{(0,ve.dispatchCallback)(I.progress_callback,{...V,...$e})}):he=new Uint8Array(await ht.arrayBuffer()),Qe&&Ie&&await B.match(Ie)===void 0&&await B.put(Ie,new Response(he,{headers:ht.headers})).catch($e=>{console.warn(`Unable to add response to browser cache: ${$e}.`)}),(0,ve.dispatchCallback)(I.progress_callback,{status:"done",name:le,file:ae}),he}async function R(le,ae,N=!0,I={}){let B=await ie(le,ae,N,I);if(B===null)return{};let _e=new TextDecoder("utf-8").decode(B);return JSON.parse(_e)}async function Y(le,ae){const N=le.headers.get("Content-Length");N===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let I=parseInt(N??"0"),B=new Uint8Array(I),A=0;const _e=le.body.getReader();async function ye(){const{done:Ce,value:ke}=await _e.read();if(Ce)return;let Ie=A+ke.length;if(Ie>I){I=Ie;let Qe=new Uint8Array(I);Qe.set(B),B=Qe}B.set(ke,A),A=Ie;const tt=A/I*100;return ae({progress:tt,loaded:A,total:I}),ye()}return await ye(),B}function se(...le){return le=le.map((ae,N)=>(N&&(ae=ae.replace(new RegExp("^/"),"")),N!==le.length-1&&(ae=ae.replace(new RegExp("/$"),"")),ae)),le.join("/")}},"./src/utils/image.js":(Mt,me,l)=>{l.r(me),l.d(me,{RawImage:()=>ne});var x=l("./src/utils/hub.js"),H=l("./src/env.js"),ge=l("./src/utils/tensor.js"),ve=l("?2b25");const xe=typeof self<"u",D=xe&&self.constructor.name==="DedicatedWorkerGlobalScope";let T,j,P;if(xe)T=(ie,R)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ie,R)},P=self.createImageBitmap,j=self.ImageData;else if(ve)P=async ie=>{const Y=(await ie.metadata()).channels,{data:se,info:le}=await ie.rotate().raw().toBuffer({resolveWithObject:!0}),ae=new ne(new Uint8ClampedArray(se),le.width,le.height,le.channels);return Y!==void 0&&Y!==le.channels&&ae.convert(Y),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,Y,se,le){this.data=R,this.width=Y,this.height=se,this.channels=le}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 Y=await(0,x.getFile)(R);if(Y.status!==200)throw new Error(`Unable to read image from "${R}" (${Y.status} ${Y.statusText})`);const se=await Y.blob();return this.fromBlob(se)}static async fromBlob(R){if(xe){const Y=await P(R),se=T(Y.width,Y.height).getContext("2d");return se.drawImage(Y,0,0),new this(se.getImageData(0,0,Y.width,Y.height).data,Y.width,Y.height,4)}else{const Y=ve(await R.arrayBuffer());return await P(Y)}}static fromTensor(R,Y="CHW"){if(R.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${R.dims.length} dimensions.`);if(Y==="CHW")R=R.transpose(1,2,0);else if(Y!=="HWC")throw new Error(`Unsupported channel format: ${Y}`);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 Y=0,se=0;Y=0?B=se:_e=-se,le>=0?A=le:ye=-le,I.drawImage(N,B,A,R,Y,_e,ye,R,Y),new ne(I.getImageData(0,0,R,Y).data,R,Y,4).convert(ae)}else{let ae=this.toSharp();if(se>=0&&le>=0)ae=ae.extract({left:Math.floor(se),top:Math.floor(le),width:R,height:Y});else if(se<=0&&le<=0){const N=Math.floor(-le),I=Math.floor(-se);ae=ae.extend({top:N,left:I,right:R-this.width-I,bottom:Y-this.height-N})}else{let N=[0,0],I=0;le<0?(N[0]=Math.floor(-le),N[1]=Y-this.height-N[0]):I=Math.floor(le);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:I,width:R,height:Y})}return await P(ae)}}async toBlob(R="image/png",Y=1){if(!xe)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:R,quality:Y})}toTensor(R="CHW"){let Y=new ge.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(R!=="HWC")if(R==="CHW")Y=Y.permute(2,0,1);else throw new Error(`Unsupported channel format: ${R}`);return Y}toCanvas(){if(!xe)throw new Error("toCanvas() is only supported in browser environments.");const R=this.clone().rgba(),Y=T(R.width,R.height),se=new j(R.data,R.width,R.height);return Y.getContext("2d").putImageData(se,0,0),Y}_update(R,Y,se,le=null){return this.data=R,this.width=Y,this.height=se,le!==null&&(this.channels=le),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 Y=R.split(".").pop().toLowerCase(),se=te.get(Y)??"image/png",le=await this.toBlob(se),ae=URL.createObjectURL(le),N=document.createElement("a");N.href=ae,N.download=R,N.click(),N.remove()}else{if(H.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 ve(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(Mt,me,l)=>{l.r(me),l.d(me,{FFT:()=>ie,bankers_round:()=>se,cos_sim:()=>D,dot:()=>xe,dynamic_time_warping:()=>le,interpolate_data:()=>x,log_softmax:()=>ve,magnitude:()=>T,max:()=>P,medianFilter:()=>R,min:()=>j,permute_data:()=>H,round:()=>Y,softmax:()=>ge});function x(ae,[N,I,B],[A,_e],ye="bilinear",Ce=!1){const ke=_e/B,Ie=A/I,tt=new ae.constructor(A*_e*N),Qe=I*B,ht=A*_e;for(let we=0;we=0;--Ce)A[Ce]=ke,B[Ce]=N[I[Ce]],ke*=B[Ce];const _e=I.map((Ce,ke)=>A[I.indexOf(ke)]),ye=new ae.constructor(ae.length);for(let Ce=0;Ce=0;--Ie)ke+=tt%N[Ie]*_e[Ie],tt=Math.floor(tt/N[Ie]);ye[ke]=ae[Ce]}return[ye,B]}function ge(ae){const N=P(ae)[0],I=ae.map(_e=>Math.exp(_e-N)),B=I.reduce((_e,ye)=>_e+ye,0);return I.map(_e=>_e/B)}function ve(ae){return ge(ae).map(B=>Math.log(B))}function xe(ae,N){let I=0;for(let B=0;BN+I*I,0))}function j(ae){if(ae.length===0)throw Error("Array must not be empty");let N=ae[0],I=0;for(let B=1;BN&&(N=ae[B],I=B);return[Number(N),I]}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)++I;this._width=I%2===0?I-1:I,this._bitrev=new Int32Array(1<>>A&3)<<_e}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(N,I){const B=I||new Array(N.length>>>1);for(let A=0;A>>1]=N[A];return B}toComplexArray(N,I){const B=I||this.createComplexArray();for(let A=0;A>>1],B[A+1]=0;return B}transform(N,I){if(N===I)throw new Error("Input and output buffers must be different");this._transform4(N,I,1)}realTransform(N,I){if(N===I)throw new Error("Input and output buffers must be different");this._realTransform4(N,I,1)}inverseTransform(N,I){if(N===I)throw new Error("Input and output buffers must be different");this._transform4(N,I,-1);for(let B=0;B>=2;ye>=2;ye>>=2){Ce=A/ye<<1;const ht=Ce>>>2;for(ke=0;ke>>1,ye>>>1)}else for(ke=0,Ie=0;ke>>1,ye>>>1,B)}const Qe=this.table;for(ye>>=2;ye>=2;ye>>=2){Ce=A/ye<<1;const we=Ce>>>1,V=we>>>1,he=V>>>1;for(ke=0;ke>>1;for(let we=2;we>1;++tt){const Qe=(tt+1-N)**2/2,ht=Math.sqrt(ke**2+Ie**2)**Qe,we=Qe*Math.atan2(Ie,ke),V=2*tt;_e[V]=ht*Math.cos(we),_e[V+1]=ht*Math.sin(we),ye[V]=_e[V],ye[V+1]=-_e[V+1]}this._slicedChirpBuffer=_e.subarray(I,B),this._f=new te(A>>1),this._f.transform(this._chirpBuffer,ye)}_transform(N,I,B){const A=this._buffer1,_e=this._buffer2,ye=this._outBuffer1,Ce=this._outBuffer2,ke=this._chirpBuffer,Ie=this._slicedChirpBuffer,tt=this._a;if(B)for(let Qe=0;Qe>1,V=I[we];A[Qe]=V*Ie[Qe],A[ht]=V*Ie[ht]}else for(let Qe=0;Qe=ae.length&&(ke=2*(ae.length-1)-ke),B[ye++]=ae[ke]}B.sort(),I[_e]=B[A]}return I}function Y(ae,N){const I=Math.pow(10,N);return Math.round(ae*I)/I}function se(ae){const N=Math.round(ae);return Math.abs(ae)%1===.5?N%2===0?N:N-1:N}function le(ae){const N=ae.length,I=ae[0].length,B=[N+1,I+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 tt=1;tt0||Ce>0;)switch(ke.push(ye-1),Ie.push(Ce-1),_e[ye][Ce]){case 0:--ye,--Ce;break;case 1:--ye;break;case 2:--Ce;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ye}, ${Ce}]. Please file a bug report.`)}return ke.reverse(),Ie.reverse(),[ke,Ie]}},"./src/utils/tensor.js":(Mt,me,l)=>{l.r(me),l.d(me,{Tensor:()=>xe,cat:()=>ae,full:()=>ye,full_like:()=>Ce,interpolate:()=>j,interpolate_4d:()=>P,layer_norm:()=>R,matmul:()=>J,mean:()=>B,mean_pooling:()=>ie,ones:()=>ke,ones_like:()=>Ie,permute:()=>T,quantize_embeddings:()=>ht,rfft:()=>te,stack:()=>N,std_mean:()=>I,topk:()=>ne,zeros:()=>tt,zeros_like:()=>Qe});var x=l("./src/utils/maths.js"),H=l("./src/backends/onnx.js"),ge=l("./src/ops/registry.js");const ve=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class xe{constructor(...V){Te(this,"ort_tensor");return(0,H.isONNXTensor)(V[0])?this.ort_tensor=V[0]:this.ort_tensor=new H.Tensor(V[0],V[1],V[2]),new Proxy(this,{get:(he,$e)=>{if(typeof $e=="string"){let ee=Number($e);if(Number.isInteger(ee))return he._getitem(ee)}return he[$e]},set:(he,$e,ee)=>he[$e]=ee})}get dims(){return this.ort_tensor.dims}set dims(V){this.ort_tensor.dims=V}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[V,...he]=this.dims;if(he.length>0){const $e=he.reduce((ee,He)=>ee*He);for(let ee=0;ee0){const ee=$e.reduce((He,pt)=>He*pt);return this._subarray(V,ee,$e)}else return new xe(this.type,[this.data[V]],$e)}indexOf(V){const he=this.data;for(let $e=0;$eze)throw new Error(`Invalid slice: ${st}`);const re=[Math.max(Tt,0),Math.min(ze,this.dims[Re])];$e.push(re),he.push(re[1]-re[0])}else throw new Error(`Invalid slice: ${st}`)}const ee=$e.map(([Re,st])=>st-Re),He=ee.reduce((Re,st)=>Re*st),pt=this.data,rt=new pt.constructor(He),lt=this.stride();for(let Re=0;Re=0;--Tt){const re=ee[Tt];st+=(ze%re+$e[Tt][0])*lt[Tt],ze=Math.floor(ze/re)}rt[Re]=pt[st]}return new xe(this.type,rt,he)}permute(...V){return T(this,V)}transpose(...V){return this.permute(...V)}sum(V=null,he=!1){return this.norm(1,V,he)}norm(V="fro",he=null,$e=!1){if(V==="fro")V=2;else if(typeof V=="string")throw Error(`Unsupported norm: ${V}`);const ee=this.data;if(he===null){let rt=ee.reduce((lt,Re)=>lt+Re**V,0)**(1/V);return new xe(this.type,[rt],[])}he=le(he,this.dims.length);const He=this.dims.slice();He[he]=1;const pt=new ee.constructor(ee.length/this.dims[he]);for(let rt=0;rt=0;--Re){const ze=this.dims[Re];if(Re!==he){const re=st%ze;lt+=re*Tt,Tt*=He[Re]}st=Math.floor(st/ze)}pt[lt]+=ee[rt]**V}if(V!==1)for(let rt=0;rt=0;--lt){const Tt=this.dims[lt];if(lt!==he){const ze=Re%Tt;rt+=ze*st,st*=this.dims[lt]}Re=Math.floor(Re/Tt)}ee[pt]/=He[rt]}return this}normalize(V=2,he=1){return this.clone().normalize_(V,he)}stride(){return A(this.dims)}squeeze(V=null){return new xe(this.type,this.data,Y(this.dims,V))}squeeze_(V=null){return this.dims=Y(this.dims,V),this}unsqueeze(V=null){return new xe(this.type,this.data,se(this.dims,V))}unsqueeze_(V=null){return this.dims=se(this.dims,V),this}flatten_(V=0,he=-1){he=(he+this.dims.length)%this.dims.length;let $e=this.dims.slice(0,V),ee=this.dims.slice(V,he+1),He=this.dims.slice(he+1);return this.dims=[...$e,ee.reduce((pt,rt)=>pt*rt,1),...He],this}flatten(V=0,he=-1){return this.clone().flatten_(V,he)}view(...V){let he=-1;for(let ee=0;eert!==he?He*pt:He,1);V[he]=$e.length/ee}return new xe(this.type,$e,V)}neg_(){const V=this.data;for(let he=0;heHe*pt);if(he!==$e)throw Error(`cannot reshape array of size ${he} into shape (${V})`);let ee=we;for(let He=V.length-1;He>=0;He--)ee=ee.reduce((pt,rt)=>{let lt=pt[pt.length-1];return lt.lengthhe!==1):typeof V=="number"?we[V]===1&&we.splice(V,1):Array.isArray(V)&&(we=we.filter((he,$e)=>he!==1||!V.includes($e))),we}function se(we,V){return V=le(V,we.length+1),we=we.slice(),we.splice(V,0,1),we}function le(we,V,he=null,$e=!0){if($e&&(we<-V||we>=V))throw new Error(`IndexError: index ${we} is out of bounds for dimension${he===null?"":" "+he} with size ${V}`);return we<0&&(we=(we%V+V)%V),we}function ae(we,V=0){V=le(V,we[0].dims.length);const he=we[0].dims.slice();he[V]=we.reduce((pt,rt)=>pt+rt.dims[V],0);const $e=he.reduce((pt,rt)=>pt*rt,1),ee=new we[0].data.constructor($e),He=we[0].type;if(V===0){let pt=0;for(const rt of we){const lt=rt.data;ee.set(lt,pt),pt+=lt.length}}else{let pt=0;for(let rt=0;rt=0;--ze){const je=Re[ze];let Ge=re%je;ze===V&&(Ge+=pt),Tt+=Ge*Ee,Ee*=he[ze],re=Math.floor(re/je)}ee[Tt]=lt[st]}pt+=Re[V]}}return new xe(He,ee,he)}function N(we,V=0){return ae(we.map(he=>he.unsqueeze(V)),V)}function I(we,V=null,he=1,$e=!1){const ee=we.data,He=we.dims;if(V===null){const ze=ee.reduce((Ge,Ve)=>Ge+Ve,0)/ee.length,re=Math.sqrt(ee.reduce((Ge,Ve)=>Ge+(Ve-ze)**2,0)/(ee.length-he)),Ee=new xe(we.type,[ze],[]);return[new xe(we.type,[re],[]),Ee]}V=le(V,He.length);const pt=B(we,V,$e),rt=pt.data,lt=He.slice();lt[V]=1;const Re=new ee.constructor(ee.length/He[V]);for(let Tt=0;Tt=0;--re){const Ge=He[re];if(re!==V){const Ve=Ee%Ge;ze+=Ve*je,je*=lt[re]}Ee=Math.floor(Ee/Ge)}Re[ze]+=(ee[Tt]-rt[ze])**2}for(let Tt=0;Ttlt+Re,0);return new xe(we.type,[rt/$e.length],[])}const ee=we.dims;V=le(V,ee.length);const He=ee.slice();He[V]=1;const pt=new $e.constructor($e.length/ee[V]);for(let rt=0;rt<$e.length;++rt){let lt=0;for(let Re=ee.length-1,st=rt,Tt=1;Re>=0;--Re){const ze=ee[Re];if(Re!==V){const re=st%ze;lt+=re*Tt,Tt*=He[Re]}st=Math.floor(st/ze)}pt[lt]+=$e[rt]}if(ee[V]!==1)for(let rt=0;rt=0;--he)V[he]=$e,$e*=we[he];return V}function _e(we,V,he,$e){const ee=we.reduce((He,pt)=>He*pt,1);return new xe(he,new $e(ee).fill(V),we)}function ye(we,V){let he,$e;if(typeof V=="number")he="float32",$e=Float32Array;else if(typeof V=="bigint")he="int64",$e=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof V}`);return _e(we,V,he,$e)}function Ce(we,V){return ye(we.dims,V)}function ke(we){return _e(we,1n,"int64",BigInt64Array)}function Ie(we){return ke(we.dims)}function tt(we){return _e(we,0n,"int64",BigInt64Array)}function Qe(we){return tt(we.dims)}function ht(we,V){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(V))throw new Error("The precision must be either 'binary' or 'ubinary'");const he=V==="binary",$e=he?"int8":"uint8",ee=he?Int8Array:Uint8Array,He=we.data,pt=new ee(He.length/8);for(let rt=0;rt0?1:0,Re=Math.floor(rt/8),st=rt%8;pt[Re]|=lt<<7-st,he&&st===0&&(pt[Re]-=128)}return new xe($e,pt,[we.dims[0],we.dims[1]/8])}}},js={};function Vr(Mt){var me=js[Mt];if(me!==void 0)return me.exports;var l=js[Mt]={exports:{}};return ns[Mt](l,l.exports,Vr),l.exports}(()=>{var Mt=Object.getPrototypeOf?l=>Object.getPrototypeOf(l):l=>l.__proto__,me;Vr.t=function(l,x){if(x&1&&(l=this(l)),x&8||typeof l=="object"&&l&&(x&4&&l.__esModule||x&16&&typeof l.then=="function"))return l;var H=Object.create(null);Vr.r(H);var ge={};me=me||[null,Mt({}),Mt([]),Mt(Mt)];for(var ve=x&2&&l;typeof ve=="object"&&!~me.indexOf(ve);ve=Mt(ve))Object.getOwnPropertyNames(ve).forEach(xe=>ge[xe]=()=>l[xe]);return ge.default=()=>l,Vr.d(H,ge),H}})(),Vr.d=(Mt,me)=>{for(var l in me)Vr.o(me,l)&&!Vr.o(Mt,l)&&Object.defineProperty(Mt,l,{enumerable:!0,get:me[l]})},Vr.o=(Mt,me)=>Object.prototype.hasOwnProperty.call(Mt,me),Vr.r=Mt=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Mt,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Mt,"__esModule",{value:!0})},(()=>{var Mt;if(typeof self.location.href=="string"&&(Mt=self.location.href),!Mt)throw new Error("Automatic publicPath is not supported in this browser");Mt=Mt.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Vr.p=Mt})(),Vr.b=void 0;var p={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/Vr.r(p),Vr.d(p,{ASTFeatureExtractor:()=>H.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:()=>x.AlbertTokenizer,AudioClassificationPipeline:()=>me.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:()=>H.AutoProcessor,AutoTokenizer:()=>x.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>me.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>l.BartForConditionalGeneration,BartForSequenceClassification:()=>l.BartForSequenceClassification,BartModel:()=>l.BartModel,BartPretrainedModel:()=>l.BartPretrainedModel,BartTokenizer:()=>x.BartTokenizer,BaseModelOutput:()=>l.BaseModelOutput,BaseStreamer:()=>j.BaseStreamer,BeitFeatureExtractor:()=>H.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:()=>x.BertTokenizer,BitImageProcessor:()=>H.BitImageProcessor,BlenderbotForConditionalGeneration:()=>l.BlenderbotForConditionalGeneration,BlenderbotModel:()=>l.BlenderbotModel,BlenderbotPreTrainedModel:()=>l.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>l.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>l.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>l.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>x.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>x.BlenderbotTokenizer,BloomForCausalLM:()=>l.BloomForCausalLM,BloomModel:()=>l.BloomModel,BloomPreTrainedModel:()=>l.BloomPreTrainedModel,BloomTokenizer:()=>x.BloomTokenizer,CLIPFeatureExtractor:()=>H.CLIPFeatureExtractor,CLIPImageProcessor:()=>H.CLIPImageProcessor,CLIPModel:()=>l.CLIPModel,CLIPPreTrainedModel:()=>l.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>l.CLIPSegForImageSegmentation,CLIPSegModel:()=>l.CLIPSegModel,CLIPSegPreTrainedModel:()=>l.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>l.CLIPTextModelWithProjection,CLIPTokenizer:()=>x.CLIPTokenizer,CLIPVisionModelWithProjection:()=>l.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>l.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>l.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>l.CamembertForSequenceClassification,CamembertForTokenClassification:()=>l.CamembertForTokenClassification,CamembertModel:()=>l.CamembertModel,CamembertPreTrainedModel:()=>l.CamembertPreTrainedModel,CamembertTokenizer:()=>x.CamembertTokenizer,CausalLMOutput:()=>l.CausalLMOutput,CausalLMOutputWithPast:()=>l.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>H.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>l.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>l.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>l.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>H.ClapFeatureExtractor,ClapModel:()=>l.ClapModel,ClapPreTrainedModel:()=>l.ClapPreTrainedModel,ClapTextModelWithProjection:()=>l.ClapTextModelWithProjection,CodeGenForCausalLM:()=>l.CodeGenForCausalLM,CodeGenModel:()=>l.CodeGenModel,CodeGenPreTrainedModel:()=>l.CodeGenPreTrainedModel,CodeGenTokenizer:()=>x.CodeGenTokenizer,CodeLlamaTokenizer:()=>x.CodeLlamaTokenizer,CohereForCausalLM:()=>l.CohereForCausalLM,CohereModel:()=>l.CohereModel,CoherePreTrainedModel:()=>l.CoherePreTrainedModel,CohereTokenizer:()=>x.CohereTokenizer,ConvBertForMaskedLM:()=>l.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>l.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>l.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>l.ConvBertForTokenClassification,ConvBertModel:()=>l.ConvBertModel,ConvBertPreTrainedModel:()=>l.ConvBertPreTrainedModel,ConvBertTokenizer:()=>x.ConvBertTokenizer,ConvNextFeatureExtractor:()=>H.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>l.ConvNextForImageClassification,ConvNextImageProcessor:()=>H.ConvNextImageProcessor,ConvNextModel:()=>l.ConvNextModel,ConvNextPreTrainedModel:()=>l.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>l.ConvNextV2ForImageClassification,ConvNextV2Model:()=>l.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>l.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>H.DPTFeatureExtractor,DPTForDepthEstimation:()=>l.DPTForDepthEstimation,DPTImageProcessor:()=>H.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:()=>x.DebertaTokenizer,DebertaV2ForMaskedLM:()=>l.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>l.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>l.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>l.DebertaV2ForTokenClassification,DebertaV2Model:()=>l.DebertaV2Model,DebertaV2PreTrainedModel:()=>l.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>x.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>H.DeiTFeatureExtractor,DeiTForImageClassification:()=>l.DeiTForImageClassification,DeiTModel:()=>l.DeiTModel,DeiTPreTrainedModel:()=>l.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>l.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>l.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>me.DepthEstimationPipeline,DetrFeatureExtractor:()=>H.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:()=>x.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>me.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>H.DonutFeatureExtractor,DonutSwinModel:()=>l.DonutSwinModel,DonutSwinPreTrainedModel:()=>l.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>l.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>H.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:()=>x.ElectraTokenizer,EosTokenCriteria:()=>P.EosTokenCriteria,EsmForMaskedLM:()=>l.EsmForMaskedLM,EsmForSequenceClassification:()=>l.EsmForSequenceClassification,EsmForTokenClassification:()=>l.EsmForTokenClassification,EsmModel:()=>l.EsmModel,EsmPreTrainedModel:()=>l.EsmPreTrainedModel,EsmTokenizer:()=>x.EsmTokenizer,FFT:()=>T.FFT,FalconForCausalLM:()=>l.FalconForCausalLM,FalconModel:()=>l.FalconModel,FalconPreTrainedModel:()=>l.FalconPreTrainedModel,FalconTokenizer:()=>x.FalconTokenizer,FastViTForImageClassification:()=>l.FastViTForImageClassification,FastViTModel:()=>l.FastViTModel,FastViTPreTrainedModel:()=>l.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>me.FeatureExtractionPipeline,FeatureExtractor:()=>H.FeatureExtractor,FillMaskPipeline:()=>me.FillMaskPipeline,Florence2ForConditionalGeneration:()=>l.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>l.Florence2PreTrainedModel,Florence2Processor:()=>H.Florence2Processor,GLPNFeatureExtractor:()=>H.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>l.GLPNForDepthEstimation,GLPNModel:()=>l.GLPNModel,GLPNPreTrainedModel:()=>l.GLPNPreTrainedModel,GPT2LMHeadModel:()=>l.GPT2LMHeadModel,GPT2Model:()=>l.GPT2Model,GPT2PreTrainedModel:()=>l.GPT2PreTrainedModel,GPT2Tokenizer:()=>x.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:()=>x.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>l.Gemma2ForCausalLM,Gemma2Model:()=>l.Gemma2Model,Gemma2PreTrainedModel:()=>l.Gemma2PreTrainedModel,GemmaForCausalLM:()=>l.GemmaForCausalLM,GemmaModel:()=>l.GemmaModel,GemmaPreTrainedModel:()=>l.GemmaPreTrainedModel,GemmaTokenizer:()=>x.GemmaTokenizer,Grok1Tokenizer:()=>x.Grok1Tokenizer,HerbertTokenizer:()=>x.HerbertTokenizer,HubertForCTC:()=>l.HubertForCTC,HubertForSequenceClassification:()=>l.HubertForSequenceClassification,HubertModel:()=>l.HubertModel,HubertPreTrainedModel:()=>l.HubertPreTrainedModel,ImageClassificationPipeline:()=>me.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>me.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>H.ImageFeatureExtractor,ImageMattingOutput:()=>l.ImageMattingOutput,ImageSegmentationPipeline:()=>me.ImageSegmentationPipeline,ImageToImagePipeline:()=>me.ImageToImagePipeline,ImageToTextPipeline:()=>me.ImageToTextPipeline,InterruptableStoppingCriteria:()=>P.InterruptableStoppingCriteria,LlamaForCausalLM:()=>l.LlamaForCausalLM,LlamaModel:()=>l.LlamaModel,LlamaPreTrainedModel:()=>l.LlamaPreTrainedModel,LlamaTokenizer:()=>x.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:()=>x.M2M100Tokenizer,MBart50Tokenizer:()=>x.MBart50Tokenizer,MBartForCausalLM:()=>l.MBartForCausalLM,MBartForConditionalGeneration:()=>l.MBartForConditionalGeneration,MBartForSequenceClassification:()=>l.MBartForSequenceClassification,MBartModel:()=>l.MBartModel,MBartPreTrainedModel:()=>l.MBartPreTrainedModel,MBartTokenizer:()=>x.MBartTokenizer,MPNetForMaskedLM:()=>l.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>l.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>l.MPNetForSequenceClassification,MPNetForTokenClassification:()=>l.MPNetForTokenClassification,MPNetModel:()=>l.MPNetModel,MPNetPreTrainedModel:()=>l.MPNetPreTrainedModel,MPNetTokenizer:()=>x.MPNetTokenizer,MT5ForConditionalGeneration:()=>l.MT5ForConditionalGeneration,MT5Model:()=>l.MT5Model,MT5PreTrainedModel:()=>l.MT5PreTrainedModel,MarianMTModel:()=>l.MarianMTModel,MarianModel:()=>l.MarianModel,MarianPreTrainedModel:()=>l.MarianPreTrainedModel,MarianTokenizer:()=>x.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:()=>x.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>H.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>l.MobileNetV1ForImageClassification,MobileNetV1Model:()=>l.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>l.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>H.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>l.MobileNetV2ForImageClassification,MobileNetV2Model:()=>l.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>l.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>H.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>l.MobileNetV3ForImageClassification,MobileNetV3Model:()=>l.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>l.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>H.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>l.MobileNetV4ForImageClassification,MobileNetV4Model:()=>l.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>l.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>H.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>l.MobileViTForImageClassification,MobileViTImageProcessor:()=>H.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:()=>x.NllbTokenizer,NomicBertModel:()=>l.NomicBertModel,NomicBertPreTrainedModel:()=>l.NomicBertPreTrainedModel,NougatImageProcessor:()=>H.NougatImageProcessor,NougatTokenizer:()=>x.NougatTokenizer,OPTForCausalLM:()=>l.OPTForCausalLM,OPTModel:()=>l.OPTModel,OPTPreTrainedModel:()=>l.OPTPreTrainedModel,ObjectDetectionPipeline:()=>me.ObjectDetectionPipeline,OpenELMForCausalLM:()=>l.OpenELMForCausalLM,OpenELMModel:()=>l.OpenELMModel,OpenELMPreTrainedModel:()=>l.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>H.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>l.OwlViTForObjectDetection,OwlViTModel:()=>l.OwlViTModel,OwlViTPreTrainedModel:()=>l.OwlViTPreTrainedModel,OwlViTProcessor:()=>H.OwlViTProcessor,Owlv2ForObjectDetection:()=>l.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>H.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:()=>me.Pipeline,PreTrainedModel:()=>l.PreTrainedModel,PreTrainedTokenizer:()=>x.PreTrainedTokenizer,PretrainedConfig:()=>ge.PretrainedConfig,PretrainedMixin:()=>l.PretrainedMixin,Processor:()=>H.Processor,PyAnnoteFeatureExtractor:()=>H.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>l.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>l.PyAnnoteModel,PyAnnotePreTrainedModel:()=>l.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>H.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>l.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>me.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>l.Qwen2ForCausalLM,Qwen2Model:()=>l.Qwen2Model,Qwen2PreTrainedModel:()=>l.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>x.Qwen2Tokenizer,RTDetrForObjectDetection:()=>l.RTDetrForObjectDetection,RTDetrImageProcessor:()=>H.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:()=>x.RoFormerTokenizer,RobertaForMaskedLM:()=>l.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>l.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>l.RobertaForSequenceClassification,RobertaForTokenClassification:()=>l.RobertaForTokenClassification,RobertaModel:()=>l.RobertaModel,RobertaPreTrainedModel:()=>l.RobertaPreTrainedModel,RobertaTokenizer:()=>x.RobertaTokenizer,SamImageProcessor:()=>H.SamImageProcessor,SamImageSegmentationOutput:()=>l.SamImageSegmentationOutput,SamModel:()=>l.SamModel,SamPreTrainedModel:()=>l.SamPreTrainedModel,SamProcessor:()=>H.SamProcessor,SeamlessM4TFeatureExtractor:()=>H.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>H.SegformerFeatureExtractor,SegformerForImageClassification:()=>l.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>l.SegformerForSemanticSegmentation,SegformerModel:()=>l.SegformerModel,SegformerPreTrainedModel:()=>l.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>l.Seq2SeqLMOutput,SequenceClassifierOutput:()=>l.SequenceClassifierOutput,SiglipImageProcessor:()=>H.SiglipImageProcessor,SiglipModel:()=>l.SiglipModel,SiglipPreTrainedModel:()=>l.SiglipPreTrainedModel,SiglipTextModel:()=>l.SiglipTextModel,SiglipTokenizer:()=>x.SiglipTokenizer,SiglipVisionModel:()=>l.SiglipVisionModel,SpeechT5FeatureExtractor:()=>H.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>l.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>l.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>l.SpeechT5HifiGan,SpeechT5Model:()=>l.SpeechT5Model,SpeechT5PreTrainedModel:()=>l.SpeechT5PreTrainedModel,SpeechT5Processor:()=>H.SpeechT5Processor,SpeechT5Tokenizer:()=>x.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>l.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>l.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>l.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>l.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>l.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>x.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:()=>me.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>l.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>H.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:()=>x.T5Tokenizer,TableTransformerForObjectDetection:()=>l.TableTransformerForObjectDetection,TableTransformerModel:()=>l.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>l.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>l.TableTransformerPreTrainedModel,Tensor:()=>D.Tensor,Text2TextGenerationPipeline:()=>me.Text2TextGenerationPipeline,TextClassificationPipeline:()=>me.TextClassificationPipeline,TextGenerationPipeline:()=>me.TextGenerationPipeline,TextStreamer:()=>j.TextStreamer,TextToAudioPipeline:()=>me.TextToAudioPipeline,TokenClassificationPipeline:()=>me.TokenClassificationPipeline,TokenClassifierOutput:()=>l.TokenClassifierOutput,TokenizerModel:()=>x.TokenizerModel,TrOCRForCausalLM:()=>l.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>l.TrOCRPreTrainedModel,TranslationPipeline:()=>me.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:()=>H.ViTFeatureExtractor,ViTForImageClassification:()=>l.ViTForImageClassification,ViTImageProcessor:()=>H.ViTImageProcessor,ViTModel:()=>l.ViTModel,ViTPreTrainedModel:()=>l.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>l.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>l.VitMatteForImageMatting,VitMatteImageProcessor:()=>H.VitMatteImageProcessor,VitMattePreTrainedModel:()=>l.VitMattePreTrainedModel,VitsModel:()=>l.VitsModel,VitsModelOutput:()=>l.VitsModelOutput,VitsPreTrainedModel:()=>l.VitsPreTrainedModel,VitsTokenizer:()=>x.VitsTokenizer,Wav2Vec2BertForCTC:()=>l.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>l.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>l.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>l.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>x.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>H.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>l.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>l.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>l.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>l.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>l.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>H.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>l.WavLMForAudioFrameClassification,WavLMForCTC:()=>l.WavLMForCTC,WavLMForSequenceClassification:()=>l.WavLMForSequenceClassification,WavLMForXVector:()=>l.WavLMForXVector,WavLMModel:()=>l.WavLMModel,WavLMPreTrainedModel:()=>l.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>H.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>l.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>l.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>H.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>l.WhisperForConditionalGeneration,WhisperModel:()=>l.WhisperModel,WhisperPreTrainedModel:()=>l.WhisperPreTrainedModel,WhisperProcessor:()=>H.WhisperProcessor,WhisperTextStreamer:()=>j.WhisperTextStreamer,WhisperTokenizer:()=>x.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:()=>x.XLMRobertaTokenizer,XLMTokenizer:()=>x.XLMTokenizer,XLMWithLMHeadModel:()=>l.XLMWithLMHeadModel,XVectorOutput:()=>l.XVectorOutput,YolosFeatureExtractor:()=>H.YolosFeatureExtractor,YolosForObjectDetection:()=>l.YolosForObjectDetection,YolosModel:()=>l.YolosModel,YolosObjectDetectionOutput:()=>l.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>l.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>me.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>me.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>me.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>me.ZeroShotObjectDetectionPipeline,bankers_round:()=>T.bankers_round,cat:()=>D.cat,cos_sim:()=>T.cos_sim,dot:()=>T.dot,dynamic_time_warping:()=>T.dynamic_time_warping,env:()=>Mt.env,full:()=>D.full,full_like:()=>D.full_like,getKeyValueShapes:()=>ge.getKeyValueShapes,hamming:()=>ve.hamming,hanning:()=>ve.hanning,interpolate:()=>D.interpolate,interpolate_4d:()=>D.interpolate_4d,interpolate_data:()=>T.interpolate_data,is_chinese_char:()=>x.is_chinese_char,layer_norm:()=>D.layer_norm,log_softmax:()=>T.log_softmax,magnitude:()=>T.magnitude,matmul:()=>D.matmul,max:()=>T.max,mean:()=>D.mean,mean_pooling:()=>D.mean_pooling,medianFilter:()=>T.medianFilter,mel_filter_bank:()=>ve.mel_filter_bank,min:()=>T.min,ones:()=>D.ones,ones_like:()=>D.ones_like,permute:()=>D.permute,permute_data:()=>T.permute_data,pipeline:()=>me.pipeline,quantize_embeddings:()=>D.quantize_embeddings,read_audio:()=>ve.read_audio,rfft:()=>D.rfft,round:()=>T.round,softmax:()=>T.softmax,spectrogram:()=>ve.spectrogram,stack:()=>D.stack,std_mean:()=>D.std_mean,topk:()=>D.topk,window_function:()=>ve.window_function,zeros:()=>D.zeros,zeros_like:()=>D.zeros_like});var Mt=Vr("./src/env.js"),me=Vr("./src/pipelines.js"),l=Vr("./src/models.js"),x=Vr("./src/tokenizers.js"),H=Vr("./src/processors.js"),ge=Vr("./src/configs.js"),ve=Vr("./src/utils/audio.js"),xe=Vr("./src/utils/image.js"),D=Vr("./src/utils/tensor.js"),T=Vr("./src/utils/maths.js"),j=Vr("./src/generation/streamers.js"),P=Vr("./src/generation/stopping_criteria.js")})(),p.ASTFeatureExtractor,p.ASTForAudioClassification,p.ASTModel,p.ASTPreTrainedModel,p.AlbertForMaskedLM,p.AlbertForQuestionAnswering,p.AlbertForSequenceClassification,p.AlbertModel,p.AlbertPreTrainedModel,p.AlbertTokenizer,p.AudioClassificationPipeline,p.AutoConfig,p.AutoModel,p.AutoModelForAudioClassification,p.AutoModelForAudioFrameClassification,p.AutoModelForCTC;var Jh=p.AutoModelForCausalLM;p.AutoModelForDepthEstimation,p.AutoModelForDocumentQuestionAnswering,p.AutoModelForImageClassification,p.AutoModelForImageFeatureExtraction,p.AutoModelForImageMatting,p.AutoModelForImageSegmentation,p.AutoModelForImageToImage,p.AutoModelForMaskGeneration,p.AutoModelForMaskedLM,p.AutoModelForObjectDetection,p.AutoModelForQuestionAnswering,p.AutoModelForSemanticSegmentation,p.AutoModelForSeq2SeqLM,p.AutoModelForSequenceClassification,p.AutoModelForSpeechSeq2Seq,p.AutoModelForTextToSpectrogram,p.AutoModelForTextToWaveform,p.AutoModelForTokenClassification,p.AutoModelForVision2Seq,p.AutoModelForXVector,p.AutoModelForZeroShotObjectDetection,p.AutoProcessor;var ef=p.AutoTokenizer;p.AutomaticSpeechRecognitionPipeline,p.BartForConditionalGeneration,p.BartForSequenceClassification,p.BartModel,p.BartPretrainedModel,p.BartTokenizer,p.BaseModelOutput,p.BaseStreamer,p.BeitFeatureExtractor,p.BeitForImageClassification,p.BeitModel,p.BeitPreTrainedModel,p.BertForMaskedLM,p.BertForQuestionAnswering,p.BertForSequenceClassification,p.BertForTokenClassification,p.BertModel,p.BertPreTrainedModel,p.BertTokenizer,p.BitImageProcessor,p.BlenderbotForConditionalGeneration,p.BlenderbotModel,p.BlenderbotPreTrainedModel,p.BlenderbotSmallForConditionalGeneration,p.BlenderbotSmallModel,p.BlenderbotSmallPreTrainedModel,p.BlenderbotSmallTokenizer,p.BlenderbotTokenizer,p.BloomForCausalLM,p.BloomModel,p.BloomPreTrainedModel,p.BloomTokenizer,p.CLIPFeatureExtractor,p.CLIPImageProcessor,p.CLIPModel,p.CLIPPreTrainedModel,p.CLIPSegForImageSegmentation,p.CLIPSegModel,p.CLIPSegPreTrainedModel,p.CLIPTextModelWithProjection,p.CLIPTokenizer,p.CLIPVisionModelWithProjection,p.CamembertForMaskedLM,p.CamembertForQuestionAnswering,p.CamembertForSequenceClassification,p.CamembertForTokenClassification,p.CamembertModel,p.CamembertPreTrainedModel,p.CamembertTokenizer,p.CausalLMOutput,p.CausalLMOutputWithPast,p.ChineseCLIPFeatureExtractor,p.ChineseCLIPModel,p.ChineseCLIPPreTrainedModel,p.ClapAudioModelWithProjection,p.ClapFeatureExtractor,p.ClapModel,p.ClapPreTrainedModel,p.ClapTextModelWithProjection,p.CodeGenForCausalLM,p.CodeGenModel,p.CodeGenPreTrainedModel,p.CodeGenTokenizer,p.CodeLlamaTokenizer,p.CohereForCausalLM,p.CohereModel,p.CoherePreTrainedModel,p.CohereTokenizer,p.ConvBertForMaskedLM,p.ConvBertForQuestionAnswering,p.ConvBertForSequenceClassification,p.ConvBertForTokenClassification,p.ConvBertModel,p.ConvBertPreTrainedModel,p.ConvBertTokenizer,p.ConvNextFeatureExtractor,p.ConvNextForImageClassification,p.ConvNextImageProcessor,p.ConvNextModel,p.ConvNextPreTrainedModel,p.ConvNextV2ForImageClassification,p.ConvNextV2Model,p.ConvNextV2PreTrainedModel,p.DPTFeatureExtractor,p.DPTForDepthEstimation,p.DPTImageProcessor,p.DPTModel,p.DPTPreTrainedModel,p.DebertaForMaskedLM,p.DebertaForQuestionAnswering,p.DebertaForSequenceClassification,p.DebertaForTokenClassification,p.DebertaModel,p.DebertaPreTrainedModel,p.DebertaTokenizer,p.DebertaV2ForMaskedLM,p.DebertaV2ForQuestionAnswering,p.DebertaV2ForSequenceClassification,p.DebertaV2ForTokenClassification,p.DebertaV2Model,p.DebertaV2PreTrainedModel,p.DebertaV2Tokenizer,p.DeiTFeatureExtractor,p.DeiTForImageClassification,p.DeiTModel,p.DeiTPreTrainedModel,p.DepthAnythingForDepthEstimation,p.DepthAnythingPreTrainedModel,p.DepthEstimationPipeline,p.DetrFeatureExtractor,p.DetrForObjectDetection,p.DetrForSegmentation,p.DetrModel,p.DetrObjectDetectionOutput,p.DetrPreTrainedModel,p.DetrSegmentationOutput,p.Dinov2ForImageClassification,p.Dinov2Model,p.Dinov2PreTrainedModel,p.DistilBertForMaskedLM,p.DistilBertForQuestionAnswering,p.DistilBertForSequenceClassification,p.DistilBertForTokenClassification,p.DistilBertModel,p.DistilBertPreTrainedModel,p.DistilBertTokenizer,p.DocumentQuestionAnsweringPipeline,p.DonutFeatureExtractor,p.DonutSwinModel,p.DonutSwinPreTrainedModel,p.EfficientNetForImageClassification,p.EfficientNetImageProcessor,p.EfficientNetModel,p.EfficientNetPreTrainedModel,p.ElectraForMaskedLM,p.ElectraForQuestionAnswering,p.ElectraForSequenceClassification,p.ElectraForTokenClassification,p.ElectraModel,p.ElectraPreTrainedModel,p.ElectraTokenizer,p.EosTokenCriteria,p.EsmForMaskedLM,p.EsmForSequenceClassification,p.EsmForTokenClassification,p.EsmModel,p.EsmPreTrainedModel,p.EsmTokenizer,p.FFT,p.FalconForCausalLM,p.FalconModel,p.FalconPreTrainedModel,p.FalconTokenizer,p.FastViTForImageClassification,p.FastViTModel,p.FastViTPreTrainedModel,p.FeatureExtractionPipeline,p.FeatureExtractor,p.FillMaskPipeline,p.Florence2ForConditionalGeneration,p.Florence2PreTrainedModel,p.Florence2Processor,p.GLPNFeatureExtractor,p.GLPNForDepthEstimation,p.GLPNModel,p.GLPNPreTrainedModel,p.GPT2LMHeadModel,p.GPT2Model,p.GPT2PreTrainedModel,p.GPT2Tokenizer,p.GPTBigCodeForCausalLM,p.GPTBigCodeModel,p.GPTBigCodePreTrainedModel,p.GPTJForCausalLM,p.GPTJModel,p.GPTJPreTrainedModel,p.GPTNeoForCausalLM,p.GPTNeoModel,p.GPTNeoPreTrainedModel,p.GPTNeoXForCausalLM,p.GPTNeoXModel,p.GPTNeoXPreTrainedModel,p.GPTNeoXTokenizer,p.Gemma2ForCausalLM,p.Gemma2Model,p.Gemma2PreTrainedModel,p.GemmaForCausalLM,p.GemmaModel,p.GemmaPreTrainedModel,p.GemmaTokenizer,p.Grok1Tokenizer,p.HerbertTokenizer,p.HubertForCTC,p.HubertForSequenceClassification,p.HubertModel,p.HubertPreTrainedModel,p.ImageClassificationPipeline,p.ImageFeatureExtractionPipeline,p.ImageFeatureExtractor,p.ImageMattingOutput,p.ImageSegmentationPipeline,p.ImageToImagePipeline,p.ImageToTextPipeline;var tf=p.InterruptableStoppingCriteria;p.LlamaForCausalLM,p.LlamaModel,p.LlamaPreTrainedModel,p.LlamaTokenizer,p.LlavaForConditionalGeneration,p.LlavaPreTrainedModel,p.LongT5ForConditionalGeneration,p.LongT5Model,p.LongT5PreTrainedModel,p.M2M100ForConditionalGeneration,p.M2M100Model,p.M2M100PreTrainedModel,p.M2M100Tokenizer,p.MBart50Tokenizer,p.MBartForCausalLM,p.MBartForConditionalGeneration,p.MBartForSequenceClassification,p.MBartModel,p.MBartPreTrainedModel,p.MBartTokenizer,p.MPNetForMaskedLM,p.MPNetForQuestionAnswering,p.MPNetForSequenceClassification,p.MPNetForTokenClassification,p.MPNetModel,p.MPNetPreTrainedModel,p.MPNetTokenizer,p.MT5ForConditionalGeneration,p.MT5Model,p.MT5PreTrainedModel,p.MarianMTModel,p.MarianModel,p.MarianPreTrainedModel,p.MarianTokenizer,p.MaskedLMOutput,p.MaxLengthCriteria,p.MistralForCausalLM,p.MistralModel,p.MistralPreTrainedModel,p.MobileBertForMaskedLM,p.MobileBertForQuestionAnswering,p.MobileBertForSequenceClassification,p.MobileBertModel,p.MobileBertPreTrainedModel,p.MobileBertTokenizer,p.MobileNetV1FeatureExtractor,p.MobileNetV1ForImageClassification,p.MobileNetV1Model,p.MobileNetV1PreTrainedModel,p.MobileNetV2FeatureExtractor,p.MobileNetV2ForImageClassification,p.MobileNetV2Model,p.MobileNetV2PreTrainedModel,p.MobileNetV3FeatureExtractor,p.MobileNetV3ForImageClassification,p.MobileNetV3Model,p.MobileNetV3PreTrainedModel,p.MobileNetV4FeatureExtractor,p.MobileNetV4ForImageClassification,p.MobileNetV4Model,p.MobileNetV4PreTrainedModel,p.MobileViTFeatureExtractor,p.MobileViTForImageClassification,p.MobileViTImageProcessor,p.MobileViTModel,p.MobileViTPreTrainedModel,p.MobileViTV2ForImageClassification,p.MobileViTV2Model,p.MobileViTV2PreTrainedModel,p.ModelOutput,p.Moondream1ForConditionalGeneration,p.MptForCausalLM,p.MptModel,p.MptPreTrainedModel,p.MusicgenForCausalLM,p.MusicgenForConditionalGeneration,p.MusicgenModel,p.MusicgenPreTrainedModel,p.NllbTokenizer,p.NomicBertModel,p.NomicBertPreTrainedModel,p.NougatImageProcessor,p.NougatTokenizer,p.OPTForCausalLM,p.OPTModel,p.OPTPreTrainedModel,p.ObjectDetectionPipeline,p.OpenELMForCausalLM,p.OpenELMModel,p.OpenELMPreTrainedModel,p.OwlViTFeatureExtractor,p.OwlViTForObjectDetection,p.OwlViTModel,p.OwlViTPreTrainedModel,p.OwlViTProcessor,p.Owlv2ForObjectDetection,p.Owlv2ImageProcessor,p.Owlv2Model,p.Owlv2PreTrainedModel,p.Phi3ForCausalLM,p.Phi3Model,p.Phi3PreTrainedModel,p.PhiForCausalLM,p.PhiModel,p.PhiPreTrainedModel,p.Pipeline,p.PreTrainedModel,p.PreTrainedTokenizer,p.PretrainedConfig,p.PretrainedMixin,p.Processor,p.PyAnnoteFeatureExtractor,p.PyAnnoteForAudioFrameClassification,p.PyAnnoteModel,p.PyAnnotePreTrainedModel,p.PyAnnoteProcessor,p.QuestionAnsweringModelOutput,p.QuestionAnsweringPipeline,p.Qwen2ForCausalLM,p.Qwen2Model,p.Qwen2PreTrainedModel,p.Qwen2Tokenizer,p.RTDetrForObjectDetection,p.RTDetrImageProcessor,p.RTDetrModel,p.RTDetrObjectDetectionOutput,p.RTDetrPreTrainedModel,p.RawImage,p.ResNetForImageClassification,p.ResNetModel,p.ResNetPreTrainedModel,p.RoFormerForMaskedLM,p.RoFormerForQuestionAnswering,p.RoFormerForSequenceClassification,p.RoFormerForTokenClassification,p.RoFormerModel,p.RoFormerPreTrainedModel,p.RoFormerTokenizer,p.RobertaForMaskedLM,p.RobertaForQuestionAnswering,p.RobertaForSequenceClassification,p.RobertaForTokenClassification,p.RobertaModel,p.RobertaPreTrainedModel,p.RobertaTokenizer,p.SamImageProcessor,p.SamImageSegmentationOutput,p.SamModel,p.SamPreTrainedModel,p.SamProcessor,p.SeamlessM4TFeatureExtractor,p.SegformerFeatureExtractor,p.SegformerForImageClassification,p.SegformerForSemanticSegmentation,p.SegformerModel,p.SegformerPreTrainedModel,p.Seq2SeqLMOutput,p.SequenceClassifierOutput,p.SiglipImageProcessor,p.SiglipModel,p.SiglipPreTrainedModel,p.SiglipTextModel,p.SiglipTokenizer,p.SiglipVisionModel,p.SpeechT5FeatureExtractor,p.SpeechT5ForSpeechToText,p.SpeechT5ForTextToSpeech,p.SpeechT5HifiGan,p.SpeechT5Model,p.SpeechT5PreTrainedModel,p.SpeechT5Processor,p.SpeechT5Tokenizer,p.SqueezeBertForMaskedLM,p.SqueezeBertForQuestionAnswering,p.SqueezeBertForSequenceClassification,p.SqueezeBertModel,p.SqueezeBertPreTrainedModel,p.SqueezeBertTokenizer,p.StableLmForCausalLM,p.StableLmModel,p.StableLmPreTrainedModel,p.Starcoder2ForCausalLM,p.Starcoder2Model,p.Starcoder2PreTrainedModel,p.StoppingCriteria,p.StoppingCriteriaList,p.SummarizationPipeline,p.Swin2SRForImageSuperResolution,p.Swin2SRImageProcessor,p.Swin2SRModel,p.Swin2SRPreTrainedModel,p.SwinForImageClassification,p.SwinModel,p.SwinPreTrainedModel,p.T5ForConditionalGeneration,p.T5Model,p.T5PreTrainedModel,p.T5Tokenizer,p.TableTransformerForObjectDetection,p.TableTransformerModel,p.TableTransformerObjectDetectionOutput,p.TableTransformerPreTrainedModel,p.Tensor,p.Text2TextGenerationPipeline,p.TextClassificationPipeline,p.TextGenerationPipeline;var rf=p.TextStreamer;p.TextToAudioPipeline,p.TokenClassificationPipeline,p.TokenClassifierOutput,p.TokenizerModel,p.TrOCRForCausalLM,p.TrOCRPreTrainedModel,p.TranslationPipeline,p.UniSpeechForCTC,p.UniSpeechForSequenceClassification,p.UniSpeechModel,p.UniSpeechPreTrainedModel,p.UniSpeechSatForAudioFrameClassification,p.UniSpeechSatForCTC,p.UniSpeechSatForSequenceClassification,p.UniSpeechSatModel,p.UniSpeechSatPreTrainedModel,p.ViTFeatureExtractor,p.ViTForImageClassification,p.ViTImageProcessor,p.ViTModel,p.ViTPreTrainedModel,p.VisionEncoderDecoderModel,p.VitMatteForImageMatting,p.VitMatteImageProcessor,p.VitMattePreTrainedModel,p.VitsModel,p.VitsModelOutput,p.VitsPreTrainedModel,p.VitsTokenizer,p.Wav2Vec2BertForCTC,p.Wav2Vec2BertForSequenceClassification,p.Wav2Vec2BertModel,p.Wav2Vec2BertPreTrainedModel,p.Wav2Vec2CTCTokenizer,p.Wav2Vec2FeatureExtractor,p.Wav2Vec2ForAudioFrameClassification,p.Wav2Vec2ForCTC,p.Wav2Vec2ForSequenceClassification,p.Wav2Vec2Model,p.Wav2Vec2PreTrainedModel,p.Wav2Vec2ProcessorWithLM,p.WavLMForAudioFrameClassification,p.WavLMForCTC,p.WavLMForSequenceClassification,p.WavLMForXVector,p.WavLMModel,p.WavLMPreTrainedModel,p.WeSpeakerFeatureExtractor,p.WeSpeakerResNetModel,p.WeSpeakerResNetPreTrainedModel,p.WhisperFeatureExtractor,p.WhisperForConditionalGeneration,p.WhisperModel,p.WhisperPreTrainedModel,p.WhisperProcessor,p.WhisperTextStreamer,p.WhisperTokenizer,p.XLMForQuestionAnswering,p.XLMForSequenceClassification,p.XLMForTokenClassification,p.XLMModel,p.XLMPreTrainedModel,p.XLMRobertaForMaskedLM,p.XLMRobertaForQuestionAnswering,p.XLMRobertaForSequenceClassification,p.XLMRobertaForTokenClassification,p.XLMRobertaModel,p.XLMRobertaPreTrainedModel,p.XLMRobertaTokenizer,p.XLMTokenizer,p.XLMWithLMHeadModel,p.XVectorOutput,p.YolosFeatureExtractor,p.YolosForObjectDetection,p.YolosModel,p.YolosObjectDetectionOutput,p.YolosPreTrainedModel,p.ZeroShotAudioClassificationPipeline,p.ZeroShotClassificationPipeline,p.ZeroShotImageClassificationPipeline,p.ZeroShotObjectDetectionPipeline,p.bankers_round,p.cat,p.cos_sim,p.dot,p.dynamic_time_warping,p.env,p.full,p.full_like,p.getKeyValueShapes,p.hamming,p.hanning,p.interpolate,p.interpolate_4d,p.interpolate_data,p.is_chinese_char,p.layer_norm,p.log_softmax,p.magnitude,p.matmul,p.max,p.mean,p.mean_pooling,p.medianFilter,p.mel_filter_bank,p.min,p.ones,p.ones_like,p.permute,p.permute_data,p.pipeline,p.quantize_embeddings,p.read_audio,p.rfft,p.round,p.softmax,p.spectrogram,p.stack,p.std_mean,p.topk,p.window_function,p.zeros,p.zeros_like;class Ed{static async getInstance(me=null){return this.tokenizer??(this.tokenizer=ef.from_pretrained(this.model_id,{progress_callback:me})),this.model??(this.model=Jh.from_pretrained(this.model_id,{dtype:"q4",device:"webgpu",progress_callback:me})),Promise.all([this.tokenizer,this.model])}}Te(Ed,"model_id","HuggingFaceTB/SmolLM-360M-Instruct");const Ou=new tf;let Sd=null;async function nf(Mt){const[me,l]=await Ed.getInstance(),x=me.apply_chat_template(Mt,{add_generation_prompt:!0,return_dict:!0});let H,ge=0,ve;const xe=()=>{H??(H=performance.now()),ge++>0&&(ve=ge/(performance.now()-H)*1e3)},D=te=>{self.postMessage({status:"update",output:te,tps:ve,numTokens:ge})},T=new rf(me,{skip_prompt:!0,skip_special_tokens:!0,callback_function:D,token_callback_function:xe});self.postMessage({status:"start"});const{past_key_values:j,sequences:P}=await l.generate({...x,past_key_values:Sd,do_sample:!0,top_k:3,temperature:.2,max_new_tokens:1024,streamer:T,stopping_criteria:Ou,return_dict_in_generate:!0});Sd=j;const J=me.batch_decode(P,{skip_special_tokens:!0});self.postMessage({status:"complete",output:J})}async function sf(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(Mt){self.postMessage({status:"error",data:Mt.toString()})}}async function af(){self.postMessage({status:"loading",data:"Loading model..."});const[Mt,me]=await Ed.getInstance(x=>{self.postMessage(x)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const l=Mt("a");await me.generate({...l,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async Mt=>{const{type:me,data:l}=Mt.data;switch(me){case"check":sf();break;case"load":af();break;case"generate":Ou.reset(),nf(l);break;case"interrupt":Ou.interrupt();break;case"reset":Sd=null,Ou.reset();break}})})();