var o_=Object.defineProperty;var l_=(Cn,ts,Qs)=>ts in Cn?o_(Cn,ts,{enumerable:!0,configurable:!0,writable:!0,value:Qs}):Cn[ts]=Qs;var xe=(Cn,ts,Qs)=>l_(Cn,typeof ts!="symbol"?ts+"":ts,Qs);(function(){"use strict";var Cn={},ts={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":($t,Ee,N)=>{$t.exports=N.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{Environment:()=>Ke,Interpreter:()=>ut,Template:()=>kt,parse:()=>Se,tokenize:()=>A});var O=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"}),fe=Object.freeze({set:O.Set,for:O.For,in:O.In,is:O.Is,if:O.If,else:O.Else,endif:O.EndIf,elif:O.ElseIf,endfor:O.EndFor,and:O.And,or:O.Or,not:O.Not,"not in":O.NotIn,macro:O.Macro,endmacro:O.EndMacro,true:O.BooleanLiteral,false:O.BooleanLiteral,True:O.BooleanLiteral,False:O.BooleanLiteral}),ye=class{constructor(v,q){this.value=v,this.type=q}};function Te(v){return/\w/.test(v)}function Ce(v){return/[0-9]/.test(v)}var j=[["{%",O.OpenStatement],["%}",O.CloseStatement],["{{",O.OpenExpression],["}}",O.CloseExpression],["(",O.OpenParen],[")",O.CloseParen],["{",O.OpenCurlyBracket],["}",O.CloseCurlyBracket],["[",O.OpenSquareBracket],["]",O.CloseSquareBracket],[",",O.Comma],[".",O.Dot],[":",O.Colon],["|",O.Pipe],["<=",O.ComparisonBinaryOperator],[">=",O.ComparisonBinaryOperator],["==",O.ComparisonBinaryOperator],["!=",O.ComparisonBinaryOperator],["<",O.ComparisonBinaryOperator],[">",O.ComparisonBinaryOperator],["+",O.AdditiveBinaryOperator],["-",O.AdditiveBinaryOperator],["*",O.MultiplicativeBinaryOperator],["/",O.MultiplicativeBinaryOperator],["%",O.MultiplicativeBinaryOperator],["=",O.Equals]],S=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function V(v,q={}){return v.endsWith(` `)&&(v=v.slice(0,-1)),v=v.replace(/{#.*?#}/gs,"{##}"),q.lstrip_blocks&&(v=v.replace(/^[ \t]*({[#%])/gm,"$1")),q.trim_blocks&&(v=v.replace(/([#%]})\n/g,"$1")),v.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function A(v,q={}){var Ye,Bt,ft;const C=[],Q=V(v,q);let he=0;const Qe=Tt=>{let bt="";for(;Tt(Q[he]);){if(Q[he]==="\\"){if(++he,he>=Q.length)throw new SyntaxError("Unexpected end of input");const Ot=Q[he++],cr=S.get(Ot);if(cr===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ot}`);bt+=cr;continue}if(bt+=Q[he++],he>=Q.length)throw new SyntaxError("Unexpected end of input")}return bt};e:for(;he0){C.push(new ye(Ot,O.Text));continue}}Qe(Ot=>/\s/.test(Ot));const bt=Q[he];if(bt==="-"||bt==="+"){const Ot=(Bt=C.at(-1))==null?void 0:Bt.type;if(Ot===O.Text||Ot===void 0)throw new SyntaxError(`Unexpected character: ${bt}`);switch(Ot){case O.Identifier:case O.NumericLiteral:case O.BooleanLiteral:case O.StringLiteral:case O.CloseParen:case O.CloseSquareBracket:break;default:{++he;const cr=Qe(Ce);C.push(new ye(`${bt}${cr}`,cr.length>0?O.NumericLiteral:O.UnaryOperator));continue}}}for(const[Ot,cr]of j)if(Q.slice(he,he+Ot.length)===Ot){C.push(new ye(Ot,cr)),he+=Ot.length;continue e}if(bt==="'"||bt==='"'){++he;const Ot=Qe(cr=>cr!==bt);C.push(new ye(Ot,O.StringLiteral)),++he;continue}if(Ce(bt)){const Ot=Qe(Ce);C.push(new ye(Ot,O.NumericLiteral));continue}if(Te(bt)){const Ot=Qe(Te),cr=Object.hasOwn(fe,Ot)?fe[Ot]:O.Identifier;cr===O.In&&((ft=C.at(-1))==null?void 0:ft.type)===O.Not?(C.pop(),C.push(new ye("not in",O.NotIn))):C.push(new ye(Ot,cr));continue}throw new SyntaxError(`Unexpected character: ${bt}`)}return C}var ee=class{constructor(){xe(this,"type","Statement")}},ne=class extends ee{constructor(q){super();xe(this,"type","Program");this.body=q}},me=class extends ee{constructor(q,C,Q){super();xe(this,"type","If");this.test=q,this.body=C,this.alternate=Q}},ce=class extends ee{constructor(q,C,Q,he){super();xe(this,"type","For");this.loopvar=q,this.iterable=C,this.body=Q,this.defaultBlock=he}},D=class extends ee{constructor(q,C){super();xe(this,"type","Set");this.assignee=q,this.value=C}},H=class extends ee{constructor(q,C,Q){super();xe(this,"type","Macro");this.name=q,this.args=C,this.body=Q}},te=class extends ee{constructor(){super(...arguments);xe(this,"type","Expression")}},se=class extends te{constructor(q,C,Q){super();xe(this,"type","MemberExpression");this.object=q,this.property=C,this.computed=Q}},X=class extends te{constructor(q,C){super();xe(this,"type","CallExpression");this.callee=q,this.args=C}},R=class extends te{constructor(q){super();xe(this,"type","Identifier");this.value=q}},I=class extends te{constructor(q){super();xe(this,"type","Literal");this.value=q}},B=class extends I{constructor(){super(...arguments);xe(this,"type","NumericLiteral")}},k=class extends I{constructor(){super(...arguments);xe(this,"type","StringLiteral")}},ue=class extends I{constructor(){super(...arguments);xe(this,"type","BooleanLiteral")}},ve=class extends I{constructor(){super(...arguments);xe(this,"type","ArrayLiteral")}},$e=class extends I{constructor(){super(...arguments);xe(this,"type","TupleLiteral")}},Ie=class extends I{constructor(){super(...arguments);xe(this,"type","ObjectLiteral")}},Ae=class extends te{constructor(q,C,Q){super();xe(this,"type","BinaryExpression");this.operator=q,this.left=C,this.right=Q}},tt=class extends te{constructor(q,C){super();xe(this,"type","FilterExpression");this.operand=q,this.filter=C}},Xe=class extends te{constructor(q,C){super();xe(this,"type","SelectExpression");this.iterable=q,this.test=C}},dt=class extends te{constructor(q,C,Q){super();xe(this,"type","TestExpression");this.operand=q,this.negate=C,this.test=Q}},ge=class extends te{constructor(q,C){super();xe(this,"type","UnaryExpression");this.operator=q,this.argument=C}},G=class extends te{constructor(q=void 0,C=void 0,Q=void 0){super();xe(this,"type","SliceExpression");this.start=q,this.stop=C,this.step=Q}},de=class extends te{constructor(q,C){super();xe(this,"type","KeywordArgumentExpression");this.key=q,this.value=C}};function Se(v){const q=new ne([]);let C=0;function Q(Me,Ze){const ot=v[C++];if(!ot||ot.type!==Me)throw new Error(`Parser Error: ${Ze}. ${ot.type} !== ${Me}.`);return ot}function he(){switch(v[C].type){case O.Text:return Bt();case O.OpenStatement:return ft();case O.OpenExpression:return Tt();default:throw new SyntaxError(`Unexpected token type: ${v[C].type}`)}}function Qe(...Me){return C+Me.length<=v.length&&Me.some((Ze,ot)=>Ze!==v[C+ot].type)}function Ye(...Me){return C+Me.length<=v.length&&Me.every((Ze,ot)=>Ze===v[C+ot].type)}function Bt(){return new k(Q(O.Text,"Expected text token").value)}function ft(){Q(O.OpenStatement,"Expected opening statement token");let Me;switch(v[C].type){case O.Set:++C,Me=bt(),Q(O.CloseStatement,"Expected closing statement token");break;case O.If:++C,Me=Ot(),Q(O.OpenStatement,"Expected {% token"),Q(O.EndIf,"Expected endif token"),Q(O.CloseStatement,"Expected %} token");break;case O.Macro:++C,Me=cr(),Q(O.OpenStatement,"Expected {% token"),Q(O.EndMacro,"Expected endmacro token"),Q(O.CloseStatement,"Expected %} token");break;case O.For:++C,Me=Yr(),Q(O.OpenStatement,"Expected {% token"),Q(O.EndFor,"Expected endfor token"),Q(O.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${v[C].type}`)}return Me}function Tt(){Q(O.OpenExpression,"Expected opening expression token");const Me=Br();return Q(O.CloseExpression,"Expected closing expression token"),Me}function bt(){const Me=Br();if(Ye(O.Equals)){++C;const Ze=bt();return new D(Me,Ze)}return Me}function Ot(){var Ht,gr,Lr,mr,yr,Tr,$n,Rr;const Me=Br();Q(O.CloseStatement,"Expected closing statement token");const Ze=[],ot=[];for(;!(((Ht=v[C])==null?void 0:Ht.type)===O.OpenStatement&&(((gr=v[C+1])==null?void 0:gr.type)===O.ElseIf||((Lr=v[C+1])==null?void 0:Lr.type)===O.Else||((mr=v[C+1])==null?void 0:mr.type)===O.EndIf));)Ze.push(he());if(((yr=v[C])==null?void 0:yr.type)===O.OpenStatement&&((Tr=v[C+1])==null?void 0:Tr.type)!==O.EndIf)if(++C,Ye(O.ElseIf))Q(O.ElseIf,"Expected elseif token"),ot.push(Ot());else for(Q(O.Else,"Expected else token"),Q(O.CloseStatement,"Expected closing statement token");!((($n=v[C])==null?void 0:$n.type)===O.OpenStatement&&((Rr=v[C+1])==null?void 0:Rr.type)===O.EndIf);)ot.push(he());return new me(Me,Ze,ot)}function cr(){const Me=Gt();if(Me.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Ze=gt();Q(O.CloseStatement,"Expected closing statement token");const ot=[];for(;Qe(O.OpenStatement,O.EndMacro);)ot.push(he());return new H(Me,Ze,ot)}function xr(Me=!1){const Ze=Me?Gt:Br,ot=[Ze()],Ht=Ye(O.Comma);for(;Ht&&(++C,ot.push(Ze()),!!Ye(O.Comma)););return Ht?new $e(ot):ot[0]}function Yr(){const Me=xr(!0);if(!(Me instanceof R||Me instanceof $e))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Me.type} instead`);Q(O.In,"Expected `in` keyword following loop variable");const Ze=Br();Q(O.CloseStatement,"Expected closing statement token");const ot=[];for(;Qe(O.OpenStatement,O.EndFor)&&Qe(O.OpenStatement,O.Else);)ot.push(he());const Ht=[];if(Ye(O.OpenStatement,O.Else))for(++C,++C,Q(O.CloseStatement,"Expected closing statement token");Qe(O.OpenStatement,O.EndFor);)Ht.push(he());return new ce(Me,Ze,ot,Ht)}function Br(){return Kr()}function Kr(){const Me=at();if(Ye(O.If)){++C;const Ze=at();if(Ye(O.Else)){++C;const ot=at();return new me(Ze,[Me],[ot])}else return new Xe(Me,Ze)}return Me}function at(){let Me=U();for(;Ye(O.Or);){const Ze=v[C];++C;const ot=U();Me=new Ae(Ze,Me,ot)}return Me}function U(){let Me=_e();for(;Ye(O.And);){const Ze=v[C];++C;const ot=_e();Me=new Ae(Ze,Me,ot)}return Me}function _e(){let Me;for(;Ye(O.Not);){const Ze=v[C];++C;const ot=_e();Me=new ge(Ze,ot)}return Me??Pe()}function Pe(){let Me=rt();for(;Ye(O.ComparisonBinaryOperator)||Ye(O.In)||Ye(O.NotIn);){const Ze=v[C];++C;const ot=rt();Me=new Ae(Ze,Me,ot)}return Me}function rt(){let Me=Ft();for(;Ye(O.AdditiveBinaryOperator);){const Ze=v[C];++C;const ot=Ft();Me=new Ae(Ze,Me,ot)}return Me}function we(){const Me=_t();return Ye(O.OpenParen)?Je(Me):Me}function Je(Me){let Ze=new X(Me,gt());return Ye(O.OpenParen)&&(Ze=Je(Ze)),Ze}function gt(){Q(O.OpenParen,"Expected opening parenthesis for arguments list");const Me=mt();return Q(O.CloseParen,"Expected closing parenthesis for arguments list"),Me}function mt(){const Me=[];for(;!Ye(O.CloseParen);){let Ze=Br();if(Ye(O.Equals)){if(++C,!(Ze instanceof R))throw new SyntaxError("Expected identifier for keyword argument");const ot=Br();Ze=new de(Ze,ot)}Me.push(Ze),Ye(O.Comma)&&++C}return Me}function Et(){const Me=[];let Ze=!1;for(;!Ye(O.CloseSquareBracket);)Ye(O.Colon)?(Me.push(void 0),++C,Ze=!0):(Me.push(Br()),Ye(O.Colon)&&(++C,Ze=!0));if(Me.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Ze){if(Me.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new G(...Me)}return Me[0]}function _t(){let Me=Gt();for(;Ye(O.Dot)||Ye(O.OpenSquareBracket);){const Ze=v[C];++C;let ot;const Ht=Ze.type!==O.Dot;if(Ht)ot=Et(),Q(O.CloseSquareBracket,"Expected closing square bracket");else if(ot=Gt(),ot.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Me=new se(Me,ot,Ht)}return Me}function Ft(){let Me=Nt();for(;Ye(O.MultiplicativeBinaryOperator);){const Ze=v[C];++C;const ot=Nt();Me=new Ae(Ze,Me,ot)}return Me}function Nt(){let Me=Rt();for(;Ye(O.Is);){++C;const Ze=Ye(O.Not);Ze&&++C;let ot=Gt();if(ot instanceof ue&&(ot=new R(ot.value.toString())),!(ot instanceof R))throw new SyntaxError("Expected identifier for the test");Me=new dt(Me,Ze,ot)}return Me}function Rt(){let Me=we();for(;Ye(O.Pipe);){++C;let Ze=Gt();if(!(Ze instanceof R))throw new SyntaxError("Expected identifier for the filter");Ye(O.OpenParen)&&(Ze=Je(Ze)),Me=new tt(Me,Ze)}return Me}function Gt(){const Me=v[C];switch(Me.type){case O.NumericLiteral:return++C,new B(Number(Me.value));case O.StringLiteral:return++C,new k(Me.value);case O.BooleanLiteral:return++C,new ue(Me.value.toLowerCase()==="true");case O.Identifier:return++C,new R(Me.value);case O.OpenParen:{++C;const Ze=xr();if(v[C].type!==O.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${v[C].type} instead`);return++C,Ze}case O.OpenSquareBracket:{++C;const Ze=[];for(;!Ye(O.CloseSquareBracket);)Ze.push(Br()),Ye(O.Comma)&&++C;return++C,new ve(Ze)}case O.OpenCurlyBracket:{++C;const Ze=new Map;for(;!Ye(O.CloseCurlyBracket);){const ot=Br();Q(O.Colon,"Expected colon between key and value in object literal");const Ht=Br();Ze.set(ot,Ht),Ye(O.Comma)&&++C}return++C,new Ie(Ze)}default:throw new SyntaxError(`Unexpected token: ${Me.type}`)}}for(;C=0?(q=(q??(q=0))<0?Math.max(v.length+q,0):Math.min(q,v.length),C=(C??(C=v.length))<0?Math.max(v.length+C,0):Math.min(C,v.length)):(q=(q??(q=v.length-1))<0?Math.max(v.length+q,-1):Math.min(q,v.length-1),C=(C??(C=-1))<-1?Math.max(v.length+C,-1):Math.min(C,v.length-1));const Qe=[];for(let Ye=q;he*Yeq.toUpperCase())}var nt=class{constructor(v=void 0){xe(this,"type","RuntimeValue");xe(this,"value");xe(this,"builtins",new Map);this.value=v}__bool__(){return new st(!!this.value)}},lt=class extends nt{constructor(){super(...arguments);xe(this,"type","NumericValue")}},Ne=class extends nt{constructor(){super(...arguments);xe(this,"type","StringValue");xe(this,"builtins",new Map([["upper",new je(()=>new Ne(this.value.toUpperCase()))],["lower",new je(()=>new Ne(this.value.toLowerCase()))],["strip",new je(()=>new Ne(this.value.trim()))],["title",new je(()=>new Ne(ct(this.value)))],["length",new lt(this.value.length)]]))}},st=class extends nt{constructor(){super(...arguments);xe(this,"type","BooleanValue")}},Pt=class extends nt{constructor(){super(...arguments);xe(this,"type","ObjectValue");xe(this,"builtins",new Map([["get",new je(([q,C])=>{if(!(q instanceof Ne))throw new Error(`Object key must be a string: got ${q.type}`);return this.value.get(q.value)??C??new qe})],["items",new je(()=>new re(Array.from(this.value.entries()).map(([q,C])=>new re([new Ne(q),C]))))]]))}__bool__(){return new st(this.value.size>0)}},Re=class extends Pt{constructor(){super(...arguments);xe(this,"type","KeywordArgumentsValue")}},re=class extends nt{constructor(){super(...arguments);xe(this,"type","ArrayValue");xe(this,"builtins",new Map([["length",new lt(this.value.length)]]))}__bool__(){return new st(this.value.length>0)}},ke=class extends re{constructor(){super(...arguments);xe(this,"type","TupleValue")}},je=class extends nt{constructor(){super(...arguments);xe(this,"type","FunctionValue")}},qe=class extends nt{constructor(){super(...arguments);xe(this,"type","NullValue")}},Ue=class extends nt{constructor(){super(...arguments);xe(this,"type","UndefinedValue")}},Ke=class{constructor(v){xe(this,"variables",new Map([["namespace",new je(v=>{if(v.length===0)return new Pt(new Map);if(v.length!==1||!(v[0]instanceof Pt))throw new Error("`namespace` expects either zero arguments or a single object argument");return v[0]})]]));xe(this,"tests",new Map([["boolean",v=>v.type==="BooleanValue"],["callable",v=>v instanceof je],["odd",v=>{if(v.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${v.type}`);return v.value%2!==0}],["even",v=>{if(v.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${v.type}`);return v.value%2===0}],["false",v=>v.type==="BooleanValue"&&!v.value],["true",v=>v.type==="BooleanValue"&&v.value],["string",v=>v.type==="StringValue"],["number",v=>v.type==="NumericValue"],["integer",v=>v.type==="NumericValue"&&Number.isInteger(v.value)],["iterable",v=>v instanceof re||v instanceof Ne],["lower",v=>{const q=v.value;return v.type==="StringValue"&&q===q.toLowerCase()}],["upper",v=>{const q=v.value;return v.type==="StringValue"&&q===q.toUpperCase()}],["none",v=>v.type==="NullValue"],["defined",v=>v.type!=="UndefinedValue"],["undefined",v=>v.type==="UndefinedValue"],["equalto",(v,q)=>v.value===q.value],["eq",(v,q)=>v.value===q.value]]));this.parent=v}set(v,q){return this.declareVariable(v,yt(q))}declareVariable(v,q){if(this.variables.has(v))throw new SyntaxError(`Variable already declared: ${v}`);return this.variables.set(v,q),q}setVariable(v,q){return this.variables.set(v,q),q}resolve(v){if(this.variables.has(v))return this;if(this.parent)return this.parent.resolve(v);throw new Error(`Unknown variable: ${v}`)}lookupVariable(v){try{return this.resolve(v).variables.get(v)??new Ue}catch{return new Ue}}},ut=class{constructor(v){xe(this,"global");this.global=v??new Ke}run(v){return this.evaluate(v,this.global)}evaluateBinaryExpression(v,q){const C=this.evaluate(v.left,q);switch(v.operator.value){case"and":return C.__bool__().value?this.evaluate(v.right,q):C;case"or":return C.__bool__().value?C:this.evaluate(v.right,q)}const Q=this.evaluate(v.right,q);switch(v.operator.value){case"==":return new st(C.value==Q.value);case"!=":return new st(C.value!=Q.value)}if(C instanceof Ue||Q instanceof Ue)throw new Error("Cannot perform operation on undefined values");if(C instanceof qe||Q instanceof qe)throw new Error("Cannot perform operation on null values");if(C instanceof lt&&Q instanceof lt)switch(v.operator.value){case"+":return new lt(C.value+Q.value);case"-":return new lt(C.value-Q.value);case"*":return new lt(C.value*Q.value);case"/":return new lt(C.value/Q.value);case"%":return new lt(C.value%Q.value);case"<":return new st(C.value":return new st(C.value>Q.value);case">=":return new st(C.value>=Q.value);case"<=":return new st(C.value<=Q.value)}else if(C instanceof re&&Q instanceof re)switch(v.operator.value){case"+":return new re(C.value.concat(Q.value))}else if(Q instanceof re){const he=Q.value.find(Qe=>Qe.value===C.value)!==void 0;switch(v.operator.value){case"in":return new st(he);case"not in":return new st(!he)}}if(C instanceof Ne||Q instanceof Ne)switch(v.operator.value){case"+":return new Ne(C.value.toString()+Q.value.toString())}if(C instanceof Ne&&Q instanceof Ne)switch(v.operator.value){case"in":return new st(Q.value.includes(C.value));case"not in":return new st(!Q.value.includes(C.value))}if(C instanceof Ne&&Q instanceof Pt)switch(v.operator.value){case"in":return new st(Q.value.has(C.value));case"not in":return new st(!Q.value.has(C.value))}throw new SyntaxError(`Unknown operator "${v.operator.value}" between ${C.type} and ${Q.type}`)}evaluateArguments(v,q){const C=[],Q=new Map;for(const he of v)if(he.type==="KeywordArgumentExpression"){const Qe=he;Q.set(Qe.key.value,this.evaluate(Qe.value,q))}else{if(Q.size>0)throw new Error("Positional arguments must come before keyword arguments");C.push(this.evaluate(he,q))}return[C,Q]}evaluateFilterExpression(v,q){const C=this.evaluate(v.operand,q);if(v.filter.type==="Identifier"){const Q=v.filter;if(Q.value==="tojson")return new Ne(vt(C));if(C instanceof re)switch(Q.value){case"list":return C;case"first":return C.value[0];case"last":return C.value[C.value.length-1];case"length":return new lt(C.value.length);case"reverse":return new re(C.value.reverse());case"sort":return new re(C.value.sort((he,Qe)=>{if(he.type!==Qe.type)throw new Error(`Cannot compare different types: ${he.type} and ${Qe.type}`);switch(he.type){case"NumericValue":return he.value-Qe.value;case"StringValue":return he.value.localeCompare(Qe.value);default:throw new Error(`Cannot compare type: ${he.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Q.value}`)}else if(C instanceof Ne)switch(Q.value){case"length":return new lt(C.value.length);case"upper":return new Ne(C.value.toUpperCase());case"lower":return new Ne(C.value.toLowerCase());case"title":return new Ne(ct(C.value));case"capitalize":return new Ne(C.value.charAt(0).toUpperCase()+C.value.slice(1));case"trim":return new Ne(C.value.trim());case"indent":return new Ne(C.value.split(` `).map((he,Qe)=>Qe===0||he.length===0?he:" "+he).join(` `));case"string":return C;default:throw new Error(`Unknown StringValue filter: ${Q.value}`)}else if(C instanceof lt)switch(Q.value){case"abs":return new lt(Math.abs(C.value));default:throw new Error(`Unknown NumericValue filter: ${Q.value}`)}else if(C instanceof Pt)switch(Q.value){case"items":return new re(Array.from(C.value.entries()).map(([he,Qe])=>new re([new Ne(he),Qe])));case"length":return new lt(C.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Q.value}`)}throw new Error(`Cannot apply filter "${Q.value}" to type: ${C.type}`)}else if(v.filter.type==="CallExpression"){const Q=v.filter;if(Q.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Q.callee.type}`);const he=Q.callee.value;if(he==="tojson"){const[,Qe]=this.evaluateArguments(Q.args,q),Ye=Qe.get("indent")??new qe;if(!(Ye instanceof lt||Ye instanceof qe))throw new Error("If set, indent must be a number");return new Ne(vt(C,Ye.value))}if(C instanceof re){switch(he){case"selectattr":{if(C.value.some(bt=>!(bt instanceof Pt)))throw new Error("`selectattr` can only be applied to array of objects");if(Q.args.some(bt=>bt.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Qe,Ye,Bt]=Q.args.map(bt=>this.evaluate(bt,q));let ft;if(Ye){const bt=q.tests.get(Ye.value);if(!bt)throw new Error(`Unknown test: ${Ye.value}`);ft=bt}else ft=(...bt)=>bt[0].__bool__().value;const Tt=C.value.filter(bt=>{const Ot=bt.value.get(Qe.value);return Ot?ft(Ot,Bt):!1});return new re(Tt)}case"map":{const[,Qe]=this.evaluateArguments(Q.args,q);if(Qe.has("attribute")){const Ye=Qe.get("attribute");if(!(Ye instanceof Ne))throw new Error("attribute must be a string");const Bt=Qe.get("default"),ft=C.value.map(Tt=>{if(!(Tt instanceof Pt))throw new Error("items in map must be an object");return Tt.value.get(Ye.value)??Bt??new Ue});return new re(ft)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${he}`)}else if(C instanceof Ne){switch(he){case"indent":{const[Qe,Ye]=this.evaluateArguments(Q.args,q),Bt=Qe.at(0)??Ye.get("width")??new lt(4);if(!(Bt instanceof lt))throw new Error("width must be a number");const ft=Qe.at(1)??Ye.get("first")??new st(!1),Tt=Qe.at(2)??Ye.get("blank")??new st(!1),bt=C.value.split(` `),Ot=" ".repeat(Bt.value),cr=bt.map((xr,Yr)=>!ft.value&&Yr===0||!Tt.value&&xr.length===0?xr:Ot+xr);return new Ne(cr.join(` `))}}throw new Error(`Unknown StringValue filter: ${he}`)}else throw new Error(`Cannot apply filter "${he}" to type: ${C.type}`)}throw new Error(`Unknown filter: ${v.filter.type}`)}evaluateTestExpression(v,q){const C=this.evaluate(v.operand,q),Q=q.tests.get(v.test.value);if(!Q)throw new Error(`Unknown test: ${v.test.value}`);const he=Q(C);return new st(v.negate?!he:he)}evaluateUnaryExpression(v,q){const C=this.evaluate(v.argument,q);switch(v.operator.value){case"not":return new st(!C.value);default:throw new SyntaxError(`Unknown operator: ${v.operator.value}`)}}evalProgram(v,q){return this.evaluateBlock(v.body,q)}evaluateBlock(v,q){let C="";for(const Q of v){const he=this.evaluate(Q,q);he.type!=="NullValue"&&he.type!=="UndefinedValue"&&(C+=he.value)}return new Ne(C)}evaluateIdentifier(v,q){return q.lookupVariable(v.value)}evaluateCallExpression(v,q){const[C,Q]=this.evaluateArguments(v.args,q);Q.size>0&&C.push(new Re(Q));const he=this.evaluate(v.callee,q);if(he.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${he.type}`);return he.value(C,q)}evaluateSliceExpression(v,q,C){if(!(v instanceof re||v instanceof Ne))throw new Error("Slice object must be an array or string");const Q=this.evaluate(q.start,C),he=this.evaluate(q.stop,C),Qe=this.evaluate(q.step,C);if(!(Q instanceof lt||Q instanceof Ue))throw new Error("Slice start must be numeric or undefined");if(!(he instanceof lt||he instanceof Ue))throw new Error("Slice stop must be numeric or undefined");if(!(Qe instanceof lt||Qe instanceof Ue))throw new Error("Slice step must be numeric or undefined");return v instanceof re?new re(He(v.value,Q.value,he.value,Qe.value)):new Ne(He(Array.from(v.value),Q.value,he.value,Qe.value).join(""))}evaluateMemberExpression(v,q){const C=this.evaluate(v.object,q);let Q;if(v.computed){if(v.property.type==="SliceExpression")return this.evaluateSliceExpression(C,v.property,q);Q=this.evaluate(v.property,q)}else Q=new Ne(v.property.value);let he;if(C instanceof Pt){if(!(Q instanceof Ne))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=C.value.get(Q.value)??C.builtins.get(Q.value)}else if(C instanceof re||C instanceof Ne)if(Q instanceof lt)he=C.value.at(Q.value),C instanceof Ne&&(he=new Ne(C.value.at(Q.value)));else if(Q instanceof Ne)he=C.builtins.get(Q.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Q.type}`);else{if(!(Q instanceof Ne))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=C.builtins.get(Q.value)}return he instanceof nt?he:new Ue}evaluateSet(v,q){const C=this.evaluate(v.value,q);if(v.assignee.type==="Identifier"){const Q=v.assignee.value;q.setVariable(Q,C)}else if(v.assignee.type==="MemberExpression"){const Q=v.assignee,he=this.evaluate(Q.object,q);if(!(he instanceof Pt))throw new Error("Cannot assign to member of non-object");if(Q.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");he.value.set(Q.property.value,C)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(v.assignee)}`);return new qe}evaluateIf(v,q){const C=this.evaluate(v.test,q);return this.evaluateBlock(C.__bool__().value?v.body:v.alternate,q)}evaluateFor(v,q){const C=new Ke(q);let Q,he;if(v.iterable.type==="SelectExpression"){const Tt=v.iterable;he=this.evaluate(Tt.iterable,C),Q=Tt.test}else he=this.evaluate(v.iterable,C);if(!(he instanceof re))throw new Error(`Expected iterable type in for loop: got ${he.type}`);const Qe=[],Ye=[];for(let Tt=0;Ttxr.setVariable(v.loopvar.value,Ot);else if(v.loopvar.type==="TupleLiteral"){const xr=v.loopvar;if(Ot.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Ot.type}`);const Yr=Ot;if(xr.value.length!==Yr.value.length)throw new Error(`Too ${xr.value.length>Yr.value.length?"few":"many"} items to unpack`);cr=Br=>{for(let Kr=0;Kr0?Qe[Tt-1]:new Ue],["nextitem",Tt{var Ye;const he=new Ke(Q);C=C.slice();let Qe;((Ye=C.at(-1))==null?void 0:Ye.type)==="KeywordArgumentsValue"&&(Qe=C.pop());for(let Bt=0;Btthis.evaluate(C,q)));case"TupleLiteral":return new ke(v.value.map(C=>this.evaluate(C,q)));case"ObjectLiteral":{const C=new Map;for(const[Q,he]of v.value){const Qe=this.evaluate(Q,q);if(!(Qe instanceof Ne))throw new Error(`Object keys must be strings: got ${Qe.type}`);C.set(Qe.value,this.evaluate(he,q))}return new Pt(C)}case"Identifier":return this.evaluateIdentifier(v,q);case"CallExpression":return this.evaluateCallExpression(v,q);case"MemberExpression":return this.evaluateMemberExpression(v,q);case"UnaryExpression":return this.evaluateUnaryExpression(v,q);case"BinaryExpression":return this.evaluateBinaryExpression(v,q);case"FilterExpression":return this.evaluateFilterExpression(v,q);case"TestExpression":return this.evaluateTestExpression(v,q);default:throw new SyntaxError(`Unknown node type: ${v.type}`)}}};function yt(v){switch(typeof v){case"number":return new lt(v);case"string":return new Ne(v);case"boolean":return new st(v);case"undefined":return new Ue;case"object":return v===null?new qe:Array.isArray(v)?new re(v.map(yt)):new Pt(new Map(Object.entries(v).map(([q,C])=>[q,yt(C)])));case"function":return new je((q,C)=>{const Q=v(...q.map(he=>he.value))??null;return yt(Q)});default:throw new Error(`Cannot convert to runtime value: ${v}`)}}function vt(v,q,C){const Q=C??0;switch(v.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(v.value);case"ArrayValue":case"ObjectValue":{const he=q?" ".repeat(q):"",Qe=` `+he.repeat(Q),Ye=Qe+he;if(v.type==="ArrayValue"){const Bt=v.value.map(ft=>vt(ft,q,Q+1));return q?`[${Ye}${Bt.join(`,${Ye}`)}${Qe}]`:`[${Bt.join(", ")}]`}else{const Bt=Array.from(v.value.entries()).map(([ft,Tt])=>{const bt=`"${ft}": ${vt(Tt,q,Q+1)}`;return q?`${Ye}${bt}`:bt});return q?`{${Bt.join(",")}${Qe}}`:`{${Bt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${v.type}`)}}var kt=class{constructor(v){xe(this,"parsed");const q=A(v,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Se(q)}render(v){const q=new Ke;q.set("false",!1),q.set("true",!0),q.set("raise_exception",he=>{throw new Error(he)}),q.set("range",Z);for(const[he,Qe]of Object.entries(v))q.set(he,Qe);return new ut(q).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{registerBackend:()=>ye,resolveBackendAndExecutionProviders:()=>Ce});const O=new Map,fe=[],ye=(j,S,V)=>{if(S&&typeof S.init=="function"&&typeof S.createInferenceSessionHandler=="function"){const A=O.get(j);if(A===void 0)O.set(j,{backend:S,priority:V});else{if(A.priority>V)return;if(A.priority===V&&A.backend!==S)throw new Error(`cannot register backend "${j}" using priority ${V}`)}if(V>=0){const ee=fe.indexOf(j);ee!==-1&&fe.splice(ee,1);for(let ne=0;ne{const S=O.get(j);if(!S)return"backend not found.";if(S.initialized)return S.backend;if(S.aborted)return S.error;{const V=!!S.initPromise;try{return V||(S.initPromise=S.backend.init(j)),await S.initPromise,S.initialized=!0,S.backend}catch(A){return V||(S.error=`${A}`,S.aborted=!0),S.error}finally{delete S.initPromise}}},Ce=async j=>{const S=j.executionProviders||[],V=S.map(D=>typeof D=="string"?D:D.name),A=V.length===0?fe:V;let ee;const ne=[],me=new Set;for(const D of A){const H=await Te(D);typeof H=="string"?ne.push({name:D,err:H}):(ee||(ee=H),ee===H&&me.add(D))}if(!ee)throw new Error(`no available backend found. ERR: ${ne.map(D=>`[${D.name}] ${D.err}`).join(", ")}`);for(const{name:D,err:H}of ne)V.includes(D)&&console.warn(`removing requested execution provider "${D}" from session options because it is not available: ${H}`);const ce=S.filter(D=>me.has(typeof D=="string"?D:D.name));return[ee,new Proxy(j,{get:(D,H)=>H==="executionProviders"?ce:Reflect.get(D,H)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{registerBackend:()=>O.registerBackend});var O=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{env:()=>ye});var O=N("./node_modules/onnxruntime-common/dist/esm/version.js");let fe="warning";const ye={wasm:{},webgl:{},webgpu:{},versions:{common:O.version},set logLevel(Te){if(Te!==void 0){if(typeof Te!="string"||["verbose","info","warning","error","fatal"].indexOf(Te)===-1)throw new Error(`Unsupported logging level: ${Te}`);fe=Te}},get logLevel(){return fe}};Object.defineProperty(ye,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{env:()=>fe});var O=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const fe=O.env},"./node_modules/onnxruntime-common/dist/esm/index.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{InferenceSession:()=>ye.InferenceSession,TRACE:()=>Ce.TRACE,TRACE_FUNC_BEGIN:()=>Ce.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Ce.TRACE_FUNC_END,Tensor:()=>Te.Tensor,TrainingSession:()=>j.TrainingSession,env:()=>fe.env,registerBackend:()=>O.registerBackend});var O=N("./node_modules/onnxruntime-common/dist/esm/backend.js"),fe=N("./node_modules/onnxruntime-common/dist/esm/env.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Te=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),N("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Ce=N("./node_modules/onnxruntime-common/dist/esm/trace.js");N("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),N("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var j=N("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{InferenceSession:()=>Te});var O=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),fe=N("./node_modules/onnxruntime-common/dist/esm/tensor.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/trace.js");class Te{constructor(j){this.handler=j}async run(j,S,V){(0,ye.TRACE_FUNC_BEGIN)();const A={};let ee={};if(typeof j!="object"||j===null||j instanceof fe.Tensor||Array.isArray(j))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ne=!0;if(typeof S=="object"){if(S===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(S instanceof fe.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(S)){if(S.length===0)throw new TypeError("'fetches' cannot be an empty array.");ne=!1;for(const D of S){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);A[D]=null}if(typeof V=="object"&&V!==null)ee=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const H=Object.getOwnPropertyNames(S);for(const te of this.outputNames)if(H.indexOf(te)!==-1){const se=S[te];(se===null||se instanceof fe.Tensor)&&(D=!0,ne=!1,A[te]=se)}if(D){if(typeof V=="object"&&V!==null)ee=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else ee=S}}else if(typeof S<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of this.inputNames)if(typeof j[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ne)for(const D of this.outputNames)A[D]=null;const me=await this.handler.run(j,A,ee),ce={};for(const D in me)if(Object.hasOwnProperty.call(me,D)){const H=me[D];H instanceof fe.Tensor?ce[D]=H:ce[D]=new fe.Tensor(H.type,H.data,H.dims)}return(0,ye.TRACE_FUNC_END)(),ce}async release(){return this.handler.dispose()}static async create(j,S,V,A){(0,ye.TRACE_FUNC_BEGIN)();let ee,ne={};if(typeof j=="string"){if(ee=j,typeof S=="object"&&S!==null)ne=S;else if(typeof S<"u")throw new TypeError("'options' must be an object.")}else if(j instanceof Uint8Array){if(ee=j,typeof S=="object"&&S!==null)ne=S;else if(typeof S<"u")throw new TypeError("'options' must be an object.")}else if(j instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&j instanceof SharedArrayBuffer){const H=j;let te=0,se=j.byteLength;if(typeof S=="object"&&S!==null)ne=S;else if(typeof S=="number"){if(te=S,!Number.isSafeInteger(te))throw new RangeError("'byteOffset' must be an integer.");if(te<0||te>=H.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${H.byteLength}).`);if(se=j.byteLength-te,typeof V=="number"){if(se=V,!Number.isSafeInteger(se))throw new RangeError("'byteLength' must be an integer.");if(se<=0||te+se>H.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${H.byteLength-te}].`);if(typeof A=="object"&&A!==null)ne=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(typeof V<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof S<"u")throw new TypeError("'options' must be an object.");ee=new Uint8Array(H,te,se)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[me,ce]=await(0,O.resolveBackendAndExecutionProviders)(ne),D=await me.createInferenceSessionHandler(ee,ce);return(0,ye.TRACE_FUNC_END)(),new Te(D)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{InferenceSession:()=>fe});var O=N("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const fe=O.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":($t,Ee,N)=>{N.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":($t,Ee,N)=>{N.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{tensorToDataURL:()=>O,tensorToImageData:()=>fe});const O=(ye,Te)=>{const Ce=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Ce.width=ye.dims[3],Ce.height=ye.dims[2];const j=Ce.getContext("2d");if(j!=null){let S,V;(Te==null?void 0:Te.tensorLayout)!==void 0&&Te.tensorLayout==="NHWC"?(S=ye.dims[2],V=ye.dims[3]):(S=ye.dims[3],V=ye.dims[2]);const A=(Te==null?void 0:Te.format)!==void 0?Te.format:"RGB",ee=Te==null?void 0:Te.norm;let ne,me;ee===void 0||ee.mean===void 0?ne=[255,255,255,255]:typeof ee.mean=="number"?ne=[ee.mean,ee.mean,ee.mean,ee.mean]:(ne=[ee.mean[0],ee.mean[1],ee.mean[2],0],ee.mean[3]!==void 0&&(ne[3]=ee.mean[3])),ee===void 0||ee.bias===void 0?me=[0,0,0,0]:typeof ee.bias=="number"?me=[ee.bias,ee.bias,ee.bias,ee.bias]:(me=[ee.bias[0],ee.bias[1],ee.bias[2],0],ee.bias[3]!==void 0&&(me[3]=ee.bias[3]));const ce=V*S;let D=0,H=ce,te=ce*2,se=-1;A==="RGBA"?(D=0,H=ce,te=ce*2,se=ce*3):A==="RGB"?(D=0,H=ce,te=ce*2):A==="RBG"&&(D=0,te=ce,H=ce*2);for(let X=0;X{const Ce=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let j;if(Ce!=null){let S,V,A;(Te==null?void 0:Te.tensorLayout)!==void 0&&Te.tensorLayout==="NHWC"?(S=ye.dims[2],V=ye.dims[1],A=ye.dims[3]):(S=ye.dims[3],V=ye.dims[2],A=ye.dims[1]);const ee=Te!==void 0&&Te.format!==void 0?Te.format:"RGB",ne=Te==null?void 0:Te.norm;let me,ce;ne===void 0||ne.mean===void 0?me=[255,255,255,255]:typeof ne.mean=="number"?me=[ne.mean,ne.mean,ne.mean,ne.mean]:(me=[ne.mean[0],ne.mean[1],ne.mean[2],255],ne.mean[3]!==void 0&&(me[3]=ne.mean[3])),ne===void 0||ne.bias===void 0?ce=[0,0,0,0]:typeof ne.bias=="number"?ce=[ne.bias,ne.bias,ne.bias,ne.bias]:(ce=[ne.bias[0],ne.bias[1],ne.bias[2],0],ne.bias[3]!==void 0&&(ce[3]=ne.bias[3]));const D=V*S;if(Te!==void 0&&(Te.format!==void 0&&A===4&&Te.format!=="RGBA"||A===3&&Te.format!=="RGB"&&Te.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const H=4;let te=0,se=1,X=2,R=3,I=0,B=D,k=D*2,ue=-1;ee==="RGBA"?(I=0,B=D,k=D*2,ue=D*3):ee==="RGB"?(I=0,B=D,k=D*2):ee==="RBG"&&(I=0,k=D,B=D*2),j=Ce.createImageData(S,V);for(let ve=0;ve{N.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{bufferToTensor:()=>fe,tensorFromGpuBuffer:()=>Ce,tensorFromImage:()=>ye,tensorFromPinnedBuffer:()=>j,tensorFromTexture:()=>Te});var O=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const fe=(S,V)=>{if(S===void 0)throw new Error("Image buffer must be defined");if(V.height===void 0||V.width===void 0)throw new Error("Image height and width must be defined");if(V.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:A,width:ee}=V,ne=V.norm??{mean:255,bias:0};let me,ce;typeof ne.mean=="number"?me=[ne.mean,ne.mean,ne.mean,ne.mean]:me=[ne.mean[0],ne.mean[1],ne.mean[2],ne.mean[3]??255],typeof ne.bias=="number"?ce=[ne.bias,ne.bias,ne.bias,ne.bias]:ce=[ne.bias[0],ne.bias[1],ne.bias[2],ne.bias[3]??0];const D=V.format!==void 0?V.format:"RGBA",H=V.tensorFormat!==void 0&&V.tensorFormat!==void 0?V.tensorFormat:"RGB",te=A*ee,se=H==="RGBA"?new Float32Array(te*4):new Float32Array(te*3);let X=4,R=0,I=1,B=2,k=3,ue=0,ve=te,$e=te*2,Ie=-1;D==="RGB"&&(X=3,R=0,I=1,B=2,k=-1),H==="RGBA"?Ie=te*3:H==="RBG"?(ue=0,$e=te,ve=te*2):H==="BGR"&&($e=0,ve=te,ue=te*2);for(let tt=0;tt{const A=typeof HTMLImageElement<"u"&&S instanceof HTMLImageElement,ee=typeof ImageData<"u"&&S instanceof ImageData,ne=typeof ImageBitmap<"u"&&S instanceof ImageBitmap,me=typeof S=="string";let ce,D=V??{};const H=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},te=se=>se instanceof HTMLCanvasElement||se instanceof OffscreenCanvas?se.getContext("2d"):null;if(A){const se=H();se.width=S.width,se.height=S.height;const X=te(se);if(X!=null){let R=S.height,I=S.width;if(V!==void 0&&V.resizedHeight!==void 0&&V.resizedWidth!==void 0&&(R=V.resizedHeight,I=V.resizedWidth),V!==void 0){if(D=V,V.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");D.tensorFormat="RGBA",D.height=R,D.width=I}else D.tensorFormat="RGBA",D.height=R,D.width=I;X.drawImage(S,0,0),ce=X.getImageData(0,0,I,R).data}else throw new Error("Can not access image data")}else if(ee){let se,X;if(V!==void 0&&V.resizedWidth!==void 0&&V.resizedHeight!==void 0?(se=V.resizedHeight,X=V.resizedWidth):(se=S.height,X=S.width),V!==void 0&&(D=V),D.format="RGBA",D.height=se,D.width=X,V!==void 0){const R=H();R.width=X,R.height=se;const I=te(R);if(I!=null)I.putImageData(S,0,0),ce=I.getImageData(0,0,X,se).data;else throw new Error("Can not access image data")}else ce=S.data}else if(ne){if(V===void 0)throw new Error("Please provide image config with format for Imagebitmap");const se=H();se.width=S.width,se.height=S.height;const X=te(se);if(X!=null){const R=S.height,I=S.width;return X.drawImage(S,0,0,I,R),ce=X.getImageData(0,0,I,R).data,D.height=R,D.width=I,fe(ce,D)}else throw new Error("Can not access image data")}else{if(me)return new Promise((se,X)=>{const R=H(),I=te(R);if(!S||!I)return X();const B=new Image;B.crossOrigin="Anonymous",B.src=S,B.onload=()=>{R.width=B.width,R.height=B.height,I.drawImage(B,0,0,R.width,R.height);const k=I.getImageData(0,0,R.width,R.height);D.height=R.height,D.width=R.width,se(fe(k.data,D))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ce!==void 0)return fe(ce,D);throw new Error("Input data provided is not supported - aborted tensor creation")},Te=(S,V)=>{const{width:A,height:ee,download:ne,dispose:me}=V,ce=[1,ee,A,4];return new O.Tensor({location:"texture",type:"float32",texture:S,dims:ce,download:ne,dispose:me})},Ce=(S,V)=>{const{dataType:A,dims:ee,download:ne,dispose:me}=V;return new O.Tensor({location:"gpu-buffer",type:A??"float32",gpuBuffer:S,dims:ee,download:ne,dispose:me})},j=(S,V,A)=>new O.Tensor({location:"cpu-pinned",type:S,data:V,dims:A??[V.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":($t,Ee,N)=>{N.r(Ee)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>fe,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>O,checkTypedArray:()=>Te});const O=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),fe=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ye=!1;const Te=()=>{if(!ye){ye=!0;const Ce=typeof BigInt64Array<"u"&&BigInt64Array.from,j=typeof BigUint64Array<"u"&&BigUint64Array.from,S=typeof Float16Array<"u"&&Float16Array.from;Ce&&(O.set("int64",BigInt64Array),fe.set(BigInt64Array,"int64")),j&&(O.set("uint64",BigUint64Array),fe.set(BigUint64Array,"uint64")),S?(O.set("float16",Float16Array),fe.set(Float16Array,"float16")):O.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{Tensor:()=>Ce});var O=N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),fe=N("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Te=N("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Ce{constructor(S,V,A){(0,ye.checkTypedArray)();let ee,ne;if(typeof S=="object"&&"location"in S)switch(this.dataLocation=S.location,ee=S.type,ne=S.dims,S.location){case"cpu-pinned":{const ce=ye.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(ee);if(!ce)throw new TypeError(`unsupported type "${ee}" to create tensor from pinned buffer`);if(!(S.data instanceof ce))throw new TypeError(`buffer should be of type ${ce.name}`);this.cpuData=S.data;break}case"texture":{if(ee!=="float32")throw new TypeError(`unsupported type "${ee}" to create tensor from texture`);this.gpuTextureData=S.texture,this.downloader=S.download,this.disposer=S.dispose;break}case"gpu-buffer":{if(ee!=="float32"&&ee!=="float16"&&ee!=="int32"&&ee!=="int64"&&ee!=="uint32"&&ee!=="uint8"&&ee!=="bool")throw new TypeError(`unsupported type "${ee}" to create tensor from gpu buffer`);this.gpuBufferData=S.gpuBuffer,this.downloader=S.download,this.disposer=S.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ce,D;if(typeof S=="string")if(ee=S,D=A,S==="string"){if(!Array.isArray(V))throw new TypeError("A string tensor's data must be a string array.");ce=V}else{const H=ye.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(S);if(H===void 0)throw new TypeError(`Unsupported tensor type: ${S}.`);if(Array.isArray(V)){if(S==="float16"&&H===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");S==="uint64"||S==="int64"?ce=H.from(V,BigInt):ce=H.from(V)}else if(V instanceof H)ce=V;else throw new TypeError(`A ${ee} tensor's data must be type of ${H}`)}else if(D=V,Array.isArray(S)){if(S.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const H=typeof S[0];if(H==="string")ee="string",ce=S;else if(H==="boolean")ee="bool",ce=Uint8Array.from(S);else throw new TypeError(`Invalid element type of data array: ${H}.`)}else{const H=ye.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(S.constructor);if(H===void 0)throw new TypeError(`Unsupported type for tensor data: ${S.constructor}.`);ee=H,ce=S}if(D===void 0)D=[ce.length];else if(!Array.isArray(D))throw new TypeError("A tensor's dims must be a number array");ne=D,this.cpuData=ce,this.dataLocation="cpu"}const me=(0,Te.calculateSize)(ne);if(this.cpuData&&me!==this.cpuData.length)throw new Error(`Tensor's size(${me}) does not match data length(${this.cpuData.length}).`);this.type=ee,this.dims=ne,this.size=me}static async fromImage(S,V){return(0,fe.tensorFromImage)(S,V)}static fromTexture(S,V){return(0,fe.tensorFromTexture)(S,V)}static fromGpuBuffer(S,V){return(0,fe.tensorFromGpuBuffer)(S,V)}static fromPinnedBuffer(S,V,A){return(0,fe.tensorFromPinnedBuffer)(S,V,A)}toDataURL(S){return(0,O.tensorToDataURL)(this,S)}toImageData(S){return(0,O.tensorToImageData)(this,S)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(S){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const V=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=V,S&&this.disposer&&(this.disposer(),this.disposer=void 0),V}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(S){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Te.tensorReshape)(this,S)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{calculateSize:()=>fe,tensorReshape:()=>ye});var O=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const fe=Te=>{let Ce=1;for(let j=0;j{switch(Te.location){case"cpu":return new O.Tensor(Te.type,Te.data,Ce);case"cpu-pinned":return new O.Tensor({location:"cpu-pinned",data:Te.data,type:Te.type,dims:Ce});case"texture":return new O.Tensor({location:"texture",texture:Te.texture,type:Te.type,dims:Ce});case"gpu-buffer":return new O.Tensor({location:"gpu-buffer",gpuBuffer:Te.gpuBuffer,type:Te.type,dims:Ce});default:throw new Error(`tensorReshape: tensor location ${Te.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{Tensor:()=>fe});var O=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const fe=O.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{TRACE:()=>fe,TRACE_FUNC_BEGIN:()=>Te,TRACE_FUNC_END:()=>Ce});var O=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const fe=(j,S)=>{(typeof O.env.trace>"u"?!O.env.wasm.trace:!O.env.trace)||console.timeStamp(`${j}::ORT::${S}`)},ye=(j,S)=>{var ee;const V=((ee=new Error().stack)==null?void 0:ee.split(/\r\n|\r|\n/g))||[];let A=!1;for(let ne=0;ne{(typeof O.env.trace>"u"?!O.env.wasm.trace:!O.env.trace)||ye("BEGIN",j)},Ce=j=>{(typeof O.env.trace>"u"?!O.env.wasm.trace:!O.env.trace)||ye("END",j)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{TrainingSession:()=>Te});var O=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),fe=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");const ye="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Te{constructor(j,S,V){this.handler=j,this.hasOptimizerModel=S,this.hasEvalModel=V}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(j,S){const V=j.evalModel||"",A=j.optimizerModel||"",ee=S||{},[ne,me]=await(0,O.resolveBackendAndExecutionProviders)(ee);if(ne.createTrainingSessionHandler){const ce=await ne.createTrainingSessionHandler(j.checkpointState,j.trainModel,V,A,me);return new Te(ce,!!j.optimizerModel,!!j.evalModel)}else throw new Error(ye)}typeNarrowingForRunStep(j,S,V,A,ee){const ne={};let me={};if(typeof V!="object"||V===null||V instanceof fe.Tensor||Array.isArray(V))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ce=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof fe.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");ce=!1;for(const D of A){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(S.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);ne[D]=null}if(typeof ee=="object"&&ee!==null)me=ee;else if(typeof ee<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const H=Object.getOwnPropertyNames(A);for(const te of S)if(H.indexOf(te)!==-1){const se=A[te];(se===null||se instanceof fe.Tensor)&&(D=!0,ce=!1,ne[te]=se)}if(D){if(typeof ee=="object"&&ee!==null)me=ee;else if(typeof ee<"u")throw new TypeError("'options' must be an object.")}else me=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of j)if(typeof V[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ce)for(const D of S)ne[D]=null;return[ne,me]}convertHandlerReturnTypeToMapOfTensors(j){const S={};for(const V in j)if(Object.hasOwnProperty.call(j,V)){const A=j[V];A instanceof fe.Tensor?S[V]=A:S[V]=new fe.Tensor(A.type,A.data,A.dims)}return S}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(j,S,V){const[A,ee]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,j,S,V),ne=await this.handler.runTrainStep(j,A,ee);return this.convertHandlerReturnTypeToMapOfTensors(ne)}async runOptimizerStep(j){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(j||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(j,S,V){if(this.hasEvalModel){const[A,ee]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,j,S,V),ne=await this.handler.runEvalStep(j,A,ee);return this.convertHandlerReturnTypeToMapOfTensors(ne)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(j=!0){return this.handler.getParametersSize(j)}async loadParametersBuffer(j,S=!0){const V=await this.getParametersSize(S);if(j.length!==4*V)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(j,S)}async getContiguousParameters(j=!0){return this.handler.getContiguousParameters(j)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{TrainingSession:()=>fe});var O=N("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const fe=O.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{version:()=>O});const O="1.19.2"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{InferenceSession:()=>vt,TRACE:()=>ke,TRACE_FUNC_BEGIN:()=>qe,TRACE_FUNC_END:()=>Ue,Tensor:()=>Re,TrainingSession:()=>Bt,default:()=>Uf,env:()=>k,registerBackend:()=>me});/*! * ONNX Runtime Web v1.20.0-dev.20240925-a47254eaef * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var O=Object.defineProperty,fe=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyNames,Te=Object.prototype.hasOwnProperty,Ce=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),j=(e,t)=>()=>(e&&(t=e(e=0)),t),S=(e,t)=>{for(var r in t)O(e,r,{get:t[r],enumerable:!0})},V=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ye(t))!Te.call(e,s)&&s!==r&&O(e,s,{get:()=>t[s],enumerable:!(n=fe(t,s))||n.enumerable});return e},A=e=>V(O({},"__esModule",{value:!0}),e),ee,ne,me,ce,D,H=j(()=>{ee=new Map,ne=[],me=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=ee.get(e);if(n===void 0)ee.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=ne.indexOf(e);s!==-1&&ne.splice(s,1);for(let a=0;a{let t=ee.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},D=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?ne:r,s,a=[],i=new Set;for(let d of n){let p=await ce(d);typeof p=="string"?a.push({name:d,err:p}):(s||(s=p),s===p&&i.add(d))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:p}of a)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${p}`);let u=t.filter(d=>i.has(typeof d=="string"?d:d.name));return[s,new Proxy(e,{get:(d,p)=>p==="executionProviders"?u:Reflect.get(d,p)})]}}),te=j(()=>{H()}),se,X=j(()=>{se="1.20.0-dev.20240912-ae39c40e5b"}),R,I,B=j(()=>{X(),R="warning",I={wasm:{},webgl:{},webgpu:{},versions:{common:se},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}`);R=e}},get logLevel(){return R}},Object.defineProperty(I,"logLevel",{enumerable:!0})}),k,ue=j(()=>{B(),k=I}),ve,$e,Ie=j(()=>{ve=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,d,p;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?p=[0,0,0,0]:typeof u.bias=="number"?p=[u.bias,u.bias,u.bias,u.bias]:(p=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(p[3]=u.bias[3]));let w=a*s,g=0,l=w,M=w*2,E=-1;i==="RGBA"?(g=0,l=w,M=w*2,E=w*3):i==="RGB"?(g=0,l=w,M=w*2):i==="RBG"&&(g=0,M=w,l=w*2);for(let $=0;${let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,p,w;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean=="number"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?w=[0,0,0,0]:typeof d.bias=="number"?w=[d.bias,d.bias,d.bias,d.bias]:(w=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(w[3]=d.bias[3]));let g=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,M=0,E=1,$=2,L=3,W=0,z=g,ie=g*2,J=-1;u==="RGBA"?(W=0,z=g,ie=g*2,J=g*3):u==="RGB"?(W=0,z=g,ie=g*2):u==="RBG"&&(W=0,ie=g,z=g*2),n=r.createImageData(s,a);for(let oe=0;oe{Pt(),Ae=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*n,w=d==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),g=4,l=0,M=1,E=2,$=3,L=0,W=p,z=p*2,ie=-1;u==="RGB"&&(g=3,l=0,M=1,E=2,$=-1),d==="RGBA"?ie=p*3:d==="RBG"?(L=0,z=p,W=p*2):d==="BGR"&&(z=0,W=p,L=p*2);for(let J=0;J{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,u=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=w=>w instanceof HTMLCanvasElement||w instanceof OffscreenCanvas?w.getContext("2d"):null;if(r){let w=d();w.width=e.width,w.height=e.height;let g=p(w);if(g!=null){let l=e.height,M=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,M=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=l,u.width=M}else u.tensorFormat="RGBA",u.height=l,u.width=M;g.drawImage(e,0,0),i=g.getImageData(0,0,M,l).data}else throw new Error("Can not access image data")}else if(n){let w,g;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(w=t.resizedHeight,g=t.resizedWidth):(w=e.height,g=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=w,u.width=g,t!==void 0){let l=d();l.width=g,l.height=w;let M=p(l);if(M!=null)M.putImageData(e,0,0),i=M.getImageData(0,0,g,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=d();w.width=e.width,w.height=e.height;let g=p(w);if(g!=null){let l=e.height,M=e.width;return g.drawImage(e,0,0,M,l),i=g.getImageData(0,0,M,l).data,u.height=l,u.width=M,Ae(i,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((w,g)=>{let l=d(),M=p(l);if(!e||!M)return g();let E=new Image;E.crossOrigin="Anonymous",E.src=e,E.onload=()=>{l.width=E.width,l.height=E.height,M.drawImage(E,0,0,l.width,l.height);let $=M.getImageData(0,0,l.width,l.height);u.height=l.height,u.width=l.width,w(Ae($.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ae(i,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Xe=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new st({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},dt=(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})},ge=(e,t,r)=>new st({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),de,Se,Z,He,ct=j(()=>{de=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Se=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Z=!1,He=()=>{if(!Z){Z=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(de.set("int64",BigInt64Array),Se.set(BigInt64Array,"int64")),t&&(de.set("uint64",BigUint64Array),Se.set(BigUint64Array,"uint64")),r?(de.set("float16",Float16Array),Se.set(Float16Array,"float16")):de.set("float16",Uint16Array)}}}),nt,lt,Ne=j(()=>{Pt(),nt=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,Pt=j(()=>{Ie(),G(),ct(),Ne(),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=de.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let d=de.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&d===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${d.name} as data.`);e==="uint64"||e==="int64"?i=d.from(t,BigInt):i=d.from(t)}else if(t instanceof d)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${d}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")n="string",i=e;else if(d==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let d=Se.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=d,i=e}if(u===void 0)u=[i.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");s=u,this.cpuData=i,this.dataLocation="cpu"}let a=nt(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return tt(e,t)}static fromTexture(e,t){return Xe(e,t)}static fromGpuBuffer(e,t){return dt(e,t)}static fromPinnedBuffer(e,t,r){return ge(e,t,r)}toDataURL(e){return ve(this,e)}toImageData(e){return $e(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return lt(this,e)}}}),Re,re=j(()=>{Pt(),Re=st}),ke,je,qe,Ue,Ke=j(()=>{B(),ke=(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)},Ue=e=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||je("END",e)}}),ut,yt=j(()=>{H(),re(),Ke(),ut=class wf{constructor(t){this.handler=t}async run(t,r,n){qe();let s={},a={};if(typeof t!="object"||t===null||t instanceof Re||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 Re)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let p of r){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);s[p]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,w=Object.getOwnPropertyNames(r);for(let g of this.outputNames)if(w.indexOf(g)!==-1){let l=r[g];(l===null||l instanceof Re)&&(p=!0,i=!1,s[g]=l)}if(p){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(i)for(let p of this.outputNames)s[p]=null;let u=await this.handler.run(t,s,a),d={};for(let p in u)if(Object.hasOwnProperty.call(u,p)){let w=u[p];w instanceof Re?d[p]=w:d[p]=new Re(w.type,w.data,w.dims)}return Ue(),d}async release(){return this.handler.dispose()}static async create(t,r,n,s){qe();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,g=0,l=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(g=r,!Number.isSafeInteger(g))throw new RangeError("'byteOffset' must be an integer.");if(g<0||g>=w.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${w.byteLength}).`);if(l=t.byteLength-g,typeof n=="number"){if(l=n,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||g+l>w.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${w.byteLength-g}].`);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,g,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await D(i),p=await u.createInferenceSessionHandler(a,d);return Ue(),new wf(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),vt,kt=j(()=>{yt(),vt=ut}),v=j(()=>{}),q=j(()=>{}),C=j(()=>{}),Q=j(()=>{}),he,Qe,Ye=j(()=>{H(),re(),he="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Qe=class yf{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let n=t.evalModel||"",s=t.optimizerModel||"",a=r||{},[i,u]=await D(a);if(i.createTrainingSessionHandler){let d=await i.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,s,u);return new yf(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(he)}typeNarrowingForRunStep(t,r,n,s,a){let i={},u={};if(typeof n!="object"||n===null||n instanceof Re||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof Re)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let p of s){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);i[p]=null}if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,w=Object.getOwnPropertyNames(s);for(let g of r)if(w.indexOf(g)!==-1){let l=s[g];(l===null||l instanceof Re)&&(p=!0,d=!1,i[g]=l)}if(p){if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else u=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of t)if(typeof n[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(d)for(let p of r)i[p]=null;return[i,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let s=t[n];s instanceof Re?r[n]=s:r[n]=new Re(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()}}}),Bt,ft=j(()=>{Ye(),Bt=Qe}),Tt={};S(Tt,{InferenceSession:()=>vt,TRACE:()=>ke,TRACE_FUNC_BEGIN:()=>qe,TRACE_FUNC_END:()=>Ue,Tensor:()=>Re,TrainingSession:()=>Bt,env:()=>k,registerBackend:()=>me});var bt=j(()=>{te(),ue(),kt(),re(),v(),q(),Ke(),C(),Q(),ft()}),Ot=j(()=>{}),cr={};S(cr,{default:()=>Br});var xr,Yr,Br,Kr=j(()=>{var e;Rp(),yr(),Rt(),xr="ort-wasm-proxy-worker",Yr=((e=globalThis.self)==null?void 0:e.name)===xr,Yr&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Lr(n.wasm).then(()=>{Mc(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;vc(a,s).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})});break}case"copy-from":{let{buffer:s}=n,a=Yd(s);postMessage({type:r,out:a});break}case"create":{let{model:s,options:a}=n;xc(s,a).then(i=>{postMessage({type:r,out:i})},i=>{postMessage({type:r,err:i})});break}case"release":Tc(n),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:a,inputs:i,outputIndices:u,options:d}=n;Cc(s,a,i,u,new Array(u.length).fill(null),d).then(p=>{p.some(w=>w[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:p},Sc([...i,...p]))},p=>{postMessage({type:r,err:p})});break}case"end-profiling":$c(n),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),Br=Yr?null:t=>new Worker(t??we,{type:"module",name:xr})}),at={};S(at,{default:()=>Pe});var U,_e,Pe,rt=j(()=>{var e;_e=(U=self.location.href,async function(t={}){function r(){return Mr.buffer!=dr.buffer&&bn(),dr}function n(){return Mr.buffer!=dr.buffer&&bn(),Or}function s(){return Mr.buffer!=dr.buffer&&bn(),Ve}function a(){return Mr.buffer!=dr.buffer&&bn(),St}function i(){return Mr.buffer!=dr.buffer&&bn(),rr}function u(){return Mr.buffer!=dr.buffer&&bn(),Vr}function d(){return Mr.buffer!=dr.buffer&&bn(),nn}function p(){return Mr.buffer!=dr.buffer&&bn(),ec}var w,g,l=Object.assign({},t),M=new Promise((o,h)=>{w=o,g=h}),E=typeof window=="object",$=typeof importScripts=="function",L=$&&self.name=="em-pthread";l.mountExternalData=(o,h)=>{o.startsWith("./")&&(o=o.substring(2)),(l.Fb||(l.Fb=new Map)).set(o,h)},l.unmountExternalData=()=>{delete l.Fb};var W=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let z=()=>{let o=(y,x,F)=>(...le)=>{let We=us,it=x==null?void 0:x();le=y(...le);let At=x==null?void 0:x();return it!==At&&(y=At,F(it),x=F=null),us!=We?new Promise((Lt,Yt)=>{Kc={resolve:Lt,reject:Yt}}):le},h=y=>async(...x)=>{var F;try{if(l.Eb)throw Error("Session already started");let le=l.Eb={cc:x[0],errors:[]},We=await y(...x);if(l.Eb!==le)throw Error("Session mismatch");(F=l.Mb)==null||F.flush();let it=le.errors;if(0Lt),0l._OrtCreateSession,y=>l._OrtCreateSession=y),l._OrtRun=h(o(l._OrtRun,()=>l._OrtRun,y=>l._OrtRun=y)),l._OrtRunWithBinding=h(o(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,y=>l._OrtRunWithBinding=y)),l._OrtBindInput=o(l._OrtBindInput,()=>l._OrtBindInput,y=>l._OrtBindInput=y),z=void 0};l.jsepInit=(o,h)=>{if(z==null||z(),o==="webgpu"){[l.Mb,l.Tb,l.Xb,l.Nb,l.Wb,l.jb,l.Yb,l.$b,l.Ub,l.Vb,l.Zb]=h;let y=l.Mb;l.jsepRegisterBuffer=(x,F,le,We)=>y.registerBuffer(x,F,le,We),l.jsepGetBuffer=x=>y.getBuffer(x),l.jsepCreateDownloader=(x,F,le)=>y.createDownloader(x,F,le),l.jsepOnReleaseSession=x=>{y.onReleaseSession(x)},l.jsepOnRunStart=x=>y.onRunStart(x),l.ac=(x,F)=>{y.upload(x,F)}}};var ie,J,oe=Object.assign({},l),Ge="./this.program",De=(o,h)=>{throw h},pt="";(E||$)&&($?pt=self.location.href:typeof document<"u"&&document.currentScript&&(pt=document.currentScript.src),U&&(pt=U),pt=pt.startsWith("blob:")?"":pt.substr(0,pt.replace(/[?#].*/,"").lastIndexOf("/")+1),$&&(J=o=>{var h=new XMLHttpRequest;return h.open("GET",o,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),ie=(o,h,y)=>{var x=new XMLHttpRequest;x.open("GET",o,!0),x.responseType="arraybuffer",x.onload=()=>{x.status==200||x.status==0&&x.response?h(x.response):y()},x.onerror=y,x.send(null)});var Dt,Vt=console.log.bind(console),lr=console.error.bind(console),fr=Vt,tr=lr;if(Object.assign(l,oe),oe=null,L){let o=function(h){try{var y=h.data,x=y.cmd;if(x==="load"){let F=[];self.onmessage=le=>F.push(le),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let le of F)o(le);self.onmessage=o};for(let le of y.handlers)l[le]&&!l[le].proxy||(l[le]=(...We)=>{postMessage({Lb:"callHandler",lc:le,args:We})},le=="print"&&(fr=l[le]),le=="printErr"&&(tr=l[le]));Mr=y.wasmMemory,bn(),jr(y.wasmModule)}else if(x==="run"){Jc(y.pthread_ptr,0,0,1,0,0),Gc(y.pthread_ptr),qf(),lh(),Qr||(af(),Qr=!0);try{Hf(y.start_routine,y.arg)}catch(F){if(F!="unwind")throw F}}else x==="cancel"?Za()&&pc(-1):y.target!=="setimmediate"&&(x==="checkMailbox"?Qr&&nc():x&&(tr(`worker: received unknown command ${x}`),tr(y)))}catch(F){throw of(),F}};var jr,Qr=!1;tr=function(...h){h=h.join(" "),console.error(h)},self.alert=function(...h){postMessage({Lb:"alert",text:h.join(" "),nc:Za()})},l.instantiateWasm=(h,y)=>new Promise(x=>{jr=F=>{F=new WebAssembly.Instance(F,nh()),y(F),x()}}),self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=o}l.wasmBinary&&(Dt=l.wasmBinary);var Mr,Ur,Jt,dr,Or,Ve,St,rr,Vr,nn,fn,Ws,ec,Nn=!1;function bn(){var o=Mr.buffer;l.HEAP8=dr=new Int8Array(o),l.HEAP16=Ve=new Int16Array(o),l.HEAPU8=Or=new Uint8Array(o),l.HEAPU16=St=new Uint16Array(o),l.HEAP32=rr=new Int32Array(o),l.HEAPU32=Vr=new Uint32Array(o),l.HEAPF32=nn=new Float32Array(o),l.HEAPF64=ec=new Float64Array(o),l.HEAP64=fn=new BigInt64Array(o),l.HEAPU64=Ws=new BigUint64Array(o)}if(!L){if(!((Mr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof W))throw tr("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");bn()}var cd=[],Mn=[],Pn=[],Wn=0,Gs=null;function tc(){if(--Wn==0&&Gs){var o=Gs;Gs=null,o()}}function Qa(o){throw tr(o="Aborted("+o+")"),Nn=!0,Jt=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),g(o),o}var Fc,Zp=o=>o.startsWith("data:application/octet-stream;base64,"),eh=o=>o.startsWith("file://");function th(o){if(o==Fc&&Dt)return new Uint8Array(Dt);if(J)return J(o);throw"both async and sync fetching of the wasm failed"}function rh(o,h,y){return function(x){if(!Dt&&(E||$)){if(typeof fetch=="function"&&!eh(x))return fetch(x,{credentials:"same-origin"}).then(F=>{if(!F.ok)throw`failed to load wasm binary file at '${x}'`;return F.arrayBuffer()}).catch(()=>th(x));if(ie)return new Promise((F,le)=>{ie(x,We=>F(new Uint8Array(We)),le)})}return Promise.resolve().then(()=>th(x))}(o).then(x=>WebAssembly.instantiate(x,h)).then(y,x=>{tr(`failed to asynchronously prepare wasm: ${x}`),Qa(x)})}function nh(){return{a:{M:Gf,za:Wf,b:Xf,$:ph,z:mh,pa:_h,X:wh,Z:yh,qa:bh,na:Mh,ga:vh,ma:xh,J:Th,Y:Eh,V:Ch,oa:$h,W:Sh,va:Qf,D:Yf,P:Jf,O:em,C:rm,t:nm,q:sm,E:im,y:pm,Q:hm,ta:fm,ja:mm,T:_m,aa:gm,F:wm,ia:Gc,sa:ym,s:bm,B:xm,o:Tm,m:Cm,c:Uc,n:$m,k:Pm,Aa:Am,p:Im,g:Fm,v:Om,l:zm,f:Dm,j:Bm,i:Lm,h:Rm,d:Nm,da:jm,ea:Vm,fa:Um,ba:Vh,ca:Uh,S:Wm,e:Gm,N:qm,G:Hm,K:Km,w:Xm,ra:Qm,U:Ym,u:Gh,x:Jm,L:Zm,R:e_,ya:t_,xa:r_,ka:Kh,la:Xh,_:Lc,A:Qh,I:Yh,ha:Jh,H:Zh,a:Mr,wa:Bc,ua:rf,r:i_}}}var Oc={862964:(o,h,y,x,F)=>{if(l===void 0||!l.Fb)return 1;if((o=gn(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=l.Fb.get(o)))return 2;if(x>>>=0,(h>>>=0)+(y>>>=0)>o.byteLength)return 3;try{let le=o.subarray(h,h+y);switch(F){case 0:n().set(le,x>>>0);break;case 1:l.ac(x,le);break;default:return 4}return 0}catch{return 4}},863647:()=>{l.Ub()},863678:()=>{l.Vb()},863707:()=>{l.Zb()},863732:o=>l.Tb(o),863765:o=>l.Xb(o),863797:(o,h,y)=>{l.Nb(o,h,y,!0)},863836:(o,h,y)=>{l.Nb(o,h,y)},863869:()=>typeof wasmOffsetConverter<"u",863926:o=>{l.jb("Abs",o,void 0)},863977:o=>{l.jb("Neg",o,void 0)},864028:o=>{l.jb("Floor",o,void 0)},864081:o=>{l.jb("Ceil",o,void 0)},864133:o=>{l.jb("Reciprocal",o,void 0)},864191:o=>{l.jb("Sqrt",o,void 0)},864243:o=>{l.jb("Exp",o,void 0)},864294:o=>{l.jb("Erf",o,void 0)},864345:o=>{l.jb("Sigmoid",o,void 0)},864400:(o,h,y)=>{l.jb("HardSigmoid",o,{alpha:h,beta:y})},864479:o=>{l.jb("Log",o,void 0)},864530:o=>{l.jb("Sin",o,void 0)},864581:o=>{l.jb("Cos",o,void 0)},864632:o=>{l.jb("Tan",o,void 0)},864683:o=>{l.jb("Asin",o,void 0)},864735:o=>{l.jb("Acos",o,void 0)},864787:o=>{l.jb("Atan",o,void 0)},864839:o=>{l.jb("Sinh",o,void 0)},864891:o=>{l.jb("Cosh",o,void 0)},864943:o=>{l.jb("Asinh",o,void 0)},864996:o=>{l.jb("Acosh",o,void 0)},865049:o=>{l.jb("Atanh",o,void 0)},865102:o=>{l.jb("Tanh",o,void 0)},865154:o=>{l.jb("Not",o,void 0)},865205:(o,h,y)=>{l.jb("Clip",o,{min:h,max:y})},865274:o=>{l.jb("Clip",o,void 0)},865326:(o,h)=>{l.jb("Elu",o,{alpha:h})},865384:o=>{l.jb("Gelu",o,void 0)},865436:o=>{l.jb("Relu",o,void 0)},865488:(o,h)=>{l.jb("LeakyRelu",o,{alpha:h})},865552:(o,h)=>{l.jb("ThresholdedRelu",o,{alpha:h})},865622:(o,h)=>{l.jb("Cast",o,{to:h})},865680:o=>{l.jb("Add",o,void 0)},865731:o=>{l.jb("Sub",o,void 0)},865782:o=>{l.jb("Mul",o,void 0)},865833:o=>{l.jb("Div",o,void 0)},865884:o=>{l.jb("Pow",o,void 0)},865935:o=>{l.jb("Equal",o,void 0)},865988:o=>{l.jb("Greater",o,void 0)},866043:o=>{l.jb("GreaterOrEqual",o,void 0)},866105:o=>{l.jb("Less",o,void 0)},866157:o=>{l.jb("LessOrEqual",o,void 0)},866216:(o,h,y,x,F)=>{l.jb("ReduceMean",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},866375:(o,h,y,x,F)=>{l.jb("ReduceMax",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},866533:(o,h,y,x,F)=>{l.jb("ReduceMin",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},866691:(o,h,y,x,F)=>{l.jb("ReduceProd",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},866850:(o,h,y,x,F)=>{l.jb("ReduceSum",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},867008:(o,h,y,x,F)=>{l.jb("ReduceL1",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},867165:(o,h,y,x,F)=>{l.jb("ReduceL2",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},867322:(o,h,y,x,F)=>{l.jb("ReduceLogSum",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},867483:(o,h,y,x,F)=>{l.jb("ReduceSumSquare",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},867647:(o,h,y,x,F)=>{l.jb("ReduceLogSumExp",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},867811:o=>{l.jb("Where",o,void 0)},867864:(o,h,y)=>{l.jb("Transpose",o,{perm:h?Array.from(i().subarray(h>>>0,y>>>0)):[]})},867972:(o,h,y,x)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:gn(y),format:x?"NHWC":"NCHW"})},868105:(o,h,y,x)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:gn(y),format:x?"NHWC":"NCHW"})},868238:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le,vr)=>{l.jb("ConvTranspose",o,{format:At?"NHWC":"NCHW",autoPad:h,dilations:[y],group:x,kernelShape:[F],pads:[le,We],strides:[it],wIsConst:()=>!!r()[Lt>>>0],outputPadding:Yt?Array.from(i().subarray(Yt>>>0,Pr>>>0)):[],outputShape:Nr?Array.from(i().subarray(Nr>>>0,Le>>>0)):[],activation:gn(vr)})},868639:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:h,dilations:Array.from(i().subarray(y>>>0,2+(y>>>0)>>>0)),group:x,kernelShape:Array.from(i().subarray(F>>>0,2+(F>>>0)>>>0)),pads:Array.from(i().subarray(le>>>0,4+(le>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[At>>>0],outputPadding:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],outputShape:Pr?Array.from(i().subarray(Pr>>>0,Nr>>>0)):[],activation:gn(Le)})},869204:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le,vr)=>{l.jb("ConvTranspose",o,{format:At?"NHWC":"NCHW",autoPad:h,dilations:[y],group:x,kernelShape:[F],pads:[le,We],strides:[it],wIsConst:()=>!!r()[Lt>>>0],outputPadding:Yt?Array.from(i().subarray(Yt>>>0,Pr>>>0)):[],outputShape:Nr?Array.from(i().subarray(Nr>>>0,Le>>>0)):[],activation:gn(vr)})},869605:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:h,dilations:Array.from(i().subarray(y>>>0,2+(y>>>0)>>>0)),group:x,kernelShape:Array.from(i().subarray(F>>>0,2+(F>>>0)>>>0)),pads:Array.from(i().subarray(le>>>0,4+(le>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[At>>>0],outputPadding:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],outputShape:Pr?Array.from(i().subarray(Pr>>>0,Nr>>>0)):[],activation:gn(Le)})},870170:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},870261:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le)=>{l.jb("AveragePool",o,{format:Le?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:x,storage_order:F,dilations:le?Array.from(i().subarray(le>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,At>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],strides:Pr?Array.from(i().subarray(Pr>>>0,Nr>>>0)):[]})},870676:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},870767:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le)=>{l.jb("AveragePool",o,{format:Le?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:x,storage_order:F,dilations:le?Array.from(i().subarray(le>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,At>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],strides:Pr?Array.from(i().subarray(Pr>>>0,Nr>>>0)):[]})},871182:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},871269:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le)=>{l.jb("MaxPool",o,{format:Le?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:x,storage_order:F,dilations:le?Array.from(i().subarray(le>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,At>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],strides:Pr?Array.from(i().subarray(Pr>>>0,Nr>>>0)):[]})},871680:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},871767:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le)=>{l.jb("MaxPool",o,{format:Le?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:x,storage_order:F,dilations:le?Array.from(i().subarray(le>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,At>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],strides:Pr?Array.from(i().subarray(Pr>>>0,Nr>>>0)):[]})},872178:(o,h,y,x,F)=>{l.jb("Gemm",o,{alpha:h,beta:y,transA:x,transB:F})},872282:o=>{l.jb("MatMul",o,void 0)},872336:(o,h,y,x)=>{l.jb("ArgMax",o,{keepDims:!!h,selectLastIndex:!!y,axis:x})},872444:(o,h,y,x)=>{l.jb("ArgMin",o,{keepDims:!!h,selectLastIndex:!!y,axis:x})},872552:(o,h)=>{l.jb("Softmax",o,{axis:h})},872615:(o,h)=>{l.jb("Concat",o,{axis:h})},872675:(o,h,y,x,F)=>{l.jb("Split",o,{axis:h,numOutputs:y,splitSizes:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},872815:o=>{l.jb("Expand",o,void 0)},872869:(o,h)=>{l.jb("Gather",o,{axis:Number(h)})},872940:(o,h)=>{l.jb("GatherElements",o,{axis:Number(h)})},873019:(o,h,y,x,F,le,We,it,At,Lt,Yt)=>{l.jb("Resize",o,{antialias:h,axes:y?Array.from(i().subarray(y>>>0,x>>>0)):[],coordinateTransformMode:gn(F),cubicCoeffA:le,excludeOutside:We,extrapolationValue:it,keepAspectRatioPolicy:gn(At),mode:gn(Lt),nearestMode:gn(Yt)})},873365:(o,h,y,x,F,le,We)=>{l.jb("Slice",o,{starts:h?Array.from(i().subarray(h>>>0,y>>>0)):[],ends:x?Array.from(i().subarray(x>>>0,F>>>0)):[],axes:le?Array.from(i().subarray(le>>>0,We>>>0)):[]})},873581:o=>{l.jb("Tile",o,void 0)},873633:(o,h,y)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:y?"NHWC":"NCHW"})},873747:(o,h,y)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:y?"NHWC":"NCHW"})},873861:o=>{l.jb("Range",o,void 0)},873914:(o,h)=>{l.jb("Einsum",o,{equation:gn(h)})},873995:(o,h,y,x,F)=>{l.jb("Pad",o,{mode:h,value:y,pads:x?Array.from(i().subarray(x>>>0,F>>>0)):[]})},874122:(o,h,y,x,F,le)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:y,spatial:!!F,trainingMode:!!x,format:le?"NHWC":"NCHW"})},874291:(o,h,y,x,F,le)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:y,spatial:!!F,trainingMode:!!x,format:le?"NHWC":"NCHW"})},874460:(o,h,y)=>{l.jb("CumSum",o,{exclusive:Number(h),reverse:Number(y)})},874557:(o,h,y)=>{l.jb("DequantizeLinear",o,{axis:h,blockSize:y})},874647:(o,h,y,x,F,le,We,it,At)=>{l.jb("Attention",o,{numHeads:h,isUnidirectional:y,maskFilterValue:x,scale:F,doRotary:le,qkvHiddenSizes:We?Array.from(i().subarray(Number(it)>>>0,Number(it)+We>>>0)):[],pastPresentShareBuffer:!!At})},874919:o=>{l.jb("BiasAdd",o,void 0)},874974:o=>{l.jb("BiasSplitGelu",o,void 0)},875035:o=>{l.jb("FastGelu",o,void 0)},875091:(o,h,y,x,F,le,We,it,At,Lt,Yt,Pr,Nr,Le,vr,Zr)=>{l.jb("Conv",o,{format:Pr?"NHWC":"NCHW",auto_pad:h,dilations:y?Array.from(i().subarray(y>>>0,x>>>0)):[],group:F,kernel_shape:le?Array.from(i().subarray(le>>>0,We>>>0)):[],pads:it?Array.from(i().subarray(it>>>0,At>>>0)):[],strides:Lt?Array.from(i().subarray(Lt>>>0,Yt>>>0)):[],w_is_const:()=>!!r()[Nr>>>0],activation:gn(Le),activation_params:vr?Array.from(d().subarray(vr>>>0,Zr>>>0)):[]})},875587:o=>{l.jb("Gelu",o,void 0)},875639:(o,h,y,x)=>{l.jb("GroupQueryAttention",o,{numHeads:h,kvNumHeads:y,scale:x})},875752:(o,h,y,x)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:y,simplified:!!x})},875863:(o,h,y,x)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:y,simplified:!!x})},875974:(o,h,y,x,F,le)=>{l.jb("MatMulNBits",o,{k:h,n:y,accuracyLevel:x,bits:F,blockSize:le})},876101:(o,h,y,x,F,le)=>{l.jb("MultiHeadAttention",o,{numHeads:h,isUnidirectional:y,maskFilterValue:x,scale:F,doRotary:le})},876260:(o,h)=>{l.jb("QuickGelu",o,{alpha:h})},876324:(o,h,y,x,F)=>{l.jb("RotaryEmbedding",o,{interleaved:!!h,numHeads:y,rotaryEmbeddingDim:x,scale:F})},876463:(o,h,y)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!y})},876565:(o,h,y)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!y})},876667:(o,h,y,x)=>{l.jb("GatherBlockQuantized",o,{gatherAxis:h,quantizeAxis:y,blockSize:x})},876788:o=>{l.Yb(o)},876822:(o,h)=>l.$b(o,h,l.Eb.cc,l.Eb.errors)};function Wf(o,h,y){return Bh(async()=>{await l.Wb(o,h,y)})}function Gf(){return typeof wasmOffsetConverter<"u"}function zc(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var Dc=o=>{o.terminate(),o.onmessage=()=>{}},sh=o=>{qs.length==0&&(dh(),uh(qs[0]));var h=qs.pop();if(!h)return 6;gi.push(h),os[o.Ab]=h,h.Ab=o.Ab;var y={cmd:"run",start_routine:o.dc,arg:o.Pb,pthread_ptr:o.Ab};return h.postMessage(y,o.jc),0},_i=0,Jr=(o,h,...y)=>{for(var x=2*y.length,F=tp(),le=ep(8*x),We=le>>>3,it=0;it>>0]=At)}return o=lf(o,0,x,le,h),hc(F),o};function Bc(o){if(L)return Jr(0,1,o);if(Jt=o,!(0<_i)){for(var h of gi)Dc(h);for(h of qs)Dc(h);qs=[],gi=[],os=[],Nn=!0}De(o,new zc(o))}function ih(o){if(L)return Jr(1,0,o);Lc(o)}var Lc=o=>{if(Jt=o,L)throw ih(o),"unwind";Bc(o)},qs=[],gi=[],ah=[],os={},oh=o=>{var h=o.Ab;delete os[h],qs.push(o),gi.splice(gi.indexOf(o),1),o.Ab=0,Zc(h)};function lh(){ah.forEach(o=>o())}var uh=o=>new Promise(h=>{o.onmessage=F=>{var le=(F=F.data).cmd;if(F.targetThread&&F.targetThread!=Za()){var We=os[F.targetThread];We?We.postMessage(F,F.transferList):tr(`Internal error! Worker sent a message "${le}" to target pthread ${F.targetThread}, but that thread no longer exists!`)}else le==="checkMailbox"?nc():le==="spawnThread"?sh(F):le==="cleanupThread"?oh(os[F.thread]):le==="killThread"?(F=F.thread,le=os[F],delete os[F],Dc(le),Zc(F),gi.splice(gi.indexOf(le),1),le.Ab=0):le==="cancelThread"?os[F.thread].postMessage({cmd:"cancel"}):le==="loaded"?(o.loaded=!0,h(o)):le==="alert"?alert(`Thread ${F.threadId}: ${F.text}`):F.target==="setimmediate"?o.postMessage(F):le==="callHandler"?l[F.handler](...F.args):le&&tr(`worker sent an unknown command ${le}`)},o.onerror=F=>{throw tr(`worker sent an error! ${F.filename}:${F.lineno}: ${F.message}`),F};var y,x=[];for(y of[])l.hasOwnProperty(y)&&x.push(y);o.postMessage({cmd:"load",handlers:x,wasmMemory:Mr,wasmModule:Ur})});function dh(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});qs.push(o)}var rc=o=>{for(;0{var o=Za(),h=u()[o+52>>>2>>>0];o=u()[o+56>>>2>>>0],df(h,h-o),hc(h)},Hf=(o,h)=>{_i=0,o=cf(o,h),0<_i?Jt=o:pc(o)};class Kf{constructor(h){this.Ib=h-24}}function Xf(o,h,y){var x=new Kf(o>>>=0);throw h>>>=0,y>>>=0,u()[x.Ib+16>>>2>>>0]=0,u()[x.Ib+4>>>2>>>0]=h,u()[x.Ib+8>>>2>>>0]=y,o}function ch(o,h,y,x){return L?Jr(2,1,o,h,y,x):ph(o,h,y,x)}function ph(o,h,y,x){if(o>>>=0,h>>>=0,y>>>=0,x>>>=0,W===void 0)return tr("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var F=[];return L&&F.length===0?ch(o,h,y,x):(o={dc:y,Ab:o,Pb:x,jc:F},L?(o.Lb="spawnThread",postMessage(o,F),0):sh(o))}var hh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,fh=(o,h,y)=>{var x=(h>>>=0)+y;for(y=h;o[y]&&!(y>=x);)++y;if(16(F=(240&F)==224?(15&F)<<12|le<<6|We:(7&F)<<18|le<<12|We<<6|63&o[h++])?x+=String.fromCharCode(F):(F-=65536,x+=String.fromCharCode(55296|F>>10,56320|1023&F))}}else x+=String.fromCharCode(F)}return x},gn=(o,h)=>(o>>>=0)?fh(n(),o,h):"";function mh(o,h,y){return L?Jr(3,1,o,h,y):0}function _h(o,h){if(L)return Jr(4,1,o,h)}var Rc=o=>{for(var h=0,y=0;y=x?h++:2047>=x?h+=2:55296<=x&&57343>=x?(h+=4,++y):h+=3}return h},gh=(o,h,y,x)=>{if(!(0>>=0;x=y+x-1;for(var le=0;le=We&&(We=65536+((1023&We)<<10)|1023&o.charCodeAt(++le)),127>=We){if(y>=x)break;h[y++>>>0]=We}else{if(2047>=We){if(y+1>=x)break;h[y++>>>0]=192|We>>6}else{if(65535>=We){if(y+2>=x)break;h[y++>>>0]=224|We>>12}else{if(y+3>=x)break;h[y++>>>0]=240|We>>18,h[y++>>>0]=128|We>>12&63}h[y++>>>0]=128|We>>6&63}h[y++>>>0]=128|63&We}}return h[y>>>0]=0,y-F},Ya=(o,h,y)=>gh(o,n(),h,y);function wh(o,h){if(L)return Jr(5,1,o,h)}function yh(o,h,y){if(L)return Jr(6,1,o,h,y)}function bh(o,h,y){return L?Jr(7,1,o,h,y):0}function Mh(o,h){if(L)return Jr(8,1,o,h)}function vh(o,h,y){if(L)return Jr(9,1,o,h,y)}function xh(o,h,y,x){if(L)return Jr(10,1,o,h,y,x)}function Th(o,h,y,x){if(L)return Jr(11,1,o,h,y,x)}function Eh(o,h,y,x){if(L)return Jr(12,1,o,h,y,x)}function Ch(o){if(L)return Jr(13,1,o)}function $h(o,h){if(L)return Jr(14,1,o,h)}function Sh(o,h,y){if(L)return Jr(15,1,o,h,y)}var kh,Hs,Qf=()=>{Qa("")},ls=o=>{for(var h="";n()[o>>>0];)h+=kh[n()[o++>>>0]];return h},Nc={},jc={};function bs(o,h,y={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(x,F,le={}){var We=F.name;if(!x)throw new Hs(`type "${We}" must have a positive integer typeid pointer`);if(jc.hasOwnProperty(x)){if(le.Rb)return;throw new Hs(`Cannot register type '${We}' twice`)}jc[x]=F,Nc.hasOwnProperty(x)&&(F=Nc[x],delete Nc[x],F.forEach(it=>it()))}(o,h,y)}var Ph=(o,h,y)=>{switch(h){case 1:return y?x=>r()[x>>>0]:x=>n()[x>>>0];case 2:return y?x=>s()[x>>>1>>>0]:x=>a()[x>>>1>>>0];case 4:return y?x=>i()[x>>>2>>>0]:x=>u()[x>>>2>>>0];case 8:return y?x=>fn[x>>>3]:x=>Ws[x>>>3];default:throw new TypeError(`invalid integer width (${h}): ${o}`)}};function Yf(o,h,y){y>>>=0,bs(o>>>=0,{name:h=ls(h>>>0),fromWireType:x=>x,toWireType:function(x,F){if(typeof F!="bigint"&&typeof F!="number")throw F=F===null?"null":(x=typeof F)=="object"||x==="array"||x==="function"?F.toString():""+F,new TypeError(`Cannot convert "${F}" to ${this.name}`);return typeof F=="number"&&(F=BigInt(F)),F},argPackAdvance:Ks,readValueFromPointer:Ph(h,y,h.indexOf("u")==-1),Db:null})}var Ks=8;function Jf(o,h,y,x){bs(o>>>=0,{name:h=ls(h>>>0),fromWireType:function(F){return!!F},toWireType:function(F,le){return le?y:x},argPackAdvance:Ks,readValueFromPointer:function(F){return this.fromWireType(n()[F>>>0])},Db:null})}var Vc=[],Ms=[];function Uc(o){9<(o>>>=0)&&--Ms[o+1]==0&&(Ms[o]=void 0,Vc.push(o))}var Gn=o=>{if(!o)throw new Hs("Cannot use deleted val. handle = "+o);return Ms[o]},qn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=Vc.pop()||Ms.length;return Ms[h]=o,Ms[h+1]=1,h}};function Wc(o){return this.fromWireType(u()[o>>>2>>>0])}var Zf={name:"emscripten::val",fromWireType:o=>{var h=Gn(o);return Uc(o),h},toWireType:(o,h)=>qn(h),argPackAdvance:Ks,readValueFromPointer:Wc,Db:null};function em(o){return bs(o>>>0,Zf)}var tm=(o,h)=>{switch(h){case 4:return function(y){return this.fromWireType(d()[y>>>2>>>0])};case 8:return function(y){return this.fromWireType(p()[y>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${o}`)}};function rm(o,h,y){y>>>=0,bs(o>>>=0,{name:h=ls(h>>>0),fromWireType:x=>x,toWireType:(x,F)=>F,argPackAdvance:Ks,readValueFromPointer:tm(h,y),Db:null})}function nm(o,h,y,x,F){if(o>>>=0,y>>>=0,h=ls(h>>>0),F===-1&&(F=4294967295),F=it=>it,x===0){var le=32-8*y;F=it=>it<>>le}var We=h.includes("unsigned")?function(it,At){return At>>>0}:function(it,At){return At};bs(o,{name:h,fromWireType:F,toWireType:We,argPackAdvance:Ks,readValueFromPointer:Ph(h,y,x!==0),Db:null})}function sm(o,h,y){function x(le){var We=u()[le>>>2>>>0];return le=u()[le+4>>>2>>>0],new F(r().buffer,le,We)}var F=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];bs(o>>>=0,{name:y=ls(y>>>0),fromWireType:x,argPackAdvance:Ks,readValueFromPointer:x},{Rb:!0})}function im(o,h){o>>>=0;var y=(h=ls(h>>>0))==="std::string";bs(o,{name:h,fromWireType:function(x){var F=u()[x>>>2>>>0],le=x+4;if(y)for(var We=le,it=0;it<=F;++it){var At=le+it;if(it==F||n()[At>>>0]==0){if(We=gn(We,At-We),Lt===void 0)var Lt=We;else Lt+="\0",Lt+=We;We=At+1}}else{for(Lt=Array(F),it=0;it>>0]);Lt=Lt.join("")}return ds(x),Lt},toWireType:function(x,F){F instanceof ArrayBuffer&&(F=new Uint8Array(F));var le=typeof F=="string";if(!(le||F instanceof Uint8Array||F instanceof Uint8ClampedArray||F instanceof Int8Array))throw new Hs("Cannot pass non-string to std::string");var We=y&&le?Rc(F):F.length,it=cc(4+We+1),At=it+4;if(u()[it>>>2>>>0]=We,y&&le)Ya(F,At,We+1);else if(le)for(le=0;le>>0]=Lt}else for(le=0;le>>0]=F[le];return x!==null&&x.push(ds,it),it},argPackAdvance:Ks,readValueFromPointer:Wc,Db(x){ds(x)}})}var Ah=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,am=(o,h)=>{for(var y=o>>1,x=y+h/2;!(y>=x)&&a()[y>>>0];)++y;if(32<(y<<=1)-o&&Ah)return Ah.decode(n().slice(o,y));for(y="",x=0;!(x>=h/2);++x){var F=s()[o+2*x>>>1>>>0];if(F==0)break;y+=String.fromCharCode(F)}return y},om=(o,h,y)=>{if(y??(y=2147483647),2>y)return 0;var x=h;y=(y-=2)<2*o.length?y/2:o.length;for(var F=0;F>>1>>>0]=le,h+=2}return s()[h>>>1>>>0]=0,h-x},lm=o=>2*o.length,um=(o,h)=>{for(var y=0,x="";!(y>=h/4);){var F=i()[o+4*y>>>2>>>0];if(F==0)break;++y,65536<=F?(F-=65536,x+=String.fromCharCode(55296|F>>10,56320|1023&F)):x+=String.fromCharCode(F)}return x},dm=(o,h,y)=>{if(h>>>=0,y??(y=2147483647),4>y)return 0;var x=h;y=x+y-4;for(var F=0;F=le&&(le=65536+((1023&le)<<10)|1023&o.charCodeAt(++F)),i()[h>>>2>>>0]=le,(h+=4)+4>y)break}return i()[h>>>2>>>0]=0,h-x},cm=o=>{for(var h=0,y=0;y=x&&++y,h+=4}return h};function pm(o,h,y){if(o>>>=0,h>>>=0,y=ls(y>>>=0),h===2)var x=am,F=om,le=lm,We=it=>a()[it>>>1>>>0];else h===4&&(x=um,F=dm,le=cm,We=it=>u()[it>>>2>>>0]);bs(o,{name:y,fromWireType:it=>{for(var At,Lt=u()[it>>>2>>>0],Yt=it+4,Pr=0;Pr<=Lt;++Pr){var Nr=it+4+Pr*h;Pr!=Lt&&We(Nr)!=0||(Yt=x(Yt,Nr-Yt),At===void 0?At=Yt:(At+="\0",At+=Yt),Yt=Nr+h)}return ds(it),At},toWireType:(it,At)=>{if(typeof At!="string")throw new Hs(`Cannot pass non-string to C++ string type ${y}`);var Lt=le(At),Yt=cc(4+Lt+h);return u()[Yt>>>2>>>0]=Lt/h,F(At,Yt+4,Lt+h),it!==null&&it.push(ds,Yt),Yt},argPackAdvance:Ks,readValueFromPointer:Wc,Db(it){ds(it)}})}function hm(o,h){bs(o>>>=0,{Sb:!0,name:h=ls(h>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var fm=()=>1;function mm(o){Jc(o>>>0,!$,1,!E,131072,!1),lh()}var Ih=o=>{if(!Nn)try{if(o(),!(0<_i))try{L?pc(Jt):Lc(Jt)}catch(h){h instanceof zc||h=="unwind"||De(1,h)}}catch(h){h instanceof zc||h=="unwind"||De(1,h)}};function Gc(o){o>>>=0,typeof Atomics.kc=="function"&&(Atomics.kc(i(),o>>>2,o).value.then(nc),o+=128,Atomics.store(i(),o>>>2,1))}var nc=()=>{var o=Za();o&&(Gc(o),Ih(uf))};function _m(o,h){(o>>>=0)==h>>>0?setTimeout(nc):L?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=os[o])&&o.postMessage({cmd:"checkMailbox"})}var qc=[];function gm(o,h,y,x,F){for(h>>>=0,x/=2,qc.length=x,y=F>>>0>>>3,F=0;F>>0];return(h?Oc[h]:a_[o])(...qc)}function wm(o){o>>>=0,L?postMessage({cmd:"cleanupThread",thread:o}):oh(os[o])}function ym(o){}var Hc=(o,h)=>{var y=jc[o];if(y===void 0)throw o=sf(o),y=ls(o),ds(o),new Hs(`${h} has unknown type ${y}`);return y},Fh=(o,h,y)=>{var x=[];return o=o.toWireType(x,y),x.length&&(u()[h>>>2>>>0]=qn(x)),o};function bm(o,h,y){return h>>>=0,y>>>=0,o=Gn(o>>>0),h=Hc(h,"emval::as"),Fh(h,y,o)}var sc=o=>{try{o()}catch(h){Qa(h)}},Xs=0,us=null,Oh=0,ic=[],zh={},Dh={},Mm=0,Kc=null,vm=[];function Bh(o){return function(h){if(!Nn){if(Xs===0){var y=!1,x=!1;h((F=0)=>{if(!Nn&&(Oh=F,y=!0,x)){Xs=2,sc(()=>ff(us)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),F=!1;try{var le=function(){var At=i()[us+8>>>2>>>0];return At=Kt[Dh[At]],--_i,At()}()}catch(At){le=At,F=!0}var We=!1;if(!us){var it=Kc;it&&(Kc=null,(F?it.reject:it.resolve)(le),We=!0)}if(F&&!We)throw le}}),x=!0,y||(Xs=1,us=function(){var F=cc(65548),le=F+12;u()[F>>>2>>>0]=le,u()[F+4>>>2>>>0]=le+65536,le=ic[0];var We=zh[le];return We===void 0&&(We=Mm++,zh[le]=We,Dh[We]=le),le=We,i()[F+8>>>2>>>0]=le,F}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),sc(()=>pf(us)))}else Xs===2?(Xs=0,sc(mf),ds(us),us=null,vm.forEach(Ih)):Qa(`invalid state: ${Xs}`);return Oh}}(h=>{o().then(h)})}function xm(o){return o>>>=0,Bh(()=>(o=Gn(o)).then(qn))}var ac=[];function Tm(o,h,y,x){return y>>>=0,x>>>=0,(o=ac[o>>>0])(null,h=Gn(h>>>0),y,x)}var Em={},oc=o=>{var h=Em[o];return h===void 0?ls(o):h};function Cm(o,h,y,x,F){return y>>>=0,x>>>=0,F>>>=0,(o=ac[o>>>0])(h=Gn(h>>>0),h[y=oc(y)],x,F)}var Lh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function $m(o){return(o>>>=0)==0?qn(Lh()):(o=oc(o),qn(Lh()[o]))}var Sm=o=>{var h=ac.length;return ac.push(o),h},km=(o,h)=>{for(var y=Array(o),x=0;x>>2>>>0],"parameter "+x);return y},Rh=(o,h)=>Object.defineProperty(h,"name",{value:o});function Pm(o,h,y){var x=(h=km(o,h>>>0)).shift();o--;var F=`return function (obj, func, destructorsRef, args) { `,le=0,We=[];y===0&&We.push("obj");for(var it=["retType"],At=[x],Lt=0;LtYt.name).join(", ")}) => ${x.name}>`,Sm(Rh(y,o))}function Am(o){return o=oc(o>>>0),qn(l[o])}function Im(o,h){return h>>>=0,o=Gn(o>>>0),h=Gn(h),qn(o[h])}function Fm(o){9<(o>>>=0)&&(Ms[o+1]+=1)}function Om(){return qn([])}function zm(o){o=Gn(o>>>0);for(var h=Array(o.length),y=0;y>>0))}function Bm(){return qn({})}function Lm(o){for(var h=Gn(o>>>=0);h.length;){var y=h.pop();h.pop()(y)}Uc(o)}function Rm(o,h,y){h>>>=0,y>>>=0,o=Gn(o>>>0),h=Gn(h),y=Gn(y),o[h]=y}function Nm(o,h){return h>>>=0,o=(o=Hc(o>>>0,"_emval_take_value")).readValueFromPointer(h),qn(o)}function jm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[h>>>2>>>0]=o.getUTCSeconds(),i()[h+4>>>2>>>0]=o.getUTCMinutes(),i()[h+8>>>2>>>0]=o.getUTCHours(),i()[h+12>>>2>>>0]=o.getUTCDate(),i()[h+16>>>2>>>0]=o.getUTCMonth(),i()[h+20>>>2>>>0]=o.getUTCFullYear()-1900,i()[h+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[h+28>>>2>>>0]=o}var Ja=o=>o%4==0&&(o%100!=0||o%400==0),Nh=[0,31,60,91,121,152,182,213,244,274,305,335],jh=[0,31,59,90,120,151,181,212,243,273,304,334];function Vm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[h>>>2>>>0]=o.getSeconds(),i()[h+4>>>2>>>0]=o.getMinutes(),i()[h+8>>>2>>>0]=o.getHours(),i()[h+12>>>2>>>0]=o.getDate(),i()[h+16>>>2>>>0]=o.getMonth(),i()[h+20>>>2>>>0]=o.getFullYear()-1900,i()[h+24>>>2>>>0]=o.getDay();var y=(Ja(o.getFullYear())?Nh:jh)[o.getMonth()]+o.getDate()-1|0;i()[h+28>>>2>>>0]=y,i()[h+36>>>2>>>0]=-60*o.getTimezoneOffset(),y=new Date(o.getFullYear(),6,1).getTimezoneOffset();var x=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(y!=x&&o.getTimezoneOffset()==Math.min(x,y)),i()[h+32>>>2>>>0]=o}function Um(o){o>>>=0;var h=new Date(i()[o+20>>>2>>>0]+1900,i()[o+16>>>2>>>0],i()[o+12>>>2>>>0],i()[o+8>>>2>>>0],i()[o+4>>>2>>>0],i()[o>>>2>>>0],0),y=i()[o+32>>>2>>>0],x=h.getTimezoneOffset(),F=new Date(h.getFullYear(),6,1).getTimezoneOffset(),le=new Date(h.getFullYear(),0,1).getTimezoneOffset(),We=Math.min(le,F);return 0>y?i()[o+32>>>2>>>0]=+(F!=le&&We==x):0>>2>>>0]=h.getDay(),y=(Ja(h.getFullYear())?Nh:jh)[h.getMonth()]+h.getDate()-1|0,i()[o+28>>>2>>>0]=y,i()[o>>>2>>>0]=h.getSeconds(),i()[o+4>>>2>>>0]=h.getMinutes(),i()[o+8>>>2>>>0]=h.getHours(),i()[o+12>>>2>>>0]=h.getDate(),i()[o+16>>>2>>>0]=h.getMonth(),i()[o+20>>>2>>>0]=h.getYear(),o=h.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Vh(o,h,y,x,F,le,We){return L?Jr(16,1,o,h,y,x,F,le,We):-52}function Uh(o,h,y,x,F,le){if(L)return Jr(17,1,o,h,y,x,F,le)}function Wm(o,h,y,x){o>>>=0,h>>>=0,y>>>=0,x>>>=0;var F=new Date().getFullYear(),le=new Date(F,0,1),We=new Date(F,6,1);F=le.getTimezoneOffset();var it=We.getTimezoneOffset(),At=Math.max(F,it);u()[o>>>2>>>0]=60*At,i()[h>>>2>>>0]=+(F!=it),le=(o=Lt=>Lt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(le),We=o(We),it{Xc.length=0;for(var y;y=n()[o++>>>0];){var x=y!=105;h+=(x&=y!=112)&&h%8?4:0,Xc.push(y==112?u()[h>>>2>>>0]:y==106?fn[h>>>3]:y==105?i()[h>>>2>>>0]:p()[h>>>3>>>0]),h+=x?8:4}return Xc};function Gm(o,h,y){return o>>>=0,h=Wh(h>>>0,y>>>0),Oc[o](...h)}function qm(o,h,y){return o>>>=0,h=Wh(h>>>0,y>>>0),Oc[o](...h)}var Hm=()=>{},Km=()=>Date.now();function Xm(o,h){return tr(gn(o>>>0,h>>>0))}var Gh,Qm=()=>{throw _i+=1,"unwind"};function Ym(){return 4294901760}Gh=()=>performance.timeOrigin+performance.now();var Jm=()=>navigator.hardwareConcurrency;function Zm(){return Qa("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function e_(o){o>>>=0;var h=n().length;if(o<=h||4294901760=y;y*=2){var x=h*(1+.2/y);x=Math.min(x,o+100663296);var F=Math;x=Math.max(o,x);e:{F=(F.min.call(F,4294901760,x+(65536-x%65536)%65536)-Mr.buffer.byteLength+65535)/65536;try{Mr.grow(F),bn();var le=1;break e}catch{}le=void 0}if(le)return!0}return!1}var lc=()=>(Qa("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),pd={},qh=o=>{o.forEach(h=>{lc()})};function t_(){var o=Error().stack.toString().split(` `);return o[0]=="Error"&&o.shift(),qh(o),pd.Ob=lc(),pd.bc=o,pd.Ob}function r_(o,h,y){if(o>>>=0,h>>>=0,pd.Ob==o)var x=pd.bc;else(x=Error().stack.toString().split(` `))[0]=="Error"&&x.shift(),qh(x);for(var F=3;x[F]&&lc()!=o;)++F;for(o=0;o>>2>>>0]=lc();return o}var Qc,Yc={},Hh=()=>{if(!Qc){var o,h={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:Ge};for(o in Yc)Yc[o]===void 0?delete h[o]:h[o]=Yc[o];var y=[];for(o in h)y.push(`${o}=${h[o]}`);Qc=y}return Qc};function Kh(o,h){if(L)return Jr(18,1,o,h);o>>>=0,h>>>=0;var y=0;return Hh().forEach((x,F)=>{var le=h+y;for(F=u()[o+4*F>>>2>>>0]=le,le=0;le>>0]=x.charCodeAt(le);r()[F>>>0]=0,y+=x.length+1}),0}function Xh(o,h){if(L)return Jr(19,1,o,h);o>>>=0,h>>>=0;var y=Hh();u()[o>>>2>>>0]=y.length;var x=0;return y.forEach(F=>x+=F.length+1),u()[h>>>2>>>0]=x,0}function Qh(o){return L?Jr(20,1,o):52}function Yh(o,h,y,x){return L?Jr(21,1,o,h,y,x):52}function Jh(o,h,y,x){return L?Jr(22,1,o,h,y,x):70}var n_=[null,[],[]];function Zh(o,h,y,x){if(L)return Jr(23,1,o,h,y,x);h>>>=0,y>>>=0,x>>>=0;for(var F=0,le=0;le>>2>>>0],it=u()[h+4>>>2>>>0];h+=8;for(var At=0;At>>0],Yt=n_[o];Lt===0||Lt===10?((o===1?fr:tr)(fh(Yt,0)),Yt.length=0):Yt.push(Lt)}F+=it}return u()[x>>>2>>>0]=F,0}var ef=[31,29,31,30,31,30,31,31,30,31,30,31],tf=[31,28,31,30,31,30,31,31,30,31,30,31],s_=(o,h)=>{r().set(o,h>>>0)};function rf(o,h,y,x){function F(Le,vr,Zr){for(Le=typeof Le=="number"?Le.toString():Le||"";Le.lengthgf?-1:0wi-Le.getDate())){Le.setDate(Le.getDate()+vr);break}vr-=wi-Le.getDate()+1,Le.setDate(1),11>Zr?Le.setMonth(Zr+1):(Le.setMonth(0),Le.setFullYear(Le.getFullYear()+1))}return Zr=new Date(Le.getFullYear()+1,0,4),vr=it(new Date(Le.getFullYear(),0,4)),Zr=it(Zr),0>=We(vr,Le)?0>=We(Zr,Le)?Le.getFullYear()+1:Le.getFullYear():Le.getFullYear()-1}o>>>=0,h>>>=0,y>>>=0,x>>>=0;var Lt=u()[x+40>>>2>>>0];for(var Yt in x={hc:i()[x>>>2>>>0],fc:i()[x+4>>>2>>>0],Gb:i()[x+8>>>2>>>0],Kb:i()[x+12>>>2>>>0],Hb:i()[x+16>>>2>>>0],Cb:i()[x+20>>>2>>>0],ub:i()[x+24>>>2>>>0],Bb:i()[x+28>>>2>>>0],oc:i()[x+32>>>2>>>0],ec:i()[x+36>>>2>>>0],ic:Lt?gn(Lt):""},y=gn(y),Lt={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})y=y.replace(new RegExp(Yt,"g"),Lt[Yt]);var Pr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Nr="January February March April May June July August September October November December".split(" ");for(Yt in Lt={"%a":Le=>Pr[Le.ub].substring(0,3),"%A":Le=>Pr[Le.ub],"%b":Le=>Nr[Le.Hb].substring(0,3),"%B":Le=>Nr[Le.Hb],"%C":Le=>le((Le.Cb+1900)/100|0,2),"%d":Le=>le(Le.Kb,2),"%e":Le=>F(Le.Kb,2," "),"%g":Le=>At(Le).toString().substring(2),"%G":At,"%H":Le=>le(Le.Gb,2),"%I":Le=>((Le=Le.Gb)==0?Le=12:12{for(var vr=0,Zr=0;Zr<=Le.Hb-1;vr+=(Ja(Le.Cb+1900)?ef:tf)[Zr++]);return le(Le.Kb+vr,3)},"%m":Le=>le(Le.Hb+1,2),"%M":Le=>le(Le.fc,2),"%n":()=>` `,"%p":Le=>0<=Le.Gb&&12>Le.Gb?"AM":"PM","%S":Le=>le(Le.hc,2),"%t":()=>" ","%u":Le=>Le.ub||7,"%U":Le=>le(Math.floor((Le.Bb+7-Le.ub)/7),2),"%V":Le=>{var vr=Math.floor((Le.Bb+7-(Le.ub+6)%7)/7);if(2>=(Le.ub+371-Le.Bb-2)%7&&vr++,vr)vr==53&&((Zr=(Le.ub+371-Le.Bb)%7)==4||Zr==3&&Ja(Le.Cb)||(vr=1));else{vr=52;var Zr=(Le.ub+7-Le.Bb-1)%7;(Zr==4||Zr==5&&Ja(Le.Cb%400-1))&&vr++}return le(vr,2)},"%w":Le=>Le.ub,"%W":Le=>le(Math.floor((Le.Bb+7-(Le.ub+6)%7)/7),2),"%y":Le=>(Le.Cb+1900).toString().substring(2),"%Y":Le=>Le.Cb+1900,"%z":Le=>{var vr=0<=(Le=Le.ec);return Le=Math.abs(Le)/60,(vr?"+":"-")+("0000"+(Le/60*100+Le%60)).slice(-4)},"%Z":Le=>Le.ic,"%%":()=>"%"},y=y.replace(/%%/g,"\0\0"),Lt)y.includes(Yt)&&(y=y.replace(new RegExp(Yt,"g"),Lt[Yt](x)));return Yt=function(Le){var vr=Array(Rc(Le)+1);return gh(Le,vr,0,vr.length),vr}(y=y.replace(/\0\0/g,"%")),Yt.length>h?0:(s_(Yt,o),Yt.length-1)}function i_(o,h,y,x){return rf(o>>>0,h>>>0,y>>>0,x>>>0)}L||function(){for(var o=l.numThreads-1;o--;)dh();cd.unshift(()=>{Wn++,function(h){L?h():Promise.all(qs.map(uh)).then(h)}(()=>tc())})}();for(var nf=Array(256),uc=0;256>uc;++uc)nf[uc]=String.fromCharCode(uc);kh=nf,Hs=l.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},l.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},Ms.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>Ms.length/2-5-Vc.length;var a_=[Bc,ih,ch,mh,_h,wh,yh,bh,Mh,vh,xh,Th,Eh,Ch,$h,Sh,Vh,Uh,Kh,Xh,Qh,Yh,Jh,Zh],Kt=function(){function o(y,x){return Kt=y.exports,Kt=function(){var F=Kt,le={};for(let[We,it]of Object.entries(F))le[We]=typeof it=="function"?(...At)=>{ic.push(We);try{return it(...At)}finally{Nn||(ic.pop(),us&&Xs===1&&ic.length===0&&(Xs=0,_i+=1,sc(hf),typeof Fibers<"u"&&Fibers.pc()))}}:it;return le}(),Kt=function(){var F=Kt,le=it=>At=>it(At)>>>0,We=it=>()=>it()>>>0;return(F=Object.assign({},F)).Ca=le(F.Ca),F.fb=We(F.fb),F.gb=le(F.gb),F.emscripten_main_runtime_thread_id=We(F.emscripten_main_runtime_thread_id),F.sb=le(F.sb),F.tb=We(F.tb),F}(),ah.push(Kt.ib),Mn.unshift(Kt.Ba),Ur=x,tc(),Kt}var h=nh();if(Wn++,l.instantiateWasm)try{return l.instantiateWasm(h,o)}catch(y){tr(`Module.instantiateWasm callback failed with error: ${y}`),g(y)}return Fc||(Fc=l.locateFile?Zp("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",pt):pt+"ort-wasm-simd-threaded.jsep.wasm":new URL(N("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),N.b).href),function(y,x){var F=Fc;return Dt||typeof WebAssembly.instantiateStreaming!="function"||Zp(F)||eh(F)||typeof fetch!="function"?rh(F,y,x):fetch(F,{credentials:"same-origin"}).then(le=>WebAssembly.instantiateStreaming(le,y).then(x,function(We){return tr(`wasm streaming compile failed: ${We}`),tr("falling back to ArrayBuffer instantiation"),rh(F,y,x)}))}(h,function(y){o(y.instance,y.module)}).catch(g),{}}(),sf=o=>(sf=Kt.Ca)(o),af=()=>(af=Kt.Da)();l._OrtInit=(o,h)=>(l._OrtInit=Kt.Ea)(o,h),l._OrtGetLastError=(o,h)=>(l._OrtGetLastError=Kt.Fa)(o,h),l._OrtCreateSessionOptions=(o,h,y,x,F,le,We,it,At,Lt)=>(l._OrtCreateSessionOptions=Kt.Ga)(o,h,y,x,F,le,We,it,At,Lt),l._OrtAppendExecutionProvider=(o,h)=>(l._OrtAppendExecutionProvider=Kt.Ha)(o,h),l._OrtAddFreeDimensionOverride=(o,h,y)=>(l._OrtAddFreeDimensionOverride=Kt.Ia)(o,h,y),l._OrtAddSessionConfigEntry=(o,h,y)=>(l._OrtAddSessionConfigEntry=Kt.Ja)(o,h,y),l._OrtReleaseSessionOptions=o=>(l._OrtReleaseSessionOptions=Kt.Ka)(o),l._OrtCreateSession=(o,h,y)=>(l._OrtCreateSession=Kt.La)(o,h,y),l._OrtReleaseSession=o=>(l._OrtReleaseSession=Kt.Ma)(o),l._OrtGetInputOutputCount=(o,h,y)=>(l._OrtGetInputOutputCount=Kt.Na)(o,h,y),l._OrtGetInputName=(o,h)=>(l._OrtGetInputName=Kt.Oa)(o,h),l._OrtGetOutputName=(o,h)=>(l._OrtGetOutputName=Kt.Pa)(o,h),l._OrtFree=o=>(l._OrtFree=Kt.Qa)(o),l._OrtCreateTensor=(o,h,y,x,F,le)=>(l._OrtCreateTensor=Kt.Ra)(o,h,y,x,F,le),l._OrtGetTensorData=(o,h,y,x,F)=>(l._OrtGetTensorData=Kt.Sa)(o,h,y,x,F),l._OrtReleaseTensor=o=>(l._OrtReleaseTensor=Kt.Ta)(o),l._OrtCreateRunOptions=(o,h,y,x)=>(l._OrtCreateRunOptions=Kt.Ua)(o,h,y,x),l._OrtAddRunConfigEntry=(o,h,y)=>(l._OrtAddRunConfigEntry=Kt.Va)(o,h,y),l._OrtReleaseRunOptions=o=>(l._OrtReleaseRunOptions=Kt.Wa)(o),l._OrtCreateBinding=o=>(l._OrtCreateBinding=Kt.Xa)(o),l._OrtBindInput=(o,h,y)=>(l._OrtBindInput=Kt.Ya)(o,h,y),l._OrtBindOutput=(o,h,y,x)=>(l._OrtBindOutput=Kt.Za)(o,h,y,x),l._OrtClearBoundOutputs=o=>(l._OrtClearBoundOutputs=Kt._a)(o),l._OrtReleaseBinding=o=>(l._OrtReleaseBinding=Kt.$a)(o),l._OrtRunWithBinding=(o,h,y,x,F)=>(l._OrtRunWithBinding=Kt.ab)(o,h,y,x,F),l._OrtRun=(o,h,y,x,F,le,We,it)=>(l._OrtRun=Kt.bb)(o,h,y,x,F,le,We,it),l._OrtEndProfiling=o=>(l._OrtEndProfiling=Kt.cb)(o),l._JsepOutput=(o,h,y)=>(l._JsepOutput=Kt.db)(o,h,y),l._JsepGetNodeName=o=>(l._JsepGetNodeName=Kt.eb)(o);var dc,Za=()=>(Za=Kt.fb)(),cc=l._malloc=o=>(cc=l._malloc=Kt.gb)(o),ds=l._free=o=>(ds=l._free=Kt.hb)(o),Jc=(o,h,y,x,F,le)=>(Jc=Kt.kb)(o,h,y,x,F,le),of=()=>(of=Kt.lb)(),lf=(o,h,y,x,F)=>(lf=Kt.mb)(o,h,y,x,F),Zc=o=>(Zc=Kt.nb)(o),pc=o=>(pc=Kt.ob)(o),uf=()=>(uf=Kt.pb)(),df=(o,h)=>(df=Kt.qb)(o,h),hc=o=>(hc=Kt.rb)(o),ep=o=>(ep=Kt.sb)(o),tp=()=>(tp=Kt.tb)(),cf=l.dynCall_ii=(o,h)=>(cf=l.dynCall_ii=Kt.vb)(o,h),pf=o=>(pf=Kt.wb)(o),hf=()=>(hf=Kt.xb)(),ff=o=>(ff=Kt.yb)(o),mf=()=>(mf=Kt.zb)();function _f(){0tp(),l.stackRestore=o=>hc(o),l.stackAlloc=o=>ep(o),l.UTF8ToString=gn,l.stringToUTF8=Ya,l.lengthBytesUTF8=Rc,Gs=function o(){dc||_f(),dc||(Gs=o)},_f(),M}),Pe=_e,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&_e()}),we,Je,gt,mt,Et,_t,Ft,Nt,Rt=j(()=>{var e,t;Ot(),we=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),Je=typeof location>"u"?void 0:location.origin,gt=(r,n)=>{try{let s=n??we;return(s?new URL(r,s):new URL(r)).origin===Je}catch{return!1}},mt=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Et=(Kr(),A(cr)).default,_t=async()=>{if(!we)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(gt(we))return[void 0,Et()];let r=await mt(we);return[r,Et(r)]},Ft=(rt(),A(at)).default,Nt=async(r,n,s)=>[void 0,Ft]}),Gt,Me,Ze,ot,Ht,gr,Lr,mr,yr=j(()=>{Rt(),Me=!1,Ze=!1,ot=!1,Ht=()=>{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}},gr=()=>{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}},Lr=async e=>{if(Me)return Promise.resolve();if(Ze)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ot)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ze=!0;let t=e.initTimeout,r=e.numThreads;if(!gr())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Ht();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,i=s==null?void 0:s.mjs,u=(i==null?void 0:i.href)??i,d=s==null?void 0:s.wasm,p=(d==null?void 0:d.href)??d,w=e.wasmBinary,[g,l]=await Nt(u,a,r>1),M=!1,E=[];if(t>0&&E.push(new Promise($=>{setTimeout(()=>{M=!0,$()},t)})),E.push(new Promise(($,L)=>{let W={numThreads:r};w?W.wasmBinary=w:(p||a)&&(W.locateFile=(z,ie)=>p??(a??ie)+z),l(W).then(z=>{Ze=!1,Me=!0,Gt=z,$(),g&&URL.revokeObjectURL(g)},z=>{Ze=!1,ot=!0,L(z)})})),await Promise.race(E),M)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},mr=()=>{if(Me&&Gt)return Gt;throw new Error("WebAssembly is not initialized yet.")}}),Tr,$n,Rr,Hn=j(()=>{yr(),Tr=(e,t)=>{let r=mr(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},$n=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let i=t?t+s:s;if(typeof a=="object")$n(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Rr=e=>{let t=mr(),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)}}}),jn,Ys=j(()=>{yr(),Hn(),jn=e=>{let t=mr(),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=Tr(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Rr("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&$n(e.extra,"",new WeakSet,(i,u)=>{let d=Tr(i,n),p=Tr(u,n);t._OrtAddRunConfigEntry(r,d,p)!==0&&Rr(`Can't set a run config entry: ${i} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),vs,xs,Ts,Es,Kn,Js=j(()=>{yr(),Hn(),vs=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}`)}},xs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ts=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)},Es=(e,t,r)=>{for(let n of t){let s=typeof n=="string"?n:n.name;switch(s){case"webnn":if(s="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let u=Tr("deviceType",r),d=Tr(i,r);mr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Rr(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(s="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let u=Tr("preferredLayout",r),d=Tr(i.preferredLayout,r);mr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Rr(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Tr(s,r);mr()._OrtAppendExecutionProvider(e,a)!==0&&Rr(`Can't append execution provider: ${s}.`)}},Kn=e=>{let t=mr(),r=0,n=[],s=e||{};Ts(s);try{let a=vs(s.graphOptimizationLevel??"all"),i=xs(s.executionMode??"sequential"),u=typeof s.logId=="string"?Tr(s.logId,n):0,d=s.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let p=s.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let w=typeof s.optimizedModelFilePath=="string"?Tr(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,u,d,p,w),r===0&&Rr("Can't create session options."),s.executionProviders&&Es(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 g=Tr("enableGraphCapture",n),l=Tr(s.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,g,l)!==0&&Rr(`Can't set a session config entry: 'enableGraphCapture' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[g,l]of Object.entries(s.freeDimensionOverrides)){if(typeof g!="string")throw new Error(`free dimension override name must be a string: ${g}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let M=Tr(g,n);t._OrtAddFreeDimensionOverride(r,M,l)!==0&&Rr(`Can't set a free dimension override: ${g} - ${l}.`)}return s.extra!==void 0&&$n(s.extra,"",new WeakSet,(g,l)=>{let M=Tr(g,n),E=Tr(l,n);t._OrtAddSessionConfigEntry(r,M,E)!==0&&Rr(`Can't set a session config entry: ${g} - ${l}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(i=>t._free(i)),a}}}),cs,Ln,Xn,Vn,rs,ps,hs,Xt=j(()=>{cs=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Ln=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Xn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},Vn=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}`)}},rs=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}`)}},ps=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",hs=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}`)}}}),ns,Cs=j(()=>{Ot(),ns=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let d=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let i=0;for(;;){let{done:u,value:d}=await s.read();if(u)break;let p=d.byteLength;new Uint8Array(a,i,p).set(d),i+=p}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),$s,fs,Ss,ks,ms,Ps,Wr,vn=j(()=>{Xt(),$s=["V","I","W","E","F"],fs=(e,t)=>{console.log(`[${$s[e]},${new Date().toISOString()}]${t}`)},ms=(e,t)=>{Ss=e,ks=t},Ps=(e,t)=>{let r=rs(e),n=rs(Ss);r>=n&&fs(r,typeof t=="function"?t():t)},Wr=(...e)=>{ks&&Ps(...e)}}),be,_=j(()=>{Xt(),be=(e,t)=>new(Vn(t))(e)}),P=j(()=>{}),K,ae,pe,Be,wt,xt,Mt,zt,er,zr=j(()=>{vn(),P(),K=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]]),ae=[],pe=e=>Math.ceil(e/16)*16,Be=e=>{for(let t=0;twt++,Mt=async(e,t,r,n)=>{let s=pe(r),a=e.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,s),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(u,0,r)),d}else return new Uint8Array(u.slice(0,r))}finally{a.destroy()}},zt=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 K)ae.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,s=t.byteLength,a=pe(s),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${s}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(r,n,s)),u.unmap();let p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(u,0,i.gpuData.buffer,0,a),Wr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(u)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=pe(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 Wr("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=xt();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,n),Wr("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),Wr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=Be(e),n,s=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||a){let u=(s?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let i={id:xt(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:e}),Wr("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 Wr("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 Mt(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=K.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))}},er=(...e)=>new zt(...e)}),ir,qt,pr=j(()=>{ir=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}},qt=e=>new ir(e)}),mn,ln,Oe,Sn,Er,sn,xn,Qt=j(()=>{mn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},ln=class{static calcShape(e,t,r=!1){let n=e.length,s=t.length;if(n===0)return t;if(s===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(r){if(n<2||s<2)return;let u=mn.calcMatMulShape([e[n-2],e[n-1]],[t[s-2],t[s-1]]);if(u===void 0)return;[i[a-2],i[a-1]]=u}for(let u=r?3:1;u<=a;u++){let d=n-u<0?1:e[n-u],p=s-u<0?1:t[s-u];if(d!==p&&d>1&&p>1)return;let w=Math.max(d,p);if(d&&p)i[a-u]=Math.max(d,p);else{if(w>1)return;i[a-u]=0}}return i}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let s=1;s<=r;s++)if(e[r-s]!==1&&e[r-s]!==t[n-s])return!1;return!0}},Oe=class fc{static size(t){return fc.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 fc.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 fc.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])}},Sn=class hd{static adjustPoolAttributes(t,r,n,s,a,i){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||i[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,s,a,i,u){if(u){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{Xt(),Qt(),Tn=64,pn=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Ar=(e,t=1)=>{let r=pn(e,t);return typeof r=="string"?r:r[0]},Cr=(e,t=1)=>{let r=pn(e,t);return typeof r=="string"?r:r[1]},It=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:Oe.computeStrides(r)})}),t},br=e=>e%4===0?4:e%2===0?2:1,Gr=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Xr=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,En=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,jt=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Zs=(e,t,r,n,s)=>{let a=typeof r=="number",i=a?r:r.length,u=[...new Array(i).keys()],d=i<2?"u32":i<=4?`vec${i}`:`array`,p=pn(t,s),w=typeof p=="string"?p:p[1],g=typeof p=="string"?p:p[0],l={indices:d,value:w,storage:g,tensor:t},M=Ve=>typeof Ve=="string"?Ve:`${Ve}u`,E={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},$=a?"uniforms.":"",L=`${$}${e}_shape`,W=`${$}${e}_strides`,z="";for(let Ve=0;Ve ${l.indices} { var indices: ${l.indices}; var current = offset; ${z} return indices; }`,J=Ve=>(E.offsetToIndices=!0,i<2?Ve:`o2i_${e}(${Ve})`),oe=[];if(i>=2)for(let Ve=i-1;Ve>=0;Ve--)oe.push(`${jt(W,Ve,i)} * (indices[${Ve}])`);let Ge=i<2?"":` fn i2o_${e}(indices: ${l.indices}) -> u32 { return ${oe.join("+")}; }`,De=Ve=>(E.indicesToOffset=!0,i<2?Ve:`i2o_${e}(${Ve})`),pt=(...Ve)=>i===0?"0u":`${l.indices}(${Ve.map(M).join(",")})`,Dt=(Ve,St)=>i<2?`${Ve}`:`${jt(Ve,St,i)}`,Vt=(Ve,St,rr)=>i<2?`${Ve}=${rr};`:`${jt(Ve,St,i)}=${rr};`,lr={},fr=(Ve,St)=>{E.broadcastedIndicesToOffset=!0;let rr=`${St.name}broadcastedIndicesTo${e}Offset`;if(rr in lr)return`${rr}(${Ve})`;let Vr=[];for(let nn=i-1;nn>=0;nn--){let fn=St.indicesGet("outputIndices",nn+St.rank-i);Vr.push(`${Dt(W,nn)} * (${fn} % ${Dt(L,nn)})`)}return lr[rr]=`fn ${rr}(outputIndices: ${St.type.indices}) -> u32 { return ${Vr.length>0?Vr.join("+"):"0u"}; }`,`${rr}(${Ve})`},tr=(Ve,St)=>(()=>{if(l.storage===l.value)return`${e}[${Ve}]=${St};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${Ve}]=vec2(u32(${St}), select(0u, 0xFFFFFFFFu, ${St} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${Ve}]=vec2(u32(${St}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${Ve}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${St}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),jr=Ve=>(()=>{if(l.storage===l.value)return`${e}[${Ve}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${Ve}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${Ve}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${Ve}] & 0xFFu), bool(${e}[${Ve}] & 0xFF00u), bool(${e}[${Ve}] & 0xFF0000u), bool(${e}[${Ve}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Qr=i<2?"":` fn get_${e}ByIndices(indices: ${l.indices}) -> ${w} { return ${jr(`i2o_${e}(indices)`)}; }`,Mr=i<2?"":(()=>{let Ve=u.map(rr=>`d${rr}: u32`).join(", "),St=u.map(rr=>`d${rr}`).join(", ");return` fn get_${e}(${Ve}) -> ${w} { return get_${e}ByIndices(${pt(St)}); }`})(),Ur=(...Ve)=>{if(Ve.length!==i)throw new Error(`indices length must be ${i}`);let St=Ve.map(M).join(",");return i===0?jr("0u"):i===1?jr(St[0]):(E.get=!0,E.getByIndices=!0,E.indicesToOffset=!0,`get_${e}(${St})`)},Jt=Ve=>i<2?jr(Ve):(E.getByIndices=!0,E.indicesToOffset=!0,`get_${e}ByIndices(${Ve})`),dr=i<2?"":` fn set_${e}ByIndices(indices: ${l.indices}, value: ${w}) { ${tr(`i2o_${e}(indices)`,"value")} }`,Or=i<2?"":(()=>{let Ve=u.map(rr=>`d${rr}: u32`).join(", "),St=u.map(rr=>`d${rr}`).join(", ");return` fn set_${e}(${Ve}, value: ${w}) { set_${e}ByIndices(${pt(St)}, value); }`})();return{impl:()=>{let Ve=[],St=!1;return E.offsetToIndices&&(Ve.push(ie),St=!0),E.indicesToOffset&&(Ve.push(Ge),St=!0),E.broadcastedIndicesToOffset&&(Object.values(lr).forEach(rr=>Ve.push(rr)),St=!0),E.set&&(Ve.push(Or),St=!0),E.setByIndices&&(Ve.push(dr),St=!0),E.get&&(Ve.push(Mr),St=!0),E.getByIndices&&(Ve.push(Qr),St=!0),!a&&St&&Ve.unshift(`const ${L} = ${l.indices}(${r.join(",")});`,`const ${W} = ${l.indices}(${Oe.computeStrides(r).join(",")});`),Ve.join(` `)},type:l,offsetToIndices:J,indicesToOffset:De,broadcastedIndicesToOffset:fr,indices:pt,indicesGet:Dt,indicesSet:Vt,set:(...Ve)=>{if(Ve.length!==i+1)throw new Error(`indices length must be ${i}`);let St=Ve[i];if(typeof St!="string")throw new Error("value must be string");let rr=Ve.slice(0,i).map(M).join(",");return i===0?tr("0u",St):i===1?tr(rr[0],St):(E.set=!0,E.setByIndices=!0,E.indicesToOffset=!0,`set_${e}(${rr}, ${St})`)},setByOffset:tr,setByIndices:(Ve,St)=>i<2?tr(Ve,St):(E.setByIndices=!0,E.indicesToOffset=!0,`set_${e}ByIndices(${Ve}, ${St});`),get:Ur,getByOffset:jr,getByIndices:Jt,usage:n,name:e,strides:W,shape:L,rank:i}},et=(e,t,r,n=1)=>Zs(e,t,r,"input",n),Ut=(e,t,r,n=1)=>Zs(e,t,r,"output",n),bi=(e,t,r,n=1)=>Zs(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=Tn){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=s?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,i=s?`let global_idx = global_id.x; let local_idx = local_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) fn main(${a}) { ${i} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",n=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${s}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},to=(e,t)=>new Mi(e,t),_s=(e,t)=>{let r=e.length,n=[];for(let s=0;s1&&i===1&&n.unshift(a)}return n}}),ro,vi,ss,no,md,In,_d,so,Qn=j(()=>{Xt(),Qt(),pr(),ar(),ro=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},vi=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,ss=(e,t)=>Oe.sortBasedOnPerm(e,vi(e.length,t)),no=(e,t,r,n)=>{let s=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`;for(let a=0;a{let r=[],n=[];for(let s=0;s{let r=e.dataType,n=e.dims.length,s=vi(n,t),a=ss(e.dims,s),{newShape:i,newPerm:u}=md(e.dims,s),d=Oe.areEqual(u,[2,3,1]),p=Oe.areEqual(u,[3,1,2]),w=i.length===2&&u[0]>u[1]||d||p,g=w?i:e.dims,l=a;w&&(g=d?[i[0],i[1]*i[2]]:p?[i[0]*i[1],i[2]]:i,l=[g[1],g[0]]);let M=et("a",r,g.length),E=Ut("output",r,l.length),$=16,L;return w?L=W=>` ${W.registerUniform("output_size","u32").declareVariables(M,E)} var tile : array, ${$}>; ${W.mainStart([$,$,1])} let stride = (uniforms.output_shape[1] - 1) / ${$} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${$}u + local_id.x; let input_row = workgroup_id_x * ${$}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${M.getByIndices(`${M.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${$}u + local_id.x; let output_row = workgroup_id_y * ${$}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${E.setByIndices(`${E.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`:L=W=>` ${W.registerUniform("output_size","u32").declareVariables(M,E)} ${no(s,n,M,E)} ${W.mainStart()} ${W.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${E.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${E.setByOffset("global_idx",M.getByIndices("aIndices"))} }`,{name:w?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let W=Oe.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:w?{x:Math.ceil(l[1]/$),y:Math.ceil(l[0]/$)}:{x:Math.ceil(W/64)},programUniforms:[{type:12,data:W},...It(g,l)]}},getShaderSource:L}},_d=(e,t)=>{ro(e.inputs),e.compute(In(e.inputs[0],t.perm))},so=e=>qt({perm:e.perm})}),io,ao,oo,lo,uo,xi,co,po,Ti,ho,Fn,Ei,fo,mo,Ci,_o,go,$i,wo,yo,Si,gd=j(()=>{Xt(),Qt(),ar(),Li(),Qn(),io={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"},ao={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"},oo={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},lo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},uo=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,s]},co=(e,t)=>{let r=e.length+t.length,n=[],s=0;for(let a=0;a{for(let r=0;r{let r=[];if(!po(e,t)){for(let n=0;nr.push(n))}return r},ho=(e,t,r,n,s,a,i)=>{let u=r[0].dims,d=Oe.size(a),p=Oe.size(i),w=et("_A",r[0].dataType,u),g=Ut("output",s,a),l=32,M=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:E=>` ${E.registerUniform("reduceSize","u32").declareVariables(w,g)} ${M} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${E.mainStart(l)} let outputIndex = global_idx / ${l}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${oo[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${l}) { let candidate = f32(${w.getByOffset("offset + k")}); bestValue = ${io[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${l}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${ao[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${g.setByOffset("outputIndex",`${n==="mean"?`${g.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${g.type.storage}(${lo[n]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:d},programUniforms:[{type:12,data:p}]})}},Fn=(e,t,r,n)=>{let s=e.inputs.length===1?r:Pi(e.inputs,r),a=s.axes;a.length===0&&!s.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((M,E)=>E));let i=Oe.normalizeAxes(a,e.inputs[0].dims.length),u=i,d=e.inputs[0],p=Ti(u,e.inputs[0].dims.length);p.length>0&&(d=e.compute(In(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],u=uo(u.length,d.dims.length));let[w,g]=xi(d.dims,u),l=w;s.keepDims&&(l=co(w,i)),e.compute(ho(t,{hint:s.cacheKey,inputDependencies:["type"]},[d],n,e.inputs[0].dataType,l,g),{inputs:[d]})},Ei=(e,t)=>{Fn(e,"ReduceMeanShared",t,"mean")},fo=(e,t)=>{Fn(e,"ReduceL1Shared",t,"l1")},mo=(e,t)=>{Fn(e,"ReduceL2Shared",t,"l2")},Ci=(e,t)=>{Fn(e,"ReduceLogSumExpShared",t,"logSumExp")},_o=(e,t)=>{Fn(e,"ReduceMaxShared",t,"max")},go=(e,t)=>{Fn(e,"ReduceMinShared",t,"min")},$i=(e,t)=>{Fn(e,"ReduceProdShared",t,"prod")},wo=(e,t)=>{Fn(e,"ReduceSumShared",t,"sum")},yo=(e,t)=>{Fn(e,"ReduceSumSquareShared",t,"sumSquare")},Si=(e,t)=>{Fn(e,"ReduceLogSumShared",t,"logSum")}}),On,ki,ei,Pi,kn,bo,Mo,Ai,vo,xo,Ii,To,Eo,Fi,Co,zn,Oi,$o,So,zi,ko,Po,Di,Ao,Io,Bi,Li=j(()=>{Xt(),Qt(),pr(),ar(),gd(),On=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},ki=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ei=(e,t,r,n,s,a,i=!1,u=!1)=>{let d=[],p=r[0].dims,w=p.length,g=Oe.normalizeAxes(s,w),l=!u&&g.length===0;p.forEach(($,L)=>{l||g.indexOf(L)>=0?i&&d.push(1):d.push($)});let M=d.length,E=Oe.size(d);return{name:e,shaderCache:t,getShaderSource:$=>{let L=[],W=et("_A",r[0].dataType,w),z=Ut("output",a,M),ie=n(W,z,g),J=ie[2];for(let oe=0,Ge=0;oe=0?(i&&Ge++,J=`for(var j${oe}: u32 = 0; j${oe} < ${p[oe]}; j${oe}++) { ${ie[2].includes("last_index")?`let last_index = j${oe};`:""} ${W.indicesSet("input_indices",oe,`j${oe}`)} ${J} }`):(L.push(`${W.indicesSet("input_indices",oe,z.indicesGet("output_indices",Ge))};`),Ge++);return` ${$.registerUniform("output_size","u32").declareVariables(W,z)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${W.type.indices}; let output_indices = ${z.offsetToIndices("global_idx")}; ${L.join(` `)} ${ie[0]} // init ops for reduce max/min ${ie[1]} ${J} ${ie[3]} ${ie.length===4?z.setByOffset("global_idx","value"):ie.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:d,dataType:a}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:[{type:12,data:E},...It(p,d)]})}},Pi=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),qt({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},kn=(e,t,r,n)=>{let s=e.inputs,a=s.length===1?r:Pi(s,r);e.compute(ei(t,{hint:a.cacheKey,inputDependencies:["rank"]},[s[0]],a.noopWithEmptyAxes&&a.axes.length===0?ki:n,a.axes,s[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},bo=(e,t)=>{On(e.inputs),kn(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Mo=(e,t)=>{On(e.inputs),kn(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Ai=(e,t)=>{On(e.inputs),kn(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);"])},vo=(e,t)=>{On(e.inputs),kn(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},xo=(e,t)=>{On(e.inputs),kn(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")});`,""]})},Ii=(e,t)=>{On(e.inputs),kn(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});`]})},To=(e,t)=>{On(e.inputs),kn(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")});`,""]})},Eo=(e,t)=>{On(e.inputs),kn(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Fi=(e,t)=>{On(e.inputs),kn(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Co=(e,t)=>{On(e.inputs),kn(e,"ReduceSumSquare",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},zn=(e,t,r)=>{if(t.length===0)return r;let n=1,s=1;for(let a=0;a1024},Oi=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ii(e,t):Ei(e,t)},$o=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Mo(e,t):fo(e,t)},So=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ai(e,t):mo(e,t)},zi=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vo(e,t):Ci(e,t)},ko=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xo(e,t):_o(e,t)},Po=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?To(e,t):go(e,t)},Di=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Eo(e,t):$i(e,t)},Ao=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fi(e,t):wo(e,t)},Io=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Co(e,t):yo(e,t)},Bi=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bo(e,t):Si(e,t)}}),Ri,Ni,Fo,ji,Oo=j(()=>{Xt(),pr(),Li(),Ri=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Ni=(e,t)=>{Ri(e.inputs);let r=(n,s,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",s.setByOffset("global_idx","best_index")]};e.compute(ei("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Fo=(e,t)=>{Ri(e.inputs);let r=(n,s,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",s.setByOffset("global_idx","best_index")]};e.compute(ei("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ji=e=>qt(e)}),zo,Do,Vi,Bo,As,Ui,Lo,Wi=j(()=>{Xt(),Qt(),P(),ar(),zo=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4],u=e[5];if(i&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],p=r.dims[1],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 g=s.dims[0]/3,l=g,M=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ie of t.qkvHiddenSizes)if(ie%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");g=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],M=t.qkvHiddenSizes[2]}let E=p;if(g!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==g+l+M)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let $=0;if(i){if(l!==M)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||($=i.dims[3])}let L=E+$,W=-1,z=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==t.numHeads||u.dims[2]!==p||u.dims[3]!==L)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:p,pastSequenceLength:$,kvSequenceLength:E,totalSequenceLength:L,maxSequenceLength:W,inputHiddenSize:w,hiddenSize:g,vHiddenSize:M,headSize:Math.floor(g/t.numHeads),vHeadSize:Math.floor(M/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:z,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Do=(e,t,r)=>{let n=br(r),s=64,a=r/n;a{let M=Ut("x",e.dataType,e.dims,n),E=Cr(e.dataType),$=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${l.registerUniforms($).declareVariables(M)} ${l.mainStart([s,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${s}) * uniforms.d_comp + local_offset; var thread_max_vector = ${p}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${p}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(n){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${n}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${s}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${p}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${p}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(n){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${n}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${s}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${M.type.value}(${E}(uniforms.d_inv)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${p}(x[offset + i]); x[offset + i] = ${M.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${d};${n}`,inputDependencies:w},getShaderSource:g,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:u})}},Vi=(e,t,r,n,s,a,i,u)=>{let d=u+a.kvSequenceLength,p=[a.batchSize,a.numHeads,a.sequenceLength,d],w=a.kvNumHeads===void 0&&e>1&&n,g=w?[a.batchSize,a.numHeads,d,a.headSize]:void 0,l=i.scale===0?1/Math.sqrt(a.headSize):i.scale,M=br(a.headSize),E=a.headSize/M,$=12,L={x:Math.ceil(d/$),y:Math.ceil(a.sequenceLength/$),z:a.batchSize*a.numHeads},W=[{type:12,data:a.sequenceLength},{type:12,data:E},{type:12,data:d},{type:12,data:a.numHeads},{type:1,data:l},{type:12,data:u},{type:12,data:a.kvSequenceLength}],z=w&&n&&Oe.size(n.dims)>0,ie=["type","type"];z&&ie.push("type"),s&&ie.push("type");let J=[{dims:p,dataType:t.dataType,gpuDataType:0}];w&&J.push({dims:g,dataType:t.dataType,gpuDataType:0});let oe=Ge=>{let De=et("q",t.dataType,t.dims,M),pt=et("key",r.dataType,r.dims,M),Dt=[De,pt];if(z){let jr=et("past_key",n.dataType,n.dims,M);Dt.push(jr)}s&&Dt.push(et("attention_bias",s.dataType,s.dims));let Vt=Ut("output",t.dataType,p),lr=[Vt];w&&lr.push(Ut("present_key",t.dataType,g,M));let fr=Cr(1,M),tr=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${$}u; var tileQ: array<${De.type.storage}, ${$*$}>; var tileK: array<${De.type.storage}, ${$*$}>; ${Ge.registerUniforms(tr).declareVariables(...Dt,...lr)} ${Ge.mainStart([$,$,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; ${z&&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 = ${fr}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${z&&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 += ${fr}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(M){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${M}`)}})()}; output[outputIdx] = ${Vt.type.value} (sum * uniforms.alpha) + ${s?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${s!==void 0};${n!==void 0};${e}`,inputDependencies:ie},getRunData:()=>({outputs:J,dispatchGroup:L,programUniforms:W}),getShaderSource:oe}},Bo=(e,t,r,n,s,a)=>{let i=a+s.kvSequenceLength,u=s.nReps?s.nReps:1,d=s.vHiddenSize*u,p=s.kvNumHeads==null&&e>1&&n,w=p?[s.batchSize,s.numHeads,i,s.headSize]:void 0,g=[s.batchSize,s.sequenceLength,d],l=12,M={x:Math.ceil(s.vHeadSize/l),y:Math.ceil(s.sequenceLength/l),z:s.batchSize*s.numHeads},E=[{type:12,data:s.sequenceLength},{type:12,data:i},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:d},{type:12,data:a},{type:12,data:s.kvSequenceLength}],$=p&&n&&Oe.size(n.dims)>0,L=["type","type"];$&&L.push("type");let W=[{dims:g,dataType:t.dataType,gpuDataType:0}];p&&W.push({dims:w,dataType:t.dataType,gpuDataType:0});let z=ie=>{let J=et("probs",t.dataType,t.dims),oe=et("v",r.dataType,r.dims),Ge=[J,oe];$&&Ge.push(et("past_value",n.dataType,n.dims));let De=[Ut("output",t.dataType,g)];p&&De.push(Ut("present_value",t.dataType,w));let pt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${l}u; var tileQ: array<${J.type.value}, ${l*l}>; var tileK: array<${J.type.value}, ${l*l}>; ${ie.registerUniforms(pt).declareVariables(...Ge,...De)} ${ie.mainStart([l,l,1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; ${$&&p?` let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; `:` let offsetB = headIdx * uniforms.N * uniforms.K + n; `} ${p?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} var value = ${J.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; ${$&&p?` if (w + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else { tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; } `:` tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; `} ${p?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:L},getRunData:()=>({outputs:W,dispatchGroup:M,programUniforms:E}),getShaderSource:z}},As=(e,t,r,n,s,a,i,u,d,p,w)=>{let g=Math.min(e.outputCount,1+(i?1:0)+(u?1:0)),l=p.kvNumHeads!==void 0||g>1?p.pastSequenceLength:0,M=l+p.kvSequenceLength,E=d&&Oe.size(d.dims)>0?d:void 0,$=[t,r];p.kvNumHeads===void 0&&g>1&&i&&Oe.size(i.dims)>0&&$.push(i),E&&$.push(E);let L=e.compute(Vi(g,t,r,i,E,p,w,l),{inputs:$,outputs:p.kvNumHeads===void 0&&g>1?[-1,1]:[-1]})[0];e.compute(Do(L,p.batchSize*p.numHeads*p.sequenceLength,M),{inputs:[L],outputs:[]});let W=[L,n];p.kvNumHeads===void 0&&g>1&&u&&Oe.size(u.dims)>0&&W.push(u),e.compute(Bo(g,L,n,u,p,l),{inputs:W,outputs:p.kvNumHeads===void 0&&g>1?[0,2]:[0]})},Ui=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,s=t.inputHiddenSize,a=t.headSize,i=12,u={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:s},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],w=g=>{let l=Ut("output_q",d[0].dataType,r),M=Ut("output_k",d[0].dataType,r),E=Ut("output_v",d[0].dataType,r),$=et("input",d[0].dataType,d[0].dims),L=et("weight",d[1].dataType,d[1].dims),W=et("bias",d[2].dataType,d[2].dims),z=$.type.storage,ie=[{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<${z}, ${i*i}>; var tileWeightQ: array<${z}, ${i*i}>; var tileWeightK: array<${z}, ${i*i}>; var tileWeightV: array<${z}, ${i*i}>; ${g.registerUniforms(ie).declareVariables($,L,W,l,M,E)} ${g.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 = ${z}(0); var valueK = ${z}(0); var valueV = ${z}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:p}),getShaderSource:w},{inputs:d,outputs:[-1,-1,-1]})},Lo=(e,t)=>{let r=zo(e.inputs,t),[n,s,a]=Ui(e,r);return As(e,n,s,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),Gi,Ro,No,qi,wd=j(()=>{bt(),Xt(),Qt(),pr(),ar(),Gi=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,s,a)=>{let i=s.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);s.forEach((u,d)=>{if(u!==n[d])throw new Error(`${a}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Ro=(e,t)=>{let{epsilon:r,spatial:n,format:s}=t,a=e[0].dims,i=n?br(a[a.length-1]):1,u=s==="NHWC"&&a.length>1?i:1,d=Oe.size(a)/i,p=n,w=p?a.length:a,g=et("x",e[0].dataType,e[0].dims,i),l=et("scale",e[1].dataType,e[1].dims,u),M=et("bias",e[2].dataType,e[2].dims,u),E=et("inputMean",e[3].dataType,e[3].dims,u),$=et("inputVar",e[4].dataType,e[4].dims,u),L=Ut("y",e[0].dataType,w,i),W=()=>{let ie="";if(n)ie=`let cOffset = ${a.length===1?"0u":s==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(s==="NCHW")ie=` ${L.indicesSet("outputIndices","0","0")} let cOffset = ${L.indicesToOffset("outputIndices")};`;else{ie=`var cIndices = ${l.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let J=1;J` const epsilon = ${r}; ${ie.registerUniform("outputSize","u32").declareVariables(g,l,M,E,$,L)} ${ie.mainStart()} ${ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${L.offsetToIndices(`global_idx * ${i}`)}; ${W()} let scale = ${l.getByOffset("cOffset")}; let bias = ${M.getByOffset("cOffset")}; let inputMean = ${E.getByOffset("cOffset")}; let inputVar = ${$.getByOffset("cOffset")}; let x = ${g.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${L.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:z,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p?[{type:12,data:d},...It(a)]:[{type:12,data:d}]})}},No=e=>qt(e),qi=(e,t)=>{let{inputs:r,outputCount:n}=e,s=No({...t,outputCount:n});if(k.webgpu.validateInputContent&&Gi(r,s),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ro(r,s))}}),jo,Vo,Uo,Wo=j(()=>{Qt(),ar(),jo=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")},Vo=e=>{let t=e[0].dims,r=e[0].dims[2],n=Oe.size(t)/4,s=e[0].dataType,a=et("input",s,t,4),i=et("bias",s,[r],4),u=et("residual",s,t,4),d=Ut("output",s,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:p=>` const channels = ${r}u / 4; ${p.declareVariables(a,i,u,d)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${a.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; ${d.setByOffset("global_idx","value")} }`}},Uo=e=>{jo(e.inputs),e.compute(Vo(e.inputs))}}),Go,$r,qo,Ho,Hi,Ko,Xo,Qo,Yo,Ki,Jo,Zo,Xi,el,tl,Qi,Is,rl,Fs,nl,sl,Yi,il,al,ti,ol,ll,Ji,Zi,ul,ea,dl,cl,pl,ta,ra,hl,na,ri,fl,ml,sa,_l,gl,ia,aa=j(()=>{Xt(),Qt(),pr(),ar(),Go=(e,t,r,n,s,a,i)=>{let u=Math.ceil(t/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let p=et("inputData",r,[u],4),w=Ut("outputData",n,[u],4),g=[{name:"vec_size",type:"u32"}];return i&&g.push(...i),` ${e.registerUniforms(g).declareVariables(p,w)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${p.getByOffset("global_idx")}; ${w.setByOffset("global_idx",d)} }`},$r=(e,t,r,n,s,a=e.dataType,i,u)=>{let d=[{type:12,data:Math.ceil(Oe.size(e.dims)/4)}];return i&&d.push(...i),{name:t,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:p=>Go(p,Oe.size(e.dims),e.dataType,a,r,n,u),getRunData:p=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Oe.size(p[0].dims)/64/4)},programUniforms:d})}},qo=e=>{e.compute($r(e.inputs[0],"Abs","abs"))},Ho=e=>{e.compute($r(e.inputs[0],"Acos","acos"))},Hi=e=>{e.compute($r(e.inputs[0],"Acosh","acosh"))},Ko=e=>{e.compute($r(e.inputs[0],"Asin","asin"))},Xo=e=>{e.compute($r(e.inputs[0],"Asinh","asinh"))},Qo=e=>{e.compute($r(e.inputs[0],"Atan","atan"))},Yo=e=>{e.compute($r(e.inputs[0],"Atanh","atanh"))},Ki=e=>qt(e),Jo=(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($r(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Zo=e=>{let t,r,n=e.length>=2&&e[1].data!==0,s=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=s?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=s?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return qt({min:t,max:r})},Xi=(e,t)=>{let r=t||Zo(e.inputs),n=Cr(e.inputs[0].dataType);e.compute($r(e.inputs[0],"Clip",s=>`clamp(${s}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},el=e=>{e.compute($r(e.inputs[0],"Ceil","ceil"))},tl=e=>{e.compute($r(e.inputs[0],"Cos","cos"))},Qi=e=>{e.compute($r(e.inputs[0],"Cosh","cosh"))},Is=e=>qt(e),rl=(e,t)=>{let r=Cr(e.inputs[0].dataType);e.compute($r(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))},Fs=(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)); }`,nl=e=>{let t=Cr(e.inputs[0].dataType);e.compute($r(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Fs(t)))},sl=e=>{e.compute($r(e.inputs[0],"Exp","exp"))},Yi=e=>{e.compute($r(e.inputs[0],"Floor","floor"))},il=e=>{let t=Cr(e.inputs[0].dataType);e.compute($r(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Fs(t)))},al=(e,t)=>{let r=Cr(e.inputs[0].dataType);e.compute($r(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))},ti=e=>{e.compute($r(e.inputs[0],"Not",t=>`!${t}`))},ol=e=>{e.compute($r(e.inputs[0],"Neg",t=>`-${t}`))},ll=e=>{e.compute($r(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Ji=e=>{let t=Cr(e.inputs[0].dataType);e.compute($r(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Zi=e=>{e.compute($r(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ul=e=>qt(e),ea=(e,t)=>{let r=Cr(e.inputs[0].dataType);e.compute($r(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))},dl=e=>{e.compute($r(e.inputs[0],"Sin","sin"))},cl=e=>{e.compute($r(e.inputs[0],"Sinh","sinh"))},pl=e=>{e.compute($r(e.inputs[0],"Sqrt","sqrt"))},ta=e=>{e.compute($r(e.inputs[0],"Tan","tan"))},ra=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,hl=e=>{e.compute($r(e.inputs[0],"Tanh",ra))},na=(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 ${ra("v")}; } `,ri=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,fl=e=>{let t=Cr(e.inputs[0].dataType);e.compute($r(e.inputs[0],"FastGelu",ri,na(t),void 0,e.inputs[0].dataType))},ml=(e,t)=>{let r=Cr(e.inputs[0].dataType);return e.compute($r(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},sa=e=>{e.compute($r(e.inputs[0],"Log","log"))},_l=(e,t)=>` const alpha = vec4<${e}>(${t}); const one = ${e}(1.0); const zero = ${e}(0.0); fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { let v = x *alpha; var x1 : vec4<${e}>; for (var i = 0; i < 4; i = i + 1) { if (v[i] >= zero) { x1[i] = one / (one + exp(-v[i])); } else { x1[i] = one - one / (one + exp(v[i])); } } return x * x1; } `,gl=e=>`quick_gelu_impl(${e})`,ia=(e,t)=>{let r=Cr(e.inputs[0].dataType);e.compute($r(e.inputs[0],"QuickGelu",gl,_l(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),wl,oa,yl,yd=j(()=>{Qt(),ar(),aa(),wl=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")},oa=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=et("input",e[0].dataType,e[0].dims,4),n=et("bias",e[0].dataType,[e[0].dims[2]],4),s=Ut("output",e[0].dataType,t,4),a=Oe.size(t)/4,i=Ar(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${u.declareVariables(r,n,s)} ${Fs(i)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${s.setByOffset("global_idx","valueLeft * geluRight")} }`}},yl=e=>{wl(e.inputs),e.compute(oa(e.inputs))}}),la,bl,Dn,ua,Ml,vl,xl,Tl,ni,El,Cl,$l,da,bd=j(()=>{Xt(),Qt(),ar(),la=(e,t,r,n,s,a,i,u,d,p,w,g)=>{let l,M;typeof u=="string"?l=M=(z,ie)=>`${u}((${z}),(${ie}))`:typeof u=="function"?l=M=u:(l=u.scalar,M=u.vector);let E=Ut("outputData",w,n.length,4),$=et("aData",d,t.length,4),L=et("bData",p,r.length,4),W;if(s)if(a){let z=Oe.size(t)===1,ie=Oe.size(r)===1,J=t.length>0&&t[t.length-1]%4===0,oe=r.length>0&&r[r.length-1]%4===0;z||ie?W=E.setByOffset("global_idx",M(z?`${$.type.value}(${$.getByOffset("0")}.x)`:$.getByOffset("global_idx"),ie?`${L.type.value}(${L.getByOffset("0")}.x)`:L.getByOffset("global_idx"))):W=` let outputIndices = ${E.offsetToIndices("global_idx * 4u")}; let offsetA = ${$.broadcastedIndicesToOffset("outputIndices",E)}; let offsetB = ${L.broadcastedIndicesToOffset("outputIndices",E)}; ${E.setByOffset("global_idx",M(i||J?$.getByOffset("offsetA / 4u"):`${$.type.value}(${$.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||oe?L.getByOffset("offsetB / 4u"):`${L.type.value}(${L.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else W=E.setByOffset("global_idx",M($.getByOffset("global_idx"),L.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let z=(ie,J,oe="")=>{let Ge=`aData[indexA${J}][componentA${J}]`,De=`bData[indexB${J}][componentB${J}]`;return` let outputIndices${J} = ${E.offsetToIndices(`global_idx * 4u + ${J}u`)}; let offsetA${J} = ${$.broadcastedIndicesToOffset(`outputIndices${J}`,E)}; let offsetB${J} = ${L.broadcastedIndicesToOffset(`outputIndices${J}`,E)}; let indexA${J} = offsetA${J} / 4u; let indexB${J} = offsetB${J} / 4u; let componentA${J} = offsetA${J} % 4u; let componentB${J} = offsetB${J} % 4u; ${ie}[${J}] = ${oe}(${l(Ge,De)}); `};w===9?W=` var data = vec4(0); ${z("data",0,"u32")} ${z("data",1,"u32")} ${z("data",2,"u32")} ${z("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:W=` ${z("outputData[global_idx]",0)} ${z("outputData[global_idx]",1)} ${z("outputData[global_idx]",2)} ${z("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables($,L,E)} ${g??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${W} }`},bl=(e,t,r,n,s,a,i=r.dataType)=>{let u=!Oe.areEqual(r.dims,n.dims),d=r.dims,p=Oe.size(r.dims),w=!1,g=!1,l=[u];if(u){let M=ln.calcShape(r.dims,n.dims,!1);if(!M)throw new Error("Can't perform binary op on the given tensors");d=M,p=Oe.size(d);let E=Oe.size(r.dims)===1,$=Oe.size(n.dims)===1,L=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,W=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;l.push(E),l.push($),l.push(L),l.push(W);let z=1;for(let ie=1;ieM.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:M=>la(M,r.dims,n.dims,d,w,u,g,s,r.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:[{type:12,data:Math.ceil(Oe.size(d)/4)},...It(r.dims,n.dims,d)]})}},Dn=(e,t,r,n,s,a)=>{e.compute(bl(t,s??"",e.inputs[0],e.inputs[1],r,n,a))},ua=e=>{Dn(e,"Add",(t,r)=>`${t}+${r}`)},Ml=e=>{Dn(e,"Div",(t,r)=>`${t}/${r}`)},vl=e=>{Dn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},xl=e=>{Dn(e,"Mul",(t,r)=>`${t}*${r}`)},Tl=e=>{let t=et("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Dn(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)); } `)},ni=e=>{Dn(e,"Sub",(t,r)=>`${t}-${r}`)},El=e=>{Dn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Cl=e=>{Dn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},$l=e=>{Dn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},da=e=>{Dn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),Sl,ca,kl,Pl,Al,Il,Fl=j(()=>{Xt(),Qt(),pr(),ar(),Sl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],s=n.dataType,a=n.dims.length;e.forEach((i,u)=>{if(u!==r){if(i.dataType!==s)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((d,p)=>{if(p!==t&&d!==n.dims[p])throw new Error("non concat dimensions must match")})}})},ca=(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; }`,kl=(e,t)=>{let r=e.length,n=[];for(let s=0;s{let s=Oe.size(r),a=new Array(e.length),i=new Array(e.length),u=0,d=[],p=[],w=[{type:12,data:s}];for(let $=0;$`uniforms.sizeInConcatAxis${$}`).join(","),E=$=>` ${(()=>{$.registerUniform("outputSize","u32");for(let L=0;L(${M}); ${l} -= sizeInConcatAxis[inputIndex - 1u]; } ${kl(i,g)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:w}),getShaderSource:E}},Al=(e,t)=>{let r=e.inputs,n=r[0].dims,s=Oe.normalizeAxis(t.axis,n.length);Sl(r,s);let a=n.slice();a[s]=r.reduce((u,d)=>u+(d.dims.length>s?d.dims[s]:0),0);let i=r.filter(u=>Oe.size(u.dims)>0);e.compute(Pl(i,s,a,r[0].dataType),{inputs:i})},Il=e=>qt({axis:e.axis})}),Yn,Jn,Un,pa,Zn=j(()=>{Xt(),Qt(),Yn=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Jn=(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})},Un=(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"})},pa=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)||[sn,xn];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}}}),un,ha,si=j(()=>{un=(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.`)}},ha=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),ii,Ol=j(()=>{ii=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)); } `}),zl,Dl,ai,fa,Bl,Os,Ll,ma,zs=j(()=>{Xt(),Qt(),ar(),Zn(),si(),zl=(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":""}); `,Dl=(e,t)=>e?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`,ai=(e,t,r="f32",n,s=!1,a=32,i=!1,u=32)=>{let d=t[1]*e[1],p=t[0]*e[0],w=s?d:a,g=s?a:d,l=w/t[0],M=a/t[1];if(!((s&&l===4&&e[1]===4||!s&&(l===3||l===4))&&w%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${l} must be 3 or 4. tileAWidth ${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/l}>, ${g}>; var mm_Bsub: array, ${p/e[0]}>, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${l}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${i?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${d}; let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${M}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${zl(s,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${M}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${l===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Dl(s,l)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},fa=(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];",Os=(e,t,r="f32",n,s=!1,a=32,i=!1,u=32,d=!1)=>{let p=e[1]*t[1],w=e[0]*t[0],g=s?p:a,l=s?a:p;if(!(l%t[1]===0&&g%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let M=l/t[1],E=g/t[0],$=a/t[1],L=d?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${p}; let globalColStart = i32(workgroupId.x) * ${w}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${g}; inputCol = inputCol + ${t[0]}) { ${fa(s,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${w}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${s?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${p}; let tileRowA = i32(localId.y) * ${M}; let tileColA = i32(localId.x) * ${E}; let tileRowB = i32(localId.y) * ${$}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${M}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${E}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${fa(s,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${$}; 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, ${l}>; var mm_Bsub : array, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${i?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; var acc : array, rowPerThread>; ${L} } `},Ll=(e,t,r,n,s,a=!1)=>{let[i,u,d]=s,[p,w,g,l]=n,M=_s(i,d),E=_s(u,d),$=Ar(n[0].type.tensor),L=()=>{let z=w.rank,ie=p.rank,J=`var aIndices: ${w.type.indices};`;for(let oe=z-2-1,Ge=ie-1;oe>=0;oe--,Ge--)J+=` aIndices[${oe}] = ${ie>1?`batchIndices[${Ge}]`:"batchIndices"};`;return M.forEach(oe=>{J+=` aIndices[${oe}] = 0;`}),J+=` aIndices[${z-2}] = u32(row); aIndices[${z-1}] = u32(colIn);`,J},W=()=>{let z=g.rank,ie=p.rank,J=`var bIndices: ${g.type.indices};`;for(let oe=z-2-1,Ge=ie-1;oe>=0;oe--,Ge--)J+=` bIndices[${oe}] = ${ie>1?`batchIndices[${Ge}]`:"batchIndices"};`;return E.forEach(oe=>{J+=` bIndices[${oe}] = 0;`}),J+=` bIndices[${z-2}] = u32(row); bIndices[${z-1}] = u32(colIn);`,J};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${un(e,$)} { var value = ${un(e,$)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${L()} value = ${w.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${un(e,$)} { var value = ${un(e,$)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${W()} value = ${g.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${un(e,$)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${a?"bias[colIn]":`${un(e,$)}(bias[row])`};`:""} ${r} ${l.setByIndices("vec3(coords)","value")} } } `},ma=(e,t,r,n,s=!1,a)=>{let i=e[0].dims,u=e[1].dims,d=i.slice(0,-2),p=u.slice(0,-2),w=n?n.slice(0,-2):r.slice(0,-2),g=Oe.size(w),l=i[i.length-2],M=i[i.length-1],E=u[u.length-1],$=M%4===0&&E%4===0,L=l<=8?[4,1,1]:[4,4,1],W=[8,8,1],z=[Math.ceil(E/W[0]/L[0]),Math.ceil(l/W[1]/L[1]),Math.ceil(g/W[2]/L[2])],ie=$?4:1,J=[...d,l,M/ie],oe=J.length,Ge=[...p,M,E/ie],De=Ge.length,pt=[g,l,E/ie],Dt=[{type:6,data:l},{type:6,data:E},{type:6,data:M}];Jn(t,Dt),Dt.push(...It(w,J,Ge));let Vt=["rank","rank"],lr=e.length>2;lr&&(Dt.push(...It(e[2].dims)),Vt.push("rank")),Dt.push(...It(pt));let fr=tr=>{let jr=w.length,Qr=bi("batchDims",e[0].dataType,jr,1),Mr=Ar(e[0].dataType),Ur=et("a",e[0].dataType,oe,ie),Jt=et("b",e[1].dataType,De,ie),dr=Ut("result",e[0].dataType,pt.length,ie),Or=[Ur,Jt];if(lr){let nn=s?ie:1;Or.push(et("bias",e[2].dataType,e[2].dims.length,nn))}let Ve=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Un(t,Ve);let St=Ar(dr.type.tensor),rr=Yn(t,dr.type.value,St),Vr=Ll(ie,lr,rr,[Qr,Ur,Jt,dr],[d,p,w],s);return` ${tr.registerUniforms(Ve).registerInternalVariables(Qr).declareVariables(...Or,dr)} ${Vr} ${$?ai(L,W,Mr,Qr):Os(L,W,Mr,Qr)} `};return{name:"MatMul",shaderCache:{hint:`${L};${t.activation};${$};${s}`,inputDependencies:Vt},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:z[0],y:z[1],z:z[2]},programUniforms:Dt}),getShaderSource:fr}}}),Rl,Nl,is=j(()=>{Xt(),vn(),ar(),Zn(),si(),Ol(),zs(),Rl=(e,t,r,n,s=!1,a,i=4,u=4,d=4,p="f32")=>{let w=Dt=>{switch(Dt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},g=Dt=>{switch(Dt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},l=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,M=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,E=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",$=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",L=e?"row":"col",W=e?"col":"row",z=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${L} / outWidth; let outCol = ${L} % outWidth; let WRow = ${W} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${W} / 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 = ${W} % inChannels; var resData = ${un(i,p)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${E} && xCol >= 0 && xCol < ${$}) { ${l} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${w(i)} } return resData;`,ie=e?t&&n?` let col = colIn * ${i}; ${z}`:` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${z} } return ${un(i,p)}(0.0);`:n&&r?` let col = colIn * ${i}; ${z}`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${z} } return ${un(i,p)}(0.0);`,J=`${g(u)}`,oe=un(d,p),Ge=un(e?i:u,p),De=un(e?u:i,p),pt=Yn(a,oe,p);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ge} { ${e?ie:J} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${De} { ${e?J:ie} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${oe}) { let col = colIn * ${d}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${M} ${ha(s)} ${pt} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Nl=(e,t,r,n,s,a,i,u,d)=>{let p=t.format==="NHWC",w=p?e[0].dims[3]:e[0].dims[1],g=r[0],l=p?r[2]:r[3],M=p?r[1]:r[2],E=p?r[3]:r[1],$=p&&(w%4===0||w%3===0)&&E%4===0,L=p?E:l*M,W=p?l*M:E,z=[8,8,1],ie=n<=8?[4,1,1]:[4,4,1],J=[Math.ceil(L/z[0]/ie[0]),Math.ceil(W/z[1]/ie[1]),Math.ceil(g/z[2]/ie[2])];Wr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${J}`);let oe=$?p&&w%4!==0?3:4:1,Ge=z[1]*ie[1],De=z[0]*ie[0],pt=Math.max(z[0]*oe,z[1]),Dt=n%Ge===0,Vt=s%De===0,lr=a%pt===0,fr=$?[oe,4,4]:[1,1,1],tr=[{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}];Jn(t,tr),tr.push(...It(e[0].dims,e[1].dims));let jr=["rank","rank"];i&&(tr.push(...It(e[2].dims)),jr.push("rank")),tr.push(...It(r));let Qr=Mr=>{let Ur=[{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}];Un(t,Ur);let Jt=$?4:1,dr=Ar(e[0].dataType),Or=` fn setOutputAtIndex(flatIndex : i32, value : ${$?`vec4<${dr}>`:dr}) { result[flatIndex] = ${$?`vec4<${dr}>`:dr}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${$?`vec4<${dr}>`:dr}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${$?"/ 4":""}, value); }`,Ve=et("x",e[0].dataType,e[0].dims.length,oe===3?1:oe),St=et("w",e[1].dataType,e[1].dims.length,Jt),rr=[Ve,St],Vr=Ut("result",e[0].dataType,r.length,Jt);if(i){let nn=et("bias",e[2].dataType,e[2].dims.length,Jt);rr.push(nn),Or+=` fn getBiasByOutputCoords(coords : vec4) -> ${$?`vec4<${dr}>`:dr} { return bias[coords.${p?"w":"y"}${$?"/ 4":""}]; }`}return` ${ii("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 }; ${Mr.registerUniforms(Ur).declareVariables(...rr,Vr)} ${Or} ${Rl(p,Dt,Vt,lr,i,t,fr[0],fr[1],fr[2],dr)} ${$?ai(ie,z,dr,void 0,!p,pt):Os(ie,z,dr,void 0,!p,pt,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${oe};${$};${Dt};${Vt};${lr};${Ge};${De};${pt}`,inputDependencies:jr},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:J[0],y:J[1],z:J[2]},programUniforms:tr}),getShaderSource:Qr}}}),jl,_a,Ds,Vl,oi,Ul,Wl,Gl,Md=j(()=>{Xt(),vn(),Qt(),ar(),Zn(),si(),jl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Ds=(e,t)=>t<=1?e:e+(e-1)*(t-1),Vl=(e,t,r,n=1)=>{let s=Ds(t,n);return Math.floor((e[0]*(r-1)-r+s)/2)},oi=(e,t,r,n,s)=>{s==null&&(s=Vl(e,t[0],n[0]));let a=[0,0,0,r];for(let i=0;i<3;i++)e[i]+2*s>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*s)/n[i]+1));return a},Ul=(e,t,r,n,s,a,i,u,d,p)=>{let w,g,l,M;if(e==="VALID"&&(e=0),typeof e=="number"){w={top:e,bottom:e,left:e,right:e,front:e,back:e};let E=oi([t,r,n,1],[u,d,p],1,[s,a,i],e);g=E[0],l=E[1],M=E[2]}else if(Array.isArray(e)){if(!e.every(($,L,W)=>$===W[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 E=oi([t,r,n,1],[u,d,p],1,[s,a,i],e[0]);g=E[0],l=E[1],M=E[2]}else if(e==="SAME_UPPER"){g=Math.ceil(t/s),l=Math.ceil(r/a),M=Math.ceil(n/i);let E=(g-1)*s+u-t,$=(l-1)*a+d-r,L=(M-1)*i+p-n,W=Math.floor(E/2),z=E-W,ie=Math.floor($/2),J=$-ie,oe=Math.floor(L/2),Ge=L-oe;w={top:ie,bottom:J,left:oe,right:Ge,front:W,back:z}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:w,outDepth:g,outHeight:l,outWidth:M}},Wl=(e,t,r,n,s,a=!1,i="channelsLast")=>{let u,d,p,w,g;if(i==="channelsLast")[u,d,p,w,g]=e;else if(i==="channelsFirst")[u,g,d,p,w]=e;else throw new Error(`Unknown dataFormat ${i}`);let[l,,M,E,$]=t,[L,W,z]=_a(r),[ie,J,oe]=_a(n),Ge=Ds(M,ie),De=Ds(E,J),pt=Ds($,oe),{padInfo:Dt,outDepth:Vt,outHeight:lr,outWidth:fr}=Ul(s,d,p,w,L,W,z,Ge,De,pt),tr=a?l*g:l,jr=[0,0,0,0,0];return i==="channelsFirst"?jr=[u,tr,Vt,lr,fr]:i==="channelsLast"&&(jr=[u,Vt,lr,fr,tr]),{batchSize:u,dataFormat:i,inDepth:d,inHeight:p,inWidth:w,inChannels:g,outDepth:Vt,outHeight:lr,outWidth:fr,outChannels:tr,padInfo:Dt,strideDepth:L,strideHeight:W,strideWidth:z,filterDepth:M,filterHeight:E,filterWidth:$,effectiveFilterDepth:Ge,effectiveFilterHeight:De,effectiveFilterWidth:pt,dilationDepth:ie,dilationHeight:J,dilationWidth:oe,inShape:e,outShape:jr,filterShape:t}},Gl=(e,t,r,n,s,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],d={x:r.map((L,W)=>W)},p=[Math.ceil(jl(d.x.map(L=>r[L]))/u[0]),1,1];Wr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);let w=1,g=Oe.size(r),l=[{type:12,data:g},{type:12,data:n},{type:12,data:s},{type:12,data:t.strides},{type:12,data:t.dilations}];Jn(t,l),l.push(...It(e[0].dims,e[1].dims));let M=["rank","rank"],E=e.length===3;E&&(l.push(...It(e[2].dims)),M.push("rank")),l.push(...It(r));let $=L=>{let W=[{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}];Un(t,W);let z=1,ie=Ar(e[0].dataType),J=et("x",e[0].dataType,e[0].dims.length,w),oe=et("W",e[1].dataType,e[1].dims.length,z),Ge=[J,oe],De=Ut("result",e[0].dataType,r.length,z),pt="";if(E){let lr=et("bias",e[2].dataType,e[2].dims.length,z);Ge.push(lr),pt+=` fn getBiasByOutputCoords(coords : array) -> ${ie} { return bias[${i?jt("coords",4,5):jt("coords",1,5)}]; }`}let Dt=un(w,ie),Vt=Yn(t,Dt,ie);return` ${pt} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${J.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")}; } ${L.registerUniforms(W).declareVariables(...Ge,De)} ${L.mainStart()} ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${De.offsetToIndices("global_idx")}; let batch = ${jt("coords",0,J.rank)}; let d2 = ${i?jt("coords",J.rank-1,J.rank):jt("coords",1,J.rank)}; let xFRCCorner = vec3(${i?jt("coords",1,J.rank):jt("coords",2,J.rank)}, ${i?jt("coords",2,J.rank):jt("coords",3,J.rank)}, ${i?jt("coords",3,J.rank):jt("coords",4,J.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${i?jt("uniforms.x_shape",1,J.rank):jt("uniforms.x_shape",2,J.rank)}; let xShapeZ = ${i?jt("uniforms.x_shape",2,J.rank):jt("uniforms.x_shape",3,J.rank)}; let xShapeW = ${i?jt("uniforms.x_shape",3,J.rank):jt("uniforms.x_shape",4,J.rank)}; let xShapeU = ${i?jt("uniforms.x_shape",4,J.rank):jt("uniforms.x_shape",1,J.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); } } } } ${E?"value = value + getBiasByOutputCoords(coords)":""}; ${Vt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${w};${E}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:l}),getShaderSource:$}}}),li,ql,vd=j(()=>{Xt(),Qt(),ar(),Zn(),li=(e,t,r,n)=>{let s=e.length>2,a=s?"value += b[output_channel];":"",i=e[0].dims,u=e[1].dims,d=t.format==="NHWC",p=d?r[3]:r[1],w=p/t.group,g=d&&w>=4?br(p):1,l=Oe.size(r)/g,M=[{type:12,data:l},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:w}];Jn(t,M),M.push(...It(i,[u[0],u[1],u[2],u[3]/g]));let E=s?["rank","rank","rank"]:["rank","rank"];M.push(...It([r[0],r[1],r[2],r[3]/g]));let $=L=>{let W=Ut("output",e[0].dataType,r.length,g),z=Ar(W.type.tensor),ie=Yn(t,W.type.value,z),J=et("x",e[0].dataType,i.length),oe=et("w",e[1].dataType,u.length,g),Ge=[J,oe];s&&Ge.push(et("b",e[2].dataType,e[2].dims,g));let De=[{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"}];Un(t,De);let pt=d?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { continue; } for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; let xVal = ${J.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${oe.get("wHeight","wWidth","wInChannel","output_channel")}; value += xVal * wVal; } } } `:` for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { continue; } let xVal = ${J.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${oe.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${L.registerUniforms(De).declareVariables(...Ge,W)} ${L.mainStart()} ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${W.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${d?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${g} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; var value: ${W.type.value} = ${W.type.value}(0); ${pt} ${a} ${ie} ${W.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${g}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:M}),getShaderSource:$}},ql=(e,t,r,n)=>{let s=e.length>2,a=br(r[3]),i=br(r[2]),u=Oe.size(r)/a/i,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],w=[r[0],r[1],r[2],r[3]/a],g=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Jn(t,g),g.push(...It(d,p,w));let l=(i-1)*t.strides[1]+p[1],M=E=>{let $=Ut("output",e[0].dataType,w.length,a),L=Ar($.type.tensor),W=Yn(t,$.type.value,L),z=et("x",e[0].dataType,d.length,a),ie=et("w",e[1].dataType,p.length,a),J=[z,ie];s&&J.push(et("b",e[2].dataType,e[2].dims,a));let oe=s?"value += b[output_channel];":"",Ge=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Un(t,Ge),` ${E.registerUniforms(Ge).declareVariables(...J,$)} ${E.mainStart()} ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${i}u; let col = (index1 % width1) * ${i}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${z.type.value}, ${l}>; var values: array<${$.type.value}, ${i}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${l}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${z.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${z.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) { let w_val = ${ie.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${i}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${i}u; i++) { var value = values[i]; ${oe} ${W} ${$.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${l};${p[0]};${p[1]}`,inputDependencies:s?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:g}),getShaderSource:M}}}),ga,Bs,Hl,Kl=j(()=>{Xt(),Qt(),zs(),ar(),Zn(),ga=(e,t,r,n,s=!1,a)=>{let i=e[0].dims,u=e[1].dims,d=i[i.length-2],p=u[u.length-1],w=i[i.length-1],g=br(p),l=br(w),M=br(d),E=Oe.size(r)/g/M,$=e.length>2,L=n?n.slice(0,-2):r.slice(0,-2),W=[Oe.size(L),d,p],z=[{type:12,data:E},{type:12,data:d},{type:12,data:p},{type:12,data:w}];Jn(t,z),z.push(...It(L,i,u)),$&&z.push(...It(e[2].dims)),z.push(...It(W));let ie=J=>{let oe=bi("batch_dims",e[0].dataType,L.length),Ge=et("a",e[0].dataType,i.length,l),De=et("b",e[1].dataType,u.length,g),pt=Ut("output",e[0].dataType,W.length,g),Dt=Ar(pt.type.tensor),Vt=Yn(t,pt.type.value,Dt),lr=[Ge,De],fr="";if($){let Or=s?g:1;lr.push(et("bias",e[2].dataType,e[2].dims.length,Or)),fr=`${s?`value += bias[col / ${Or}];`:`value += ${pt.type.value}(bias[row + i]);`}`}let tr=i.slice(0,-2),jr=u.slice(0,-2),Qr=_s(tr,L),Mr=_s(jr,L),Ur=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Un(t,Ur);let Jt=(Or,Ve)=>{let St=Or.rank,rr=Or.name;if(St===2)return`var ${rr}_indices = ${Or.type.indices}(0u, 0u);`;let Vr=oe.rank,nn=`var ${rr}_indices: ${Or.type.indices};`;for(let fn=St-2-1,Ws=Vr-1;fn>=0;fn--,Ws--)nn+=` ${rr}_indices[${fn}] = ${Vr>1?`batch_indices[${Ws}]`:"batch_indices"};`;return Ve.forEach(fn=>{nn+=` ${rr}_indices[${fn}] = 0;`}),nn+=`${rr}_indices[${St-2}] = 0u; ${rr}_indices[${St-1}] = 0u;`,nn},dr=()=>{let Or=`var a_data: ${Ge.type.value};`;for(let Ve=0;Ve; for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { ${dr()} } for (var i = 0u; i < ${M}u; i++) { var value = values[i]; ${fr} ${Vt} let cur_indices = ${pt.type.indices}(batch, row + i, col); let offset = ${pt.indicesToOffset("cur_indices")}; ${pt.setByOffset(`offset / ${g}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${g};${l};${M};${s}`,inputDependencies:$?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:z}),getShaderSource:ie}},Bs=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.")},Hl=e=>{Bs(e.inputs);let t=ln.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&n<8?e.compute(ga(e.inputs,{activation:""},t)):e.compute(ma(e.inputs,{activation:""},t))}}),Xl,ui,di,ci,wa,ya,xd,Ql,ba,Td=j(()=>{Qt(),is(),Md(),zs(),vd(),Zn(),Kl(),Qn(),Xl=(e,t,r,n,s,a)=>{let i=e[0],u=e.slice(a?1:2,a?3:4),d=u.length,p=t[0],w=t.slice(2).map((l,M)=>l+(l-1)*(r[M]-1)),g=u.map((l,M)=>l+n[M]+n[M+d]).map((l,M)=>Math.floor((l-w[M]+s[M])/s[M]));return g.splice(0,0,i),g.splice(a?3:1,0,p),g},ui=[2,3,1,0],di=(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")},ci=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=pa(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],s=e.dilations,a=e.group,i=e.kernel_shape,u=e.pads,d=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,pads:u,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},ya=(e,t,r,n)=>{let s=r.format==="NHWC",a=Xl(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,s);if(r.group!==1){let Ge=[t[0]];if(s){let De=e.kernelCustomData.wT??e.compute(In(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=De),Ge.push(De)}else Ge.push(t[1]);t.length===3&&Ge.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&s&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(ql(Ge,r,a,n),{inputs:Ge}):e.compute(li(Ge,r,a,n),{inputs:Ge});return}let i=t.length===3,u=t[0].dims[s?1:2],d=t[0].dims[s?2:3],p=t[0].dims[s?3:1],w=t[1].dims[2],g=t[1].dims[3],l=a[s?1:2],M=a[s?2:3],E=a[s?3:1],$=s&&w===u&&g===d&&r.pads[0]===0&&r.pads[1]===0;if($||w===1&&g===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let Ge=a[0],De,pt,Dt,Vt=[];if(s){let tr=e.kernelCustomData.wT??e.compute(In(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=tr),$){let jr=u*d*p;De=t[0].reshape([1,Ge,jr]),pt=tr.reshape([1,jr,E]),Dt=[1,Ge,E]}else De=t[0].reshape([Ge,u*d,p]),pt=tr.reshape([1,p,E]),Dt=[Ge,l*M,E];Vt.push(De),Vt.push(pt)}else De=t[0].reshape([Ge,p,u*d]),pt=t[1].reshape([1,E,p]),Dt=[Ge,E,l*M],Vt.push(pt),Vt.push(De);i&&Vt.push(t[2]);let lr=Dt[2],fr=Vt[0].dims[Vt[0].dims.length-1];lr<8&&fr<8?e.compute(ga(Vt,r,a,Dt,s,n),{inputs:Vt}):e.compute(ma(Vt,r,a,Dt,s,n),{inputs:Vt});return}let L=!0,W=e.kernelCustomData.wT??e.compute(In(t[1],ui),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W);let z=[t[0],W];i&&z.push(t[2]);let ie=s?l*M:E,J=s?E:l*M,oe=w*g*p;e.compute(Nl(z,r,a,ie,J,oe,i,L,n),{inputs:z})},xd=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=ci({...t,pads:s,strides:a,dilations:i,kernelShape:u},n);ya(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Ql=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",s=ci(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,i=Wl(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(Gl(t,s,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},ba=(e,t)=>{if(di(e.inputs,t),e.inputs[0].dims.length===3)xd(e,t);else if(e.inputs[0].dims.length===5)Ql(e,e.inputs,t);else{let r=ci(t,e.inputs);ya(e,e.inputs,r)}}}),gs,Yl,Ed=j(()=>{Xt(),vn(),ar(),Zn(),si(),Ol(),zs(),gs=(e,t=!1,r,n,s=4)=>{let a=L=>{switch(L){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 ${L} is not supported.`)}},i=e?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,u=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,d=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",p=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",w=e?"row":"col",g=e?"col":"row",l=` let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${w} / outWidth; let outCol = ${w} % outWidth; let WRow = ${g} / (uniforms.filter_dims[1] * inChannels); let WCol = ${g} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) { return ${n}(0.0); } if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) { return ${n}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${g} % inChannels; ${i} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,M=e?` let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${l} } return ${n}(0.0);`:` let col = colIn * ${s}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${l} } return ${n}(0.0);`,E=` 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); `,$=Yn(r,n);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?M:E} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?E:M} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${u} ${ha(t)} ${$} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; } }`},Yl=(e,t,r,n,s,a,i,u)=>{let d=t.format==="NHWC",p=d?e[0].dims[3]:e[0].dims[1],w=r[0],g=d?r[2]:r[3],l=d?r[1]:r[2],M=d?r[3]:r[1],E=d&&p%4===0&&p%3&&M%4===0,$=d?M:g*l,L=d?g*l:M,W=[8,8,1],z=n<=8?[4,1,1]:[4,4,1],ie=[Math.ceil($/W[0]/z[0]),Math.ceil(L/W[1]/z[1]),Math.ceil(w/W[2]/z[2])];Wr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ie}`);let J=E?4:1,oe=Math.max(W[0]*J,W[1]),Ge=E?4:1,De=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],pt=[De[0]+(t.dilations[0]<=1?0:(De[0]-1)*(t.dilations[0]-1)),De[1]+(t.dilations[1]<=1?0:(De[1]-1)*(t.dilations[1]-1))],Dt=[pt[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),pt[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Vt=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:De},{type:6,data:Dt}];Jn(t,Vt),Vt.push(...It(e[0].dims,e[1].dims));let lr=["rank","rank"];i&&(Vt.push(...It(e[2].dims)),lr.push("rank")),Vt.push(...It(r));let fr=tr=>{let jr=et("x",e[0].dataType,e[0].dims.length,Ge),Qr=et("w",e[1].dataType,e[1].dims.length,1),Mr=Ut("result",e[0].dataType,r.length,Ge),Ur=[jr,Qr],Jt="";if(i){let Ve=et("bias",e[2].dataType,e[2].dims.length,Ge);Ur.push(Ve),Jt+=` fn getBiasByOutputCoords(coords : vec4) -> ${Ve.type.value} { return bias[coords.${d?"w":"y"}${E?"/ 4":""}]; }`}let dr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:De.length},{name:"pads",type:"i32",length:Dt.length}];Un(t,dr);let Or=Ar(e[0].dataType,1);if(Or!=="f16"&&Or!=="f32")throw new Error(`elemType ${Or} is not supported.`);return` ${ii("uniforms.result_strides")} ${tr.registerUniforms(dr).declareVariables(...Ur,Mr)}; ${Jt} ${gs(d,i,t,jr.type.value,J)} ${E?ai(z,W,Or,void 0,!d,oe):Os(z,W,Or,void 0,!d,oe,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${z};${W};${E}`,inputDependencies:lr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ie[0],y:ie[1],z:ie[2]},programUniforms:Vt}),getShaderSource:fr}}}),Jl,Ma,Cd=j(()=>{Xt(),vn(),Qt(),ar(),Jl=(e,t,r,n,s,a=!1,i,u,d=!1)=>{let p=d?1:2,w=d?2:3,g=d?3:1,l=a?2:1,M=` fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${i}>`:i}) { result[flatIndex] = ${a?`vec4<${i}>`:i}(value); }`;n&&(M+=` fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${i}>`:i} { return bias[coords.${d?"w":"y"}${a?"/ 4":""}]; }`);let E=a?4:1,$=et("W",t[1].dataType,t[1].dims.length,E),L=et("Dy",t[0].dataType,t[0].dims.length,E),W=[L,$];n&&W.push(et("bias",t[2].dataType,[r[g]].length,E));let z=Ut("result",t[0].dataType,r.length,E),ie=`{ let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${s?"global_id.y":"workgroup_id.y"} * ${l}; let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${l}>; for (var i = 0; i < ${l}; i++) { dotProd[i] = vec4<${i}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${i}(dyCorner.x) + ${i}(wR)) / ${i}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${i}(dyCorner.y) + ${i}(wC)) / ${i}(uniforms.strides.y); let dyC2 = (${i}(dyCorner.y) + 1.0 + ${i}(wC)) / ${i}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${i}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${L.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 = ${L.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[${g}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${L.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 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${L.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${l}; i = i + 1) { let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${i}>(0.0)`}; ${z.set("batch","r","c + i","d1","value")}; } }`,J=` let outputIndices = ${z.offsetToIndices("global_idx")}; let batch = ${z.indicesGet("outputIndices",0)}; let d1 = ${z.indicesGet("outputIndices",g)}; let r = ${z.indicesGet("outputIndices",p)}; let c = ${z.indicesGet("outputIndices",w)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${i}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[${p}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[${w}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${d?L.get("batch","idyR","idyC","inputChannel"):L.get("batch","inputChannel","idyR","idyC")}; let wValue = ${$.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${n?"bias[d1]":`${i}(0.0)`}; ${z.setByOffset("global_idx","value")}; `;return` ${e.registerUniforms(u).declareVariables(...W,z)} ${M} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${a?ie:J}}`},Ma=(e,t,r)=>{let n=e.length>2,s=t.outputShape,a=Oe.size(s),i=[Math.ceil(a/64),1,1];Wr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let u=t.format==="NHWC",d=["rank","rank"],p=[t.strides[0],t.strides[1]],w=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],g=[t.dilations[0],t.dilations[1]],l=[w[0]+(t.dilations[0]<=1?0:(t.kernelShape[u?1:2]-1)*(t.dilations[0]-1)),w[1]+(t.dilations[1]<=1?0:(t.kernelShape[u?2:3]-1)*(t.dilations[1]-1))],M=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],E=!1,$=t.group,L=e[1].dims,W=L[0]/$,z=L[1],ie=[{type:12,data:a},{type:12,data:p},{type:12,data:w},{type:12,data:g},{type:12,data:l},{type:6,data:M},{type:12,data:W},{type:12,data:z},...It(e[0].dims,e[1].dims)];n&&(ie.push(...It(e[2].dims)),d.push("rank")),ie.push(...It(s));let J=i[1]===1&&i[2]===1,oe=Ge=>{let De=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:p.length},{name:"filter_dims",type:"u32",length:w.length},{name:"dilations",type:"u32",length:w.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:M.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],pt=Ar(e[0].dataType);return`${Jl(Ge,e,s,n,J,E,pt,De,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:r?r(s):s,dataType:e[0].dataType}],programUniforms:ie}),getShaderSource:oe}}}),pi,$d,Zl,va,eu,tu,ru,xa,nu,su,iu=j(()=>{Ed(),Cd(),Zn(),Qn(),pi=(e,t,r,n,s,a)=>(e-1)*t+r+(n-1)*s+1-a,$d=(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)},Zl=(e,t,r,n,s,a,i,u,d,p)=>{let w=e.length-2,g=p.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((g,l)=>g*l,1)===0){r.length=0;for(let g=2;gg+l,0)===0){let g=t[0].dims.length-2;d=new Array(g).fill(1)}let p=e.strides.slice();if(p.reduce((g,l)=>g+l,0)===0){let g=t[0].dims.length-2;p=new Array(g).fill(1)}Zl(u,r,d,e.autoPad,e.group,s,p,n,i,a);let w=Object.assign({},e);return Object.assign(w,{kernelShape:r,pads:s,outputPadding:i,outputShape:a,dilations:d,strides:p}),w},eu=e=>{let t=pa(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],s=e.dilations,a=e.group,i=e.kernelShape,u=e.pads,d=e.strides,p=e.wIsConst(),w=e.outputPadding,g=e.outputShape;return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,outputPadding:w,outputShape:g,pads:u,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},tu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==s))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,u)=>i+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,u)=>i+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,u)=>i+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,u)=>i+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},ru=[2,3,1,0],xa=(e,t,r)=>{let n=va(r,t),s=r.format==="NHWC",a=n.outputShape,i=a[s?3:1],u=t[0].dims[s?3:1];if(n.group!==1||i===1&&u===1){e.compute(Ma(t,n));return}let d=a[s?1:2],p=a[s?2:3],w=t[1].dims[2],g=t[1].dims[3],l=s?d*p:i,M=s?i:d*p,E=w*g*u,$=!0,L=e.kernelCustomData.wT??e.compute(In(t[1],ru),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=L);let W=[t[0],L],z=t.length===3;z&&(!s&&t[2].dims.length===1?W.push(t[2].reshape([t[2].dims[0],1,1])):W.push(t[2])),e.compute(Yl(W,n,a,l,M,E,z,$),{inputs:W})},nu=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=t.kernelShape;(s.length===0||s[0]===0)&&(s=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],i=[1].concat(i),a=[1].concat(a),s=[1].concat(s);let d=va({...t,pads:u,strides:i,dilations:a,kernelShape:s},n);e.compute(Ma(n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},su=(e,t)=>{tu(e.inputs,t),e.inputs[0].dims.length===3?nu(e,t):xa(e,e.inputs,t)}}),au,ou,Ta,Sd=j(()=>{Xt(),Qt(),pr(),ar(),au=(e,t,r,n)=>{let s=Oe.size(t),a=t.length,i=et("input",e,a),u=Ut("output",e,a),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=Oe.normalizeAxis(d,a),w=g=>{let l=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,M=jt("uniforms.input_shape","uniforms.axis",a),E=n.reverse?l+(n.exclusive?" + 1":""):"0",$=n.reverse?M:l+(n.exclusive?"":" + 1");return` ${g.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,u)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${u.offsetToIndices("global_idx")}; var sum = ${u.type.value}(0); let first : i32 = ${E}; let last : i32 = ${$}; for (var i : i32 = first; i < last; i++) { ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${i.getByIndices("inputIndices")}; } ${u.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},{type:12,data:p},...It(t,t)]}),getShaderSource:w}},ou=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,s=e.inputs[1];e.compute(au(n,r,s,t),{inputs:[0]})},Ta=e=>{let t=e.exclusive===1,r=e.reverse===1;return qt({exclusive:t,reverse:r})}}),lu,hi,uu,du,cu,kd=j(()=>{Xt(),Qt(),pr(),ar(),lu=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.")},hi=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let a=0;a{let r,n,s,a,i,u,d=t.format==="NHWC",p=t.blocksize,w=t.mode==="DCR";d?([r,n,s,a]=e.dims,i=w?[r,n,s,p,p,a/p**2]:[r,n,s,a/p**2,p,p],u=w?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,s,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=w?[r,p,p,a/p**2,n,s]:[r,a/p**2,p,p,n,s],u=w?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let g=e.reshape(i),l=g.dims.length,M=e.dataType,E=et("a",M,l),$=Ut("output",M,l),L=W=>` ${W.registerUniform("output_size","u32").declareVariables(E,$)} ${hi(u,l,E,$)} ${W.mainStart()} ${W.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${$.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${$.setByOffset("global_idx",E.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:W=>{let z=d?[r,n*p,s*p,a/p**2]:[r,a/p**2,n*p,s*p],ie=Oe.size(z),J=g.dims,oe=Oe.sortBasedOnPerm(J,u);return{outputs:[{dims:z,dataType:W[0].dataType}],dispatchGroup:{x:Math.ceil(ie/64)},programUniforms:[{type:12,data:ie},...It(J,oe)]}},getShaderSource:L}},du=(e,t)=>{lu(e.inputs),e.compute(uu(e.inputs[0],t))},cu=e=>qt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ls,as,pu,hu,fu,Ea,mu,Ca,$a,_u,gu,wu=j(()=>{Xt(),Qt(),pr(),ar(),Ls="[a-zA-Z]|\\.\\.\\.",as="("+Ls+")+",pu="^"+as+"$",hu="("+as+",)*"+as,fu="^"+hu+"$",Ea=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)}},mu=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(fu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let u=e[i].dims.slice();if(!a.match(RegExp(pu)))throw new Error("Invalid LHS term");let d=this.processTerm(a,!0,u,i);this.lhs.push(d)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(as)))throw new Error("Invalid RHS");(s=n.match(RegExp(Ls,"g")))==null||s.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let s=r.length,a=!1,i=[],u=0;if(!e.match(RegExp(pu))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(Ls,"g")),p=new Ea(n);return d==null||d.forEach((w,g)=>{if(w==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let l=s-d.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(u,u+l),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let M=0;Me+"_max",$a=(e,t,r,n)=>{let s=e.map(p=>p.length).map((p,w)=>et(`input${w}`,t,p)),a=Oe.size(n),i=Ut("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(p=>!r.rhs.symbolToIndices.has(p)),d=p=>{let w=[],g="var prod = 1.0;",l="var sum = 0.0;",M="sum += prod;",E=[],$=[],L=[],W=[],z=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((J,oe)=>{var Ge;if(r.rhs.symbolToIndices.has(oe)){let De=(Ge=r.rhs.symbolToIndices.get(oe))==null?void 0:Ge[0];De!==void 0&&r.lhs.forEach((pt,Dt)=>{if(J.inputIndices.includes(Dt)){let Vt=pt.symbolToIndices.get(oe);if(Vt===void 0)throw new Error("Invalid symbol error");Vt.forEach(lr=>{w.push(`${s[Dt].indicesSet(`input${Dt}Indices`,lr,i.indicesGet("outputIndices",De))}`)})}})}else r.lhs.forEach((De,pt)=>{if(J.inputIndices.includes(pt)){let Dt=De.symbolToIndices.get(oe);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(Vt=>{E.push(`${s[pt].indicesSet(`input${pt}Indices`,Vt,`${oe}`)}`)}),W.push(`prod *= ${s[pt].getByIndices(`input${pt}Indices`)};`)}}),$.push(`for(var ${oe}: u32 = 0; ${oe} < uniforms.${Ca(oe)}; ${oe}++) {`),L.push("}")});let ie=z?[...w,`let sum = ${s.map((J,oe)=>J.getByIndices(`input${oe}Indices`)).join(" * ")};`]:[...w,l,...$,...E,g,...W,M,...L];return` ${p.registerUniforms(u.map(J=>({name:`${Ca(J)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,i)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${i.offsetToIndices("global_idx")}; ${s.map((J,oe)=>`var input${oe}Indices: ${s[oe].type.indices};`).join(` `)} ${ie.join(` `)}; ${i.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=u.filter(g=>r.symbolToInfo.has(g)).map(g=>{var l;return{type:12,data:((l=r.symbolToInfo.get(g))==null?void 0:l.dimValue)||0}});p.push({type:12,data:a});let w=e.map((g,l)=>[...It(g)]).reduce((g,l)=>g.concat(l),p);return w.push(...It(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:w}},getShaderSource:d}},_u=(e,t)=>{let r=new mu(e.inputs,t.equation),n=r.outputDims,s=e.inputs.map((a,i)=>a.dims);e.compute($a(s,e.inputs[0].dataType,r,n))},gu=e=>{let t=e.equation.replace(/\s+/g,"");return qt({equation:t})}}),Pd,yu,Sa,ka,bu,Ad=j(()=>{Xt(),Qt(),ar(),Pd=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?yu(e,t):yu(t,e),ka=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Sa(t,r),s=e[0].dataType,a=s===9?4:1,i=Math.ceil(Oe.size(n)/a),u=p=>{let w=et("input",s,t.length,a),g=Ut("output",s,n.length,a),l;if(s===9){let M=(E,$,L="")=>` let outputIndices${$} = ${g.offsetToIndices(`outputOffset + ${$}u`)}; let offset${$} = ${w.broadcastedIndicesToOffset(`outputIndices${$}`,g)}; let index${$} = offset${$} / 4u; let component${$} = offset${$} % 4u; ${E}[${$}] = ${L}(${w.getByOffset(`index${$}`)}[component${$}]); `;l=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${M("data",0,"u32")} ${M("data",1,"u32")} ${M("data",2,"u32")} ${M("data",3,"u32")} ${g.setByOffset("global_idx","data")} }`}else l=` let outputIndices = ${g.offsetToIndices("global_idx")}; let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",g)}; ${g.setByOffset("global_idx",w.getByOffset("inputOffset"))} }`;return` ${p.registerUniform("vec_size","u32").declareVariables(w,g)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${l}`},d=[{type:12,data:i},...It(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d})}},bu=e=>{Pd(e.inputs),e.compute(ka(e.inputs),{inputs:[0]})}}),Pa,Mu,Id=j(()=>{Xt(),Qt(),ar(),aa(),Pa=e=>{let t=e[0].dataType,r=Oe.size(e[0].dims),n=Oe.size(e[1].dims),s=n%4===0,a=i=>{let u=et("x",t,[1],4),d=et("bias",t,[1],4),p=Ut("y",t,[1],4),w=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],g=M=>` let bias${M}_offset: u32 = (global_idx * 4 + ${M}) % uniforms.bias_size; let bias${M} = ${d.getByOffset(`bias${M}_offset / 4`)}[bias${M}_offset % 4];`,l=s?` let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${g(0)}${g(1)}${g(2)}${g(3)} let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(w).declareVariables(u,d,p)} ${na(Cr(t))} ${i.mainStart(Tn)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${u.getByOffset("global_idx")}; ${l} let x_in = x + bias; ${p.setByOffset("global_idx",ri("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Tn/4)}})}},Mu=e=>{e.inputs.length<2||Oe.size(e.inputs[1].dims)===0?fl(e):e.compute(Pa(e.inputs))}}),Aa,vu,xu,Ia,Fd=j(()=>{Xt(),Qt(),pr(),ar(),Aa=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},vu=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Oe.normalizeAxis(t.axis,s),i=r.slice(0);i.splice(a,1,...n);let u=r[a],d=e[0].dataType===9?4:1,p=Math.ceil(Oe.size(i)/d),w=[{type:12,data:p},{type:6,data:u},{type:12,data:a},...It(e[0].dims,e[1].dims,i)],g=l=>{let M=et("data",e[0].dataType,e[0].dims.length,d),E=et("inputIndices",e[1].dataType,e[1].dims.length),$=Ut("output",e[0].dataType,i.length,d),L=z=>{let ie=n.length,J=`var indicesIndices${z} = ${E.type.indices}(0);`;for(let oe=0;oe1?`indicesIndices${z}[${oe}]`:`indicesIndices${z}`} = ${i.length>1?`outputIndices${z}[uniforms.axis + ${oe}]`:`outputIndices${z}`};`;J+=` var idx${z} = ${E.getByIndices(`indicesIndices${z}`)}; if (idx${z} < 0) { idx${z} = idx${z} + uniforms.axisDimLimit; } var dataIndices${z} : ${M.type.indices}; `;for(let oe=0,Ge=0;oe1?`dataIndices${z}[${oe}]`:`dataIndices${z}`} = u32(idx${z});`,Ge+=ie):(J+=`${s>1?`dataIndices${z}[${oe}]`:`dataIndices${z}`} = ${i.length>1?`outputIndices${z}[${Ge}]`:`outputIndices${z}`};`,Ge++);return J},W;if(e[0].dataType===9){let z=(ie,J,oe="")=>` let outputIndices${J} = ${$.offsetToIndices(`outputOffset + ${J}u`)}; ${L(J)}; let offset${J} = ${M.indicesToOffset(`dataIndices${J}`)}; let index${J} = offset${J} / 4u; let component${J} = offset${J} % 4u; ${ie}[${J}] = ${oe}(${M.getByOffset(`index${J}`)}[component${J}]); `;W=` let outputOffset = global_idx * ${d}; var value = vec4(0); ${z("value",0,"u32")} ${z("value",1,"u32")} ${z("value",2,"u32")} ${z("value",3,"u32")} ${$.setByOffset("global_idx","value")} `}else W=` let outputIndices = ${$.offsetToIndices("global_idx")}; ${L("")}; let value = ${M.getByIndices("dataIndices")}; ${$.setByOffset("global_idx","value")}; `;return` ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(M,E,$)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${W} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:w}),getShaderSource:g}},xu=e=>qt({axis:e.axis}),Ia=(e,t)=>{let r=e.inputs;Aa(r),e.compute(vu(e.inputs,t))}}),Tu,Eu,Cu,Dr,wc=j(()=>{Xt(),Qt(),pr(),ar(),Tu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=Oe.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,s=e[0],a=e[2],i=e.length===4?e[3]:void 0;if(a.dims.length!==s.dims.length||!s.dims.map((u,d)=>d===r?Math.ceil(u/n)===a.dims[d]:u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==s.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==a.dims.length||!i.dims.map((u,d)=>u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Eu=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Oe.normalizeAxis(t.gatherAxis,s),i=Oe.normalizeAxis(t.quantizeAxis,s),u=r.slice(0);u.splice(a,1,...n);let d=Oe.size(u),p=e[2].dataType,w=e[0].dataType===22,g=[{type:12,data:d},{type:12,data:i},{type:12,data:a},{type:12,data:t.blockSize},...It(...e.map((M,E)=>M.dims),u)],l=M=>{let E=et("data",e[0].dataType,e[0].dims.length),$=et("inputIndices",e[1].dataType,e[1].dims.length),L=et("scales",e[2].dataType,e[2].dims.length),W=e.length>3?et("zeroPoint",e[3].dataType,e[3].dims.length):void 0,z=Ut("output",p,u.length),ie=[E,$,L];W&&ie.push(W);let J=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${M.registerUniforms(J).declareVariables(...ie,z)} ${M.mainStart()} let output_indices = ${z.offsetToIndices("global_idx")}; var indices_indices = ${$.type.indices}(0); ${n.length>1?` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${z.indicesGet("output_indices","uniforms.gather_axis + i")}; ${$.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${z.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${E.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${z.indicesGet("output_indices","i")}; ${E.indicesSet("data_indices","i","index")}; } var index_from_indices = ${$.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${r[a]}; } ${E.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { let index = ${z.indicesGet("output_indices",`i + ${n.length} - 1`)}; ${E.indicesSet("data_indices","i","index")}; } let data_offset = ${E.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${E.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${w?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${L.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${L.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${L.getByIndices("scale_indices")}; ${W?` let zero_point_indices = scale_indices; let zero_point_offset = ${W.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${W.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${w?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${Cr(p)}(quantized_data - zero_point) * scale; ${z.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((M,E)=>E!==1).map(M=>M.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(M,E)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:p}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:g}),getShaderSource:l}},Cu=(e,t)=>{let r=e.inputs;Tu(r,t),e.compute(Eu(e.inputs,t))},Dr=e=>qt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Od,zd,Fa,$u,Dd=j(()=>{Xt(),Qt(),pr(),ar(),Od=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.`)},zd=(e,t)=>{let r=e[0].dims,n=e[0].dataType,s=r.length,a=e[1].dims,i=e[1].dataType,u=Oe.normalizeAxis(t.axis,s),d=r[u],p=a.slice(0),w=Oe.size(p),g=et("input",n,s),l=et("indicesInput",i,a.length),M=Ut("output",n,p.length),E=[{type:12,data:w},{type:6,data:d},{type:12,data:u}];return E.push(...It(r,a,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:E}),getShaderSource:$=>` ${$.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,l,M)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${M.offsetToIndices("global_idx")}; var idx = ${l.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${g.type.indices}(outputIndices); ${g.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${g.getByIndices("inputIndices")}; ${M.setByOffset("global_idx","value")}; }`}},Fa=e=>qt({axis:e.axis}),$u=(e,t)=>{let r=e.inputs;Od(r),e.compute(zd(e.inputs,t))}}),Su,ku,Oa,za,Bd=j(()=>{Xt(),Qt(),ar(),Su=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")},ku=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[s,a,i]=Er.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[s,a];if(!u)throw new Error("Can't use gemm on the given tensors");let d=Oe.size(u),p=[{type:12,data:d},{type:12,data:s},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],w=["type","type"];e.length===3&&(p.push(...It(e[2].dims)),w.push("rank")),p.push(...It(u));let g=l=>{let M="";t.transA&&t.transB?M="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?M="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?M="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(M="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let E=t.alpha===1?"":"value *= uniforms.alpha;",$=et("a",e[0].dataType,e[0].dims),L=et("b",e[1].dataType,e[1].dims),W=$.type.value,z=null,ie=[$,L];e.length===3&&(z=et("c",e[2].dataType,e[2].dims.length),ie.push(z));let J=Ut("output",e[0].dataType,u.length);ie.push(J);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` ${l.registerUniforms(oe).declareVariables(...ie)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${W}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${M} } ${E} ${z!=null?`let cOffset = ${z.broadcastedIndicesToOffset("vec2(m, n)",J)}; value += ${W}(uniforms.beta) * ${z.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:g}},Oa=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}`}},za=(e,t)=>{Su(e.inputs),e.compute(ku(e.inputs,t))}}),_n,Da,Ld,Pu,Au,Rs,Iu,Fu=j(()=>{Xt(),Qt(),pr(),P(),Wi(),ar(),Qn(),_n=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Da=(e,t)=>{let r=e[0],n=_n(e,1),s=_n(e,2),a=_n(e,3),i=_n(e,4),u=_n(e,5),d=_n(e,6),p=_n(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let w=r.dims[0],g=r.dims[1],l=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],M=g,E=0,$=0,L=Math.floor(l/t.numHeads);if(d&&p&&Oe.size(d.dims)&&Oe.size(p.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==w||d.dims[1]!==t.numHeads||d.dims[3]!==L)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==w||p.dims[1]!==t.numHeads||p.dims[3]!==L)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');E=d.dims[2],$=d.dims[2]}else if(d&&Oe.size(d.dims)||p&&Oe.size(p.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let W;if(n&&Oe.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');W=2,M=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==L)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.');W=5,M=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==L)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');W=0,M=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');W=3}if(a&&Oe.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let z=E+M,ie=0;if(i&&Oe.size(i.dims)>0){ie=8;let De=i.dims;throw De.length===1?De[0]===w?ie=1:De[0]===3*w+2&&(ie=3):De.length===2&&De[0]===w&&De[1]===z&&(ie=5),ie===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let J=!1,oe=l;if(s&&Oe.size(s.dims)>0){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(M!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');oe=s.dims[2]}else{if(M!==s.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');oe=s.dims[1]*s.dims[3],J=!0}}let Ge=!1;if(i&&Oe.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(u&&Oe.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==w||u.dims[1]!==t.numHeads||u.dims[2]!==g||u.dims[3]!==z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:w,sequenceLength:g,pastSequenceLength:E,kvSequenceLength:M,totalSequenceLength:z,maxSequenceLength:$,inputHiddenSize:0,hiddenSize:l,vHiddenSize:oe,headSize:L,vHeadSize:Math.floor(oe/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ie,scale:t.scale,broadcastResPosBias:Ge,passPastInKv:J,qkvFormat:W}},Ld=e=>qt({...e}),Pu=qt({perm:[0,2,1,3]}),Au=(e,t,r,n,s,a,i)=>{let u=[n,s,a],d=Oe.size(u),p=[{type:12,data:d},{type:12,data:i},{type:12,data:a}],w=g=>{let l=Ut("qkv_with_bias",t.dataType,u),M=et("qkv",t.dataType,u),E=et("bias",r.dataType,u),$=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${g.registerUniforms($).declareVariables(M,E,l)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:w},{inputs:[t,r],outputs:[-1]})[0]},Rs=(e,t,r,n,s,a,i,u)=>{let d=a;if(i&&Oe.size(i.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Au(e,a,i,t,n,r*s,u),d=d.reshape([t,n,r,s]),e.compute(In(d,Pu.perm),{inputs:[d],outputs:[-1]})[0]}else return a.dims.length===3&&(d=a.reshape([t,n,r,s])),e.compute(In(d,Pu.perm),{inputs:[d],outputs:[-1]})[0]},Iu=(e,t)=>{let r=Da(e.inputs,t),n=e.inputs[0],s=_n(e.inputs,1),a=_n(e.inputs,2),i=_n(e.inputs,3),u=_n(e.inputs,4),d=_n(e.inputs,5),p=_n(e.inputs,6),w=_n(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 g=s&&a&&s.dims.length===4&&a.dims.length===4,l=Rs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(g)return As(e,l,s,a,u,void 0,p,w,d,r,t);if(!s||!a)throw new Error("key and value must be provided");let M=Rs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,s,i,r.hiddenSize),E=Rs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,i,2*r.hiddenSize);As(e,l,M,E,u,void 0,p,w,d,r,t)}}),Ba,Ou,zu,La,Du,Bu=j(()=>{Xt(),Qt(),ar(),Ba=e=>Array.from(e.getBigInt64Array(),Number),Ou=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(Ba(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")},zu=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Ba(e[1]),s=zu(r,n),a=Oe.size(s),i=e[0].dataType,u=et("input",i,r.length),d=Ut("output",i,s.length),p=w=>` const inputShape = ${u.indices(...r)}; ${w.registerUniform("output_size","u32").declareVariables(u,d)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${d.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; for (var i = 0; i < ${r.length}; i++) { let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i; ${u.indicesSet("input_indices","i","input_dim_value")} } ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...It(e[0].dims,s)]}),getShaderSource:p}},Du=e=>{Ou(e.inputs),e.compute(La(e.inputs),{inputs:[0]})}}),Lu,Ra,Ru,Nu,Na,ju,Rd=j(()=>{Xt(),Qt(),pr(),Wi(),ar(),Fu(),Bu(),Qn(),Lu=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,d=r.dims[0],p=r.dims[1],w=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],g=p,l=0,M=0,E=Math.floor(w/t.numHeads),$=a&&a.dims.length!==0,L=i&&i.dims.length!==0,W=!0;if($&&L){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=a.dims[1],M=a.dims[1]}else if($||L)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let z;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"');z=2,g=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==E)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.');z=5,g=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==E)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');z=0,g=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');z=3}let ie=0,J=!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(g!==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(g!==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],J=!0}}let Ge=l+g;return{batchSize:d,sequenceLength:p,pastSequenceLength:l,kvSequenceLength:g,totalSequenceLength:Ge,maxSequenceLength:M,inputHiddenSize:0,hiddenSize:w,vHiddenSize:oe,headSize:E,vHeadSize:Math.floor(oe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:ie,scale:t.scale,broadcastResPosBias:!1,passPastInKv:J,qkvFormat:z,isPastkvBSNH:W}},Ra=(e,t,r,n)=>{let s=[n.batchSize,n.totalSequenceLength,n.kvNumHeads,n.headSize],a=4,i=Oe.size(s)/a,u=n.totalSequenceLength,d=Ut("present_kv",r,s.length,a),p=et("new_kv",e.dataType,e.dims.length,a),w=t?et("past_kv",t.dataType,t.dims.length,a):void 0,g=Math.ceil(n.headSize/a),l={x:u,y:e.dims[0],z:1},M=t?["rank","rank"]:["rank"],E=[{type:12,data:i},{type:12,data:n.pastSequenceLength},{type:12,data:n.kvSequenceLength},{type:12,data:n.totalSequenceLength}],$=[p];w?(E.push(...It(e.dims),...It(t.dims),...It(s)),$.push(w)):E.push(...It(e.dims),...It(s));let L=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],W=` 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];`,z=` 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];`,ie=t?`if (s < past_seqlen) { ${W} } else if (s < past_seqlen + uniforms.new_seqlen) { ${z} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${z} }`,J=oe=>` ${oe.registerUniforms(L).declareVariables(...$,d)} ${oe.mainStart([g,n.kvNumHeads,1])} ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${d.offsetToIndices("global_idx")}; let h = local_id.x; let n = local_id.y; let s = workgroup_id.x; let b = workgroup_id.y; let num_heads = ${n.kvNumHeads}u; let H = ${g}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; ${ie} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${n.kvNumHeads}${g}${!!t}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:l,programUniforms:E}),getShaderSource:J}},Ru=e=>qt({...e}),Nu=qt({perm:[0,2,1,3]}),Na=(e,t,r,n,s)=>{let a=t,i=n.kvNumHeads,u=n.nReps;return t.dims.length===3&&n.kvSequenceLength!==0&&(a=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize])),r?a=e.compute(Ra(a,r,a.dataType,n),{inputs:[a,r],outputs:[n.isPastkvBSNH?s:-1]})[0]:a=e.compute(Ra(a,void 0,a.dataType,n),{inputs:[a],outputs:[n.isPastkvBSNH?s:-1]})[0],u!==1&&(a=e.compute(La([a],[1,1,1,u]),{inputs:[a],outputs:[-1]})[0],a=a.reshape([n.batchSize,n.totalSequenceLength,i*u,n.headSize])),e.compute(In(a,Nu.perm),{inputs:[a],outputs:[-1]})[0]},ju=(e,t)=>{var d;let r=Lu(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((d=e.inputs[1])==null?void 0:d.dims.length)===5)throw new Error("Packed KV is not implemented");let n=Rs(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=Na(e,e.inputs[1],s,r,1),u=Na(e,e.inputs[2],a,r,2);As(e,n,i,u,void 0,void 0,void 0,void 0,void 0,r,t)}}),Vu,ja,Uu,Wu,Nd=j(()=>{Xt(),Qt(),Qn(),ar(),Vu=(e,t,r,n,s,a,i,u)=>{let d=br(a),p=d===1?"f32":`vec${d}f`,w=d===1?"vec2f":`mat2x${d}f`,g=s*i,l=[s,i,a/d],M=[s,i,2],E=["rank","type","type"],$=[];$.push(...It(l,M));let L=W=>{let z=et("x",t.dataType,3,d),ie=et("scale",r.dataType,r.dims),J=et("bias",n.dataType,n.dims),oe=Ut("output",1,3,2),Ge=[z,ie,J,oe],De=64;return` var workgroup_shared : array<${w}, ${De}>; const workgroup_size = ${De}u; ${W.declareVariables(...Ge)} ${W.mainStart(De)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${p}(0); var squared_sum = ${p}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${p}(${z.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${w}(sum, squared_sum); workgroupBarrier(); for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { if (local_idx < currSize) { workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; } workgroupBarrier(); } if (local_idx == 0) { let sum_final = ${En("workgroup_shared[0][0]",d)} / f32(hight * ${d}); let squared_sum_final = ${En("workgroup_shared[0][1]",d)} / f32(hight * ${d}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:M,dataType:1}],dispatchGroup:{x:g},programUniforms:$}),getShaderSource:L},{inputs:[t,r,n],outputs:[-1]})[0]},ja=(e,t,r)=>{let n=t[0].dims,s=n,a=2,i=n[0],u=n[1],d=Oe.sizeFromDimension(n,a),p=br(d),w=Oe.size(s)/p,g=Vu(e,t[0],t[1],t[2],i,d,u,r.epsilon),l=[i,u,d/p],M=[i,u],E=["type","none"],$=L=>{let W=et("x",t[0].dataType,l.length,p),z=et("scale_shift",1,M.length,2),ie=Ut("output",t[0].dataType,l.length,p),J=[W,z,ie];return` ${L.registerUniform("output_size","u32").declareVariables(...J)} ${L.mainStart()} ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${ie.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${z.getByIndices("vec2(batch, channel)")}; let value = ${W.getByOffset("global_idx")} * ${ie.type.value}(scale_shift.x) + ${ie.type.value}(scale_shift.y); ${ie.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${p}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},...It(l,M,l)]}),getShaderSource:$},{inputs:[t[0],g]})},Uu=(e,t,r)=>{let n=t[0].dims,s=n,a=n[0],i=n[n.length-1],u=Oe.sizeFromDimension(n,1)/i,d=br(i),p=Oe.size(s)/d,w=[{type:12,data:u},{type:12,data:Math.floor(i/d)}],g=["type","type"],l=[0,n.length-1];for(let L=0;L{let W=Ar(t[0].dataType),z=d===1?"vec2f":`mat${d}x2f`,ie=Ge=>{let De=Ge===0?"x":"y",pt=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${W}(${pt}(scale.${De}))`;case 2:return`vec2<${W}>(${pt}(scale[0].${De}, scale[1].${De}))`;case 4:return`vec4<${W}>(${pt}(scale[0].${De}, scale[1].${De}, scale[2].${De}, scale[3].${De}))`;default:throw new Error(`Not supported compoents ${d}`)}},J=et("input",t[0].dataType,t[0].dims,d),oe=Ut("output",t[0].dataType,s,d);return` @group(0) @binding(0) var input : array<${J.type.storage}>; @group(0) @binding(1) var scale_input : array<${z}>; @group(0) @binding(2) var output : array<${oe.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${L.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${ie(0)}, ${ie(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:w}),getShaderSource:$},{inputs:[t[0],E]})},Wu=(e,t)=>{t.format==="NHWC"?Uu(e,e.inputs,t):ja(e,e.inputs,t)}}),Gu,qu,Hu,jd=j(()=>{Xt(),Qt(),ar(),Gu=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},qu=(e,t,r)=>{let n=t.simplified,s=e[0].dims,a=e[1],i=!n&&e[2],u=s,d=Oe.normalizeAxis(t.axis,s.length),p=Oe.sizeToDimension(s,d),w=Oe.sizeFromDimension(s,d),g=Oe.size(a.dims),l=i?Oe.size(i.dims):0;if(g!==w||i&&l!==w)throw new Error(`Size of X.shape()[axis:] == ${w}. Size of scale and bias (if provided) must match this. Got scale size of ${g} and bias size of ${l}`);let M=[];for(let oe=0;oe1,z=r>2,ie=oe=>{let Ge=Ar(e[0].dataType),De=[et("x",e[0].dataType,e[0].dims,E),et("scale",a.dataType,a.dims,E)];i&&De.push(et("bias",i.dataType,i.dims,E)),De.push(Ut("output",e[0].dataType,u,E)),W&&De.push(Ut("mean_data_output",1,M)),z&&De.push(Ut("inv_std_output",1,M));let pt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${oe.registerUniforms(pt).declareVariables(...De)} ${oe.mainStart()} ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Gr("f32",E)}; var mean_square_vector = ${Gr("f32",E)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Xr(Ge,E,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${En("mean_vector",E)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${En("mean_square_vector",E)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Xr(Ge,E,"x[j + offset]")}; let f32scale = ${Xr(Ge,E,"scale[j]")}; output[j + offset] = ${De[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${i?`+ ${Xr(Ge,E,"bias[j]")}`:""} ); } ${W?"mean_data_output[global_idx] = mean":""}; ${z?"inv_std_output[global_idx] = inv_std_dev":""}; }`},J=[{dims:u,dataType:e[0].dataType}];return W&&J.push({dims:M,dataType:1}),z&&J.push({dims:M,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${E};${r};${n}`,inputDependencies:$},getRunData:()=>({outputs:J,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:L}),getShaderSource:ie}},Hu=(e,t)=>{Gu(e.inputs),e.compute(qu(e.inputs,t,e.outputCount))}}),Ku,Xu,Qu,Yu,Vd=j(()=>{Xt(),Qt(),pr(),ar(),Ku=(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(!Oe.areEqual(i.dims,[t.n,s,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(Oe.size(u)!==t.n*s)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,p=t.bits>4?t.n*s:t.n*Math.floor((s+1)/2);if(Oe.size(d)!==p)throw new Error("zeroPoints input size error.")}},Xu=(e,t)=>{let r=e[0].dims,n=r.length,s=r[n-2],a=t.k,i=t.n,u=r.slice(0,n-2),d=Oe.size(u),p=e[1].dims[2]/4,w=e[0].dataType,g=br(t.k),l=br(p),M=br(i),E=u.concat([s,i]),$=s>1&&i/M%2===0?2:1,L=Oe.size(E)/M/$,W=64,z=[],ie=[d,s,a/g],J=Oe.convertShape(e[1].dims).slice();J.splice(-1,1,p/l),z.push(...It(ie)),z.push(...It(J)),z.push(...It(e[2].dims)),e.length===4&&z.push(...It(Oe.convertShape(e[3].dims)));let oe=[d,s,i/M];z.push(...It(oe));let Ge=De=>{let pt=ie.length,Dt=et("a",e[0].dataType,pt,g),Vt=et("b",12,J.length,l),lr=et("scales",e[2].dataType,e[2].dims.length),fr=[Dt,Vt,lr],tr=e.length===4?et("zero_points",12,e[3].dims.length):void 0;tr&&fr.push(tr);let jr=oe.length,Qr=Ut("output",e[0].dataType,jr,M),Mr=Ar(e[0].dataType),Ur=(()=>{switch(g){case 1:return`array<${Mr}, 8>`;case 2:return`mat4x2<${Mr}>`;case 4:return`mat2x4<${Mr}>`;default:throw new Error(`${g}-component is not supported.`)}})(),Jt=()=>{let Ve=` // reuse a data var input_offset = ${Dt.indicesToOffset(`${Dt.type.indices}(batch, row, word_offset)`)}; var a_data: ${Ur}; for (var j: u32 = 0; j < ${8/g}; j++) { a_data[j] = ${Dt.getByOffset("input_offset")}; input_offset++; } `;for(let St=0;St> 4) & b_mask); b_quantized_values = ${Ur}(${Array.from({length:4},(rr,Vr)=>`${Mr}(b_value_lower[${Vr}]), ${Mr}(b_value_upper[${Vr}])`).join(", ")}); b_dequantized_values = ${g===1?`${Ur}(${Array.from({length:8},(rr,Vr)=>`(b_quantized_values[${Vr}] - ${tr?`zero_point${St}`:"zero_point"}) * scale${St}`).join(", ")});`:`(b_quantized_values - ${Ur}(${Array(8).fill(`${tr?`zero_point${St}`:"zero_point"}`).join(",")})) * scale${St};`}; workgroup_shared[local_id.x * ${$} + ${Math.floor(St/M)}]${M>1?`[${St%M}]`:""} += ${Array.from({length:8/g},(rr,Vr)=>`${g===1?`a_data[${Vr}] * b_dequantized_values[${Vr}]`:`dot(a_data[${Vr}], b_dequantized_values[${Vr}])`}`).join(" + ")}; `;return Ve},dr=()=>{let Ve=` var col_index = col * ${M}; ${tr?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Mr}(8);`} `;for(let St=0;St> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${tr.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${St} = ${Mr}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return Ve},Or=()=>{let Ve=`col_index = col * ${M};`;for(let St=0;St; var b_value_upper: vec4; var b_quantized_values: ${Ur}; var b_dequantized_values: ${Ur};`,Ve};return` var workgroup_shared: array<${Qr.type.value}, ${$*W}>; ${De.declareVariables(...fr,Qr)} ${De.mainStart([W,1,1])} let output_indices = ${Qr.offsetToIndices(`(global_idx / ${W}) * ${$}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${W}) { //process one block var word_offset: u32 = block * ${t.blockSize/g}; ${dr()} for (var word: u32 = 0; word < ${p}; word += ${l}) { ${Or()} for (var i: u32 = 0; i < ${l}; i++) { ${Jt()} word_offset += ${8/g}; } } } workgroupBarrier(); if (local_id.x < ${$}) { var output_value: ${Qr.type.value} = ${Qr.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${W}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${$}; } ${Qr.setByIndices(`${Qr.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${g};${l};${M};${$};${W}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:E,dataType:w}],dispatchGroup:{x:L},programUniforms:z}),getShaderSource:Ge}},Qu=(e,t)=>{Ku(e.inputs,t),e.compute(Xu(e.inputs,t))},Yu=e=>qt(e)}),Ju,Zu,ed,td,rd,nd,sd,id,ad,Ud=j(()=>{Xt(),Qt(),ar(),Ju=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].")}},Zu=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; if (k < 0) { break; } if (k >= i32(${jt("uniforms.x_shape",s,t)})) { break; } offset += k * i32(${jt("uniforms.x_strides",s,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `},ed=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${jt("uniforms.x_shape",s,t)}) - 1); k = k % _2n_1; if(k >= i32(${jt("uniforms.x_shape",s,t)})) { k = _2n_1 - k; } } offset += k * i32(${jt("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},td=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; if (k < 0) { k = 0; } if (k >= i32(${jt("uniforms.x_shape",s,t)})) { k = i32(${jt("uniforms.x_shape",s,t)}) - 1; } offset += k * i32(${jt("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},rd=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; if (k < 0) { k += i32(${jt("uniforms.x_shape",s,t)}]); } if (k >= i32(${jt("uniforms.x_shape",s,t)})) { k -= i32(${jt("uniforms.x_shape",s,t)}); } offset += k * i32(${jt("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},nd=(e,t,r)=>{switch(r.mode){case 0:return Zu(e,t,r.pads.length);case 1:return ed(e,t,r.pads.length);case 2:return td(e,t,r.pads.length);case 3:return rd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},sd=(e,t)=>{let r=Oe.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,s=Oe.size(r),a=[{type:12,data:s},{type:6,data:t.pads}],i=e.length>=3&&e[2].data;t.mode===0&&a.push({type:i?e[2].dataType:1,data:t.value}),a.push(...It(e[0].dims,r));let u=["rank"],d=p=>{let w=Ut("output",e[0].dataType,r.length),g=et("x",e[0].dataType,n.length),l=g.type.value,M=nd(w,n.length,t),E=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&E.push({name:"constant_value",type:i?l:"f32"}),` ${p.registerUniforms(E).declareVariables(g,w)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${w.offsetToIndices("global_idx")}; var value = ${l}(0); ${M} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${i}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Oe.size(r)/64)},programUniforms:a}),getShaderSource:d}},id=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,s=e[0].dims.length,a=new Int32Array(2*s).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;da[Number(d)]=Number(u));let i=[];return a.forEach(u=>i.push(u)),{mode:t.mode,value:n,pads:i}}else return t},ad=(e,t)=>{Ju(e.inputs);let r=id(e.inputs,t);e.compute(sd(e.inputs,r),{inputs:[0]})}}),Ns,Va,Ua,Wa,Ga,Wd,or,qa,en,dn,hn,es,Gd,od,Ha,f,m,T,Y,Fe=j(()=>{bt(),Xt(),Qt(),ar(),Ns=e=>{if(k.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Va=(e,t,r)=>{let n=t.format==="NHWC",s=e.dims.slice();n&&s.splice(1,0,s.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),u=t.strides.slice(),d=a?t.dilations.slice():[],p=t.pads.slice();Sn.adjustPoolAttributes(r,s,i,u,d,p);let w=Sn.computePoolOutputShape(r,s,u,d,i,p,t.autoPad),g=Object.assign({},t);a?Object.assign(g,{kernelShape:i,strides:u,pads:p,dilations:d,cacheKey:t.cacheKey}):Object.assign(g,{kernelShape:i,strides:u,pads:p,cacheKey:t.cacheKey});let l=w.slice();return l.push(l.splice(1,1)[0]),[g,n?l:w]},Ua=(e,t)=>{let r=t.format==="NHWC",n=Oe.size(e),s=Oe.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:s}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],w=t.pads[t.pads.length-1],g=!!(p+w);a.push({type:12,data:u},{type:12,data:d},{type:12,data:p},{type:12,data:w}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(t.kernelShape.length===2){let M=t.kernelShape[t.kernelShape.length-2],E=t.strides[t.strides.length-2],$=t.pads[t.pads.length/2-2],L=t.pads[t.pads.length-2];l=!!($+L),a.push({type:12,data:M},{type:12,data:E},{type:12,data:$},{type:12,data:L}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,g,l]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=Oe.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((p,w)=>p+w);return[a,i,!!d,!1,!1]}},Wa=(e,t,r,n,s,a,i,u,d,p,w,g)=>{let l=s.format==="NHWC",M=t.type.value,E=Ut("output",t.type.tensor,n);if(s.kernelShape.length<=2){let $="",L="",W="",z=r-(l?2:1);if(w?$=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${z}] = indices[${z}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${z}] < 0 || xIndices[${z}] >= uniforms.x_shape[${z}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:$=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${z}] = indices[${z}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`,s.kernelShape.length===2){let ie=r-(l?3:2);g?L=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ie}] = indices[${ie}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${ie}] < 0 || xIndices[${ie}] >= uniforms.x_shape[${ie}]) { pad += i32(uniforms.kw); continue; } `:L=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ie}] = indices[${ie}] * uniforms.sh - uniforms.phStart + j; `,W=` } `}return` ${e.registerUniforms(d).declareVariables(t,E)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${E.offsetToIndices("global_idx")}; var xIndices = ${E.offsetToIndices("global_idx")}; var value = ${M}(${u}); var pad = 0; ${L} ${$} ${W} ${i} output[global_idx] = value; }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let $=s.kernelShape.length,L=s.pads.length,W="";return p?W=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:W=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} `,` ${e.registerUniforms(d).declareVariables(t,E)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${E.offsetToIndices("global_idx")}; var xIndices = ${E.offsetToIndices("global_idx")}; var offsets: array; var value = ${M}(${u}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${$-1}u; j++) { offsets[j] = offset / ${jt("uniforms.kernelStrides","j",$)}; offset -= offsets[j] * ${jt("uniforms.kernelStrides","j",$)}; } offsets[${$-1}] = offset; isPad = false; for (var j = ${r-$}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${jt("uniforms.strides",`j - ${r-$}u`,$)} + offsets[j - ${r-$}u] - ${jt("uniforms.pads","j - 2u",L)}; ${W} } ${i} output[global_idx] = value; }`}},Ga=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Wd=e=>`${Ga(e)};${e.countIncludePad}`,or=e=>`${Ga(e)};${e.storageOrder};${e.dilations}`,qa=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),en=(e,t,r,n)=>{let[s,a]=Va(t,n,r),i=et("x",t.dataType,t.dims.length),u=i.type.value,d="value += x_val;",p="";s.countIncludePad?p+=`value /= ${u}(uniforms.kernelSize);`:p+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[w,g,l,M,E]=Ua(a,s);w.push(...It(t.dims,a));let $=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${l};${M};${E}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Oe.size(a)/64)},programUniforms:w}),getShaderSource:L=>Wa(L,i,t.dims.length,a.length,s,d,p,0,g,l,M,E)}},dn=e=>{let t=e.count_include_pad!==0,r=qa(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:Wd(n)}},hn=(e,t)=>{Ns(e.inputs),e.compute(en("AveragePool",e.inputs[0],!1,t))},es={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Gd=e=>{let t=e.format;return{format:t,...es,cacheKey:t}},od=(e,t)=>{Ns(e.inputs),e.compute(en("GlobalAveragePool",e.inputs[0],!0,t))},Ha=(e,t,r,n)=>{let[s,a]=Va(t,n,r),i=` value = max(x_val, value); `,u="",d=et("x",t.dataType,t.dims.length),p=["rank"],[w,g,l,M,E]=Ua(a,s);return w.push(...It(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${l};${M};${E}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Oe.size(a)/64)},programUniforms:w}),getShaderSource:$=>Wa($,d,t.dims.length,a.length,s,i,u,t.dataType===10?-65504:-1e5,g,l,M,E)}},f=(e,t)=>{Ns(e.inputs),e.compute(Ha("MaxPool",e.inputs[0],!1,t))},m=e=>{let t=e.storage_order,r=e.dilations,n=qa(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let s={storageOrder:t,dilations:r,...n,cacheKey:""};return{...s,cacheKey:or(s)}},T=e=>{let t=e.format;return{format:t,...es,cacheKey:t}},Y=(e,t)=>{Ns(e.inputs),e.compute(Ha("GlobalMaxPool",e.inputs[0],!0,t))}}),ze,ht,Ct,Wt,sr=j(()=>{Xt(),Qt(),pr(),ar(),ze=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((s,a)=>a===t.axis||s===e[0].dims[a]).reduce((s,a)=>s&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},ht=(e,t)=>{let r=Oe.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,s=n===3,a=e[0].dims,i=e[1].dataType,u=Oe.size(a),d=n===3||n===2,p=d?[Math.ceil(Oe.size(e[0].dims)/4)]:e[0].dims,w=e[1].dims,g=e.length>2?e[2]:void 0,l=g?d?[Math.ceil(Oe.size(g.dims)/4)]:g.dims:void 0,M=w.length===0||w.length===1&&w[0]===1,E=M===!1&&w.length===1,$=br(u),L=M&&(!d||$===4),W=L?$:1,z=L&&!d?$:1,ie=et("input",d?12:n,p.length,z),J=et("scale",i,w.length),oe=g?et("zero_point",d?12:n,l.length):void 0,Ge=Ut("output",i,a.length,W),De=[ie,J];oe&&De.push(oe);let pt=[p,w];g&&pt.push(l);let Dt=[{type:12,data:u/W},{type:12,data:r},{type:12,data:t.blockSize},...It(...pt,a)],Vt=lr=>{let fr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${lr.registerUniforms(fr).declareVariables(...De,Ge)} ${lr.mainStart()} ${lr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${Ge.offsetToIndices("global_idx")}; // Set input x ${d?` let input = ${ie.getByOffset("global_idx / 4")}; let x_vec = ${s?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${W===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ie.getByOffset("global_idx")};`}; // Set scale input ${M?`let scale_value= ${J.getByOffset("0")}`:E?` let scale_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${J.getByOffset("scale_index")};`:` var scale_indices: ${J.type.indices} = output_indices; let index = ${J.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${J.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${J.getByIndices("scale_indices")};`}; // Set zero-point input ${oe?M?d?` let zero_point_input = ${oe.getByOffset("0")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${oe.getByOffset("0")}`:E?d?` let zero_point_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${oe.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${oe.getByOffset("zero_point_index")};`:d?` let zero_point_offset = ${J.indicesToOffset("scale_indices")}; let zero_point_input = ${oe.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${oe.getByIndices("scale_indices")};`:`let zero_point_value = ${d?s?"i32":"u32":ie.type.value}(0);`}; // Compute and write output ${Ge.setByOffset("global_idx",`${Ge.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:oe?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Vt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(u/W/64),y:1,z:1},programUniforms:Dt})}},Ct=(e,t)=>{ze(e.inputs,t),e.compute(ht(e.inputs,t))},Wt=e=>qt({axis:e.axis,blockSize:e.blockSize})}),Ir,ur,hr,wr=j(()=>{bt(),Xt(),ar(),Ir=(e,t,r)=>{let n=e===t,s=et&&r>0;if(n||s||a)throw new Error("Range these inputs' contents are invalid.")},ur=(e,t,r,n)=>{let s=Math.abs(Math.ceil((t-e)/r)),a=[s],i=s,u=[{type:12,data:i},{type:n,data:e},{type:n,data:r},...It(a)],d=p=>{let w=Ut("output",n,a.length),g=w.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:g},{name:"delta",type:g}];return` ${p.registerUniforms(l).declareVariables(w)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${g}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:u})}},hr=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),k.webgpu.validateInputContent&&Ir(t,r,n),e.compute(ur(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),Sr,Fr,kr,_r,tn,rn,wn,cn,an,yn,ws,js,Ka,yc,Rn,ys,qd,Hd,Kd,Xd=j(()=>{Xt(),Qt(),pr(),ar(),Sr=(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")}},Fr=(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},kr=(e,t,r,n,s,a)=>{let[i,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(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(u>0&&e.length>u&&e[u].dims.length>0){if(e[u].getFloat32Array().forEach(w=>n.push(w)),n.length!==0&&n.length!==p&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Sr(n,t),t.axes.length>0&&Fr(n,t.axes,p).forEach((w,g)=>n[g]=w)}if(d>0&&e.length>d&&(e[d].getBigInt64Array().forEach(w=>s.push(Number(w))),s.length!==p||r>=18&&s.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(s.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof s<"u"&&n.length>0&&s.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},_r=(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`)}})()+"}",tn=(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`)}})()+"}",rn=(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},wn=(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},cn=(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},an=(e,t,r,n,s)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${jt("uniforms.scales","i",n)}; var roi_low = ${jt("uniforms.roi","i",s)}; var roi_hi = ${jt("uniforms.roi",`i + ${t.length}`,s)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${jt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${jt("uniforms.output_shape","i",r.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,yn=(e,t,r,n,s,a,i)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${jt("uniforms.scales","i",s)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${jt("uniforms.roi","i",a)}; var roi_hi = ${jt("uniforms.roi",`i + ${r.length}`,a)}; var input_shape_i = ${jt("uniforms.input_shape","i",r.length)}; var output_shape_i = ${jt("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${i} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,ws=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${jt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,js=(e,t,r,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",Ka=(e,t,r,n,s)=>{let[a,i,u,d]=r.length===2?[-1,0,1,-1]:[0,2,3,1],p=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(row, ${r[i]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; ${js(e,d,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${p} = originalIndices[${i}]; var col:${p} = originalIndices[${u}]; ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[u]} - 1)) { return ${s}; }`:""}; row = max(0, min(row, ${r[i]} - 1)); col = max(0, min(col, ${r[u]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${r.length>2?`u32(originalIndices[${d}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${p} = getInputValue(batch, channel, row1, col1); var x12: ${p} = getInputValue(batch, channel, row1, col2); var x21: ${p} = getInputValue(batch, channel, row2, col1); var x22: ${p} = getInputValue(batch, channel, row2, col2); var dx1: ${p} = abs(row - ${p}(row1)); var dx2: ${p} = abs(${p}(row2) - row); var dy1: ${p} = abs(col - ${p}(col1)); var dy2: ${p} = abs(${p}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},yc=(e,t,r,n,s,a,i,u,d,p)=>{let w=r.length===2,[g,l]=w?[0,1]:[2,3],M=e.type.value,E=$=>{let L=$===g?"row":"col";return` fn ${L}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${M} { var output_index = ${t.indicesGet("output_indices",$)}; var originalIdx: ${M} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[$]}, ${n[$]}, ${r[$]}, ${a[$]}, ${a[$]} + ${r.length}); var fractOriginalIdx: ${M} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${u} && (originalIdx < 0 || originalIdx > (${r[$]} - 1))) { return ${d}; } var data: array<${M}, 4> = array<${M}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${L}: ${M} = originalIdx + ${M}(i); if (${L} < 0 || ${L} >= ${r[$]}) { ${p?`coefs[i + 1] = 0.0; continue;`:u?`return ${d};`:`${L} = max(0, min(${L}, ${r[$]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",$,`u32(${L})`)}; data[i + 1] = ${$===g?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${E(g)}; ${E(l)}; fn getCubicInterpolationCoefs(s: ${M}) -> array<${M}, 4> { var absS = abs(s); var coeffs: array<${M}, 4> = array<${M}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${M} = 1.0 - absS; var twoMinusAbsS: ${M} = 2.0 - absS; var onePlusAbsS: ${M} = 1.0 + absS; coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; return coeffs; } fn cubicInterpolation1D(x: array<${M}, 4>, coefs: array<${M}, 4>) -> ${M} { var coefsSum: ${M} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${M} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},Rn=(e,t,r,n,s)=>{let[a,i,u,d,p]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],w=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${w} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(depth, ${r[i]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(width, ${r[d]} - 1))`)}; ${js(e,p,a,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${w} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${w} = originalIndices[${i}]; var height:${w} = originalIndices[${u}]; var width:${w} = originalIndices[${d}]; ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { return ${s}; }`:""}; depth = max(0, min(depth, ${r[i]} - 1)); height = max(0, min(height, ${r[u]} - 1)); width = max(0, min(width, ${r[d]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${r.length>3?`u32(originalIndices[${p}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${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); }`},ys=(e,t,r,n,s,a)=>{let i=e.dims,u=rn(a,t.axes,i.length),d=wn(i,n,s,t.axes),p=n.slice();n.length===0&&(p=i.map((z,ie)=>z===0?1:d[ie]/z),t.keepAspectRatioPolicy!=="stretch"&&(d=cn(i,p,t)));let w=Ut("output",e.dataType,d.length),g=et("input",e.dataType,i.length),l=Oe.size(d),M=i.length===d.length&&i.every((z,ie)=>z===d[ie]),E=t.coordinateTransformMode==="tf_crop_and_resize",$=t.extrapolationValue,L=g.type.value,W=z=>` ${M?"":` ${_r(t.coordinateTransformMode,L)}; ${(()=>{switch(t.mode){case"nearest":return` ${ws(g,i)}; ${tn(t.nearestMode,r,L)}; ${yn(g,w,i,d,p.length,u.length,E)}; `;case"linear":return` ${an(w,i,d,p.length,u.length)}; ${(()=>{if(i.length===2||i.length===4)return`${Ka(g,w,i,E,$)}`;if(i.length===3||i.length===5)return`${Rn(g,w,i,E,$)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(i.length===2||i.length===4)return`${yc(g,w,i,d,p,u,t.cubicCoeffA,E,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")}})()}; `} ${z.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",u.length).declareVariables(g,w)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${M?"output[global_idx] = input[global_idx];":` let output_indices = ${w.offsetToIndices("global_idx")}; var input_indices: ${g.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${g.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${s.length>0?s:""}|${u.length>0?u:""}|${M}|${i}`,inputDependencies:["rank"]},getShaderSource:W,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:p},{type:1,data:u},...It(i,d)]})}},qd=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Hd=(e,t)=>{let r=[],n=[],s=[],a=qd(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");kr(e.inputs,t,a,r,n,s),e.compute(ys(e.inputs[0],t,a,r,n,s),{inputs:[0]})},Kd=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,s=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return qt({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:s,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:u,mode:d,nearestMode:p})}}),rp,np,sp,Pf=j(()=>{Xt(),Qt(),pr(),ar(),rp=(e,t)=>{let[r,n,s,a]=e,{numHeads:i,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!Oe.areEqual(n.dims,[])&&!Oe.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(!Oe.areEqual(s.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],p=r.dims[r.dims.length-2],w=s.dims[0],g=Oe.sizeFromDimension(r.dims,1)/p,l=u===0?s.dims[1]*2:g/i;if(u>l)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(p!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(l/2!==s.dims[1]&&u/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(p>w)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},np=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:s,scale:a}=t,i=e[0].dims[0],u=Oe.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],p=u/d,w=e[2].dims[1],g=s===0?w*2:p/n,l=new Array(i,d,p/g,g-w),M=Oe.computeStrides(l),E=[{type:1,data:a},{type:12,data:l},{type:12,data:M},...e[0].dims.length===3?new Array({type:12,data:[u,p,g,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,g,d*g,1]}):[],...It(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],$=L=>{let W=et("input",e[0].dataType,e[0].dims.length),z=et("position_ids",e[1].dataType,e[1].dims.length),ie=et("cos_cache",e[2].dataType,e[2].dims.length),J=et("sin_cache",e[3].dataType,e[3].dims.length),oe=Ut("output",e[0].dataType,e[0].dims.length);return L.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:M.length},{name:"input_output_strides",type:"u32",length:M.length}]),` ${L.declareVariables(W,z,ie,J,oe)} ${L.mainStart(Tn)} let half_rotary_emb_dim = uniforms.${ie.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${L.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${z.broadcastedIndicesToOffset("bsnh.xy",Ut("",z.type.tensor,2))}; let position_id = u32(${z.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 = ${W.getByOffset("i")} * ${ie.get("position_id","bsnh[3]")} - ${W.getByOffset("j")} * ${J.get("position_id","bsnh[3]")}; ${oe.setByOffset("i","re")} let im = ${W.getByOffset("i")} * ${J.get("position_id","bsnh[3]")} + ${W.getByOffset("j")} * ${ie.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",W.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:qt({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Oe.size(l)/Tn)},programUniforms:E})}},sp=(e,t)=>{rp(e.inputs,t),e.compute(np(e.inputs,t))}}),ip,ap,op,Af=j(()=>{Xt(),Qt(),ar(),ip=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")}},ap=(e,t,r,n)=>{let s=t.simplified,a=e[0].dims,i=Oe.size(a),u=a,d=i,p=a.slice(-1)[0],w=n?a.slice(0,-1).concat(1):[],g=!s&&e.length>3,l=e.length>4,M=n&&r>1,E=n&&r>2,$=r>3,L=64,W=br(p),z=[{type:12,data:d},{type:12,data:W},{type:12,data:p},{type:1,data:t.epsilon}],ie=oe=>{let Ge=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],De=[et("x",e[0].dataType,e[0].dims,W),et("skip",e[1].dataType,e[1].dims,W),et("gamma",e[2].dataType,e[2].dims,W)];g&&De.push(et("beta",e[3].dataType,e[3].dims,W)),l&&De.push(et("bias",e[4].dataType,e[4].dims,W)),De.push(Ut("output",e[0].dataType,u,W)),M&&De.push(Ut("mean_output",1,w)),E&&De.push(Ut("inv_std_output",1,w)),$&&De.push(Ut("input_skip_bias_sum",e[0].dataType,u,W));let pt=Ar(e[0].dataType),Dt=Ar(1,W);return` ${oe.registerUniforms(Ge).declareVariables(...De)} var sum_shared : array<${Dt}, ${L}>; var sum_squared_shared : array<${Dt}, ${L}>; ${oe.mainStart([L,1,1])} let ix = local_id.x; let iy = global_id.x / ${L}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${L}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${L-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${l?"bias[offset1d + i]":pt+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${$?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Xr(pt,W,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${L}; 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 = ${En("sum",W)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${En("square_sum",W)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); ${M?"mean_output[global_idx] = mean;":""} ${E?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${s?"":`- ${pt}(mean)`}) * ${pt}(inv_std_dev) * gamma[offset1d + i] ${g?"+ beta[offset1d + i]":""}; } }`},J=[{dims:u,dataType:e[0].dataType}];return r>1&&J.push({dims:w,dataType:1}),r>2&&J.push({dims:w,dataType:1}),r>3&&J.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${W};${M};${E};${$}`,inputDependencies:e.map((oe,Ge)=>"type")},getShaderSource:ie,getRunData:()=>({outputs:J,dispatchGroup:{x:Math.ceil(d/p)},programUniforms:z})}},op=(e,t)=>{ip(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(ap(e.inputs,t,e.outputCount,!1),{outputs:r})}}),lp,ld,up,bc,dp,cp,pp,hp,If=j(()=>{Xt(),Qt(),pr(),ar(),lp=(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`)})},ld=(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},up=(e,t)=>{if(e.length>1){let r=ld(e,1),n=ld(e,2),s=ld(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),qt({starts:r,ends:n,axes:s})}else return t},bc=(e,t,r,n,s)=>{let a=e;return e<0&&(a+=r[n[t]]),s[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},dp=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${jt("uniforms.input_shape","i",r.length)}; let steps_i = ${jt("uniforms.steps","i",r.length)}; let signs_i = ${jt("uniforms.signs","i",r.length)}; let starts_i = ${jt("uniforms.starts","i",r.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,cp=(e,t)=>{let r=e[0].dims,n=Oe.size(r),s=t.axes.length>0?Oe.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=ld(e,4);a.forEach(W=>W!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(s.length).fill(1));let i=t.starts.map((W,z)=>bc(W,z,r,s,a)),u=t.ends.map((W,z)=>bc(W,z,r,s,a));if(s.length!==i.length||s.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==r.length)for(let W=0;WMath.sign(W));a.forEach((W,z,ie)=>{if(W<0){let J=(u[z]-i[z])/W,oe=i[z],Ge=oe+J*a[z];i[z]=Ge,u[z]=oe,ie[z]=-W}});let p=r.slice(0);s.forEach((W,z)=>{p[W]=Math.ceil((u[W]-i[W])/a[W])});let w={dims:p,dataType:e[0].dataType},g=Ut("output",e[0].dataType,p.length),l=et("input",e[0].dataType,e[0].dims.length),M=Oe.size(p),E=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:a.length}],$=[{type:12,data:M},{type:12,data:i},{type:6,data:d},{type:12,data:a},...It(e[0].dims,p)],L=W=>` ${W.registerUniforms(E).declareVariables(l,g)} ${dp(l,g,r)} ${W.mainStart()} ${W.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${g.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${g.setByOffset("global_idx",l.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:L,getRunData:()=>({outputs:[w],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:$})}},pp=(e,t)=>{lp(e.inputs,t);let r=up(e.inputs,t);e.compute(cp(e.inputs,r),{inputs:[0]})},hp=e=>{let t=e.starts,r=e.ends,n=e.axes;return qt({starts:t,ends:r,axes:n})}}),fp,mp,_p,gp,Ff=j(()=>{Xt(),Qt(),pr(),ar(),fp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},mp=(e,t)=>{let r=e.dims,n=Oe.size(r),s=64,a=t.axis;if(a<0&&(a=r.length+a),aW===4?`max(max(${L}.x, ${L}.y), max(${L}.z, ${L}.w))`:W===2?`max(${L}.x, ${L}.y)`:W===3?`max(max(${L}.x, ${L}.y), ${L}.z)`:L,g=et("x",e.dataType,e.dims,d),l=Ut("result",e.dataType,e.dims,d),M=g.type.value,E=Ar(e.dataType)==="f32"?`var threadMax = ${M}(-3.402823e+38f);`:`var threadMax = ${M}(-65504.0h);`,$=L=>` var rowMaxShared : ${M}; var rowSumShared : ${M}; var threadShared : array<${M}, ${s}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${M} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${M}) { let index = row * row_stride + col; result[index] = value; } ${L.registerUniform("packedCols","i32").declareVariables(g,l)} ${L.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 ${E} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${M}(${w("threadShared[0]",d)}); } workgroupBarrier(); // find the rows sum var threadSum = ${M}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; } threadShared[lindex] = threadSum; workgroupBarrier(); for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { if (lindex < currSize) { threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; } workgroupBarrier(); } if (lindex == 0) { rowSumShared = ${M}(${En("threadShared[0]",d)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`;return{name:"Softmax",shaderCache:{hint:`${d}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:p}]}),getShaderSource:$}},_p=(e,t)=>{fp(e.inputs),e.compute(mp(e.inputs[0],t))},gp=e=>qt({axis:e.axis})}),wp,yp,bp,Mp,vp,xp,Tp,Of=j(()=>{Xt(),Qt(),pr(),ar(),wp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},yp=(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),qt({numOutputs:n,axis:t.axis,splitSizes:r})},bp=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${jt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Mp=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=Oe.size(r),s=e[0].dataType,a=Oe.normalizeAxis(t.axis,r.length),i=new Array(t.numOutputs),u=et("input",s,r.length),d=new Array(t.numOutputs),p=[],w=[],g=0,l=[{type:12,data:n}];for(let E=0;E` ${E.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...i)} ${bp(d.length)} ${Mp(i)} ${E.mainStart()} ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${u.offsetToIndices("global_idx")}; var index = ${u.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${jt("uniforms.size_in_split_axis","output_number - 1u",d.length)}; ${u.indicesSet("indices",a,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:l})}},xp=(e,t)=>{wp(e.inputs);let r=e.inputs.length===1?t:yp(e.inputs,t);e.compute(vp(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 qt({axis:t,numOutputs:n,splitSizes:r})}}),Ep,Cp,$p,zf=j(()=>{Xt(),Qt(),ar(),Ep=(e,t,r,n,s)=>{let a=Ut("output_data",s,r.length,4),i=et("a_data",t[1].dataType,t[1].dims.length,4),u=et("b_data",t[2].dataType,t[2].dims.length,4),d=et("c_data",t[0].dataType,t[0].dims.length,4),p,w=(g,l,M)=>`select(${l}, ${g}, ${M})`;if(!n)p=a.setByOffset("global_idx",w(i.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let g=(l,M,E="")=>{let $=`a_data[index_a${M}][component_a${M}]`,L=`b_data[index_b${M}][component_b${M}]`,W=`bool(c_data[index_c${M}] & (0xffu << (component_c${M} * 8)))`;return` let output_indices${M} = ${a.offsetToIndices(`global_idx * 4u + ${M}u`)}; let offset_a${M} = ${i.broadcastedIndicesToOffset(`output_indices${M}`,a)}; let offset_b${M} = ${u.broadcastedIndicesToOffset(`output_indices${M}`,a)}; let offset_c${M} = ${d.broadcastedIndicesToOffset(`output_indices${M}`,a)}; let index_a${M} = offset_a${M} / 4u; let index_b${M} = offset_b${M} / 4u; let index_c${M} = offset_c${M} / 4u; let component_a${M} = offset_a${M} % 4u; let component_b${M} = offset_b${M} % 4u; let component_c${M} = offset_c${M} % 4u; ${l}[${M}] = ${E}(${w($,L,W)}); `};s===9?p=` var data = vec4(0); ${g("data",0,"u32")} ${g("data",1,"u32")} ${g("data",2,"u32")} ${g("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=` ${g("output_data[global_idx]",0)} ${g("output_data[global_idx]",1)} ${g("output_data[global_idx]",2)} ${g("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(d,i,u,a)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${p} }`},Cp=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,s=e[1].dataType,a=!(Oe.areEqual(t,r)&&Oe.areEqual(r,n)),i=t,u=Oe.size(t);if(a){let p=ln.calcShape(ln.calcShape(t,r,!1),n,!1);if(!p)throw new Error("Can't perform where op on the given tensors");i=p,u=Oe.size(i)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>Ep(p,e,i,a,s),getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...It(n,t,r,i)]})}},$p=e=>{e.compute(Cp(e.inputs))}}),Sp,Df=j(()=>{Oo(),Wi(),wd(),Wo(),yd(),bd(),Fl(),Td(),iu(),Sd(),kd(),wu(),Ad(),Id(),Fd(),wc(),Dd(),Bd(),Rd(),Nd(),jd(),Kl(),Vd(),Fu(),Ud(),Fe(),sr(),wr(),Li(),Xd(),Pf(),Af(),If(),Ff(),Of(),Bu(),Qn(),aa(),zf(),Sp=new Map([["Abs",[qo]],["Acos",[Ho]],["Acosh",[Hi]],["Add",[ua]],["ArgMax",[Fo,ji]],["ArgMin",[Ni,ji]],["Asin",[Ko]],["Asinh",[Xo]],["Atan",[Qo]],["Atanh",[Yo]],["Attention",[Lo]],["AveragePool",[hn,dn]],["BatchNormalization",[qi]],["BiasAdd",[Uo]],["BiasSplitGelu",[yl]],["Cast",[Jo,Ki]],["Ceil",[el]],["Clip",[Xi]],["Concat",[Al,Il]],["Conv",[ba,wa]],["ConvTranspose",[su,eu]],["Cos",[tl]],["Cosh",[Qi]],["CumSum",[ou,Ta]],["DepthToSpace",[du,cu]],["DequantizeLinear",[Ct,Wt]],["Div",[Ml]],["Einsum",[_u,gu]],["Elu",[rl,Is]],["Equal",[vl]],["Erf",[nl]],["Exp",[sl]],["Expand",[bu]],["FastGelu",[Mu]],["Floor",[Yi]],["FusedConv",[ba,wa]],["Gather",[Ia,xu]],["GatherElements",[$u,Fa]],["GatherBlockQuantized",[Cu,Dr]],["Gelu",[il]],["Gemm",[za,Oa]],["GlobalAveragePool",[od,Gd]],["GlobalMaxPool",[Y,T]],["Greater",[El]],["GreaterOrEqual",[$l]],["GroupQueryAttention",[ju,Ru]],["HardSigmoid",[ea,ul]],["InstanceNormalization",[Wu]],["LayerNormalization",[Hu]],["LeakyRelu",[al,Is]],["Less",[Cl]],["LessOrEqual",[da]],["Log",[sa]],["MatMul",[Hl]],["MatMulNBits",[Qu,Yu]],["MaxPool",[f,m]],["Mul",[xl]],["MultiHeadAttention",[Iu,Ld]],["Neg",[ol]],["Not",[ti]],["Pad",[ad]],["Pow",[Tl]],["QuickGelu",[ia,Is]],["Range",[hr]],["Reciprocal",[ll]],["ReduceMin",[Po]],["ReduceMean",[Oi]],["ReduceMax",[ko]],["ReduceSum",[Ao]],["ReduceProd",[Di]],["ReduceL1",[$o]],["ReduceL2",[So]],["ReduceLogSum",[Bi]],["ReduceLogSumExp",[zi]],["ReduceSumSquare",[Io]],["Relu",[Ji]],["Resize",[Hd,Kd]],["RotaryEmbedding",[sp]],["Sigmoid",[Zi]],["Sin",[dl]],["Sinh",[cl]],["Slice",[pp,hp]],["SkipLayerNormalization",[op]],["Split",[xp,Tp]],["Sqrt",[pl]],["Softmax",[_p,gp]],["Sub",[ni]],["Tan",[ta]],["Tanh",[hl]],["ThresholdedRelu",[ml,Is]],["Tile",[Du]],["Transpose",[_d,so]],["Where",[$p]]])}),kp,Bf=j(()=>{bt(),vn(),ar(),kp=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){qe(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let p of t)u.push({binding:u.length,resource:{buffer:p.buffer}});for(let p of r)u.push({binding:u.length,resource:{buffer:p.buffer}});s&&u.push({binding:u.length,resource:s});let d=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:d,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}i.setPipeline(e.computePipeline),i.setBindGroup(0,d),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ue(e.programInfo.name)}dispose(){}build(e,t){qe(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let s=to(t,this.backend.device.limits),a=e.getShaderSource(s),i=`${n.join(` `)} ${s.additionalImplementations} ${a}`,u=r.createShaderModule({code:i,label:e.name});Wr("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let d=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Ue(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:s.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=s&&r<=s&&n<=s)return[t,r,n];let a=t*r*n,i=Math.ceil(Math.sqrt(a));if(i>s){if(i=Math.ceil(Math.cbrt(a)),i>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),Pp,Ap,Ip,Fp,Lf=j(()=>{bt(),Xt(),vn(),_(),zr(),Df(),Bf(),Pp=(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+`:${Pp(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Ip=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Fp=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 Ip(t.info||await t.requestAdapterInfo()),this.gpuDataManager=er(this),this.programManager=new kp(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ms(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;qe(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=M);let $=Number(M-this.queryTimeBase),L=Number(E-this.queryTimeBase);if(!Number.isSafeInteger($)||!Number.isSafeInteger(L))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map(W=>({dims:W.dims,dataType:Ln(W.dataType)})),outputsMetadata:l.map(W=>({dims:W.dims,dataType:Ln(W.dataType)})),kernelId:i,kernelType:d,kernelName:p,programName:w,startTime:$,endTime:L});else{let W="";g.forEach((ie,J)=>{W+=`input[${J}]: [${ie.dims}] | ${Ln(ie.dataType)}, `});let z="";l.forEach((ie,J)=>{z+=`output[${J}]: [${ie.dims}] | ${Ln(ie.dataType)}, `}),console.log(`[profiling] kernel "${i}|${d}|${p}|${w}" ${W}${z}execution time: ${L-$} ns`)}ke("GPU",`${w}::${M}::${E}`)}e.unmap(),this.pendingQueries.delete(e)}),Ue()}run(e,t,r,n,s,a){qe(e.name);let i=[];for(let z=0;zie):r;if(w.length!==u.length)throw new Error(`Output size ${w.length} must be equal to ${u.length}.`);let g=[],l=[];for(let z=0;z=a)throw new Error(`Invalid output index: ${w[z]}`);if(w[z]===-3)continue;let ie=w[z]===-1,J=w[z]===-2,oe=ie||J?s(u[z].dataType,u[z].dims):n(w[z],u[z].dataType,u[z].dims);if(g.push(oe),oe.data===0)continue;let Ge=this.gpuDataManager.get(oe.data);if(!Ge)throw new Error(`no GPU data for output: ${oe.data}`);if(ie&&this.temporaryData.push(Ge),J){let De=this.kernelPersistentData.get(this.currentKernelId);De||(De=[],this.kernelPersistentData.set(this.currentKernelId,De)),De.push(Ge)}l.push(Ge)}if(i.length!==t.length||l.length!==g.length){if(l.length===0)return Ue(e.name),g;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let M;if(p){let z=0,ie=[];p.forEach(De=>{let pt=typeof De.data=="number"?[De.data]:De.data;if(pt.length===0)return;let Dt=De.type===10?2:4,Vt,lr;De.type===10?(lr=pt.length>4?16:pt.length>2?8:pt.length*Dt,Vt=pt.length>4?16:Dt*pt.length):(lr=pt.length<=2?pt.length*Dt:16,Vt=16),z=Math.ceil(z/lr)*lr,ie.push(z);let fr=De.type===10?8:4;z+=pt.length>4?Math.ceil(pt.length/fr)*Vt:pt.length*Dt});let J=16;z=Math.ceil(z/J)*J;let oe=new ArrayBuffer(z);p.forEach((De,pt)=>{let Dt=ie[pt],Vt=typeof De.data=="number"?[De.data]:De.data;if(De.type===6)new Int32Array(oe,Dt,Vt.length).set(Vt);else if(De.type===12)new Uint32Array(oe,Dt,Vt.length).set(Vt);else if(De.type===10)new Uint16Array(oe,Dt,Vt.length).set(Vt);else if(De.type===1)new Float32Array(oe,Dt,Vt.length).set(Vt);else throw new Error(`Unsupported uniform type: ${Ln(De.type)}`)});let Ge=this.gpuDataManager.create(z,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ge.buffer,0,oe,0,z),this.gpuDataManager.release(Ge.id),M={offset:0,size:z,buffer:Ge.buffer}}let E=this.programManager.normalizeDispatchGroupSize(d),$=E[1]===1&&E[2]===1,L=Ap(e,t,$),W=this.programManager.getArtifact(L);if(W||(W=this.programManager.build(e,E),this.programManager.setArtifact(L,W),Wr("info",()=>`[artifact] key: ${L}, programName: ${e.name}`)),p&&W.uniformVariablesInfo){if(p.length!==W.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${W.uniformVariablesInfo.length}, got ${p.length} in program "${W.programInfo.name}".`);for(let z=0;z`[ProgramManager] run "${e.name}" (key=${L}) with ${E[0]}x${E[1]}x${E[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let z={kernelId:this.currentKernelId,programName:W.programInfo.name,inputTensorViews:t,outputTensorViews:g};this.pendingKernels.push(z),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(z)}return this.programManager.run(W,i,l,E,M),Ue(e.name),g}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=Sp.get(e);if(!s)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:s[0],attributes:[s[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let s=n.kernelType,a=n.kernelName,i=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),Wr("info",()=>`[WebGPU] Start to run kernel "[${s}] ${a}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),i(t,u[1]),0}catch(p){return r.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${a}" failed. ${p}`)),1}finally{d&&r.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${s}] ${a}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let s=this.sessionExternalDataMapping.get(e);s||(s=new Map,this.sessionExternalDataMapping.set(e,s));let a=s.get(t),i=this.gpuDataManager.registerExternalBuffer(r,n,a==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 Mt(this,e,t);return be(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(){Wr("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(){Wr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Wr("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()}}}),Op={};S(Op,{init:()=>Dp});var Qd,zp,Dp,Rf=j(()=>{Xt(),Lf(),vn(),Qt(),Qd=class bf{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=Oe.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=Oe.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=Oe.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Oe.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Oe.size(t)!==Oe.size(this.dims))throw new Error("Invalid new shape");return new bf(this.module,this.dataType,this.data,t)}},zp=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.HEAPU32,s=r>>>2;this.opKernelContext=n[s++];let a=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let i=[];for(let u=0;utypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],s=(u,d,p)=>new Qd(this.module,d,this.output(u,p),p),a=(u,d)=>{let p=Xn(u,d);if(!p)throw new Error(`Unsupported data type: ${u}`);let w=p>0?this.backend.gpuDataManager.create(p).id:0;return new Qd(this.module,u,w,d)};return this.backend.run(e,r,n,s,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),s=n>>2;this.module.HEAPU32[s++]=t.length;for(let a=0;a{let s=t.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Fp;await a.initialize(r,n),s("webgpu",[a,i=>a.alloc(i),i=>a.free(i),(i,u,d,p=!1)=>{if(p)Wr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${u}, size=${d}`),a.memcpy(i,u);else{Wr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${u}, size=${d}`);let w=t.HEAPU8.subarray(i>>>0,(i>>>0)+d);a.upload(u,w)}},async(i,u,d)=>{Wr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${u}, size=${d}`),await a.download(i,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+d))},(i,u,d)=>a.createKernel(i,u,d,t.UTF8ToString(t._JsepGetNodeName(u))),i=>a.releaseKernel(i),(i,u,d,p)=>{Wr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${i}, contextDataOffset=${u}`);let w=new zp(t,a,u);return a.computeKernel(i,w,p)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else s("webnn")}}),Bp,Mc,vc,Vs,Lp,Yd,xc,Tc,Ec,Cc,$c,Sc,Rp=j(()=>{Ys(),Js(),Xt(),yr(),Hn(),Cs(),Bp=(e,t)=>{mr()._OrtInit(e,t)!==0&&Rr("Can't initialize onnxruntime.")},Mc=async e=>{Bp(e.wasm.numThreads,rs(e.logLevel))},vc=async(e,t)=>{{let r=(Rf(),A(Op)).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",mr(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",mr(),e)}}},Vs=new Map,Lp=e=>{let t=mr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Rr("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},Yd=e=>{let t=mr(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},xc=async(e,t)=>{var g,l;let r,n,s=mr();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Yd(e);let a=0,i=0,u=0,d=[],p=[],w=[];try{if([i,d]=Kn(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let J=[];for(let oe of t.externalData){let Ge=typeof oe=="string"?oe:oe.path;J.push(ns(typeof oe=="string"?oe:oe.data).then(De=>{s.mountExternalData(Ge,De)}))}await Promise.all(J)}for(let J of(t==null?void 0:t.executionProviders)??[])if((typeof J=="string"?J:J.name)==="webnn"){if(s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof J!="string"){let oe=J,Ge=oe==null?void 0:oe.context,De=oe==null?void 0:oe.gpuDevice,pt=oe==null?void 0:oe.deviceType,Dt=oe==null?void 0:oe.numThreads,Vt=oe==null?void 0:oe.powerPreference;Ge?s.currentContext=Ge:De?s.currentContext=await navigator.ml.createContext(De):s.currentContext=await navigator.ml.createContext({deviceType:pt,numThreads:Dt,powerPreference:Vt})}else s.currentContext=await navigator.ml.createContext();break}a=await s._OrtCreateSession(r,n,i),a===0&&Rr("Can't create a session."),s.currentContext&&(s.currentContext=void 0);let[M,E]=Lp(a),$=!!(t!=null&&t.enableGraphCapture),L=[],W=[],z=[];for(let J=0;JJ==="gpu-buffer")&&(u=s._OrtCreateBinding(a),u===0&&Rr("Can't create IO binding."),ie={handle:u,outputPreferredLocations:z,outputPreferredLocationsEncoded:z.map(J=>hs(J))}),Vs.set(a,[a,p,w,ie,$,!1]),[a,L,W]}catch(M){throw p.forEach(E=>s._OrtFree(E)),w.forEach(E=>s._OrtFree(E)),u!==0&&s._OrtReleaseBinding(u),a!==0&&s._OrtReleaseSession(a),M}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i),d.forEach(M=>s._free(M)),(l=s.unmountExternalData)==null||l.call(s)}},Tc=e=>{var d;let t=mr(),r=Vs.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,i,u]=r;i&&(u&&t._OrtClearBoundOutputs(i.handle),t._OrtReleaseBinding(i.handle)),(d=t.jsepOnReleaseSession)==null||d.call(t,e),s.forEach(p=>t._OrtFree(p)),a.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n),Vs.delete(e)},Ec=(e,t,r,n,s,a=!1)=>{if(!e){t.push(0);return}let i=mr(),u=e[0],d=e[1],p=e[3],w,g;if(u==="string"&&p==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let E=e[2].gpuBuffer;g=Xn(cs(u),d);let $=i.jsepRegisterBuffer;if(!$)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');w=$(n,s,E,g)}else{let E=e[2];if(Array.isArray(E)){g=4*E.length,w=i._malloc(g),r.push(w);let $=w/4;for(let L=0;Li.HEAP32[E++]=L);let $=i._OrtCreateTensor(cs(u),w,g,M,d.length,hs(p));$===0&&Rr(`Can't create tensor for input/output. session=${n}, index=${s}.`),t.push($)}finally{i.stackRestore(l)}},Cc=async(e,t,r,n,s,a)=>{var Vt,lr;let i=mr(),u=Vs.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=u[0],p=u[1],w=u[2],g=u[3],l=u[4],M=u[5],E=t.length,$=n.length,L=0,W=[],z=[],ie=[],J=[],oe=i.stackSave(),Ge=i.stackAlloc(E*4),De=i.stackAlloc(E*4),pt=i.stackAlloc($*4),Dt=i.stackAlloc($*4);try{[L,W]=jn(a);for(let Jt=0;JtMn*Pn,1);rr=Ln(fn);let cd=g==null?void 0:g.outputPreferredLocations[n[Jt]];if(rr==="string"){if(cd==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Mn=[],Pn=Vr/4;for(let Wn=0;Wn0){let Mn=i.jsepGetBuffer;if(!Mn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Pn=Mn(Vr),Wn=Xn(fn,bn);if(Wn===void 0||!ps(rr))throw new Error(`Unsupported data type: ${rr}`);St=!0,Ur.push([rr,Nn,{gpuBuffer:Pn,download:i.jsepCreateDownloader(Pn,Wn,rr),dispose:()=>{i._OrtReleaseTensor(dr)}},"gpu-buffer"])}else{let Mn=Vn(rr),Pn=new Mn(bn);new Uint8Array(Pn.buffer,Pn.byteOffset,Pn.byteLength).set(i.HEAPU8.subarray(Vr,Vr+Pn.byteLength)),Ur.push([rr,Nn,Pn,"cpu"])}}finally{i.stackRestore(Or),rr==="string"&&Vr&&i._free(Vr),St||i._OrtReleaseTensor(dr)}}return g&&!l&&(i._OrtClearBoundOutputs(g.handle),Vs.set(e,[d,p,w,g,l,!1])),Ur}finally{i.stackRestore(oe),z.forEach(fr=>i._OrtReleaseTensor(fr)),ie.forEach(fr=>i._OrtReleaseTensor(fr)),J.forEach(fr=>i._free(fr)),L!==0&&i._OrtReleaseRunOptions(L),W.forEach(fr=>i._free(fr))}},$c=e=>{let t=mr(),r=Vs.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Rr("Can't get an profile file name."),t._OrtFree(s)},Sc=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Us,Bn,Xa,ud,dd,Jd,kc,Zd,fi,mi,Np,jp,Vp,Up,Wp,Gp,qp,Hp,Kp=j(()=>{bt(),Rp(),yr(),Rt(),Us=()=>!!k.wasm.proxy&&typeof document<"u",Xa=!1,ud=!1,dd=!1,Zd=new Map,fi=(e,t)=>{let r=Zd.get(e);r?r.push(t):Zd.set(e,[t])},mi=()=>{if(Xa||!ud||dd||!Bn)throw new Error("worker not ready")},Np=e=>{switch(e.data.type){case"init-wasm":Xa=!1,e.data.err?(dd=!0,kc[1](e.data.err)):(ud=!0,kc[0]()),Jd&&(URL.revokeObjectURL(Jd),Jd=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Zd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},jp=async()=>{if(!ud){if(Xa)throw new Error("multiple calls to 'initWasm()' detected.");if(dd)throw new Error("previous call to 'initWasm()' failed.");if(Xa=!0,Us())return new Promise((e,t)=>{Bn==null||Bn.terminate(),_t().then(([r,n])=>{try{Bn=n,Bn.onerror=a=>t(a),Bn.onmessage=Np,kc=[e,t];let s={type:"init-wasm",in:k};Bn.postMessage(s),Jd=r}catch(s){t(s)}},t)});try{await Lr(k.wasm),await Mc(k),ud=!0}catch(e){throw dd=!0,e}finally{Xa=!1}}},Vp=async e=>{if(Us())return mi(),new Promise((t,r)=>{fi("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:k}};Bn.postMessage(n)});await vc(k,e)},Up=async e=>Us()?(mi(),new Promise((t,r)=>{fi("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Bn.postMessage(n,[e.buffer])})):Yd(e),Wp=async(e,t)=>{if(Us()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return mi(),new Promise((r,n)=>{fi("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Bn.postMessage(s,a)})}else return xc(e,t)},Gp=async e=>{if(Us())return mi(),new Promise((t,r)=>{fi("release",[t,r]);let n={type:"release",in:e};Bn.postMessage(n)});Tc(e)},qp=async(e,t,r,n,s,a)=>{if(Us()){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 mi(),new Promise((i,u)=>{fi("run",[i,u]);let d=r,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:a}};Bn.postMessage(p,Sc(d))})}else return Cc(e,t,r,n,s,a)},Hp=async e=>{if(Us())return mi(),new Promise((t,r)=>{fi("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Bn.postMessage(n)});$c(e)}}),Pc,Xp,Qp,Nf=j(()=>{bt(),Kp(),Xt(),Ot(),Cs(),Pc=(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()}`)}},Xp=e=>{switch(e[3]){case"cpu":return new Re(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ps(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Re.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},Qp=class{async fetchModelAndCopyToWasmMemory(e){return Up(await ns(e))}async loadModel(e,t){qe();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await Wp(r,t),Ue()}async dispose(){return Gp(this.sessionId)}async run(e,t,r){qe();let n=[],s=[];Object.entries(e).forEach(g=>{let l=g[0],M=g[1],E=this.inputNames.indexOf(l);if(E===-1)throw new Error(`invalid input '${l}'`);n.push(M),s.push(E)});let a=[],i=[];Object.entries(t).forEach(g=>{let l=g[0],M=g[1],E=this.outputNames.indexOf(l);if(E===-1)throw new Error(`invalid output '${l}'`);a.push(M),i.push(E)});let u=n.map((g,l)=>Pc(g,()=>`input "${this.inputNames[s[l]]}"`)),d=a.map((g,l)=>g?Pc(g,()=>`output "${this.outputNames[i[l]]}"`):null),p=await qp(this.sessionId,s,u,i,d,r),w={};for(let g=0;gIc,initializeFlags:()=>Ac,wasmBackend:()=>Jp});var Ac,Ic,Jp,jf=j(()=>{bt(),Kp(),Nf(),Rt(),Ac=()=>{if((typeof k.wasm.initTimeout!="number"||k.wasm.initTimeout<0)&&(k.wasm.initTimeout=0),k.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof k.wasm.proxy!="boolean"&&(k.wasm.proxy=!1),typeof k.wasm.trace!="boolean"&&(k.wasm.trace=!1),typeof k.wasm.numThreads!="number"||!Number.isInteger(k.wasm.numThreads)||k.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)k.wasm.numThreads=1;else{let e=typeof navigator>"u"?Ce("node:os").cpus().length:navigator.hardwareConcurrency;k.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Ic=class{async init(e){Ac(),await jp(),await Vp(e)}async createInferenceSessionHandler(e,t){let r=new Qp;return await r.loadModel(e,t),Promise.resolve(r)}},Jp=new Ic});bt(),bt(),bt();var Vf="1.20.0-dev.20240925-a47254eaef",Uf=Tt;{let e=(jf(),A(Yp)).wasmBackend;me("webgpu",e,5),me("webnn",e,5),me("cpu",e,10),me("wasm",e,10)}Object.defineProperty(k.versions,"web",{value:Vf,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":($t,Ee,N)=>{var O;N.r(Ee),N.d(Ee,{Tensor:()=>Ce.Tensor,createInferenceSession:()=>ce,deviceToExecutionProviders:()=>ne,isONNXProxy:()=>te,isONNXTensor:()=>D});var fe=N("./src/env.js"),ye=N("?2ce3"),Te=N("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Ce=N("./node_modules/onnxruntime-common/dist/esm/index.js");const j=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),S=[];let V,A;if(fe.apis.IS_NODE_ENV){switch(A=ye??(O||(O=N.t(ye,2))),process.platform){case"win32":S.push("dml");break;case"linux":process.arch==="x64"&&S.push("cuda");break}S.push("cpu"),V=["cpu"]}else A=Te,fe.apis.IS_WEBNN_AVAILABLE&&S.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),fe.apis.IS_WEBGPU_AVAILABLE&&S.push("webgpu"),S.push("wasm"),V=["wasm"];const ee=A.InferenceSession;function ne(se=null){if(!se)return V;switch(se){case"auto":return S;case"gpu":return S.filter(X=>["webgpu","cuda","dml","webnn-gpu"].includes(X))}if(S.includes(se))return[j[se]??se];throw new Error(`Unsupported device: "${se}". Should be one of: ${S.join(", ")}.`)}let me=null;async function ce(se,X){me&&await me;const R=ee.create(se,X);return me??(me=R),await R}function D(se){return se instanceof A.Tensor}const H=A==null?void 0:A.env;H!=null&&H.wasm&&(H.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${fe.env.version}/dist/`,H.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(H.wasm.numThreads=1)),H!=null&&H.webgpu&&(H.webgpu.powerPreference="high-performance");function te(){var se;return(se=H==null?void 0:H.wasm)==null?void 0:se.proxy}fe.env.backends.onnx=H},"./src/configs.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{AutoConfig:()=>S,PretrainedConfig:()=>j,getKeyValueShapes:()=>Ce});var O=N("./src/utils/core.js"),fe=N("./src/utils/hub.js");async function ye(V,A){return await(0,fe.getModelJSON)(V,"config.json",!0,A)}function Te(V){const A={};let ee={};switch(V.model_type){case"llava":case"paligemma":case"florence2":ee=Te(V.text_config);break;case"moondream1":ee=Te(V.phi_config);break;case"musicgen":ee=Te(V.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":A.num_heads="n_head",A.num_layers="n_layer",A.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":A.num_heads="num_attention_heads",A.num_layers="num_hidden_layers",A.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":A.num_heads="num_key_value_heads",A.num_layers="num_hidden_layers",A.hidden_size="hidden_size",A.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":A.num_heads="num_key_value_heads",A.num_layers="num_hidden_layers",A.dim_kv="head_dim";break;case"openelm":A.num_heads="num_kv_heads",A.num_layers="num_transformer_layers",A.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":A.num_heads="num_heads",A.num_layers="num_layers",A.hidden_size="hidden_size";break;case"bloom":A.num_heads="n_head",A.num_layers="n_layer",A.hidden_size="hidden_size";break;case"mpt":A.num_heads="n_heads",A.num_layers="n_layers",A.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":A.num_decoder_layers="num_decoder_layers",A.num_decoder_heads="num_heads",A.decoder_dim_kv="d_kv",A.num_encoder_layers="num_layers",A.num_encoder_heads="num_heads",A.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":A.num_decoder_layers="decoder_layers",A.num_decoder_heads="decoder_attention_heads",A.decoder_hidden_size="d_model",A.num_encoder_layers="encoder_layers",A.num_encoder_heads="encoder_attention_heads",A.encoder_hidden_size="d_model";break;case"speecht5":A.num_decoder_layers="decoder_layers",A.num_decoder_heads="decoder_attention_heads",A.decoder_hidden_size="hidden_size",A.num_encoder_layers="encoder_layers",A.num_encoder_heads="encoder_attention_heads",A.encoder_hidden_size="hidden_size";break;case"trocr":A.num_encoder_layers=A.num_decoder_layers="decoder_layers",A.num_encoder_heads=A.num_decoder_heads="decoder_attention_heads",A.encoder_hidden_size=A.decoder_hidden_size="d_model";break;case"musicgen_decoder":A.num_encoder_layers=A.num_decoder_layers="num_hidden_layers",A.num_encoder_heads=A.num_decoder_heads="num_attention_heads",A.encoder_hidden_size=A.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const me=Te(V.decoder),ce="num_decoder_layers"in me,D=(0,O.pick)(V,["model_type","is_encoder_decoder"]);return ce?(D.num_decoder_layers=me.num_decoder_layers,D.num_decoder_heads=me.num_decoder_heads,D.decoder_hidden_size=me.decoder_hidden_size,D.num_encoder_layers=me.num_encoder_layers,D.num_encoder_heads=me.num_encoder_heads,D.encoder_hidden_size=me.encoder_hidden_size):(D.num_layers=me.num_layers,D.num_heads=me.num_heads,D.hidden_size=me.hidden_size),D}const ne={...ee,...(0,O.pick)(V,["model_type","multi_query","is_encoder_decoder"])};for(const me in A)ne[me]=V[A[me]];return ne}function Ce(V,{prefix:A="past_key_values"}={}){const ee={},ne=V.normalized_config,me=1;if(ne.is_encoder_decoder&&"num_encoder_heads"in ne&&"num_decoder_heads"in ne){const ce=ne.encoder_dim_kv??ne.encoder_hidden_size/ne.num_encoder_heads,D=ne.decoder_dim_kv??ne.decoder_hidden_size/ne.num_decoder_heads,H=[me,ne.num_encoder_heads,0,ce],te=[me,ne.num_decoder_heads,0,D];for(let se=0;se{var k;N.r(Ee),N.d(Ee,{apis:()=>D,env:()=>I});var O=N("?569f"),fe=N("?3f59"),ye=N("?154a");const Te="3.0.0-alpha.17",Ce=typeof self<"u",j=Ce&&self.constructor.name==="DedicatedWorkerGlobalScope",S=Ce&&"caches"in self,V=typeof navigator<"u"&&"gpu"in navigator,A=typeof navigator<"u"&&"ml"in navigator,ee=typeof process<"u",ne=ee&&((k=process==null?void 0:process.release)==null?void 0:k.name)==="node",me=!B(O),ce=!B(fe),D=Object.freeze({IS_BROWSER_ENV:Ce,IS_WEBWORKER_ENV:j,IS_WEB_CACHE_AVAILABLE:S,IS_WEBGPU_AVAILABLE:V,IS_WEBNN_AVAILABLE:A,IS_PROCESS_AVAILABLE:ee,IS_NODE_ENV:ne,IS_FS_AVAILABLE:me,IS_PATH_AVAILABLE:ce}),H=me&&ce,te=H?fe.dirname(fe.dirname(ye.fileURLToPath(self.location.href))):"./",se=H?fe.join(te,"/.cache/"):null,X="/models/",R=H?fe.join(te,X):X,I={version:Te,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co./",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ce,localModelPath:R,useFS:me,useBrowserCache:S,useFSCache:me,cacheDir:se,useCustomCache:!1,customCache:null};function B(ue){return Object.keys(ue).length===0}},"./src/generation/configuration_utils.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{GenerationConfig:()=>fe});var O=N("./src/utils/core.js");class fe{constructor(Te){xe(this,"max_length",20);xe(this,"max_new_tokens",null);xe(this,"min_length",0);xe(this,"min_new_tokens",null);xe(this,"early_stopping",!1);xe(this,"max_time",null);xe(this,"do_sample",!1);xe(this,"num_beams",1);xe(this,"num_beam_groups",1);xe(this,"penalty_alpha",null);xe(this,"use_cache",!0);xe(this,"temperature",1);xe(this,"top_k",50);xe(this,"top_p",1);xe(this,"typical_p",1);xe(this,"epsilon_cutoff",0);xe(this,"eta_cutoff",0);xe(this,"diversity_penalty",0);xe(this,"repetition_penalty",1);xe(this,"encoder_repetition_penalty",1);xe(this,"length_penalty",1);xe(this,"no_repeat_ngram_size",0);xe(this,"bad_words_ids",null);xe(this,"force_words_ids",null);xe(this,"renormalize_logits",!1);xe(this,"constraints",null);xe(this,"forced_bos_token_id",null);xe(this,"forced_eos_token_id",null);xe(this,"remove_invalid_values",!1);xe(this,"exponential_decay_length_penalty",null);xe(this,"suppress_tokens",null);xe(this,"begin_suppress_tokens",null);xe(this,"forced_decoder_ids",null);xe(this,"guidance_scale",null);xe(this,"num_return_sequences",1);xe(this,"output_attentions",!1);xe(this,"output_hidden_states",!1);xe(this,"output_scores",!1);xe(this,"return_dict_in_generate",!1);xe(this,"pad_token_id",null);xe(this,"bos_token_id",null);xe(this,"eos_token_id",null);xe(this,"encoder_no_repeat_ngram_size",0);xe(this,"decoder_start_token_id",null);xe(this,"generation_kwargs",{});Object.assign(this,(0,O.pick)(Te,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{ClassifierFreeGuidanceLogitsProcessor:()=>H,ForcedBOSTokenLogitsProcessor:()=>j,ForcedEOSTokenLogitsProcessor:()=>S,LogitsProcessor:()=>ye,LogitsProcessorList:()=>Ce,LogitsWarper:()=>Te,MinLengthLogitsProcessor:()=>me,MinNewTokensLengthLogitsProcessor:()=>ce,NoBadWordsLogitsProcessor:()=>D,NoRepeatNGramLogitsProcessor:()=>ee,RepetitionPenaltyLogitsProcessor:()=>ne,SuppressTokensAtBeginLogitsProcessor:()=>V,TemperatureLogitsWarper:()=>te,TopKLogitsWarper:()=>X,TopPLogitsWarper:()=>se,WhisperTimeStampLogitsProcessor:()=>A});var O=N("./src/utils/generic.js");N("./src/utils/tensor.js");var fe=N("./src/utils/maths.js");class ye extends O.Callable{_call(I,B){throw Error("`_call` should be implemented in a subclass")}}class Te extends O.Callable{_call(I,B){throw Error("`_call` should be implemented in a subclass")}}class Ce extends O.Callable{constructor(){super(),this.processors=[]}push(I){this.processors.push(I)}extend(I){this.processors.push(...I)}_call(I,B){let k=B;for(const ue of this.processors)k=ue(I,k);return k}[Symbol.iterator](){return this.processors.values()}}class j extends ye{constructor(I){super(),this.bos_token_id=I}_call(I,B){for(let k=0;k=1&&ve[ve.length-1]>=this.timestamp_begin,Ie=ve.length<2||ve[ve.length-2]>=this.timestamp_begin;if($e&&(Ie?ue.subarray(this.timestamp_begin).fill(-1/0):ue.subarray(0,this.eos_token_id).fill(-1/0)),I[k].length===this.begin_index&&this.max_initial_timestamp_index!==null){const dt=this.timestamp_begin+this.max_initial_timestamp_index;ue.subarray(dt+1).fill(-1/0)}const Ae=(0,fe.log_softmax)(ue),tt=Math.log(Ae.subarray(this.timestamp_begin).map(Math.exp).reduce((dt,ge)=>dt+ge)),Xe=(0,fe.max)(Ae.subarray(0,this.timestamp_begin))[0];tt>Xe&&ue.subarray(0,this.timestamp_begin).fill(-1/0)}return B}}class ee extends ye{constructor(I){super(),this.no_repeat_ngram_size=I}getNgrams(I){const B=I.length,k=[];for(let ve=0;ve1 to use the classifier free guidance processor, got guidance scale ${I}.`);this.guidance_scale=I}_call(I,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 k=I.length,ue=B.slice([0,k],null),ve=B.slice([k,B.dims[0]],null);for(let $e=0;$e1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${I}`);if(!Number.isInteger(k)||k<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${k}`);this.top_p=I,this.filter_value=B,this.min_tokens_to_keep=k}}class X extends Te{constructor(I,{filter_value:B=-1/0,min_tokens_to_keep:k=1}={}){if(super(),!Number.isInteger(I)||I<0)throw new Error(`\`top_k\` must be a positive integer, but is ${I}`);this.top_k=Math.max(I,k),this.filter_value=B}}},"./src/generation/logits_sampler.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{LogitsSampler:()=>Te});var O=N("./src/utils/generic.js"),fe=N("./src/utils/tensor.js"),ye=N("./src/utils/maths.js");N("./src/generation/configuration_utils.js");class Te extends O.Callable{constructor(A){super(),this.generation_config=A}async _call(A){return this.sample(A)}async sample(A){throw Error("sample should be implemented in subclasses.")}getLogits(A,ee){let ne=A.dims.at(-1),me=A.data;if(ee===-1)me=me.slice(-ne);else{let ce=ee*ne;me=me.slice(ce,ce+ne)}return me}randomSelect(A){let ee=0;for(let me=0;me1)return new S(A);if(A.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${A.num_return_sequences}.`);return new Ce(A)}}class Ce extends Te{async sample(A){const ee=(0,ye.max)(A.data)[1];return[[BigInt(ee),0]]}}class j extends Te{async sample(A){let ee=A.dims.at(-1);this.generation_config.top_k>0&&(ee=Math.min(this.generation_config.top_k,ee));const[ne,me]=await(0,fe.topk)(A,ee),ce=(0,ye.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},()=>{const D=this.randomSelect(ce);return[me.data[D],Math.log(ce[D])]})}}class S extends Te{async sample(A){let ee=A.dims.at(-1);this.generation_config.top_k>0&&(ee=Math.min(this.generation_config.top_k,ee));const[ne,me]=await(0,fe.topk)(A,ee),ce=(0,ye.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},(D,H)=>[me.data[H],Math.log(ce[H])])}}},"./src/generation/stopping_criteria.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{EosTokenCriteria:()=>Ce,InterruptableStoppingCriteria:()=>j,MaxLengthCriteria:()=>Te,StoppingCriteria:()=>fe,StoppingCriteriaList:()=>ye});var O=N("./src/utils/generic.js");class fe extends O.Callable{_call(V,A){throw Error("StoppingCriteria needs to be subclassed")}}class ye extends O.Callable{constructor(){super(),this.criteria=[]}push(V){this.criteria.push(V)}extend(V){V instanceof ye?V=V.criteria:V instanceof fe&&(V=[V]),this.criteria.push(...V)}_call(V,A){const ee=new Array(V.length).fill(!1);for(const ne of this.criteria){const me=ne(V,A);for(let ce=0;ceA.length>=this.max_length)}}class Ce extends fe{constructor(V){super(),Array.isArray(V)||(V=[V]),this.eos_token_id=V}_call(V,A){return V.map(ee=>{const ne=ee.at(-1);return this.eos_token_id.some(me=>ne==me)})}}class j extends fe{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(V,A){return new Array(V.length).fill(this.interrupted)}}},"./src/generation/streamers.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{BaseStreamer:()=>Te,TextStreamer:()=>j,WhisperTextStreamer:()=>S});var O=N("./src/utils/core.js"),fe=N("./src/tokenizers.js"),ye=N("./src/env.js");class Te{put(A){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Ce=ye.apis.IS_PROCESS_AVAILABLE?V=>process.stdout.write(V):V=>console.log(V);class j extends Te{constructor(A,{skip_prompt:ee=!1,callback_function:ne=null,token_callback_function:me=null,decode_kwargs:ce={},...D}={}){super(),this.tokenizer=A,this.skip_prompt=ee,this.callback_function=ne??Ce,this.token_callback_function=me,this.decode_kwargs={...ce,...D},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(A){var ce;if(A.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 ee=A[0];(ce=this.token_callback_function)==null||ce.call(this,ee),this.token_cache=(0,O.mergeArrays)(this.token_cache,ee);const ne=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let me;ne.endsWith(` `)?(me=ne.slice(this.print_len),this.token_cache=[],this.print_len=0):ne.length>0&&(0,fe.is_chinese_char)(ne.charCodeAt(ne.length-1))?(me=ne.slice(this.print_len),this.print_len+=me.length):(me=ne.slice(this.print_len,ne.lastIndexOf(" ")+1),this.print_len+=me.length),this.on_finalized_text(me,!1)}end(){let A;this.token_cache.length>0?(A=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):A="",this.next_tokens_are_prompt=!0,this.on_finalized_text(A,!0)}on_finalized_text(A,ee){var ne,me;A.length>0&&((ne=this.callback_function)==null||ne.call(this,A)),ee&&this.callback_function===Ce&&ye.apis.IS_PROCESS_AVAILABLE&&((me=this.callback_function)==null||me.call(this,` `))}}class S extends j{constructor(A,{skip_prompt:ee=!1,callback_function:ne=null,token_callback_function:me=null,on_chunk_start:ce=null,on_chunk_end:D=null,on_finalize:H=null,time_precision:te=.02,skip_special_tokens:se=!0,decode_kwargs:X={}}={}){super(A,{skip_prompt:ee,callback_function:ne,token_callback_function:me,decode_kwargs:{skip_special_tokens:se,...X}}),this.timestamp_begin=A.timestamp_begin,this.on_chunk_start=ce,this.on_chunk_end=D,this.on_finalize=H,this.time_precision=te,this.waiting_for_timestamp=!1}put(A){var ne,me;if(A.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const ee=A[0];if(ee.length===1){const ce=Number(ee[0])-this.timestamp_begin;if(ce>=0){const D=ce*this.time_precision;this.waiting_for_timestamp?(ne=this.on_chunk_end)==null||ne.call(this,D):(me=this.on_chunk_start)==null||me.call(this,D),this.waiting_for_timestamp=!this.waiting_for_timestamp,A=[[]]}}return super.put(A)}end(){var A;super.end(),(A=this.on_finalize)==null||A.call(this)}}},"./src/models.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{ASTForAudioClassification:()=>Zs,ASTModel:()=>jt,ASTPreTrainedModel:()=>En,AlbertForMaskedLM:()=>Xt,AlbertForQuestionAnswering:()=>hs,AlbertForSequenceClassification:()=>ps,AlbertModel:()=>rs,AlbertPreTrainedModel:()=>Vn,AutoModel:()=>ja,AutoModelForAudioClassification:()=>sd,AutoModelForAudioFrameClassification:()=>ad,AutoModelForCTC:()=>nd,AutoModelForCausalLM:()=>jd,AutoModelForDepthEstimation:()=>Ua,AutoModelForDocumentQuestionAnswering:()=>Ud,AutoModelForImageClassification:()=>Yu,AutoModelForImageFeatureExtraction:()=>Ga,AutoModelForImageMatting:()=>Ns,AutoModelForImageSegmentation:()=>Vd,AutoModelForImageToImage:()=>Va,AutoModelForMaskGeneration:()=>rd,AutoModelForMaskedLM:()=>Ku,AutoModelForNormalEstimation:()=>Wa,AutoModelForObjectDetection:()=>ed,AutoModelForQuestionAnswering:()=>Xu,AutoModelForSemanticSegmentation:()=>Ju,AutoModelForSeq2SeqLM:()=>Nd,AutoModelForSequenceClassification:()=>Uu,AutoModelForSpeechSeq2Seq:()=>Gu,AutoModelForTextToSpectrogram:()=>qu,AutoModelForTextToWaveform:()=>Hu,AutoModelForTokenClassification:()=>Wu,AutoModelForUniversalSegmentation:()=>Zu,AutoModelForVision2Seq:()=>Qu,AutoModelForXVector:()=>id,AutoModelForZeroShotObjectDetection:()=>td,BartForConditionalGeneration:()=>_,BartForSequenceClassification:()=>P,BartModel:()=>be,BartPretrainedModel:()=>vn,BaseModelOutput:()=>ct,BeitForImageClassification:()=>al,BeitModel:()=>il,BeitPreTrainedModel:()=>Yi,BertForMaskedLM:()=>Ne,BertForQuestionAnswering:()=>Re,BertForSequenceClassification:()=>st,BertForTokenClassification:()=>Pt,BertModel:()=>lt,BertPreTrainedModel:()=>nt,BlenderbotForConditionalGeneration:()=>zt,BlenderbotModel:()=>Mt,BlenderbotPreTrainedModel:()=>xt,BlenderbotSmallForConditionalGeneration:()=>ir,BlenderbotSmallModel:()=>zr,BlenderbotSmallPreTrainedModel:()=>er,BloomForCausalLM:()=>Do,BloomModel:()=>zo,BloomPreTrainedModel:()=>Oo,CLIPModel:()=>no,CLIPPreTrainedModel:()=>ss,CLIPSegForImageSegmentation:()=>po,CLIPSegModel:()=>co,CLIPSegPreTrainedModel:()=>xi,CLIPTextModel:()=>md,CLIPTextModelWithProjection:()=>In,CLIPVisionModel:()=>_d,CLIPVisionModelWithProjection:()=>so,CamembertForMaskedLM:()=>cr,CamembertForQuestionAnswering:()=>Br,CamembertForSequenceClassification:()=>xr,CamembertForTokenClassification:()=>Yr,CamembertModel:()=>Ot,CamembertPreTrainedModel:()=>bt,CausalLMOutput:()=>es,CausalLMOutputWithPast:()=>Gd,ChineseCLIPModel:()=>uo,ChineseCLIPPreTrainedModel:()=>lo,ClapAudioModelWithProjection:()=>cu,ClapModel:()=>uu,ClapPreTrainedModel:()=>hi,ClapTextModelWithProjection:()=>du,CodeGenForCausalLM:()=>Mo,CodeGenModel:()=>bo,CodeGenPreTrainedModel:()=>kn,CohereForCausalLM:()=>Eo,CohereModel:()=>To,CoherePreTrainedModel:()=>Ii,ConvBertForMaskedLM:()=>v,ConvBertForQuestionAnswering:()=>Q,ConvBertForSequenceClassification:()=>q,ConvBertForTokenClassification:()=>C,ConvBertModel:()=>kt,ConvBertPreTrainedModel:()=>vt,ConvNextForImageClassification:()=>Jn,ConvNextModel:()=>Yn,ConvNextPreTrainedModel:()=>Fl,ConvNextV2ForImageClassification:()=>Zn,ConvNextV2Model:()=>pa,ConvNextV2PreTrainedModel:()=>Un,DPTForDepthEstimation:()=>vl,DPTModel:()=>Ml,DPTPreTrainedModel:()=>ua,DebertaForMaskedLM:()=>U,DebertaForQuestionAnswering:()=>rt,DebertaForSequenceClassification:()=>_e,DebertaForTokenClassification:()=>Pe,DebertaModel:()=>at,DebertaPreTrainedModel:()=>Kr,DebertaV2ForMaskedLM:()=>gt,DebertaV2ForQuestionAnswering:()=>_t,DebertaV2ForSequenceClassification:()=>mt,DebertaV2ForTokenClassification:()=>Et,DebertaV2Model:()=>Je,DebertaV2PreTrainedModel:()=>we,DecisionTransformerModel:()=>Cu,DecisionTransformerPreTrainedModel:()=>Eu,DeiTForImageClassification:()=>ml,DeiTModel:()=>fl,DeiTPreTrainedModel:()=>ri,DepthAnythingForDepthEstimation:()=>Tl,DepthAnythingPreTrainedModel:()=>xl,DetrForObjectDetection:()=>ll,DetrForSegmentation:()=>Ji,DetrModel:()=>ol,DetrObjectDetectionOutput:()=>Zi,DetrPreTrainedModel:()=>ti,DetrSegmentationOutput:()=>ul,Dinov2ForImageClassification:()=>si,Dinov2Model:()=>ha,Dinov2PreTrainedModel:()=>un,DistilBertForMaskedLM:()=>Ze,DistilBertForQuestionAnswering:()=>Me,DistilBertForSequenceClassification:()=>Rt,DistilBertForTokenClassification:()=>Gt,DistilBertModel:()=>Nt,DistilBertPreTrainedModel:()=>Ft,DonutSwinModel:()=>Il,DonutSwinPreTrainedModel:()=>Al,EfficientNetForImageClassification:()=>gu,EfficientNetModel:()=>_u,EfficientNetPreTrainedModel:()=>$a,ElectraForMaskedLM:()=>Ye,ElectraForQuestionAnswering:()=>Tt,ElectraForSequenceClassification:()=>Bt,ElectraForTokenClassification:()=>ft,ElectraModel:()=>Qe,ElectraPreTrainedModel:()=>he,EsmForMaskedLM:()=>gr,EsmForSequenceClassification:()=>Lr,EsmForTokenClassification:()=>mr,EsmModel:()=>Ht,EsmPreTrainedModel:()=>ot,FalconForCausalLM:()=>lu,FalconModel:()=>Sd,FalconPreTrainedModel:()=>Ta,FastViTForImageClassification:()=>Xo,FastViTModel:()=>Ko,FastViTPreTrainedModel:()=>Hi,Florence2ForConditionalGeneration:()=>vi,Florence2PreTrainedModel:()=>ro,GLPNForDepthEstimation:()=>Pl,GLPNModel:()=>kl,GLPNPreTrainedModel:()=>ca,GPT2LMHeadModel:()=>Fn,GPT2Model:()=>ho,GPT2PreTrainedModel:()=>Ti,GPTBigCodeForCausalLM:()=>Pi,GPTBigCodeModel:()=>ei,GPTBigCodePreTrainedModel:()=>ki,GPTJForCausalLM:()=>On,GPTJModel:()=>gd,GPTJPreTrainedModel:()=>Si,GPTNeoForCausalLM:()=>go,GPTNeoModel:()=>_o,GPTNeoPreTrainedModel:()=>Ci,GPTNeoXForCausalLM:()=>yo,GPTNeoXModel:()=>wo,GPTNeoXPreTrainedModel:()=>$i,Gemma2ForCausalLM:()=>So,Gemma2Model:()=>$o,Gemma2PreTrainedModel:()=>Oi,GemmaForCausalLM:()=>zn,GemmaModel:()=>Co,GemmaPreTrainedModel:()=>Fi,GroupViTModel:()=>Ho,GroupViTPreTrainedModel:()=>qo,HieraForImageClassification:()=>gl,HieraModel:()=>_l,HieraPreTrainedModel:()=>sa,HubertForCTC:()=>ba,HubertForSequenceClassification:()=>Td,HubertModel:()=>Ql,HubertPreTrainedModel:()=>xd,ImageMattingOutput:()=>od,JAISLMHeadModel:()=>mo,JAISModel:()=>fo,JAISPreTrainedModel:()=>Ei,LlamaForCausalLM:()=>xo,LlamaModel:()=>vo,LlamaPreTrainedModel:()=>Ai,LlavaForConditionalGeneration:()=>_s,LlavaPreTrainedModel:()=>to,LongT5ForConditionalGeneration:()=>ks,LongT5Model:()=>Ss,LongT5PreTrainedModel:()=>fs,M2M100ForConditionalGeneration:()=>Nl,M2M100Model:()=>Rl,M2M100PreTrainedModel:()=>zs,MBartForCausalLM:()=>wt,MBartForConditionalGeneration:()=>pe,MBartForSequenceClassification:()=>Be,MBartModel:()=>ae,MBartPreTrainedModel:()=>K,MPNetForMaskedLM:()=>vs,MPNetForQuestionAnswering:()=>Es,MPNetForSequenceClassification:()=>xs,MPNetForTokenClassification:()=>Ts,MPNetModel:()=>Ys,MPNetPreTrainedModel:()=>jn,MT5ForConditionalGeneration:()=>Wr,MT5Model:()=>Ps,MT5PreTrainedModel:()=>ms,MarianMTModel:()=>ma,MarianModel:()=>Ll,MarianPreTrainedModel:()=>Os,MaskFormerForInstanceSegmentation:()=>Sl,MaskFormerModel:()=>bd,MaskFormerPreTrainedModel:()=>da,MaskedLMOutput:()=>dn,MistralForCausalLM:()=>su,MistralModel:()=>nu,MistralPreTrainedModel:()=>xa,MobileBertForMaskedLM:()=>$n,MobileBertForQuestionAnswering:()=>Hn,MobileBertForSequenceClassification:()=>Rr,MobileBertModel:()=>Tr,MobileBertPreTrainedModel:()=>yr,MobileNetV1ForImageClassification:()=>Ad,MobileNetV1Model:()=>bu,MobileNetV1PreTrainedModel:()=>ka,MobileNetV2ForImageClassification:()=>Id,MobileNetV2Model:()=>Mu,MobileNetV2PreTrainedModel:()=>Pa,MobileNetV3ForImageClassification:()=>xu,MobileNetV3Model:()=>vu,MobileNetV3PreTrainedModel:()=>Aa,MobileNetV4ForImageClassification:()=>Tu,MobileNetV4Model:()=>Fd,MobileNetV4PreTrainedModel:()=>Ia,MobileViTForImageClassification:()=>Zo,MobileViTModel:()=>Jo,MobileViTPreTrainedModel:()=>Ki,MobileViTV2ForImageClassification:()=>tl,MobileViTV2Model:()=>el,MobileViTV2PreTrainedModel:()=>Xi,ModelOutput:()=>He,Moondream1ForConditionalGeneration:()=>ar,MptForCausalLM:()=>As,MptModel:()=>Bo,MptPreTrainedModel:()=>Vi,MusicgenForCausalLM:()=>yu,MusicgenForConditionalGeneration:()=>Sa,MusicgenModel:()=>Pd,MusicgenPreTrainedModel:()=>wu,NomicBertModel:()=>ke,NomicBertPreTrainedModel:()=>re,OPTForCausalLM:()=>Wi,OPTModel:()=>Lo,OPTPreTrainedModel:()=>Ui,OpenELMForCausalLM:()=>Po,OpenELMModel:()=>ko,OpenELMPreTrainedModel:()=>zi,OwlViTForObjectDetection:()=>rl,OwlViTModel:()=>Is,OwlViTPreTrainedModel:()=>Qi,Owlv2ForObjectDetection:()=>sl,Owlv2Model:()=>nl,Owlv2PreTrainedModel:()=>Fs,Phi3ForCausalLM:()=>ji,Phi3Model:()=>Fo,Phi3PreTrainedModel:()=>Ni,PhiForCausalLM:()=>Ri,PhiModel:()=>Li,PhiPreTrainedModel:()=>Bi,PreTrainedModel:()=>Z,PretrainedMixin:()=>Dr,PvtForImageClassification:()=>jo,PvtModel:()=>wd,PvtPreTrainedModel:()=>qi,PyAnnoteForAudioFrameClassification:()=>Wl,PyAnnoteModel:()=>Ul,PyAnnotePreTrainedModel:()=>oi,QuestionAnsweringModelOutput:()=>hn,Qwen2ForCausalLM:()=>Io,Qwen2Model:()=>Ao,Qwen2PreTrainedModel:()=>Di,RTDetrForObjectDetection:()=>cl,RTDetrModel:()=>dl,RTDetrObjectDetectionOutput:()=>pl,RTDetrPreTrainedModel:()=>ea,ResNetForImageClassification:()=>wl,ResNetModel:()=>aa,ResNetPreTrainedModel:()=>ia,RoFormerForMaskedLM:()=>Ue,RoFormerForQuestionAnswering:()=>yt,RoFormerForSequenceClassification:()=>Ke,RoFormerForTokenClassification:()=>ut,RoFormerModel:()=>qe,RoFormerPreTrainedModel:()=>je,RobertaForMaskedLM:()=>mn,RobertaForQuestionAnswering:()=>Sn,RobertaForSequenceClassification:()=>ln,RobertaForTokenClassification:()=>Oe,RobertaModel:()=>pr,RobertaPreTrainedModel:()=>qt,SamImageSegmentationOutput:()=>Bl,SamModel:()=>fa,SamPreTrainedModel:()=>ai,SapiensForDepthEstimation:()=>Cl,SapiensForNormalEstimation:()=>$l,SapiensForSemanticSegmentation:()=>El,SapiensPreTrainedModel:()=>ni,SegformerForImageClassification:()=>hu,SegformerForSemanticSegmentation:()=>fu,SegformerModel:()=>pu,SegformerPreTrainedModel:()=>as,Seq2SeqLMOutput:()=>Wd,SequenceClassifierOutput:()=>or,SiglipModel:()=>io,SiglipPreTrainedModel:()=>Qn,SiglipTextModel:()=>ao,SiglipVisionModel:()=>oo,SpeechT5ForSpeechToText:()=>Zl,SpeechT5ForTextToSpeech:()=>va,SpeechT5HifiGan:()=>eu,SpeechT5Model:()=>$d,SpeechT5PreTrainedModel:()=>pi,SqueezeBertForMaskedLM:()=>cs,SqueezeBertForQuestionAnswering:()=>Xn,SqueezeBertForSequenceClassification:()=>Ln,SqueezeBertModel:()=>Js,SqueezeBertPreTrainedModel:()=>Kn,StableLmForCausalLM:()=>Ca,StableLmModel:()=>mu,StableLmPreTrainedModel:()=>Ea,Starcoder2ForCausalLM:()=>ou,Starcoder2Model:()=>au,Starcoder2PreTrainedModel:()=>iu,Swin2SRForImageSuperResolution:()=>Dn,Swin2SRModel:()=>bl,Swin2SRPreTrainedModel:()=>la,SwinForImageClassification:()=>yd,SwinModel:()=>yl,SwinPreTrainedModel:()=>oa,T5ForConditionalGeneration:()=>$s,T5Model:()=>Cs,T5PreTrainedModel:()=>ns,TableTransformerForObjectDetection:()=>hl,TableTransformerModel:()=>ra,TableTransformerObjectDetectionOutput:()=>na,TableTransformerPreTrainedModel:()=>ta,TokenClassifierOutput:()=>en,TrOCRForCausalLM:()=>ru,TrOCRPreTrainedModel:()=>tu,UniSpeechForCTC:()=>vd,UniSpeechForSequenceClassification:()=>ga,UniSpeechModel:()=>ql,UniSpeechPreTrainedModel:()=>li,UniSpeechSatForAudioFrameClassification:()=>ui,UniSpeechSatForCTC:()=>Kl,UniSpeechSatForSequenceClassification:()=>Xl,UniSpeechSatModel:()=>Hl,UniSpeechSatPreTrainedModel:()=>Bs,ViTForImageClassification:()=>No,ViTMAEModel:()=>Uo,ViTMAEPreTrainedModel:()=>Vo,ViTMSNForImageClassification:()=>$r,ViTMSNModel:()=>Go,ViTMSNPreTrainedModel:()=>Wo,ViTModel:()=>Ro,ViTPreTrainedModel:()=>Gi,VisionEncoderDecoderModel:()=>Mi,VitMatteForImageMatting:()=>Yo,VitMattePreTrainedModel:()=>Qo,VitsModel:()=>Ls,VitsModelOutput:()=>Ha,VitsPreTrainedModel:()=>kd,Wav2Vec2BertForCTC:()=>wa,Wav2Vec2BertForSequenceClassification:()=>ya,Wav2Vec2BertModel:()=>ci,Wav2Vec2BertPreTrainedModel:()=>di,Wav2Vec2ForAudioFrameClassification:()=>Vl,Wav2Vec2ForCTC:()=>_a,Wav2Vec2ForSequenceClassification:()=>Ds,Wav2Vec2Model:()=>jl,Wav2Vec2PreTrainedModel:()=>is,WavLMForAudioFrameClassification:()=>Cd,WavLMForCTC:()=>Ed,WavLMForSequenceClassification:()=>Jl,WavLMForXVector:()=>Ma,WavLMModel:()=>Yl,WavLMPreTrainedModel:()=>gs,WeSpeakerResNetModel:()=>Md,WeSpeakerResNetPreTrainedModel:()=>Gl,WhisperForConditionalGeneration:()=>bi,WhisperModel:()=>Ut,WhisperPreTrainedModel:()=>et,XLMForQuestionAnswering:()=>pn,XLMForSequenceClassification:()=>Qt,XLMForTokenClassification:()=>Tn,XLMModel:()=>sn,XLMPreTrainedModel:()=>Er,XLMRobertaForMaskedLM:()=>It,XLMRobertaForQuestionAnswering:()=>Xr,XLMRobertaForSequenceClassification:()=>br,XLMRobertaForTokenClassification:()=>Gr,XLMRobertaModel:()=>Cr,XLMRobertaPreTrainedModel:()=>Ar,XLMWithLMHeadModel:()=>xn,XVectorOutput:()=>qa,YolosForObjectDetection:()=>zl,YolosModel:()=>Ol,YolosObjectDetectionOutput:()=>Dl,YolosPreTrainedModel:()=>ii});var O=N("./src/configs.js"),fe=N("./src/backends/onnx.js"),ye=N("./src/utils/dtypes.js"),Te=N("./src/utils/generic.js"),Ce=N("./src/utils/core.js"),j=N("./src/utils/hub.js"),S=N("./src/generation/logits_process.js"),V=N("./src/generation/configuration_utils.js"),A=N("./src/utils/tensor.js"),ee=N("./src/utils/maths.js"),ne=N("./src/generation/stopping_criteria.js"),me=N("./src/generation/logits_sampler.js"),ce=N("./src/env.js"),D=N("./src/models/whisper/generation_whisper.js"),H=N("./src/models/whisper/common_whisper.js");const te={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},se=new Map,X=new Map,R=new Map;async function I(f,m,T){var kr;const Y=((kr=T.config)==null?void 0:kr["transformers.js_config"])??{};let Fe=T.device??Y.device;Fe&&typeof Fe!="string"&&(Fe.hasOwnProperty(m)?Fe=Fe[m]:(console.warn(`device not specified for "${m}". Using the default device.`),Fe=null));const ze=Fe??(ce.apis.IS_NODE_ENV?"cpu":"wasm"),ht=(0,fe.deviceToExecutionProviders)(ze);let Ct=T.dtype??Y.dtype;typeof Ct!="string"&&(Ct&&Ct.hasOwnProperty(m)?Ct=Ct[m]:(Ct=ye.DEFAULT_DEVICE_DTYPE_MAPPING[ze]??ye.DATA_TYPES.fp32,console.warn(`dtype not specified for "${m}". Using the default dtype (${Ct}) for this device (${ze}).`)));const Wt=Ct;if(ye.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Wt)){if(Wt===ye.DATA_TYPES.fp16&&ze==="webgpu"&&!await(0,ye.isWebGpuFp16Supported)())throw new Error(`The device (${ze}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Wt}. Should be one of: ${Object.keys(ye.DATA_TYPES).join(", ")}`);const sr=ye.DEFAULT_DTYPE_SUFFIX_MAPPING[Wt],Ir=`${T.subfolder??""}/${m}${sr}.onnx`,ur={...T.session_options};ur.executionProviders??(ur.executionProviders=ht);const hr=Y.free_dimension_overrides;hr?ur.freeDimensionOverrides??(ur.freeDimensionOverrides=hr):ze.startsWith("webnn")&&!ur.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const wr=(0,j.getModelFile)(f,Ir,!0,T);let Sr=[];if(T.use_external_data_format&&(T.use_external_data_format===!0||typeof T.use_external_data_format=="object"&&T.use_external_data_format.hasOwnProperty(m)&&T.use_external_data_format[m]===!0)){if(ce.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const _r=`${m}${sr}.onnx_data`,tn=`${T.subfolder??""}/${_r}`;Sr.push(new Promise(async(rn,wn)=>{const cn=await(0,j.getModelFile)(f,tn,!0,T);rn({path:_r,data:cn})}))}else ur.externalData!==void 0&&(Sr=ur.externalData.map(async _r=>{if(typeof _r.data=="string"){const tn=await(0,j.getModelFile)(f,_r.data,!0,T);return{..._r,data:tn}}return _r}));if(Sr.length>0&&(ur.externalData=await Promise.all(Sr)),ze==="webgpu"){const _r=(0,O.getKeyValueShapes)(T.config,{prefix:"present"});if(Object.keys(_r).length>0&&!(0,fe.isONNXProxy)()){const tn={};for(const rn in _r)rn.includes("encoder")||(tn[rn]="gpu-buffer");ur.preferredOutputLocation=tn}}return{buffer:await wr,session_options:ur}}async function B(f,m,T){return Object.fromEntries(await Promise.all(Object.keys(m).map(async Y=>{const{buffer:Fe,session_options:ze}=await I(f,m[Y],T),ht=await(0,fe.createInferenceSession)(Fe,ze);return[Y,ht]})))}function k(f,m){const T=Object.create(null),Y=[];for(const ht of f.inputNames){const Ct=m[ht];if(!(Ct instanceof A.Tensor)){Y.push(ht);continue}T[ht]=(0,fe.isONNXProxy)()?Ct.clone():Ct}if(Y.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Y.join(", ")}.`);const Fe=Object.keys(m).length,ze=f.inputNames.length;if(Fe>ze){let ht=Object.keys(m).filter(Ct=>!f.inputNames.includes(Ct));console.warn(`WARNING: Too many inputs were provided (${Fe} > ${ze}). The following inputs will be ignored: "${ht.join(", ")}".`)}return T}async function ue(f,m){const T=k(f,m);try{const Y=Object.fromEntries(Object.entries(T).map(([ze,ht])=>[ze,ht.ort_tensor]));let Fe=await f.run(Y);return Fe=ve(Fe),Fe}catch(Y){throw console.error(`An error occurred during model execution: "${Y}".`),console.error("Inputs given to model:",T),Y}}function ve(f){for(let m in f)(0,fe.isONNXTensor)(f[m])?f[m]=new A.Tensor(f[m]):typeof f[m]=="object"&&ve(f[m]);return f}function $e(f){if(f instanceof A.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(m=>m.length!==f[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new A.Tensor("int64",BigInt64Array.from(f.flat().map(m=>BigInt(m))),[f.length,f[0].length])}else return new A.Tensor("int64",BigInt64Array.from(f.map(m=>BigInt(m))),[1,f.length])}function Ie(f){return new A.Tensor("bool",[f],[1])}async function Ae(f,m){let{encoder_outputs:T,input_ids:Y,decoder_input_ids:Fe,...ze}=m;if(!T){const Ct=(0,Ce.pick)(m,f.sessions.model.inputNames);T=(await tt(f,Ct)).last_hidden_state}return ze.input_ids=Fe,ze.encoder_hidden_states=T,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(ze.encoder_attention_mask=m.attention_mask),await Xe(f,ze,!0)}async function tt(f,m){const T=f.sessions.model,Y=(0,Ce.pick)(m,T.inputNames);if(T.inputNames.includes("inputs_embeds")&&!Y.inputs_embeds){if(!m.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Y.inputs_embeds=await f.encode_text({input_ids:m.input_ids})}return T.inputNames.includes("token_type_ids")&&!Y.token_type_ids&&(Y.token_type_ids=new A.Tensor("int64",new BigInt64Array(Y.input_ids.data.length),Y.input_ids.dims)),await ue(T,Y)}async function Xe(f,m,T=!1){const Y=f.sessions[T?"decoder_model_merged":"model"],{past_key_values:Fe,...ze}=m;Y.inputNames.includes("use_cache_branch")&&(ze.use_cache_branch=Ie(!!Fe)),Y.inputNames.includes("position_ids")&&ze.attention_mask&&!ze.position_ids&&(ze.position_ids=ge(ze,Fe)),f.addPastKeyValues(ze,Fe);const ht=(0,Ce.pick)(ze,Y.inputNames);return await ue(Y,ht)}async function dt(f,{input_ids:m=null,attention_mask:T=null,pixel_values:Y=null,position_ids:Fe=null,inputs_embeds:ze=null,past_key_values:ht=null,generation_config:Ct=null,logits_processor:Wt=null,...sr}){if(!ze){if(ze=await f.encode_text({input_ids:m}),Y&&m.dims[1]!==1){const ur=await f.encode_image({pixel_values:Y});({inputs_embeds:ze,attention_mask:T}=f._merge_input_ids_with_image_features({image_features:ur,inputs_embeds:ze,input_ids:m,attention_mask:T}))}else if(ht&&Y&&m.dims[1]===1){const ur=m.dims[1],hr=Object.values(ht)[0].dims.at(-2);T=(0,A.cat)([(0,A.ones)([m.dims[0],hr]),T.slice(null,[T.dims[1]-ur,T.dims[1]])],1)}}return await Xe(f,{inputs_embeds:ze,past_key_values:ht,attention_mask:T,position_ids:Fe,generation_config:Ct,logits_processor:Wt},!0)}function ge(f,m=null){const{input_ids:T,inputs_embeds:Y,attention_mask:Fe}=f,[ze,ht]=Fe.dims,Ct=new BigInt64Array(Fe.data.length);for(let sr=0;srze.dims[1])){if(FeCt==f.config.image_token_index)){const Ct=f.config.num_image_tokens;if(!Ct)throw new Error("`num_image_tokens` is missing in the model configuration.");const Wt=ze.dims[1]-(Fe-Ct);T.input_ids=ze.slice(null,[-Wt,null]),T.attention_mask=(0,A.ones)([1,Fe+Wt])}}}return T}function de(f,m,T,Y){return T.past_key_values&&(m=m.map(Fe=>[Fe.at(-1)])),{...T,decoder_input_ids:$e(m)}}function Se(f,...m){return f.config.is_encoder_decoder?de(f,...m):G(f,...m)}class Z extends Te.Callable{constructor(T,Y){super();xe(this,"main_input_name","input_ids");xe(this,"forward_params",["input_ids","attention_mask"]);this.config=T,this.sessions=Y;const Fe=R.get(this.constructor),ze=se.get(Fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,ze){case te.DecoderOnly:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=G;break;case te.Seq2Seq:case te.Vision2Seq:case te.Musicgen:this.can_generate=!0,this._forward=Ae,this._prepare_inputs_for_generation=de;break;case te.EncoderDecoder:this._forward=Ae;break;case te.ImageTextToText:this.can_generate=!0,this._forward=dt,this._prepare_inputs_for_generation=Se;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 Y;const T=[];for(const Fe of Object.values(this.sessions))(Y=Fe==null?void 0:Fe.handler)!=null&&Y.dispose&&T.push(Fe.handler.dispose());return await Promise.all(T)}static async from_pretrained(T,{progress_callback:Y=null,config:Fe=null,cache_dir:ze=null,local_files_only:ht=!1,revision:Ct="main",model_file_name:Wt=null,subfolder:sr="onnx",device:Ir=null,dtype:ur=null,use_external_data_format:hr=null,session_options:wr={}}={}){let Sr={progress_callback:Y,config:Fe,cache_dir:ze,local_files_only:ht,revision:Ct,model_file_name:Wt,subfolder:sr,device:Ir,dtype:ur,use_external_data_format:hr,session_options:wr};const Fr=R.get(this),kr=se.get(Fr);Fe=Sr.config=await O.AutoConfig.from_pretrained(T,Sr);let _r;if(kr===te.DecoderOnly)_r=await Promise.all([B(T,{model:Sr.model_file_name??"model"},Sr),(0,j.getModelJSON)(T,"generation_config.json",!1,Sr)]);else if(kr===te.Seq2Seq||kr===te.Vision2Seq)_r=await Promise.all([B(T,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Sr),(0,j.getModelJSON)(T,"generation_config.json",!1,Sr)]);else if(kr===te.MaskGeneration)_r=await Promise.all([B(T,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Sr)]);else if(kr===te.EncoderDecoder)_r=await Promise.all([B(T,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Sr)]);else if(kr===te.ImageTextToText){const tn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Fe.is_encoder_decoder&&(tn.model="encoder_model"),_r=await Promise.all([B(T,tn,Sr),(0,j.getModelJSON)(T,"generation_config.json",!1,Sr)])}else kr===te.Musicgen?_r=await Promise.all([B(T,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Sr),(0,j.getModelJSON)(T,"generation_config.json",!1,Sr)]):(kr!==te.EncoderOnly&&console.warn(`Model type for '${Fr??(Fe==null?void 0:Fe.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),_r=await Promise.all([B(T,{model:Sr.model_file_name??"model"},Sr)]));return new this(Fe,..._r)}async _call(T){return await this.forward(T)}async forward(T){return await this._forward(this,T)}_get_logits_warper(T){const Y=new S.LogitsProcessorList;return T.temperature!==null&&T.temperature!==1&&Y.push(new S.TemperatureLogitsWarper(T.temperature)),T.top_k!==null&&T.top_k!==0&&Y.push(new S.TopKLogitsWarper(T.top_k)),T.top_p!==null&&T.top_p<1&&Y.push(new S.TopPLogitsWarper(T.top_p)),Y}_get_logits_processor(T,Y,Fe=null){const ze=new S.LogitsProcessorList;if(T.repetition_penalty!==null&&T.repetition_penalty!==1&&ze.push(new S.RepetitionPenaltyLogitsProcessor(T.repetition_penalty)),T.no_repeat_ngram_size!==null&&T.no_repeat_ngram_size>0&&ze.push(new S.NoRepeatNGramLogitsProcessor(T.no_repeat_ngram_size)),T.bad_words_ids!==null&&ze.push(new S.NoBadWordsLogitsProcessor(T.bad_words_ids,T.eos_token_id)),T.min_length!==null&&T.eos_token_id!==null&&T.min_length>0&&ze.push(new S.MinLengthLogitsProcessor(T.min_length,T.eos_token_id)),T.min_new_tokens!==null&&T.eos_token_id!==null&&T.min_new_tokens>0&&ze.push(new S.MinNewTokensLengthLogitsProcessor(Y,T.min_new_tokens,T.eos_token_id)),T.forced_bos_token_id!==null&&ze.push(new S.ForcedBOSTokenLogitsProcessor(T.forced_bos_token_id)),T.forced_eos_token_id!==null&&ze.push(new S.ForcedEOSTokenLogitsProcessor(T.max_length,T.forced_eos_token_id)),T.begin_suppress_tokens!==null){const ht=Y>1||T.forced_bos_token_id===null?Y:Y+1;ze.push(new S.SuppressTokensAtBeginLogitsProcessor(T.begin_suppress_tokens,ht))}return T.guidance_scale!==null&&T.guidance_scale>1&&ze.push(new S.ClassifierFreeGuidanceLogitsProcessor(T.guidance_scale)),Fe!==null&&ze.extend(Fe),ze}_prepare_generation_config(T,Y,Fe=V.GenerationConfig){const ze={...this.config};for(const Ct of["decoder","generator","text_config"])Ct in ze&&Object.assign(ze,ze[Ct]);const ht=new Fe(ze);return"generation_config"in this&&Object.assign(ht,this.generation_config),T&&Object.assign(ht,T),Y&&Object.assign(ht,(0,Ce.pick)(Y,Object.getOwnPropertyNames(ht))),ht}_get_stopping_criteria(T,Y=null){const Fe=new ne.StoppingCriteriaList;return T.max_length!==null&&Fe.push(new ne.MaxLengthCriteria(T.max_length,this.config.max_position_embeddings??null)),T.eos_token_id!==null&&Fe.push(new ne.EosTokenCriteria(T.eos_token_id)),Y&&Fe.extend(Y),Fe}_validate_model_class(){if(!this.can_generate){const T=[za,Da,Oa,Fa],Y=R.get(this.constructor),Fe=new Set,ze=this.config.model_type;for(const Ct of T){const Wt=Ct.get(ze);Wt&&Fe.add(Wt[0])}let ht=`The current model class (${Y}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Fe.size>0&&(ht+=` Please use the following class instead: ${[...Fe].join(", ")}`),Error(ht)}}prepare_inputs_for_generation(...T){return this._prepare_inputs_for_generation(this,...T)}_update_model_kwargs_for_generation({generated_input_ids:T,outputs:Y,model_inputs:Fe,is_encoder_decoder:ze}){return Fe.past_key_values=this.getPastKeyValues(Y,Fe.past_key_values),Fe.input_ids=new A.Tensor("int64",T.flat(),[T.length,1]),ze||(Fe.attention_mask=(0,A.cat)([Fe.attention_mask,(0,A.ones)([Fe.attention_mask.dims[0],1])],1)),Fe.position_ids=null,Fe}_prepare_model_inputs({inputs:T,bos_token_id:Y,model_kwargs:Fe}){const ze=(0,Ce.pick)(Fe,this.forward_params),ht=this.main_input_name;if(ht in ze){if(T)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else ze[ht]=T;return{inputs_tensor:ze[ht],model_inputs:ze,model_input_name:ht}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:T,model_inputs:Y,model_input_name:Fe,generation_config:ze}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Y.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Ct,pixel_values:Wt,attention_mask:sr,...Ir}=Y,ur=await this._prepare_inputs_embeds(Y);Y={...Ir,...(0,Ce.pick)(ur,["inputs_embeds","attention_mask"])}}let{last_hidden_state:ht}=await tt(this,Y);if(ze.guidance_scale!==null&&ze.guidance_scale>1)ht=(0,A.cat)([ht,(0,A.full_like)(ht,0)],0),"attention_mask"in Y&&(Y.attention_mask=(0,A.cat)([Y.attention_mask,(0,A.zeros_like)(Y.attention_mask)],0));else if(Y.decoder_input_ids){const Ct=$e(Y.decoder_input_ids).dims[0];if(Ct!==ht.dims[0]){if(ht.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${ht.dims[0]}) than the decoder inputs (${Ct}).`);ht=(0,A.cat)(Array.from({length:Ct},()=>ht),0)}}return Y.encoder_outputs=ht,Y}_prepare_decoder_input_ids_for_generation({batch_size:T,model_input_name:Y,model_kwargs:Fe,decoder_start_token_id:ze,bos_token_id:ht,generation_config:Ct}){let{decoder_input_ids:Wt,...sr}=Fe;if(Wt)Array.isArray(Wt[0])||(Wt=Array.from({length:T},()=>Wt));else if(ze??(ze=ht),this.config.model_type==="musicgen")Wt=Array.from({length:T*this.config.decoder.num_codebooks},()=>[ze]);else if(Array.isArray(ze)){if(ze.length!==T)throw new Error(`\`decoder_start_token_id\` expcted to have length ${T} but got ${ze.length}`);Wt=ze}else Wt=Array.from({length:T},()=>[ze]);return Wt=$e(Wt),Fe.decoder_attention_mask=(0,A.ones_like)(Wt),{input_ids:Wt,model_inputs:sr}}async generate({inputs:T=null,generation_config:Y=null,logits_processor:Fe=null,stopping_criteria:ze=null,streamer:ht=null,...Ct}){this._validate_model_class(),Y=this._prepare_generation_config(Y,Ct);let{inputs_tensor:Wt,model_inputs:sr,model_input_name:Ir}=this._prepare_model_inputs({inputs:T,model_kwargs:Ct});const ur=this.config.is_encoder_decoder;ur&&("encoder_outputs"in sr||(sr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Wt,model_inputs:sr,model_input_name:Ir,generation_config:Y})));let hr;ur?{input_ids:hr,model_inputs:sr}=this._prepare_decoder_input_ids_for_generation({batch_size:sr[Ir].dims.at(0),model_input_name:Ir,model_kwargs:sr,decoder_start_token_id:Y.decoder_start_token_id,bos_token_id:Y.bos_token_id,generation_config:Y}):hr=sr[Ir];let wr=hr.dims.at(-1);Y.max_new_tokens!==null&&(Y.max_length=wr+Y.max_new_tokens);const Sr=this._get_logits_processor(Y,wr,Fe),Fr=this._get_stopping_criteria(Y,ze),kr=sr[Ir].dims.at(0),_r=me.LogitsSampler.getSampler(Y),tn=new Array(kr).fill(0),rn=hr.tolist();ht&&ht.put(rn);let wn,cn={};for(;;){if(sr=this.prepare_inputs_for_generation(rn,sr,Y),wn=await this.forward(sr),Y.output_attentions&&Y.return_dict_in_generate){const Rn=this.getAttentions(wn);for(const ys in Rn)ys in cn||(cn[ys]=[]),cn[ys].push(Rn[ys])}const ws=wn.logits.slice(null,-1,null),js=Sr(rn,ws),Ka=[];for(let Rn=0;RnRn))break;sr=this._update_model_kwargs_for_generation({generated_input_ids:Ka,outputs:wn,model_inputs:sr,is_encoder_decoder:ur})}ht&&ht.end();const an=this.getPastKeyValues(wn,sr.past_key_values,!0),yn=new A.Tensor("int64",rn.flat(),[rn.length,rn[0].length]);if(Y.return_dict_in_generate)return{sequences:yn,past_key_values:an,...cn};for(const ws of Object.values(wn))ws.location==="gpu-buffer"&&ws.dispose();return yn}getPastKeyValues(T,Y,Fe=!1){const ze=Object.create(null);for(const ht in T)if(ht.startsWith("present")){const Ct=ht.replace("present","past_key_values"),Wt=ht.includes("encoder");if(Wt&&Y?ze[Ct]=Y[Ct]:ze[Ct]=T[ht],Y&&(!Wt||Fe)){const sr=Y[Ct];sr.location==="gpu-buffer"&&sr.dispose()}}return ze}getAttentions(T){const Y={};for(const Fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const ze in T)ze.startsWith(Fe)&&(Fe in Y||(Y[Fe]=[]),Y[Fe].push(T[ze]));return Y}addPastKeyValues(T,Y){if(Y)Object.assign(T,Y);else{const Fe=this.custom_config.kv_cache_dtype??"float32",ze=Fe==="float16"?new Uint16Array:[],ht=(0,O.getKeyValueShapes)(this.config);for(const Ct in ht)T[Ct]=new A.Tensor(Fe,ze,ht[Ct])}}async encode_image({pixel_values:T}){const Y=(await ue(this.sessions.vision_encoder,{pixel_values:T})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${Y.dims[1]}).`),this.config.num_image_tokens=Y.dims[1]),Y}async encode_text({input_ids:T}){return(await ue(this.sessions.embed_tokens,{input_ids:T})).inputs_embeds}}class He{}class ct extends He{constructor({last_hidden_state:m,hidden_states:T=null,attentions:Y=null}){super(),this.last_hidden_state=m,this.hidden_states=T,this.attentions=Y}}class nt extends Z{}class lt extends nt{}class Ne extends nt{async _call(m){return new dn(await super._call(m))}}class st extends nt{async _call(m){return new or(await super._call(m))}}class Pt extends nt{async _call(m){return new en(await super._call(m))}}class Re extends nt{async _call(m){return new hn(await super._call(m))}}class re extends Z{}class ke extends re{}class je extends Z{}class qe extends je{}class Ue extends je{async _call(m){return new dn(await super._call(m))}}class Ke extends je{async _call(m){return new or(await super._call(m))}}class ut extends je{async _call(m){return new en(await super._call(m))}}class yt extends je{async _call(m){return new hn(await super._call(m))}}class vt extends Z{}class kt extends vt{}class v extends vt{async _call(m){return new dn(await super._call(m))}}class q extends vt{async _call(m){return new or(await super._call(m))}}class C extends vt{async _call(m){return new en(await super._call(m))}}class Q extends vt{async _call(m){return new hn(await super._call(m))}}class he extends Z{}class Qe extends he{}class Ye extends he{async _call(m){return new dn(await super._call(m))}}class Bt extends he{async _call(m){return new or(await super._call(m))}}class ft extends he{async _call(m){return new en(await super._call(m))}}class Tt extends he{async _call(m){return new hn(await super._call(m))}}class bt extends Z{}class Ot extends bt{}class cr extends bt{async _call(m){return new dn(await super._call(m))}}class xr extends bt{async _call(m){return new or(await super._call(m))}}class Yr extends bt{async _call(m){return new en(await super._call(m))}}class Br extends bt{async _call(m){return new hn(await super._call(m))}}class Kr extends Z{}class at extends Kr{}class U extends Kr{async _call(m){return new dn(await super._call(m))}}class _e extends Kr{async _call(m){return new or(await super._call(m))}}class Pe extends Kr{async _call(m){return new en(await super._call(m))}}class rt extends Kr{async _call(m){return new hn(await super._call(m))}}class we extends Z{}class Je extends we{}class gt extends we{async _call(m){return new dn(await super._call(m))}}class mt extends we{async _call(m){return new or(await super._call(m))}}class Et extends we{async _call(m){return new en(await super._call(m))}}class _t extends we{async _call(m){return new hn(await super._call(m))}}class Ft extends Z{}class Nt extends Ft{}class Rt extends Ft{async _call(m){return new or(await super._call(m))}}class Gt extends Ft{async _call(m){return new en(await super._call(m))}}class Me extends Ft{async _call(m){return new hn(await super._call(m))}}class Ze extends Ft{async _call(m){return new dn(await super._call(m))}}class ot extends Z{}class Ht extends ot{}class gr extends ot{async _call(m){return new dn(await super._call(m))}}class Lr extends ot{async _call(m){return new or(await super._call(m))}}class mr extends ot{async _call(m){return new en(await super._call(m))}}class yr extends Z{}class Tr extends yr{}class $n extends yr{async _call(m){return new dn(await super._call(m))}}class Rr extends yr{async _call(m){return new or(await super._call(m))}}class Hn extends yr{async _call(m){return new hn(await super._call(m))}}class jn extends Z{}class Ys extends jn{}class vs extends jn{async _call(m){return new dn(await super._call(m))}}class xs extends jn{async _call(m){return new or(await super._call(m))}}class Ts extends jn{async _call(m){return new en(await super._call(m))}}class Es extends jn{async _call(m){return new hn(await super._call(m))}}class Kn extends Z{}class Js extends Kn{}class cs extends Kn{async _call(m){return new dn(await super._call(m))}}class Ln extends Kn{async _call(m){return new or(await super._call(m))}}class Xn extends Kn{async _call(m){return new hn(await super._call(m))}}class Vn extends Z{}class rs extends Vn{}class ps extends Vn{async _call(m){return new or(await super._call(m))}}class hs extends Vn{async _call(m){return new hn(await super._call(m))}}class Xt extends Vn{async _call(m){return new dn(await super._call(m))}}class ns extends Z{constructor(T,Y,Fe){super(T,Y);xe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Cs extends ns{}class $s extends ns{}class fs extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class Ss extends fs{}class ks extends fs{}class ms extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class Ps extends ms{}class Wr extends ms{}class vn extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class be extends vn{}class _ extends vn{}class P extends vn{async _call(m){return new or(await super._call(m))}}class K extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class ae extends K{}class pe extends K{}class Be extends K{async _call(m){return new or(await super._call(m))}}class wt extends K{}class xt extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class Mt extends xt{}class zt extends xt{}class er extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class zr extends er{}class ir extends er{}class qt extends Z{}class pr extends qt{}class mn extends qt{async _call(m){return new dn(await super._call(m))}}class ln extends qt{async _call(m){return new or(await super._call(m))}}class Oe extends qt{async _call(m){return new en(await super._call(m))}}class Sn extends qt{async _call(m){return new hn(await super._call(m))}}class Er extends Z{}class sn extends Er{}class xn extends Er{async _call(m){return new dn(await super._call(m))}}class Qt extends Er{async _call(m){return new or(await super._call(m))}}class Tn extends Er{async _call(m){return new en(await super._call(m))}}class pn extends Er{async _call(m){return new hn(await super._call(m))}}class Ar extends Z{}class Cr extends Ar{}class It extends Ar{async _call(m){return new dn(await super._call(m))}}class br extends Ar{async _call(m){return new or(await super._call(m))}}class Gr extends Ar{async _call(m){return new en(await super._call(m))}}class Xr extends Ar{async _call(m){return new hn(await super._call(m))}}class En extends Z{}class jt extends En{}class Zs extends En{}class et extends Z{constructor(T,Y,Fe){super(T,Y);xe(this,"requires_attention_mask",!1);xe(this,"main_input_name","input_features");xe(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Ut extends et{}class bi extends et{_prepare_generation_config(m,T){return super._prepare_generation_config(m,T,D.WhisperGenerationConfig)}_retrieve_init_tokens(m){const T=[m.decoder_start_token_id];let Y=m.language;const Fe=m.task;if(m.is_multilingual){Y||(console.warn("No language specified - defaulting to English (en)."),Y="en");const ht=`<|${(0,H.whisper_language_to_code)(Y)}|>`;T.push(m.lang_to_id[ht]),T.push(m.task_to_id[Fe??"transcribe"])}else if(Y||Fe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!m.return_timestamps&&m.no_timestamps_token_id&&T.at(-1)!==m.no_timestamps_token_id?T.push(m.no_timestamps_token_id):m.return_timestamps&&T.at(-1)===m.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),T.pop()),T.filter(ze=>ze!=null)}async generate({inputs:m=null,generation_config:T=null,logits_processor:Y=null,stopping_criteria:Fe=null,...ze}){T=this._prepare_generation_config(T,ze);const ht=ze.decoder_input_ids??this._retrieve_init_tokens(T);if(T.return_timestamps&&(Y??(Y=new S.LogitsProcessorList),Y.push(new S.WhisperTimeStampLogitsProcessor(T,ht))),T.begin_suppress_tokens&&(Y??(Y=new S.LogitsProcessorList),Y.push(new S.SuppressTokensAtBeginLogitsProcessor(T.begin_suppress_tokens,ht.length))),T.return_token_timestamps){if(!T.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");T.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),T.output_attentions=!0,T.return_dict_in_generate=!0}const Ct=await super.generate({inputs:m,generation_config:T,logits_processor:Y,decoder_input_ids:ht,...ze});return T.return_token_timestamps&&(Ct.token_timestamps=this._extract_token_timestamps(Ct,T.alignment_heads,T.num_frames)),Ct}_extract_token_timestamps(m,T,Y=null,Fe=.02){if(!m.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`.");Y==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 ze=this.config.median_filter_width;ze===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),ze=7);const ht=m.cross_attentions,Ct=Array.from({length:this.config.decoder_layers},(Fr,kr)=>(0,A.cat)(ht.map(_r=>_r[kr]),2)),Wt=(0,A.stack)(T.map(([Fr,kr])=>{if(Fr>=Ct.length)throw new Error(`Layer index ${Fr} is out of bounds for cross attentions (length ${Ct.length}).`);return Y?Ct[Fr].slice(null,kr,null,[0,Y]):Ct[Fr].slice(null,kr)})).transpose(1,0,2,3),[sr,Ir]=(0,A.std_mean)(Wt,-2,0,!0),ur=Wt.clone();for(let Fr=0;Fr_r[yn+1]-_r[yn]),wn=(0,Ce.mergeArrays)([1],rn).map(an=>!!an),cn=[];for(let an=0;anhr.findIndex(wr=>wr==ze)),Wt=Ct.every(hr=>hr===-1),sr=Ct.every(hr=>hr!==-1);if(!Wt&&!sr)throw new Error("Every input should contain either 0 or 1 image token.");if(Wt)return{inputs_embeds:m,attention_mask:Fe};const Ir=[],ur=[];for(let hr=0;hrze*ht,1);m.input_labels=new A.Tensor("int64",new BigInt64Array(Fe).fill(1n),Y)}const T={image_embeddings:m.image_embeddings,image_positional_embeddings:m.image_positional_embeddings};return m.input_points&&(T.input_points=m.input_points),m.input_labels&&(T.input_labels=m.input_labels),m.input_boxes&&(T.input_boxes=m.input_boxes),await ue(this.sessions.prompt_encoder_mask_decoder,T)}async _call(m){return new Bl(await super._call(m))}}class Bl extends He{constructor({iou_scores:m,pred_masks:T}){super(),this.iou_scores=m,this.pred_masks=T}}class Os extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class Ll extends Os{}class ma extends Os{}class zs extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class Rl extends zs{}class Nl extends zs{}class is extends Z{}class jl extends is{}class _a extends is{async _call(m){return new es(await super._call(m))}}class Ds extends is{async _call(m){return new or(await super._call(m))}}class Vl extends is{async _call(m){return new en(await super._call(m))}}class oi extends Z{}class Ul extends oi{}class Wl extends oi{async _call(m){return new en(await super._call(m))}}class Gl extends Z{}class Md extends Gl{}class li extends Z{}class ql extends li{}class vd extends li{async _call(m){return new es(await super._call(m))}}class ga extends li{async _call(m){return new or(await super._call(m))}}class Bs extends Z{}class Hl extends Bs{}class Kl extends Bs{async _call(m){return new es(await super._call(m))}}class Xl extends Bs{async _call(m){return new or(await super._call(m))}}class ui extends Bs{async _call(m){return new en(await super._call(m))}}class di extends Z{}class ci extends di{}class wa extends di{async _call(m){return new es(await super._call(m))}}class ya extends di{async _call(m){return new or(await super._call(m))}}class xd extends Z{}class Ql extends is{}class ba extends is{async _call(m){return new es(await super._call(m))}}class Td extends is{async _call(m){return new or(await super._call(m))}}class gs extends Z{}class Yl extends gs{}class Ed extends gs{async _call(m){return new es(await super._call(m))}}class Jl extends gs{async _call(m){return new or(await super._call(m))}}class Ma extends gs{async _call(m){return new qa(await super._call(m))}}class Cd extends gs{async _call(m){return new en(await super._call(m))}}class pi extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class $d extends pi{}class Zl extends pi{}class va extends pi{async generate_speech(m,T,{threshold:Y=.5,minlenratio:Fe=0,maxlenratio:ze=20,vocoder:ht=null}={}){const Ct={input_ids:m},{encoder_outputs:Wt,encoder_attention_mask:sr}=await tt(this,Ct),Ir=Wt.dims[1]/this.config.reduction_factor,ur=Math.floor(Ir*ze),hr=Math.floor(Ir*Fe),wr=this.config.num_mel_bins;let Sr=[],Fr=null,kr=null,_r=0;for(;;){++_r;const wn=Ie(!!kr);let cn;kr?cn=kr.output_sequence_out:cn=new A.Tensor("float32",new Float32Array(wr),[1,1,wr]);let an={use_cache_branch:wn,output_sequence:cn,encoder_attention_mask:sr,speaker_embeddings:T,encoder_hidden_states:Wt};this.addPastKeyValues(an,Fr),kr=await ue(this.sessions.decoder_model_merged,an),Fr=this.getPastKeyValues(kr,Fr);const{prob:yn,spectrum:ws}=kr;if(Sr.push(ws),_r>=hr&&(Array.from(yn.data).filter(js=>js>=Y).length>0||_r>=ur))break}const tn=(0,A.cat)(Sr),{waveform:rn}=await ue(ht.sessions.model,{spectrogram:tn});return{spectrogram:tn,waveform:rn}}}class eu extends Z{constructor(){super(...arguments);xe(this,"main_input_name","spectrogram")}}class tu extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class ru extends tu{}class xa extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class nu extends xa{}class su extends xa{}class iu extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class au extends iu{}class ou extends iu{}class Ta extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class Sd extends Ta{}class lu extends Ta{}class hi extends Z{}class uu extends hi{}class du extends hi{static async from_pretrained(m,T={}){return T.model_file_name??(T.model_file_name="text_model"),super.from_pretrained(m,T)}}class cu extends hi{static async from_pretrained(m,T={}){return T.model_file_name??(T.model_file_name="audio_model"),super.from_pretrained(m,T)}}class kd extends Z{}class Ls extends kd{async _call(m){return new Ha(await super._call(m))}}class as extends Z{}class pu extends as{}class hu extends as{}class fu extends as{}class Ea extends Z{constructor(m,T,Y){super(m,T),this.generation_config=Y}}class mu extends Ea{}class Ca extends Ea{}class $a extends Z{}class _u extends $a{}class gu extends $a{async _call(m){return new or(await super._call(m))}}class wu extends Z{}class Pd extends wu{}class yu extends wu{}class Sa extends Z{constructor(T,Y,Fe){super(T,Y);xe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}_apply_and_filter_by_delay_pattern_mask(T){const[Y,Fe]=T.dims,ze=this.config.decoder.num_codebooks,ht=Fe-ze;let Ct=0;for(let Ir=0;Ir0&&wr<=ht&&(T.data[Ct++]=T.data[Ir])}const Wt=Math.floor(Y/ze),sr=Ct/(Wt*ze);return new A.Tensor(T.type,T.data.slice(0,Ct),[Wt,ze,sr])}prepare_inputs_for_generation(T,Y,Fe){let ze=structuredClone(T);for(let Ct=0;Ct=Wt&&(ze[Ct][Wt]=BigInt(this.config.decoder.pad_token_id));return Fe.guidance_scale!==null&&Fe.guidance_scale>1&&(ze=ze.concat(ze)),super.prepare_inputs_for_generation(ze,Y,Fe)}async generate(T){const Y=await super.generate(T),Fe=this._apply_and_filter_by_delay_pattern_mask(Y).unsqueeze_(0),{audio_values:ze}=await ue(this.sessions.encodec_decode,{audio_codes:Fe});return ze}}class ka extends Z{}class bu extends ka{}class Ad extends ka{async _call(m){return new or(await super._call(m))}}class Pa extends Z{}class Mu extends Pa{}class Id extends Pa{async _call(m){return new or(await super._call(m))}}class Aa extends Z{}class vu extends Aa{}class xu extends Aa{async _call(m){return new or(await super._call(m))}}class Ia extends Z{}class Fd extends Ia{}class Tu extends Ia{async _call(m){return new or(await super._call(m))}}class Eu extends Z{}class Cu extends Eu{}class Dr{static async from_pretrained(m,{progress_callback:T=null,config:Y=null,cache_dir:Fe=null,local_files_only:ze=!1,revision:ht="main",model_file_name:Ct=null,subfolder:Wt="onnx",device:sr=null,dtype:Ir=null,use_external_data_format:ur=null,session_options:hr={}}={}){const wr={progress_callback:T,config:Y,cache_dir:Fe,local_files_only:ze,revision:ht,model_file_name:Ct,subfolder:Wt,device:sr,dtype:Ir,use_external_data_format:ur,session_options:hr};if(wr.config=await O.AutoConfig.from_pretrained(m,wr),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const Sr of this.MODEL_CLASS_MAPPINGS){const Fr=Sr.get(wr.config.model_type);if(Fr)return await Fr[1].from_pretrained(m,wr)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${wr.config.model_type}", attempting to construct from base class.`),await Z.from_pretrained(m,wr);throw Error(`Unsupported model type: ${wr.config.model_type}`)}}xe(Dr,"MODEL_CLASS_MAPPINGS",null),xe(Dr,"BASE_IF_FAIL",!1);const wc=new Map([["bert",["BertModel",lt]],["nomic_bert",["NomicBertModel",ke]],["roformer",["RoFormerModel",qe]],["electra",["ElectraModel",Qe]],["esm",["EsmModel",Ht]],["convbert",["ConvBertModel",kt]],["camembert",["CamembertModel",Ot]],["deberta",["DebertaModel",at]],["deberta-v2",["DebertaV2Model",Je]],["mpnet",["MPNetModel",Ys]],["albert",["AlbertModel",rs]],["distilbert",["DistilBertModel",Nt]],["roberta",["RobertaModel",pr]],["xlm",["XLMModel",sn]],["xlm-roberta",["XLMRobertaModel",Cr]],["clap",["ClapModel",uu]],["clip",["CLIPModel",no]],["clipseg",["CLIPSegModel",co]],["chinese_clip",["ChineseCLIPModel",uo]],["siglip",["SiglipModel",io]],["mobilebert",["MobileBertModel",Tr]],["squeezebert",["SqueezeBertModel",Js]],["wav2vec2",["Wav2Vec2Model",jl]],["wav2vec2-bert",["Wav2Vec2BertModel",ci]],["unispeech",["UniSpeechModel",ql]],["unispeech-sat",["UniSpeechSatModel",Hl]],["hubert",["HubertModel",Ql]],["wavlm",["WavLMModel",Yl]],["audio-spectrogram-transformer",["ASTModel",jt]],["vits",["VitsModel",Ls]],["pyannote",["PyAnnoteModel",Ul]],["wespeaker-resnet",["WeSpeakerResNetModel",Md]],["detr",["DetrModel",ol]],["rt_detr",["RTDetrModel",dl]],["table-transformer",["TableTransformerModel",ra]],["vit",["ViTModel",Ro]],["pvt",["PvtModel",wd]],["vit_msn",["ViTMSNModel",Go]],["vit_mae",["ViTMAEModel",Uo]],["groupvit",["GroupViTModel",Ho]],["fastvit",["FastViTModel",Ko]],["mobilevit",["MobileViTModel",Jo]],["mobilevitv2",["MobileViTV2Model",el]],["owlvit",["OwlViTModel",Is]],["owlv2",["Owlv2Model",nl]],["beit",["BeitModel",il]],["deit",["DeiTModel",fl]],["hiera",["HieraModel",_l]],["convnext",["ConvNextModel",Yn]],["convnextv2",["ConvNextV2Model",pa]],["dinov2",["Dinov2Model",ha]],["resnet",["ResNetModel",aa]],["swin",["SwinModel",yl]],["swin2sr",["Swin2SRModel",bl]],["donut-swin",["DonutSwinModel",Il]],["yolos",["YolosModel",Ol]],["dpt",["DPTModel",Ml]],["glpn",["GLPNModel",kl]],["hifigan",["SpeechT5HifiGan",eu]],["efficientnet",["EfficientNetModel",_u]],["decision_transformer",["DecisionTransformerModel",Cu]],["mobilenet_v1",["MobileNetV1Model",bu]],["mobilenet_v2",["MobileNetV2Model",Mu]],["mobilenet_v3",["MobileNetV3Model",vu]],["mobilenet_v4",["MobileNetV4Model",Fd]],["maskformer",["MaskFormerModel",bd]]]),Od=new Map([["t5",["T5Model",Cs]],["longt5",["LongT5Model",Ss]],["mt5",["MT5Model",Ps]],["bart",["BartModel",be]],["mbart",["MBartModel",ae]],["marian",["MarianModel",Ll]],["whisper",["WhisperModel",Ut]],["m2m_100",["M2M100Model",Rl]],["blenderbot",["BlenderbotModel",Mt]],["blenderbot-small",["BlenderbotSmallModel",zr]]]),zd=new Map([["bloom",["BloomModel",zo]],["jais",["JAISModel",fo]],["gpt2",["GPT2Model",ho]],["gptj",["GPTJModel",gd]],["gpt_bigcode",["GPTBigCodeModel",ei]],["gpt_neo",["GPTNeoModel",_o]],["gpt_neox",["GPTNeoXModel",wo]],["codegen",["CodeGenModel",bo]],["llama",["LlamaModel",vo]],["cohere",["CohereModel",To]],["gemma",["GemmaModel",Co]],["gemma2",["Gemma2Model",$o]],["openelm",["OpenELMModel",ko]],["qwen2",["Qwen2Model",Ao]],["phi",["PhiModel",Li]],["phi3",["Phi3Model",Fo]],["mpt",["MptModel",Bo]],["opt",["OPTModel",Lo]],["mistral",["MistralModel",nu]],["starcoder2",["Starcoder2Model",au]],["falcon",["FalconModel",Sd]],["stablelm",["StableLmModel",mu]]]),Fa=new Map([["speecht5",["SpeechT5ForSpeechToText",Zl]],["whisper",["WhisperForConditionalGeneration",bi]]]),$u=new Map([["speecht5",["SpeechT5ForTextToSpeech",va]]]),Dd=new Map([["vits",["VitsModel",Ls]],["musicgen",["MusicgenForConditionalGeneration",Sa]]]),Su=new Map([["bert",["BertForSequenceClassification",st]],["roformer",["RoFormerForSequenceClassification",Ke]],["electra",["ElectraForSequenceClassification",Bt]],["esm",["EsmForSequenceClassification",Lr]],["convbert",["ConvBertForSequenceClassification",q]],["camembert",["CamembertForSequenceClassification",xr]],["deberta",["DebertaForSequenceClassification",_e]],["deberta-v2",["DebertaV2ForSequenceClassification",mt]],["mpnet",["MPNetForSequenceClassification",xs]],["albert",["AlbertForSequenceClassification",ps]],["distilbert",["DistilBertForSequenceClassification",Rt]],["roberta",["RobertaForSequenceClassification",ln]],["xlm",["XLMForSequenceClassification",Qt]],["xlm-roberta",["XLMRobertaForSequenceClassification",br]],["bart",["BartForSequenceClassification",P]],["mbart",["MBartForSequenceClassification",Be]],["mobilebert",["MobileBertForSequenceClassification",Rr]],["squeezebert",["SqueezeBertForSequenceClassification",Ln]]]),ku=new Map([["bert",["BertForTokenClassification",Pt]],["roformer",["RoFormerForTokenClassification",ut]],["electra",["ElectraForTokenClassification",ft]],["esm",["EsmForTokenClassification",mr]],["convbert",["ConvBertForTokenClassification",C]],["camembert",["CamembertForTokenClassification",Yr]],["deberta",["DebertaForTokenClassification",Pe]],["deberta-v2",["DebertaV2ForTokenClassification",Et]],["mpnet",["MPNetForTokenClassification",Ts]],["distilbert",["DistilBertForTokenClassification",Gt]],["roberta",["RobertaForTokenClassification",Oe]],["xlm",["XLMForTokenClassification",Tn]],["xlm-roberta",["XLMRobertaForTokenClassification",Gr]]]),Oa=new Map([["t5",["T5ForConditionalGeneration",$s]],["longt5",["LongT5ForConditionalGeneration",ks]],["mt5",["MT5ForConditionalGeneration",Wr]],["bart",["BartForConditionalGeneration",_]],["mbart",["MBartForConditionalGeneration",pe]],["marian",["MarianMTModel",ma]],["m2m_100",["M2M100ForConditionalGeneration",Nl]],["blenderbot",["BlenderbotForConditionalGeneration",zt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ir]]]),za=new Map([["bloom",["BloomForCausalLM",Do]],["gpt2",["GPT2LMHeadModel",Fn]],["jais",["JAISLMHeadModel",mo]],["gptj",["GPTJForCausalLM",On]],["gpt_bigcode",["GPTBigCodeForCausalLM",Pi]],["gpt_neo",["GPTNeoForCausalLM",go]],["gpt_neox",["GPTNeoXForCausalLM",yo]],["codegen",["CodeGenForCausalLM",Mo]],["llama",["LlamaForCausalLM",xo]],["cohere",["CohereForCausalLM",Eo]],["gemma",["GemmaForCausalLM",zn]],["gemma2",["Gemma2ForCausalLM",So]],["openelm",["OpenELMForCausalLM",Po]],["qwen2",["Qwen2ForCausalLM",Io]],["phi",["PhiForCausalLM",Ri]],["phi3",["Phi3ForCausalLM",ji]],["mpt",["MptForCausalLM",As]],["opt",["OPTForCausalLM",Wi]],["mbart",["MBartForCausalLM",wt]],["mistral",["MistralForCausalLM",su]],["starcoder2",["Starcoder2ForCausalLM",ou]],["falcon",["FalconForCausalLM",lu]],["trocr",["TrOCRForCausalLM",ru]],["stablelm",["StableLmForCausalLM",Ca]]]),Bd=new Map([["bert",["BertForMaskedLM",Ne]],["roformer",["RoFormerForMaskedLM",Ue]],["electra",["ElectraForMaskedLM",Ye]],["esm",["EsmForMaskedLM",gr]],["convbert",["ConvBertForMaskedLM",v]],["camembert",["CamembertForMaskedLM",cr]],["deberta",["DebertaForMaskedLM",U]],["deberta-v2",["DebertaV2ForMaskedLM",gt]],["mpnet",["MPNetForMaskedLM",vs]],["albert",["AlbertForMaskedLM",Xt]],["distilbert",["DistilBertForMaskedLM",Ze]],["roberta",["RobertaForMaskedLM",mn]],["xlm",["XLMWithLMHeadModel",xn]],["xlm-roberta",["XLMRobertaForMaskedLM",It]],["mobilebert",["MobileBertForMaskedLM",$n]],["squeezebert",["SqueezeBertForMaskedLM",cs]]]),_n=new Map([["bert",["BertForQuestionAnswering",Re]],["roformer",["RoFormerForQuestionAnswering",yt]],["electra",["ElectraForQuestionAnswering",Tt]],["convbert",["ConvBertForQuestionAnswering",Q]],["camembert",["CamembertForQuestionAnswering",Br]],["deberta",["DebertaForQuestionAnswering",rt]],["deberta-v2",["DebertaV2ForQuestionAnswering",_t]],["mpnet",["MPNetForQuestionAnswering",Es]],["albert",["AlbertForQuestionAnswering",hs]],["distilbert",["DistilBertForQuestionAnswering",Me]],["roberta",["RobertaForQuestionAnswering",Sn]],["xlm",["XLMForQuestionAnswering",pn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Xr]],["mobilebert",["MobileBertForQuestionAnswering",Hn]],["squeezebert",["SqueezeBertForQuestionAnswering",Xn]]]),Da=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Mi]]]),Ld=new Map([["llava",["LlavaForConditionalGeneration",_s]],["moondream1",["Moondream1ForConditionalGeneration",ar]],["florence2",["Florence2ForConditionalGeneration",vi]]]),Pu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Mi]]]),Au=new Map([["vit",["ViTForImageClassification",No]],["pvt",["PvtForImageClassification",jo]],["vit_msn",["ViTMSNForImageClassification",$r]],["fastvit",["FastViTForImageClassification",Xo]],["mobilevit",["MobileViTForImageClassification",Zo]],["mobilevitv2",["MobileViTV2ForImageClassification",tl]],["beit",["BeitForImageClassification",al]],["deit",["DeiTForImageClassification",ml]],["hiera",["HieraForImageClassification",gl]],["convnext",["ConvNextForImageClassification",Jn]],["convnextv2",["ConvNextV2ForImageClassification",Zn]],["dinov2",["Dinov2ForImageClassification",si]],["resnet",["ResNetForImageClassification",wl]],["swin",["SwinForImageClassification",yd]],["segformer",["SegformerForImageClassification",hu]],["efficientnet",["EfficientNetForImageClassification",gu]],["mobilenet_v1",["MobileNetV1ForImageClassification",Ad]],["mobilenet_v2",["MobileNetV2ForImageClassification",Id]],["mobilenet_v3",["MobileNetV3ForImageClassification",xu]],["mobilenet_v4",["MobileNetV4ForImageClassification",Tu]]]),Rs=new Map([["detr",["DetrForObjectDetection",ll]],["rt_detr",["RTDetrForObjectDetection",cl]],["table-transformer",["TableTransformerForObjectDetection",hl]],["yolos",["YolosForObjectDetection",zl]]]),Iu=new Map([["owlvit",["OwlViTForObjectDetection",rl]],["owlv2",["Owlv2ForObjectDetection",sl]]]),Fu=new Map([["detr",["DetrForSegmentation",Ji]],["clipseg",["CLIPSegForImageSegmentation",po]]]),Ba=new Map([["segformer",["SegformerForSemanticSegmentation",fu]],["sapiens",["SapiensForSemanticSegmentation",El]]]),Ou=new Map([["detr",["DetrForSegmentation",Ji]],["maskformer",["MaskFormerForInstanceSegmentation",Sl]]]),zu=new Map([["sam",["SamModel",fa]]]),La=new Map([["wav2vec2",["Wav2Vec2ForCTC",_a]],["wav2vec2-bert",["Wav2Vec2BertForCTC",wa]],["unispeech",["UniSpeechForCTC",vd]],["unispeech-sat",["UniSpeechSatForCTC",Kl]],["wavlm",["WavLMForCTC",Ed]],["hubert",["HubertForCTC",ba]]]),Du=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Ds]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",ya]],["unispeech",["UniSpeechForSequenceClassification",ga]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Xl]],["wavlm",["WavLMForSequenceClassification",Jl]],["hubert",["HubertForSequenceClassification",Td]],["audio-spectrogram-transformer",["ASTForAudioClassification",Zs]]]),Bu=new Map([["wavlm",["WavLMForXVector",Ma]]]),Lu=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",ui]],["wavlm",["WavLMForAudioFrameClassification",Cd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Vl]],["pyannote",["PyAnnoteForAudioFrameClassification",Wl]]]),Ra=new Map([["vitmatte",["VitMatteForImageMatting",Yo]]]),Ru=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Dn]]]),Nu=new Map([["dpt",["DPTForDepthEstimation",vl]],["depth_anything",["DepthAnythingForDepthEstimation",Tl]],["glpn",["GLPNForDepthEstimation",Pl]],["sapiens",["SapiensForDepthEstimation",Cl]]]),Na=new Map([["sapiens",["SapiensForNormalEstimation",$l]]]),ju=new Map([["clip",["CLIPVisionModelWithProjection",so]],["siglip",["SiglipVisionModel",oo]]]),Rd=[[wc,te.EncoderOnly],[Od,te.EncoderDecoder],[zd,te.DecoderOnly],[Su,te.EncoderOnly],[ku,te.EncoderOnly],[Oa,te.Seq2Seq],[Fa,te.Seq2Seq],[za,te.DecoderOnly],[Bd,te.EncoderOnly],[_n,te.EncoderOnly],[Da,te.Vision2Seq],[Ld,te.ImageTextToText],[Au,te.EncoderOnly],[Fu,te.EncoderOnly],[Ou,te.EncoderOnly],[Ba,te.EncoderOnly],[Ra,te.EncoderOnly],[Ru,te.EncoderOnly],[Nu,te.EncoderOnly],[Na,te.EncoderOnly],[Rs,te.EncoderOnly],[Iu,te.EncoderOnly],[zu,te.MaskGeneration],[La,te.EncoderOnly],[Du,te.EncoderOnly],[$u,te.Seq2Seq],[Dd,te.EncoderOnly],[Bu,te.EncoderOnly],[Lu,te.EncoderOnly],[ju,te.EncoderOnly]];for(const[f,m]of Rd)for(const[T,Y]of f.values())se.set(T,m),R.set(Y,T),X.set(T,Y);const Vu=[["MusicgenForConditionalGeneration",Sa,te.Musicgen],["CLIPTextModelWithProjection",In,te.EncoderOnly],["SiglipTextModel",ao,te.EncoderOnly],["ClapTextModelWithProjection",du,te.EncoderOnly],["ClapAudioModelWithProjection",cu,te.EncoderOnly]];for(const[f,m,T]of Vu)se.set(f,T),R.set(m,f),X.set(f,m);class ja extends Dr{}xe(ja,"MODEL_CLASS_MAPPINGS",Rd.map(m=>m[0])),xe(ja,"BASE_IF_FAIL",!0);class Uu extends Dr{}xe(Uu,"MODEL_CLASS_MAPPINGS",[Su]);class Wu extends Dr{}xe(Wu,"MODEL_CLASS_MAPPINGS",[ku]);class Nd extends Dr{}xe(Nd,"MODEL_CLASS_MAPPINGS",[Oa]);class Gu extends Dr{}xe(Gu,"MODEL_CLASS_MAPPINGS",[Fa]);class qu extends Dr{}xe(qu,"MODEL_CLASS_MAPPINGS",[$u]);class Hu extends Dr{}xe(Hu,"MODEL_CLASS_MAPPINGS",[Dd]);class jd extends Dr{}xe(jd,"MODEL_CLASS_MAPPINGS",[za]);class Ku extends Dr{}xe(Ku,"MODEL_CLASS_MAPPINGS",[Bd]);class Xu extends Dr{}xe(Xu,"MODEL_CLASS_MAPPINGS",[_n]);class Qu extends Dr{}xe(Qu,"MODEL_CLASS_MAPPINGS",[Da]);class Yu extends Dr{}xe(Yu,"MODEL_CLASS_MAPPINGS",[Au]);class Vd extends Dr{}xe(Vd,"MODEL_CLASS_MAPPINGS",[Fu]);class Ju extends Dr{}xe(Ju,"MODEL_CLASS_MAPPINGS",[Ba]);class Zu extends Dr{}xe(Zu,"MODEL_CLASS_MAPPINGS",[Ou]);class ed extends Dr{}xe(ed,"MODEL_CLASS_MAPPINGS",[Rs]);class td extends Dr{}xe(td,"MODEL_CLASS_MAPPINGS",[Iu]);class rd extends Dr{}xe(rd,"MODEL_CLASS_MAPPINGS",[zu]);class nd extends Dr{}xe(nd,"MODEL_CLASS_MAPPINGS",[La]);class sd extends Dr{}xe(sd,"MODEL_CLASS_MAPPINGS",[Du]);class id extends Dr{}xe(id,"MODEL_CLASS_MAPPINGS",[Bu]);class ad extends Dr{}xe(ad,"MODEL_CLASS_MAPPINGS",[Lu]);class Ud extends Dr{}xe(Ud,"MODEL_CLASS_MAPPINGS",[Pu]);class Ns extends Dr{}xe(Ns,"MODEL_CLASS_MAPPINGS",[Ra]);class Va extends Dr{}xe(Va,"MODEL_CLASS_MAPPINGS",[Ru]);class Ua extends Dr{}xe(Ua,"MODEL_CLASS_MAPPINGS",[Nu]);class Wa extends Dr{}xe(Wa,"MODEL_CLASS_MAPPINGS",[Na]);class Ga extends Dr{}xe(Ga,"MODEL_CLASS_MAPPINGS",[ju]);class Wd extends He{constructor({logits:m,past_key_values:T,encoder_outputs:Y,decoder_attentions:Fe=null,cross_attentions:ze=null}){super(),this.logits=m,this.past_key_values=T,this.encoder_outputs=Y,this.decoder_attentions=Fe,this.cross_attentions=ze}}class or extends He{constructor({logits:m}){super(),this.logits=m}}class qa extends He{constructor({logits:m,embeddings:T}){super(),this.logits=m,this.embeddings=T}}class en extends He{constructor({logits:m}){super(),this.logits=m}}class dn extends He{constructor({logits:m}){super(),this.logits=m}}class hn extends He{constructor({start_logits:m,end_logits:T}){super(),this.start_logits=m,this.end_logits=T}}class es extends He{constructor({logits:m}){super(),this.logits=m}}class Gd extends He{constructor({logits:m,past_key_values:T}){super(),this.logits=m,this.past_key_values=T}}class od extends He{constructor({alphas:m}){super(),this.alphas=m}}class Ha extends He{constructor({waveform:m,spectrogram:T}){super(),this.waveform=m,this.spectrogram=T}}},"./src/models/whisper/common_whisper.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{WHISPER_LANGUAGE_MAPPING:()=>fe,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>ye,whisper_language_to_code:()=>Te});const O=[["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"]],fe=new Map(O),ye=new Map([...O.map(([Ce,j])=>[j,Ce]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Te(Ce){Ce=Ce.toLowerCase();let j=ye.get(Ce);if(j===void 0)if(fe.has(Ce))j=Ce;else{const V=Ce.length===2?fe.keys():fe.values();throw new Error(`Language "${Ce}" is not supported. Must be one of: ${JSON.stringify(V)}`)}return j}},"./src/models/whisper/generation_whisper.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{WhisperGenerationConfig:()=>fe});var O=N("./src/generation/configuration_utils.js");class fe extends O.GenerationConfig{constructor(){super(...arguments);xe(this,"return_timestamps",null);xe(this,"return_token_timestamps",null);xe(this,"num_frames",null);xe(this,"alignment_heads",null);xe(this,"task",null);xe(this,"language",null);xe(this,"no_timestamps_token_id",null);xe(this,"prompt_ids",null);xe(this,"is_multilingual",null);xe(this,"lang_to_id",null);xe(this,"task_to_id",null);xe(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{TensorOpRegistry:()=>Te});var O=N("./src/backends/onnx.js"),fe=N("./src/utils/tensor.js");const ye=async(Ce,j,S)=>{const V=await(0,O.createInferenceSession)(new Uint8Array(Ce),j);return async A=>{const ee=Object.fromEntries(Object.entries(A).map(([me,ce])=>[me,ce.ort_tensor])),ne=await V.run(ee);return Array.isArray(S)?S.map(me=>new fe.Tensor(ne[me])):new fe.Tensor(ne[S])}};class Te{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=ye([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=ye([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=ye([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=ye([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=ye([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=ye([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}}xe(Te,"session_options",{})},"./src/pipelines.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{AudioClassificationPipeline:()=>Ie,AutomaticSpeechRecognitionPipeline:()=>tt,DepthEstimationPipeline:()=>nt,DocumentQuestionAnsweringPipeline:()=>Z,FeatureExtractionPipeline:()=>ve,FillMaskPipeline:()=>se,ImageClassificationPipeline:()=>dt,ImageFeatureExtractionPipeline:()=>$e,ImageSegmentationPipeline:()=>ge,ImageToImagePipeline:()=>ct,ImageToTextPipeline:()=>Xe,ObjectDetectionPipeline:()=>de,Pipeline:()=>ce,QuestionAnsweringPipeline:()=>te,SummarizationPipeline:()=>R,Text2TextGenerationPipeline:()=>X,TextClassificationPipeline:()=>D,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>He,TokenClassificationPipeline:()=>H,TranslationPipeline:()=>I,ZeroShotAudioClassificationPipeline:()=>Ae,ZeroShotClassificationPipeline:()=>ue,ZeroShotImageClassificationPipeline:()=>G,ZeroShotObjectDetectionPipeline:()=>Se,pipeline:()=>st});var O=N("./src/tokenizers.js"),fe=N("./src/models.js"),ye=N("./src/processors.js"),Te=N("./src/utils/generic.js"),Ce=N("./src/utils/core.js"),j=N("./src/utils/maths.js"),S=N("./src/utils/audio.js"),V=N("./src/utils/tensor.js"),A=N("./src/utils/image.js");async function ee(Re){return Array.isArray(Re)||(Re=[Re]),await Promise.all(Re.map(re=>A.RawImage.read(re)))}async function ne(Re,re){return Array.isArray(Re)||(Re=[Re]),await Promise.all(Re.map(ke=>typeof ke=="string"||ke instanceof URL?(0,S.read_audio)(ke,re):ke instanceof Float64Array?new Float32Array(ke):ke))}function me(Re,re){re&&(Re=Re.map(Ke=>Ke|0));const[ke,je,qe,Ue]=Re;return{xmin:ke,ymin:je,xmax:qe,ymax:Ue}}class ce extends Te.Callable{constructor({task:re,model:ke,tokenizer:je=null,processor:qe=null}){super(),this.task=re,this.model=ke,this.tokenizer=je,this.processor=qe}async dispose(){await this.model.dispose()}}class D extends ce{constructor(re){super(re)}async _call(re,{top_k:ke=1}={}){const je=this.tokenizer(re,{padding:!0,truncation:!0}),qe=await this.model(je),Ue=this.model.config.problem_type==="multi_label_classification"?yt=>yt.sigmoid():yt=>new V.Tensor("float32",(0,j.softmax)(yt.data),yt.dims),Ke=this.model.config.id2label,ut=[];for(const yt of qe.logits){const vt=Ue(yt),kt=await(0,V.topk)(vt,ke),v=kt[0].tolist(),C=kt[1].tolist().map((Q,he)=>({label:Ke?Ke[Q]:`LABEL_${Q}`,score:v[he]}));ke===1?ut.push(...C):ut.push(C)}return Array.isArray(re)||ke===1?ut:ut[0]}}class H extends ce{constructor(re){super(re)}async _call(re,{ignore_labels:ke=["O"]}={}){const je=Array.isArray(re),qe=this.tokenizer(je?re:[re],{padding:!0,truncation:!0}),Ke=(await this.model(qe)).logits,ut=this.model.config.id2label,yt=[];for(let vt=0;vtft==this.tokenizer.sep_token_id);yt[v].map((ft,Tt)=>ft==1&&(Tt===0||Tt>C&&vt.findIndex(bt=>bt==q[Tt])===-1));const Q=Ue[v].tolist(),he=Ke[v].tolist();for(let ft=1;ftTt==q[ft])!==-1)&&(Q[ft]=-1/0,he[ft]=-1/0);const Qe=(0,j.softmax)(Q).map((ft,Tt)=>[ft,Tt]),Ye=(0,j.softmax)(he).map((ft,Tt)=>[ft,Tt]);Qe[0][0]=0,Ye[0][0]=0;const Bt=(0,Ce.product)(Qe,Ye).filter(ft=>ft[0][1]<=ft[1][1]).map(ft=>[ft[0][1],ft[1][1],ft[0][0]*ft[1][0]]).sort((ft,Tt)=>Tt[2]-ft[2]);for(let ft=0;ftQ==this.tokenizer.mask_token_id);if(vt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const kt=qe[ut][vt],v=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(kt.data),kt.dims),ke),q=v[0].tolist(),C=v[1].tolist();Ue.push(C.map((Q,he)=>{const Qe=yt.slice();return Qe[vt]=Q,{score:q[he],token:Number(Q),token_str:this.tokenizer.model.vocab[Q],sequence:this.tokenizer.decode(Qe,{skip_special_tokens:!0})}}))}return Array.isArray(re)?Ue:Ue[0]}}class X extends ce{constructor(ke){super(ke);xe(this,"_key","generated_text")}async _call(ke,je={}){Array.isArray(ke)||(ke=[ke]),this.model.config.prefix&&(ke=ke.map(vt=>this.model.config.prefix+vt));const qe=this.model.config.task_specific_params;qe&&qe[this.task]&&qe[this.task].prefix&&(ke=ke.map(vt=>qe[this.task].prefix+vt));const Ue=this.tokenizer,Ke={padding:!0,truncation:!0};let ut;this instanceof I&&"_build_translation_inputs"in Ue?ut=Ue._build_translation_inputs(ke,Ke,je):ut=Ue(ke,Ke);const yt=await this.model.generate({...ut,...je});return Ue.batch_decode(yt,{skip_special_tokens:!0}).map(vt=>({[this._key]:vt}))}}class R extends X{constructor(ke){super(ke);xe(this,"_key","summary_text")}}class I extends X{constructor(ke){super(ke);xe(this,"_key","translation_text")}}function B(Re){return Array.isArray(Re)&&Re.every(re=>"role"in re&&"content"in re)}class k extends ce{constructor(re){super(re)}async _call(re,ke={}){let je=!1,qe=!1,Ue;if(typeof re=="string")Ue=re=[re];else if(Array.isArray(re)&&re.every(C=>typeof C=="string"))je=!0,Ue=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");qe=!0,Ue=re.map(C=>this.tokenizer.apply_chat_template(C,{tokenize:!1,add_generation_prompt:!0}))}const Ke=ke.add_special_tokens??!1,ut=qe?!1:ke.return_full_text??!0;this.tokenizer.padding_side="left";const yt=this.tokenizer(Ue,{add_special_tokens:Ke,padding:!0,truncation:!0}),vt=await this.model.generate({...yt,...ke}),kt=this.tokenizer.batch_decode(vt,{skip_special_tokens:!0});let v;!ut&&yt.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(yt.input_ids,{skip_special_tokens:!0}).map(C=>C.length));const q=Array.from({length:re.length},C=>[]);for(let C=0;C[ke.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,ke,{hypothesis_template:je="This example is {}.",multi_label:qe=!1}={}){const Ue=Array.isArray(re);Ue||(re=[re]),Array.isArray(ke)||(ke=[ke]);const Ke=ke.map(vt=>je.replace("{}",vt)),ut=qe||ke.length===1,yt=[];for(const vt of re){const kt=[];for(const C of Ke){const Q=this.tokenizer(vt,{text_pair:C,padding:!0,truncation:!0}),he=await this.model(Q);ut?kt.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):kt.push(he.logits.data[this.entailment_id])}const q=(ut?kt.map(C=>(0,j.softmax)(C)[1]):(0,j.softmax)(kt)).map((C,Q)=>[C,Q]).sort((C,Q)=>Q[0]-C[0]);yt.push({sequence:vt,labels:q.map(C=>ke[C[1]]),scores:q.map(C=>C[0])})}return Ue?yt:yt[0]}}class ve extends ce{constructor(re){super(re)}async _call(re,{pooling:ke="none",normalize:je=!1,quantize:qe=!1,precision:Ue="binary"}={}){const Ke=this.tokenizer(re,{padding:!0,truncation:!0}),ut=await this.model(Ke);let yt=ut.last_hidden_state??ut.logits??ut.token_embeddings;if(ke!=="none")if(ke==="mean")yt=(0,V.mean_pooling)(yt,Ke.attention_mask);else if(ke==="cls")yt=yt.slice(null,0);else throw Error(`Pooling method '${ke}' not supported.`);return je&&(yt=yt.normalize(2,-1)),qe&&(yt=(0,V.quantize_embeddings)(yt,Ue)),yt}}class $e extends ce{constructor(re){super(re)}async _call(re,{pool:ke=null}={}){const je=await ee(re),{pixel_values:qe}=await this.processor(je),Ue=await this.model({pixel_values:qe});let Ke;if(ke){if(!("pooler_output"in Ue))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ke=Ue.pooler_output}else Ke=Ue.last_hidden_state??Ue.logits??Ue.image_embeds;return Ke}}class Ie extends ce{constructor(re){super(re)}async _call(re,{top_k:ke=5}={}){const je=this.processor.feature_extractor.config.sampling_rate,qe=await ne(re,je),Ue=this.model.config.id2label,Ke=[];for(const ut of qe){const yt=await this.processor(ut),kt=(await this.model(yt)).logits[0],v=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(kt.data),kt.dims),ke),q=v[0].tolist(),Q=v[1].tolist().map((he,Qe)=>({label:Ue?Ue[he]:`LABEL_${he}`,score:q[Qe]}));Ke.push(Q)}return Array.isArray(re)?Ke:Ke[0]}}class Ae extends ce{constructor(re){super(re)}async _call(re,ke,{hypothesis_template:je="This is a sound of {}."}={}){const qe=!Array.isArray(re);qe&&(re=[re]);const Ue=ke.map(kt=>je.replace("{}",kt)),Ke=this.tokenizer(Ue,{padding:!0,truncation:!0}),ut=this.processor.feature_extractor.config.sampling_rate,yt=await ne(re,ut),vt=[];for(const kt of yt){const v=await this.processor(kt),q=await this.model({...Ke,...v}),C=(0,j.softmax)(q.logits_per_audio.data);vt.push([...C].map((Q,he)=>({score:Q,label:ke[he]})))}return qe?vt[0]:vt}}class tt extends ce{constructor(re){super(re)}async _call(re,ke={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(re,ke);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(re,ke);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(re,ke){ke.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ke.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const je=!Array.isArray(re);je&&(re=[re]);const qe=this.processor.feature_extractor.config.sampling_rate,Ue=await ne(re,qe),Ke=[];for(const ut of Ue){const yt=await this.processor(ut),kt=(await this.model(yt)).logits[0],v=[];for(const C of kt)v.push((0,j.max)(C.data)[1]);const q=this.tokenizer.decode(v);Ke.push({text:q})}return je?Ke[0]:Ke}async _call_whisper(re,ke){const je=ke.return_timestamps??!1,qe=ke.chunk_length_s??0,Ue=ke.force_full_sequences??!1;let Ke=ke.stride_length_s??null;const ut={...ke};je==="word"&&(ut.return_token_timestamps=!0,ut.return_timestamps=!1);const yt=!Array.isArray(re);yt&&(re=[re]);const vt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,kt=this.processor.feature_extractor.config.hop_length,v=this.processor.feature_extractor.config.sampling_rate,q=await ne(re,v),C=[];for(const Q of q){let he=[];if(qe>0){if(Ke===null)Ke=qe/6;else if(qe<=Ke)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Bt=v*qe,ft=v*Ke,Tt=Bt-2*ft;let bt=0;for(;;){const Ot=bt+Bt,cr=Q.subarray(bt,Ot),xr=await this.processor(cr),Yr=bt===0,Br=Ot>=Q.length;if(he.push({stride:[cr.length,Yr?0:ft,Br?0:ft],input_features:xr.input_features,is_last:Br}),Br)break;bt+=Tt}}else he=[{stride:[Q.length,0,0],input_features:(await this.processor(Q)).input_features,is_last:!0}];for(const Bt of he){ut.num_frames=Math.floor(Bt.stride[0]/kt);const ft=await this.model.generate({inputs:Bt.input_features,...ut});je==="word"?(Bt.tokens=ft.sequences.tolist()[0],Bt.token_timestamps=ft.token_timestamps.tolist()[0].map(Tt=>(0,j.round)(Tt,2))):Bt.tokens=ft[0].tolist(),Bt.stride=Bt.stride.map(Tt=>Tt/v)}const[Qe,Ye]=this.tokenizer._decode_asr(he,{time_precision:vt,return_timestamps:je,force_full_sequences:Ue});C.push({text:Qe,...Ye})}return yt?C[0]:C}}class Xe extends ce{constructor(re){super(re)}async _call(re,ke={}){const je=Array.isArray(re),qe=await ee(re),{pixel_values:Ue}=await this.processor(qe),Ke=[];for(const ut of Ue){ut.dims=[1,...ut.dims];const yt=await this.model.generate({inputs:ut,...ke}),vt=this.tokenizer.batch_decode(yt,{skip_special_tokens:!0}).map(kt=>({generated_text:kt.trim()}));Ke.push(vt)}return je?Ke:Ke[0]}}class dt extends ce{constructor(re){super(re)}async _call(re,{top_k:ke=5}={}){const je=await ee(re),{pixel_values:qe}=await this.processor(je),Ue=await this.model({pixel_values:qe}),Ke=this.model.config.id2label,ut=[];for(const yt of Ue.logits){const vt=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(yt.data),yt.dims),ke),kt=vt[0].tolist(),q=vt[1].tolist().map((C,Q)=>({label:Ke?Ke[C]:`LABEL_${C}`,score:kt[Q]}));ut.push(q)}return Array.isArray(re)?ut:ut[0]}}class ge extends ce{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:ke=.5,mask_threshold:je=.5,overlap_mask_area_threshold:qe=.8,label_ids_to_fuse:Ue=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 vt=await ee(re),kt=vt.map(Ye=>[Ye.height,Ye.width]),{pixel_values:v,pixel_mask:q}=await this.processor(vt),C=await this.model({pixel_values:v,pixel_mask:q});let Q=null;if(ut!==null)Q=this.subtasks_mapping[ut];else for(let[Ye,Bt]of Object.entries(this.subtasks_mapping))if(Bt in this.processor.feature_extractor){Q=this.processor.feature_extractor[Bt].bind(this.processor.feature_extractor),ut=Ye;break}const he=this.model.config.id2label,Qe=[];if(ut==="panoptic"||ut==="instance"){const Ye=Q(C,ke,je,qe,Ue,Ke??kt)[0],Bt=Ye.segmentation;for(const ft of Ye.segments_info){const Tt=new Uint8ClampedArray(Bt.data.length);for(let Ot=0;Otje.replace("{}",q)),ut=this.tokenizer(Ke,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:yt}=await this.processor(Ue),vt=await this.model({...ut,pixel_values:yt}),kt=this.model.config.model_type==="siglip"?q=>q.sigmoid().data:q=>(0,j.softmax)(q.data),v=[];for(const q of vt.logits_per_image){const Q=[...kt(q)].map((he,Qe)=>({score:he,label:ke[Qe]}));Q.sort((he,Qe)=>Qe.score-he.score),v.push(Q)}return qe?v:v[0]}}class de extends ce{constructor(re){super(re)}async _call(re,{threshold:ke=.9,percentage:je=!1}={}){const qe=Array.isArray(re);if(qe&&re.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ue=await ee(re),Ke=je?null:Ue.map(C=>[C.height,C.width]),{pixel_values:ut,pixel_mask:yt}=await this.processor(Ue),vt=await this.model({pixel_values:ut,pixel_mask:yt}),kt=this.processor.feature_extractor.post_process_object_detection(vt,ke,Ke),v=this.model.config.id2label,q=kt.map(C=>C.boxes.map((Q,he)=>({score:C.scores[he],label:v[C.classes[he]],box:me(Q,!je)})));return qe?q:q[0]}}class Se extends ce{constructor(re){super(re)}async _call(re,ke,{threshold:je=.1,top_k:qe=null,percentage:Ue=!1}={}){const Ke=Array.isArray(re),ut=await ee(re),yt=this.tokenizer(ke,{padding:!0,truncation:!0}),vt=await this.processor(ut),kt=[];for(let v=0;v({score:Qe.scores[ft],label:ke[Qe.classes[ft]],box:me(Bt,!Ue)})).sort((Bt,ft)=>ft.score-Bt.score);qe!==null&&(Ye=Ye.slice(0,qe)),kt.push(Ye)}return Ke?kt:kt[0]}}class Z extends ce{constructor(re){super(re)}async _call(re,ke,je={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class He extends ce{constructor(ke){super(ke);xe(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ke.vocoder??null}async _call(ke,{speaker_embeddings:je=null}={}){return this.processor?this._call_text_to_spectrogram(ke,{speaker_embeddings:je}):this._call_text_to_waveform(ke)}async _call_text_to_waveform(ke){const je=this.tokenizer(ke,{padding:!0,truncation:!0}),{waveform:qe}=await this.model(je),Ue=this.model.config.sampling_rate;return{audio:qe.data,sampling_rate:Ue}}async _call_text_to_spectrogram(ke,{speaker_embeddings:je}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await fe.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 V.Tensor("float32",je,[1,je.length]);else if(!(je instanceof V.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:qe}=this.tokenizer(ke,{padding:!0,truncation:!0}),{waveform:Ue}=await this.model.generate_speech(qe,je,{vocoder:this.vocoder}),Ke=this.processor.feature_extractor.config.sampling_rate;return{audio:Ue.data,sampling_rate:Ke}}}class ct extends ce{constructor(re){super(re)}async _call(re){const ke=await ee(re),je=await this.processor(ke),qe=await this.model(je),Ue=[];for(const Ke of qe.reconstruction){const ut=Ke.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ue.push(A.RawImage.fromTensor(ut))}return Ue.length>1?Ue:Ue[0]}}class nt extends ce{constructor(re){super(re)}async _call(re){const ke=await ee(re),je=await this.processor(ke),{predicted_depth:qe}=await this.model(je),Ue=[];for(let Ke=0;Ke1?Ue:Ue[0]}}const lt=Object.freeze({"text-classification":{tokenizer:O.AutoTokenizer,pipeline:D,model:fe.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:O.AutoTokenizer,pipeline:H,model:fe.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:O.AutoTokenizer,pipeline:te,model:fe.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:O.AutoTokenizer,pipeline:se,model:fe.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:O.AutoTokenizer,pipeline:R,model:fe.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:O.AutoTokenizer,pipeline:I,model:fe.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:O.AutoTokenizer,pipeline:X,model:fe.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:O.AutoTokenizer,pipeline:k,model:fe.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:O.AutoTokenizer,pipeline:ue,model:fe.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Ie,model:fe.AutoModelForAudioClassification,processor:ye.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:O.AutoTokenizer,pipeline:Ae,model:fe.AutoModel,processor:ye.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:O.AutoTokenizer,pipeline:tt,model:[fe.AutoModelForSpeechSeq2Seq,fe.AutoModelForCTC],processor:ye.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:O.AutoTokenizer,pipeline:He,model:[fe.AutoModelForTextToWaveform,fe.AutoModelForTextToSpectrogram],processor:[ye.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:O.AutoTokenizer,pipeline:Xe,model:fe.AutoModelForVision2Seq,processor:ye.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:dt,model:fe.AutoModelForImageClassification,processor:ye.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ge,model:[fe.AutoModelForImageSegmentation,fe.AutoModelForSemanticSegmentation,fe.AutoModelForUniversalSegmentation],processor:ye.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:O.AutoTokenizer,pipeline:G,model:fe.AutoModel,processor:ye.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:de,model:fe.AutoModelForObjectDetection,processor:ye.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:O.AutoTokenizer,pipeline:Se,model:fe.AutoModelForZeroShotObjectDetection,processor:ye.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:O.AutoTokenizer,pipeline:Z,model:fe.AutoModelForDocumentQuestionAnswering,processor:ye.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ct,model:fe.AutoModelForImageToImage,processor:ye.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:nt,model:fe.AutoModelForDepthEstimation,processor:ye.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:O.AutoTokenizer,pipeline:ve,model:fe.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:ye.AutoProcessor,pipeline:$e,model:[fe.AutoModelForImageFeatureExtraction,fe.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ne=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(Re,re=null,{progress_callback:ke=null,config:je=null,cache_dir:qe=null,local_files_only:Ue=!1,revision:Ke="main",device:ut=null,dtype:yt=null,model_file_name:vt=null,session_options:kt={}}={}){Re=Ne[Re]??Re;const v=lt[Re.split("_",1)[0]];if(!v)throw Error(`Unsupported pipeline: ${Re}. Must be one of [${Object.keys(lt)}]`);re||(re=v.default.model,console.log(`No model specified. Using default model: "${re}".`));const q={progress_callback:ke,config:je,cache_dir:qe,local_files_only:Ue,revision:Ke,device:ut,dtype:yt,model_file_name:vt,session_options:kt},C=new Map([["tokenizer",v.tokenizer],["model",v.model],["processor",v.processor]]),Q=await Pt(C,re,q);Q.task=Re,(0,Ce.dispatchCallback)(ke,{status:"ready",task:Re,model:re});const he=v.pipeline;return new he(Q)}async function Pt(Re,re,ke){const je=Object.create(null),qe=[];for(const[Ue,Ke]of Re.entries()){if(!Ke)continue;let ut;Array.isArray(Ke)?ut=new Promise(async(yt,vt)=>{var v,q;let kt;for(const C of Ke){if(C===null){yt(null);return}try{yt(await C.from_pretrained(re,ke));return}catch(Q){if((v=Q.message)!=null&&v.includes("Unsupported model type"))kt=Q;else if((q=Q.message)!=null&&q.includes("Could not locate file"))kt=Q;else{vt(Q);return}}}vt(kt)}):ut=Ke.from_pretrained(re,ke),je[Ue]=ut,qe.push(ut)}await Promise.all(qe);for(const[Ue,Ke]of Object.entries(je))je[Ue]=await Ke;return je}},"./src/processors.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{ASTFeatureExtractor:()=>Q,AutoProcessor:()=>Kr,BeitFeatureExtractor:()=>ke,BitImageProcessor:()=>ve,CLIPFeatureExtractor:()=>Ie,CLIPImageProcessor:()=>Ae,ChineseCLIPFeatureExtractor:()=>tt,ClapFeatureExtractor:()=>he,ConvNextFeatureExtractor:()=>dt,ConvNextImageProcessor:()=>ge,DPTFeatureExtractor:()=>k,DPTImageProcessor:()=>ue,DeiTFeatureExtractor:()=>re,DetrFeatureExtractor:()=>Ue,DonutFeatureExtractor:()=>je,EfficientNetImageProcessor:()=>Se,FeatureExtractor:()=>se,Florence2Processor:()=>Br,GLPNFeatureExtractor:()=>$e,ImageFeatureExtractor:()=>X,MaskFormerFeatureExtractor:()=>Ke,MobileNetV1FeatureExtractor:()=>Z,MobileNetV2FeatureExtractor:()=>He,MobileNetV3FeatureExtractor:()=>ct,MobileNetV4FeatureExtractor:()=>nt,MobileViTFeatureExtractor:()=>lt,MobileViTImageProcessor:()=>Ne,NougatImageProcessor:()=>qe,OwlViTFeatureExtractor:()=>st,OwlViTProcessor:()=>Yr,Owlv2ImageProcessor:()=>Pt,Processor:()=>ft,PvtImageProcessor:()=>B,PyAnnoteFeatureExtractor:()=>Qe,PyAnnoteProcessor:()=>cr,RTDetrImageProcessor:()=>Re,SamImageProcessor:()=>yt,SamProcessor:()=>Tt,SapiensFeatureExtractor:()=>R,SeamlessM4TFeatureExtractor:()=>C,SegformerFeatureExtractor:()=>I,SiglipImageProcessor:()=>Xe,SpeechT5FeatureExtractor:()=>Bt,SpeechT5Processor:()=>xr,Swin2SRImageProcessor:()=>vt,ViTFeatureExtractor:()=>G,ViTImageProcessor:()=>de,VitMatteImageProcessor:()=>kt,Wav2Vec2FeatureExtractor:()=>q,Wav2Vec2ProcessorWithLM:()=>Ot,WeSpeakerFeatureExtractor:()=>Ye,WhisperFeatureExtractor:()=>v,WhisperProcessor:()=>bt,YolosFeatureExtractor:()=>ut});var O=N("./src/utils/generic.js"),fe=N("./src/utils/core.js"),ye=N("./src/utils/hub.js"),Te=N("./src/utils/maths.js"),Ce=N("./src/utils/tensor.js");N("./src/utils/image.js");var j=N("./src/utils/audio.js");function S([at,U,_e,Pe]){return[at-_e/2,U-Pe/2,at+_e/2,U+Pe/2]}function V(at,U=.5,_e=null,Pe=!1){const rt=at.logits,we=at.pred_boxes,[Je,gt,mt]=rt.dims;if(_e!==null&&_e.length!==Je)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Et=[];for(let _t=0;_tU&&ot.push(gr)}else{let gr=(0,Te.max)(Ze.data)[1];if(gr===mt-1||(Ht=(0,Te.softmax)(Ze.data),Ht[gr]mr*Ft[(yr+1)%2])),Nt.boxes.push(Lr),Nt.classes.push(gr),Nt.scores.push(Ht[gr])}}Et.push(Nt)}return Et}function A(at,U=null){const _e=at.logits,Pe=_e.dims[0];if(U!==null&&U.length!==Pe)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const rt=[];for(let we=0;weFt[ot]&&(Ft[ot]=Ze[ot],Nt[ot]=Me)}const Rt=new Array(gt.dims[0]);for(let Me=0;MeMe!==void 0);rt.push({segmentation:_t,labels:Gt})}return rt}function ee(at,U,_e,Pe){const rt=[],we=[],Je=[];for(let gt=0;gt_e&&(rt.push(Et),we.push(Nt),Je.push(_t))}return[rt,we,Je]}function ne(at,U,_e,Pe=.5,rt=.8){const we=[];let Je=0,gt=0;const mt=U[_e].data;for(let _t=0;_t=Pe&&++gt;let Et=Je>0&>>0;return Et&&(Et=Je/gt>rt),[Et,we]}function me(at,U,_e,Pe,rt,we=null,Je=null){const[gt,mt]=Je??at[0].dims,Et=new Ce.Tensor("int32",new Int32Array(gt*mt),[gt,mt]),_t=[];if(Je!==null)for(let Me=0;MeNt[Ht]&&(Ft[Ht]=Me,Nt[Ht]=ot[Ht])}let Rt=0;const Gt=Et.data;for(let Me=0;Me<_e.length;++Me){const Ze=_e[Me],[ot,Ht]=ne(Ft,at,Me,Pe,rt);if(ot){++Rt;for(const gr of Ht)Gt[gr]=Rt;_t.push({id:Rt,label_id:Ze,score:U[Me]})}}return[Et,_t]}function ce(at,U=.5,_e=.5,Pe=.8,rt=null,we=null){rt===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),rt=new Set);const Je=at.class_queries_logits??at.logits,mt=(at.masks_queries_logits??at.pred_masks).sigmoid();let[Et,_t,Ft]=Je.dims;if(Ft-=1,we!==null&&we.length!==Et)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Nt=[];for(let Rt=0;RtPe&&(we=Math.floor(rt)*U),we<_e&&(we=Math.ceil(rt)*U),we}function te([at,U],_e){return[Math.max(Math.floor(at/_e),1)*_e,Math.max(Math.floor(U/_e),1)*_e]}class se extends O.Callable{constructor(U){super(),this.config=U}}class X extends se{constructor(U){super(U),this.image_mean=this.config.image_mean??this.config.mean,this.image_std=this.config.image_std??this.config.std,this.resample=this.config.resample??2,this.do_rescale=this.config.do_rescale??!0,this.rescale_factor=this.config.rescale_factor??.00392156862745098,this.do_normalize=this.config.do_normalize,this.do_resize=this.config.do_resize,this.do_thumbnail=this.config.do_thumbnail,this.size=this.config.size,this.size_divisibility=this.config.size_divisibility??this.config.size_divisor,this.do_center_crop=this.config.do_center_crop,this.crop_size=this.config.crop_size,this.do_convert_rgb=this.config.do_convert_rgb??!0,this.do_crop_margin=this.config.do_crop_margin,this.pad_size=this.config.pad_size,this.do_pad=this.config.do_pad,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=this.config.do_flip_channel_order??!1}async thumbnail(U,_e,Pe=2){const rt=U.height,we=U.width,Je=_e.height,gt=_e.width;let mt=Math.min(rt,Je),Et=Math.min(we,gt);return mt===rt&&Et===we?U:(rt>we?Et=Math.floor(we*mt/rt):we>rt&&(mt=Math.floor(rt*Et/we)),await U.resize(Et,mt,{resample:Pe}))}async crop_margin(U,_e=200){const Pe=U.clone().grayscale(),rt=(0,Te.min)(Pe.data)[0],Je=(0,Te.max)(Pe.data)[0]-rt;if(Je===0)return U;const gt=_e/255;let mt=Pe.width,Et=Pe.height,_t=0,Ft=0;const Nt=Pe.data;for(let Rt=0;Rtthis.preprocess(we)));return{pixel_values:(0,Ce.stack)(Pe.map(we=>we.pixel_values),0),original_sizes:Pe.map(we=>we.original_size),reshaped_input_sizes:Pe.map(we=>we.reshaped_input_size)}}}class R extends X{post_process_semantic_segmentation(...U){return A(...U)}}class I extends X{post_process_semantic_segmentation(...U){return A(...U)}}class B extends X{}class k extends X{}class ue extends k{}class ve extends X{}class $e extends X{}class Ie extends X{}class Ae extends Ie{}class tt extends X{}class Xe extends X{}class dt extends X{constructor(U){super(U),this.crop_pct=this.config.crop_pct??.875}async resize(U){var Pe;const _e=(Pe=this.size)==null?void 0:Pe.shortest_edge;if(_e===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(_e<384){const rt=Math.floor(_e/this.crop_pct),[we,Je]=this.get_resize_output_image_size(U,{shortest_edge:rt});U=await U.resize(we,Je,{resample:this.resample}),U=await U.center_crop(_e,_e)}else U=await U.resize(_e,_e,{resample:this.resample});return U}}class ge extends dt{}class G extends X{}class de extends X{}class Se extends X{constructor(U){super(U),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(_e=>_e*_e))}}class Z extends X{}class He extends X{}class ct extends X{}class nt extends X{}class lt extends X{}class Ne extends lt{}class st extends X{post_process_object_detection(...U){return V(...U)}}class Pt extends st{}class Re extends X{post_process_object_detection(...U){return V(...U)}}class re extends X{}class ke extends X{}class je extends X{pad_image(U,_e,Pe,rt={}){const[we,Je,gt]=_e;let mt=this.image_mean;Array.isArray(this.image_mean)||(mt=new Array(gt).fill(mt));let Et=this.image_std;Array.isArray(Et)||(Et=new Array(gt).fill(mt));const _t=mt.map((Ft,Nt)=>-Ft/Et[Nt]);return super.pad_image(U,_e,Pe,{center:!0,constant_values:_t,...rt})}}class qe extends je{}class Ue extends X{async _call(U){const _e=await super._call(U),Pe=[_e.pixel_values.dims[0],64,64],rt=(0,Ce.full)(Pe,1n);return{..._e,pixel_mask:rt}}post_process_object_detection(...U){return V(...U)}post_process_panoptic_segmentation(...U){return ce(...U)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class Ke extends X{post_process_panoptic_segmentation(...U){return ce(...U)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class ut extends X{post_process_object_detection(...U){return V(...U)}}class yt extends X{reshape_input_points(U,_e,Pe,rt=!1){U=structuredClone(U);let we=(0,fe.calculateDimensions)(U);if(we.length===3)rt||(we=[1,...we]),U=[U];else if(we.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let Je=0;Jert!==_e.dims[we]))throw Error(`The first ${Pe.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Ce.Tensor("int64",U.flat(1/0).map(BigInt),Pe)}async _call(U,{input_points:_e=null,input_labels:Pe=null,input_boxes:rt=null}={}){const we=await super._call(U);if(_e&&(we.input_points=this.reshape_input_points(_e,we.original_sizes,we.reshaped_input_sizes)),Pe){if(!we.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");we.input_labels=this.add_input_labels(Pe,we.input_points)}return rt&&(we.input_boxes=this.reshape_input_points(rt,we.original_sizes,we.reshaped_input_sizes,!0)),we}async post_process_masks(U,_e,Pe,{mask_threshold:rt=0,binarize:we=!0,pad_size:Je=null}={}){const gt=[];Je=Je??this.pad_size;const mt=[Je.height,Je.width];for(let Et=0;Et<_e.length;++Et){const _t=_e[Et],Ft=Pe[Et];let Nt=await(0,Ce.interpolate_4d)(U[Et],{mode:"bilinear",size:mt});if(Nt=Nt.slice(null,null,[0,Ft[0]],[0,Ft[1]]),Nt=await(0,Ce.interpolate_4d)(Nt,{mode:"bilinear",size:_t}),we){const Rt=Nt.data,Gt=new Uint8Array(Rt.length);for(let Me=0;Mert&&(Gt[Me]=1);Nt=new Ce.Tensor("bool",Gt,Nt.dims)}gt.push(Nt)}return gt}generate_crop_boxes(U,_e,{crop_n_layers:Pe=0,overlap_ratio:rt=.3413333333333333,points_per_crop:we=32,crop_n_points_downscale_factor:Je=1}={}){}}class vt extends X{pad_image(U,_e,Pe,rt={}){const[we,Je,gt]=_e;return super.pad_image(U,_e,{width:Je+(Pe-Je%Pe)%Pe,height:we+(Pe-we%Pe)%Pe},{mode:"symmetric",center:!1,constant_values:-1,...rt})}}class kt extends X{async _call(U,_e){Array.isArray(U)||(U=[U]),Array.isArray(_e)||(_e=[_e]);const Pe=await Promise.all(U.map(Je=>this.preprocess(Je))),rt=await Promise.all(_e.map(Je=>this.preprocess(Je,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,Ce.stack)(Pe.map((Je,gt)=>(0,Ce.cat)([Je.pixel_values,rt[gt].pixel_values],0)),0),original_sizes:Pe.map(Je=>Je.original_size),reshaped_input_sizes:Pe.map(Je=>Je.reshaped_input_size)}}}class v extends se{constructor(U){var _e;super(U),(_e=this.config).mel_filters??(_e.mel_filters=(0,j.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,j.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(U){const _e=await(0,j.spectrogram)(U,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),Pe=_e.data,rt=(0,Te.max)(Pe)[0];for(let we=0;wethis.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`."),_e=U.slice(0,this.config.n_samples)):(_e=new Float32Array(this.config.n_samples),_e.set(U)),{input_features:(await this._extract_fbank_features(_e)).unsqueeze_(0)}}}class q extends se{_zero_mean_unit_var_norm(U){const Pe=U.reduce((we,Je)=>we+Je,0)/U.length,rt=U.reduce((we,Je)=>we+(Je-Pe)**2,0)/U.length;return U.map(we=>(we-Pe)/Math.sqrt(rt+1e-7))}async _call(U){D(U,"Wav2Vec2FeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));let _e=U;this.config.do_normalize&&(_e=this._zero_mean_unit_var_norm(_e));const Pe=[1,_e.length];return{input_values:new Ce.Tensor("float32",_e,Pe),attention_mask:new Ce.Tensor("int64",new BigInt64Array(_e.length).fill(1n),Pe)}}}class C extends se{constructor(U){super(U);const _e=this.config.sampling_rate,Pe=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(_e/2),_e,null,"kaldi",!0);for(let rt=0;rtPe*32768),(0,j.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:_e,transpose:!0})}async _call(U,{padding:_e=!0,pad_to_multiple_of:Pe=2,do_normalize_per_mel_bins:rt=!0,return_attention_mask:we=!0}={}){D(U,"SeamlessM4TFeatureExtractor");let Je=await this._extract_fbank_features(U,this.config.max_length);if(rt){const[Gt,Me]=Je.dims,Ze=Je.data;for(let ot=0;ot0){const Ht=new Float32Array(Me*(Gt+ot));Ht.set(Ze),Ht.fill(this.config.padding_value,Ze.length);const gr=Gt+ot;Je=new Ce.Tensor(Je.type,Ht,[gr,Me]),we&&(gt=new Ce.Tensor("int64",new BigInt64Array(gr),[1,gr]),gt.data.fill(1n,0,Gt))}}const[mt,Et]=Je.dims,_t=this.config.stride;if(mt%_t!==0)throw new Error(`The number of frames (${mt}) must be a multiple of the stride (${_t}).`);const Nt=Je.view(1,Math.floor(mt/_t),Et*_t),Rt={input_features:Nt};if(we){const Gt=Nt.dims[1],Me=new BigInt64Array(Gt);if(gt){const Ze=gt.data;for(let ot=1,Ht=0;ot0)if(Pe==="rand_trunc"){const gt=Math.floor(Math.random()*(Je+1));U=U.subarray(gt,gt+_e),we=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Pe}" not implemented`);else{if(Je<0){let gt=new Float64Array(_e);if(gt.set(U),rt==="repeat")for(let mt=U.length;mt<_e;mt+=U.length)gt.set(U.subarray(0,Math.min(U.length,_e-mt)),mt);else if(rt==="repeatpad")for(let mt=U.length;mt<-Je;mt+=U.length)gt.set(U,mt);U=gt}if(Pe==="fusion")throw new Error(`Truncation strategy "${Pe}" not implemented`);we=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}return we.unsqueeze_(0)}async _extract_fbank_features(U,_e,Pe=null){return(0,j.spectrogram)(U,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:_e,log_mel:"dB",max_num_frames:Pe,do_pad:!1,transpose:!0})}async _call(U,{max_length:_e=null}={}){return D(U,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(U,_e??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}class Qe extends se{async _call(U){D(U,"PyAnnoteFeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));const _e=[1,1,U.length];return{input_values:new Ce.Tensor("float32",U,_e)}}samples_to_frames(U){return(U-this.config.offset)/this.config.step}post_process_speaker_diarization(U,_e){const Pe=_e/this.samples_to_frames(_e)/this.config.sampling_rate,rt=[];for(const we of U.tolist()){const Je=[];let gt=-1;for(let mt=0;mt({id:mt,start:Et*Pe,end:_t*Pe,confidence:Ft/(_t-Et)})))}return rt}}class Ye extends se{constructor(U){super(U);const _e=this.config.sampling_rate,Pe=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(_e/2),_e,null,"kaldi",!0);for(let rt=0;rt_e*32768),(0,j.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(U){D(U,"WeSpeakerFeatureExtractor");const _e=(await this._extract_fbank_features(U)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Pe=_e.mean(1).data,rt=_e.data,[we,Je,gt]=_e.dims;for(let mt=0;mt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(U){typeof U=="string"&&(U=[U]);const _e=[];for(const Pe of U)if(this.task_prompts_without_inputs.has(Pe))_e.push(this.task_prompts_without_inputs.get(Pe));else{for(const[rt,we]of this.task_prompts_with_input)if(Pe.includes(rt)){_e.push(we.replaceAll("{input}",Pe).replaceAll(rt,""));break}_e.length!==U.length&&_e.push(Pe)}return _e}post_process_generation(U,_e,Pe){const rt=this.tasks_answer_post_processing_type.get(_e)??"pure_text";U=U.replaceAll("","").replaceAll("","");let we;switch(rt){case"pure_text":we=U;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Je=rt==="ocr"?"quad_boxes":"bboxes",gt=U.matchAll(this.regexes[Je]),mt=[],Et=[];for(const[_t,Ft,...Nt]of gt)mt.push(Ft?Ft.trim():mt.at(-1)??""),Et.push(Nt.map((Rt,Gt)=>(Number(Rt)+.5)/this.size_per_bin*Pe[Gt%2]));we={labels:mt,[Je]:Et};break;default:throw new Error(`Task "${_e}" (of type "${rt}") not yet implemented.`)}return{[_e]:we}}}class Kr{static async from_pretrained(U,{progress_callback:_e=null,config:Pe=null,cache_dir:rt=null,local_files_only:we=!1,revision:Je="main"}={}){let gt=Pe??await(0,ye.getModelJSON)(U,"preprocessor_config.json",!0,{progress_callback:_e,config:Pe,cache_dir:rt,local_files_only:we,revision:Je}),mt=gt.feature_extractor_type??gt.image_processor_type,Et=this.FEATURE_EXTRACTOR_CLASS_MAPPING[mt];if(!Et)if(gt.size!==void 0)console.warn(`Feature extractor type "${mt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Et=X;else throw new Error(`Unknown Feature Extractor type: ${mt}`);let _t=this.PROCESSOR_CLASS_MAPPING[gt.processor_class]??ft,Ft=new Et(gt);return new _t(Ft)}}xe(Kr,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:X,WhisperFeatureExtractor:v,ViTFeatureExtractor:G,MobileViTFeatureExtractor:lt,MobileViTImageProcessor:Ne,MobileNetV1FeatureExtractor:Z,MobileNetV2FeatureExtractor:He,MobileNetV3FeatureExtractor:ct,MobileNetV4FeatureExtractor:nt,OwlViTFeatureExtractor:st,Owlv2ImageProcessor:Pt,CLIPFeatureExtractor:Ie,CLIPImageProcessor:Ae,Florence2Processor:Br,ChineseCLIPFeatureExtractor:tt,SiglipImageProcessor:Xe,ConvNextFeatureExtractor:dt,ConvNextImageProcessor:ge,SegformerFeatureExtractor:I,SapiensFeatureExtractor:R,BitImageProcessor:ve,DPTImageProcessor:ue,DPTFeatureExtractor:k,PvtImageProcessor:B,GLPNFeatureExtractor:$e,BeitFeatureExtractor:ke,DeiTFeatureExtractor:re,DetrFeatureExtractor:Ue,RTDetrImageProcessor:Re,MaskFormerFeatureExtractor:Ke,YolosFeatureExtractor:ut,DonutFeatureExtractor:je,NougatImageProcessor:qe,EfficientNetImageProcessor:Se,ViTImageProcessor:de,VitMatteImageProcessor:kt,SamImageProcessor:yt,Swin2SRImageProcessor:vt,Wav2Vec2FeatureExtractor:q,SeamlessM4TFeatureExtractor:C,SpeechT5FeatureExtractor:Bt,ASTFeatureExtractor:Q,ClapFeatureExtractor:he,PyAnnoteFeatureExtractor:Qe,WeSpeakerFeatureExtractor:Ye}),xe(Kr,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:bt,Wav2Vec2ProcessorWithLM:Ot,PyAnnoteProcessor:cr,SamProcessor:Tt,SpeechT5Processor:xr,OwlViTProcessor:Yr,Florence2Processor:Br})},"./src/tokenizers.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{AlbertTokenizer:()=>gt,AutoTokenizer:()=>vn,BartTokenizer:()=>mr,BertTokenizer:()=>Je,BlenderbotSmallTokenizer:()=>Ss,BlenderbotTokenizer:()=>fs,BloomTokenizer:()=>Rr,CLIPTokenizer:()=>Xt,CamembertTokenizer:()=>Ze,CodeGenTokenizer:()=>hs,CodeLlamaTokenizer:()=>Ys,CohereTokenizer:()=>Wr,ConvBertTokenizer:()=>Rt,DebertaTokenizer:()=>_t,DebertaV2Tokenizer:()=>Ft,DistilBertTokenizer:()=>Me,ElectraTokenizer:()=>Ht,EsmTokenizer:()=>Kn,FalconTokenizer:()=>Ts,GPT2Tokenizer:()=>Lr,GPTNeoXTokenizer:()=>Es,GemmaTokenizer:()=>cs,Grok1Tokenizer:()=>Ln,HerbertTokenizer:()=>Nt,LlamaTokenizer:()=>jn,M2M100Tokenizer:()=>rs,MBart50Tokenizer:()=>Tr,MBartTokenizer:()=>yr,MPNetTokenizer:()=>xs,MarianTokenizer:()=>Cs,MobileBertTokenizer:()=>mt,NllbTokenizer:()=>Vn,NougatTokenizer:()=>ms,PreTrainedTokenizer:()=>we,Qwen2Tokenizer:()=>Js,RoFormerTokenizer:()=>Gt,RobertaTokenizer:()=>$n,SiglipTokenizer:()=>ns,SpeechT5Tokenizer:()=>ks,SqueezeBertTokenizer:()=>Et,T5Tokenizer:()=>gr,TokenizerModel:()=>$e,VitsTokenizer:()=>Ps,Wav2Vec2CTCTokenizer:()=>$s,WhisperTokenizer:()=>ps,XLMRobertaTokenizer:()=>vs,XLMTokenizer:()=>ot,is_chinese_char:()=>X});var O=N("./src/utils/generic.js"),fe=N("./src/utils/core.js"),ye=N("./src/utils/hub.js"),Te=N("./src/utils/maths.js"),Ce=N("./src/utils/tensor.js"),j=N("./src/utils/data-structures.js"),S=N("./node_modules/@huggingface/jinja/dist/index.js"),V=N("./src/models/whisper/common_whisper.js"),A=N("./src/utils/constants.js");async function ee(be,_){const P=await Promise.all([(0,ye.getModelJSON)(be,"tokenizer.json",!0,_),(0,ye.getModelJSON)(be,"tokenizer_config.json",!0,_)]);return _.legacy!==null&&(P[1].legacy=_.legacy),P}function ne(be,_){const P=[];let K=0;for(const ae of be.matchAll(_)){const pe=ae[0];K0&&P.push(pe),K=ae.index+pe.length}return K=19968&&be<=40959||be>=13312&&be<=19903||be>=131072&&be<=173791||be>=173824&&be<=177983||be>=177984&&be<=178207||be>=178208&&be<=183983||be>=63744&&be<=64255||be>=194560&&be<=195103}function R(be,_,P){const K=[];let ae=0;for(;aethis.tokens_to_ids.get(P)??this.unk_token_id)}convert_ids_to_tokens(_){return _.map(P=>this.vocab[P]??this.unk_token)}}class Ie extends $e{constructor(_){super(_),this.tokens_to_ids=ce(_.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[P,K]of this.tokens_to_ids)this.vocab[K]=P}encode(_){const P=[];for(const K of _){const ae=[...K];if(ae.length>this.max_input_chars_per_word){P.push(this.unk_token);continue}let pe=!1,Be=0;const wt=[];for(;Be0&&(zt=this.config.continuing_subword_prefix+zt),this.tokens_to_ids.has(zt)){Mt=zt;break}--xt}if(Mt===null){pe=!0;break}wt.push(Mt),Be=xt}pe?P.push(this.unk_token):P.push(...wt)}return P}}class Ae extends $e{constructor(_,P){super(_);const K=_.vocab.length;this.vocab=new Array(K),this.scores=new Array(K);for(let ae=0;ae[ae,pe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=P.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,Te.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new j.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(_){const P=_.chars,K=1;let ae=0;for(;ae{const be=[...Array.from({length:94},(ae,pe)=>pe+33),...Array.from({length:12},(ae,pe)=>pe+161),...Array.from({length:82},(ae,pe)=>pe+174)],_=be.slice();let P=0;for(let ae=0;ae<256;++ae)be.includes(ae)||(be.push(ae),_.push(256+P),P+=1);const K=_.map(ae=>String.fromCharCode(ae));return Object.fromEntries(be.map((ae,pe)=>[ae,K[pe]]))})(),Xe=(0,fe.reverseDictionary)(tt);class dt extends $e{constructor(_){super(_),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=ce(_.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[P,K]of this.tokens_to_ids)this.vocab[K]=P;this.bpe_ranks=new Map(_.merges.map((P,K)=>[P,K])),this.merges=_.merges.map(P=>P.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 P=this.cache.get(_);if(P!==void 0)return P;const K=Array.from(_);this.end_of_word_suffix&&(K[K.length-1]+=this.end_of_word_suffix);let ae=[];if(K.length>1){const pe=new j.PriorityQueue((xt,Mt)=>xt.score`<0x${wt.toString(16).toUpperCase().padStart(2,"0")}>`);Be.every(wt=>this.tokens_to_ids.has(wt))?P.push(...Be):P.push(this.unk_token)}else P.push(this.unk_token)}return P}}class ge extends $e{constructor(_,P){super(_),this.tokens_to_ids=ce(P.target_lang?_.vocab[P.target_lang]:_.vocab),this.bos_token=P.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=P.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=P.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=P.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[K,ae]of this.tokens_to_ids)this.vocab[ae]=K}encode(_){return _}}class G extends O.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"BertNormalizer":return new Pt(_);case"Precompiled":return new Yr(_);case"Sequence":return new st(_);case"Replace":return new de(_);case"NFC":return new Se(_);case"NFKC":return new Z(_);case"NFKD":return new He(_);case"Strip":return new ct(_);case"StripAccents":return new nt(_);case"Lowercase":return new lt(_);case"Prepend":return new Ne(_);default:throw new Error(`Unknown Normalizer type: ${_.type}`)}}normalize(_){throw Error("normalize should be implemented in subclass.")}_call(_){return this.normalize(_)}}class de extends G{normalize(_){const P=me(this.config.pattern);return P===null?_:_.replaceAll(P,this.config.content)}}class Se extends G{normalize(_){return _=_.normalize("NFC"),_}}class Z extends G{normalize(_){return _=_.normalize("NFKC"),_}}class He extends G{normalize(_){return _=_.normalize("NFKD"),_}}class ct extends G{normalize(_){return this.config.strip_left&&this.config.strip_right?_=_.trim():(this.config.strip_left&&(_=_.trimStart()),this.config.strip_right&&(_=_.trimEnd())),_}}class nt extends G{normalize(_){return _=te(_),_}}class lt extends G{normalize(_){return _=_.toLowerCase(),_}}class Ne extends G{normalize(_){return _=this.config.prepend+_,_}}class st extends G{constructor(_){super(_),this.normalizers=_.normalizers.map(P=>G.fromConfig(P))}normalize(_){return this.normalizers.reduce((P,K)=>K.normalize(P),_)}}class Pt extends G{_tokenize_chinese_chars(_){const P=[];for(let K=0;K<_.length;++K){const ae=_[K],pe=ae.charCodeAt(0);X(pe)?(P.push(" "),P.push(ae),P.push(" ")):P.push(ae)}return P.join("")}stripAccents(_){return _.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control(_){switch(_){case" ":case` `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(_)}}_clean_text(_){const P=[];for(const K of _){const ae=K.charCodeAt(0);ae===0||ae===65533||this._is_control(K)||(/^\s$/.test(K)?P.push(" "):P.push(K))}return P.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 Re extends O.Callable{static fromConfig(_){if(_===null)return null;switch(_.type){case"BertPreTokenizer":return new re(_);case"Sequence":return new Br(_);case"Whitespace":return new Kr(_);case"WhitespaceSplit":return new at(_);case"Metaspace":return new cr(_);case"ByteLevel":return new ke(_);case"Split":return new je(_);case"Punctuation":return new qe(_);case"Digits":return new Ue(_);case"Replace":return new U(_);default:throw new Error(`Unknown PreTokenizer type: ${_.type}`)}}pre_tokenize_text(_,P){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(_,P){return(Array.isArray(_)?_.map(K=>this.pre_tokenize_text(K,P)):this.pre_tokenize_text(_,P)).flat()}_call(_,P){return this.pre_tokenize(_,P)}}class re extends Re{constructor(_){super(),this.pattern=new RegExp(`[^\\s${B}]+|[${B}]`,"gu")}pre_tokenize_text(_,P){return _.trim().match(this.pattern)||[]}}class ke extends Re{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(_,P){return this.add_prefix_space&&!_.startsWith(" ")&&(_=" "+_),(this.use_regex?_.match(this.pattern)||[]:[_]).map(ae=>Array.from(this.text_encoder.encode(ae),pe=>this.byte_encoder[pe]).join(""))}}class je extends Re{constructor(_){super(),this.config=_,this.pattern=me(this.config.pattern,this.config.invert)}pre_tokenize_text(_,P){return this.pattern===null?[]:this.config.invert?_.match(this.pattern)||[]:ne(_,this.pattern)}}class qe extends Re{constructor(_){super(),this.config=_,this.pattern=new RegExp(`[^${B}]+|[${B}]+`,"gu")}pre_tokenize_text(_,P){return _.match(this.pattern)||[]}}class Ue extends Re{constructor(_){super(),this.config=_;const P=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(P,"gu")}pre_tokenize_text(_,P){return _.match(this.pattern)||[]}}class Ke extends O.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"TemplateProcessing":return new vt(_);case"ByteLevel":return new kt(_);case"RobertaProcessing":return new yt(_);case"BertProcessing":return new ut(_);case"Sequence":return new v(_);default:throw new Error(`Unknown PostProcessor type: ${_.type}`)}}post_process(_,...P){throw Error("post_process should be implemented in subclass.")}_call(_,...P){return this.post_process(_,...P)}}class ut extends Ke{constructor(_){super(_),this.cls=_.cls[0],this.sep=_.sep[0]}post_process(_,P=null,{add_special_tokens:K=!0}={}){K&&(_=(0,fe.mergeArrays)([this.cls],_,[this.sep]));let ae=new Array(_.length).fill(0);if(P!==null){const pe=K&&this instanceof yt?[this.sep]:[],Be=K?[this.sep]:[];_=(0,fe.mergeArrays)(_,pe,P,Be),ae=(0,fe.mergeArrays)(ae,new Array(P.length+pe.length+Be.length).fill(1))}return{tokens:_,token_type_ids:ae}}}class yt extends ut{}class vt extends Ke{constructor(_){super(_),this.single=_.single,this.pair=_.pair}post_process(_,P=null,{add_special_tokens:K=!0}={}){const ae=P===null?this.single:this.pair;let pe=[],Be=[];for(const wt of ae)"SpecialToken"in wt?K&&(pe.push(wt.SpecialToken.id),Be.push(wt.SpecialToken.type_id)):"Sequence"in wt&&(wt.Sequence.id==="A"?(pe=(0,fe.mergeArrays)(pe,_),Be=(0,fe.mergeArrays)(Be,new Array(_.length).fill(wt.Sequence.type_id))):wt.Sequence.id==="B"&&(pe=(0,fe.mergeArrays)(pe,P),Be=(0,fe.mergeArrays)(Be,new Array(P.length).fill(wt.Sequence.type_id))));return{tokens:pe,token_type_ids:Be}}}class kt extends Ke{post_process(_,P=null){return P&&(_=(0,fe.mergeArrays)(_,P)),{tokens:_}}}class v extends Ke{constructor(_){super(_),this.processors=_.processors.map(P=>Ke.fromConfig(P))}post_process(_,P=null,K={}){let ae;for(const pe of this.processors)if(pe instanceof kt)_=pe.post_process(_).tokens,P&&(P=pe.post_process(P).tokens);else{const Be=pe.post_process(_,P,K);_=Be.tokens,ae=Be.token_type_ids}return{tokens:_,token_type_ids:ae}}}class q extends O.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 Ye(_);case"Metaspace":return new xr(_);case"ByteLevel":return new Bt(_);case"Replace":return new C(_);case"ByteFallback":return new Q(_);case"Fuse":return new he(_);case"Strip":return new Qe(_);case"Sequence":return new Tt(_);case"CTC":return new ft(_);case"BPEDecoder":return new bt(_);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 C extends q{decode_chain(_){const P=me(this.config.pattern);return P===null?_:_.map(K=>K.replaceAll(P,this.config.content))}}class Q extends q{constructor(_){super(_),this.text_decoder=new TextDecoder}decode_chain(_){const P=[];let K=[];for(const ae of _){let pe=null;if(ae.length===6&&ae.startsWith("<0x")&&ae.endsWith(">")){const Be=parseInt(ae.slice(3,5),16);isNaN(Be)||(pe=Be)}if(pe!==null)K.push(pe);else{if(K.length>0){const Be=this.text_decoder.decode(Uint8Array.from(K));P.push(Be),K=[]}P.push(ae)}}if(K.length>0){const ae=this.text_decoder.decode(Uint8Array.from(K));P.push(ae),K=[]}return P}}class he extends q{decode_chain(_){return[_.join("")]}}class Qe extends q{constructor(_){super(_),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(_){return _.map(P=>{let K=0;for(let pe=0;pe(K!==0&&(P.startsWith(this.config.prefix)?P=P.replace(this.config.prefix,""):P=" "+P),this.cleanup&&(P=H(P)),P))}}class Bt extends q{constructor(_){super(_),this.byte_decoder=Xe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(_){const P=_.join(""),K=new Uint8Array([...P].map(pe=>this.byte_decoder[pe]));return this.text_decoder.decode(K)}decode_chain(_){const P=[];let K=[];for(const ae of _)this.added_tokens.find(pe=>pe.content===ae)!==void 0?(K.length>0&&(P.push(this.convert_tokens_to_string(K)),K=[]),P.push(ae)):K.push(ae);return K.length>0&&P.push(this.convert_tokens_to_string(K)),P}}class ft extends q{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 P=[_[0]];for(let pe=1;pe<_.length;++pe)_[pe]!==P.at(-1)&&P.push(_[pe]);let ae=P.filter(pe=>pe!==this.pad_token).join("");return this.cleanup&&(ae=H(ae).replaceAll(this.word_delimiter_token," ").trim()),ae}decode_chain(_){return[this.convert_tokens_to_string(_)]}}class Tt extends q{constructor(_){super(_),this.decoders=_.decoders.map(P=>q.fromConfig(P))}decode_chain(_){return this.decoders.reduce((P,K)=>K.decode_chain(P),_)}}class bt extends q{constructor(_){super(_),this.suffix=this.config.suffix}decode_chain(_){return _.map((P,K)=>P.replaceAll(this.suffix,K===_.length-1?"":" "))}}class Ot extends q{decode_chain(_){let P="";for(let K=1;K<_.length;K+=2)P+=_[K];return[P]}}class cr extends Re{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:P=void 0}={}){let K=_.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!K.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&P===0)&&(K=this.strRep+K),[K]}}class xr extends q{constructor(_){super(_),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement}decode_chain(_){const P=[];for(let K=0;K<_.length;++K){let ae=_[K].replaceAll(this.replacement," ");this.addPrefixSpace&&K==0&&ae.startsWith(" ")&&(ae=ae.substring(1)),P.push(ae)}return P}}class Yr extends G{constructor(_){super(_),this.charsmap=_.precompiled_charsmap}normalize(_){return _=_.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),_=_.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),_.includes("~")?_=_.split("~").map(K=>K.normalize("NFKC")).join("~"):_=_.normalize("NFKC"),_}}class Br extends Re{constructor(_){super(),this.tokenizers=_.pretokenizers.map(P=>Re.fromConfig(P))}pre_tokenize_text(_,P){return this.tokenizers.reduce((K,ae)=>ae.pre_tokenize(K,P),[_])}}class Kr extends Re{constructor(_){super()}pre_tokenize_text(_,P){return _.match(/\w+|[^\w\s]+/g)||[]}}class at extends Re{constructor(_){super()}pre_tokenize_text(_,P){return I(_)}}class U extends Re{constructor(_){super(),this.config=_,this.pattern=me(this.config.pattern),this.content=this.config.content}pre_tokenize_text(_,P){return this.pattern===null?[_]:[_.replaceAll(this.pattern,this.config.content)]}}const _e=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Pe(be,_,P,K){for(const ae of Object.keys(be)){const pe=_-be[ae].length,Be=P(ae),wt=new Array(pe).fill(Be);be[ae]=K==="right"?(0,fe.mergeArrays)(be[ae],wt):(0,fe.mergeArrays)(wt,be[ae])}}function rt(be,_){for(const P of Object.keys(be))be[P].length=_}class we extends O.Callable{constructor(P,K){super();xe(this,"return_token_type_ids",!1);xe(this,"padding_side","right");this._tokenizer_config=K,this.normalizer=G.fromConfig(P.normalizer),this.pre_tokenizer=Re.fromConfig(P.pre_tokenizer),this.model=$e.fromConfig(P.model,K),this.post_processor=Ke.fromConfig(P.post_processor),this.decoder=q.fromConfig(P.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ae of P.added_tokens){const pe=new ve(ae);this.added_tokens.push(pe),this.model.tokens_to_ids.set(pe.content,pe.id),this.model.vocab[pe.id]=pe.content,pe.special&&(this.special_tokens.push(pe.content),this.all_special_ids.push(pe.id))}if(this.additional_special_tokens=K.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((ae,pe)=>pe.content.length-ae.content.length).map(ae=>`${ae.lstrip?"\\s*":""}(${(0,fe.escapeRegExp)(ae.content)})${ae.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=K.model_max_length,this.remove_space=K.remove_space,this.clean_up_tokenization_spaces=K.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=K.do_lowercase_and_remove_accent??!1,K.padding_side&&(this.padding_side=K.padding_side),this.legacy=!1,this.chat_template=K.chat_template??null,Array.isArray(this.chat_template)){const ae=Object.create(null);for(const{name:pe,template:Be}of this.chat_template){if(typeof pe!="string"||typeof Be!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ae[pe]=Be}this.chat_template=ae}this._compiled_template_cache=new Map}getToken(...P){for(const K of P){const ae=this._tokenizer_config[K];if(ae)if(typeof ae=="object"){if(ae.__type==="AddedToken")return ae.content;throw Error(`Unknown token: ${ae}`)}else return ae}return null}static async from_pretrained(P,{progress_callback:K=null,config:ae=null,cache_dir:pe=null,local_files_only:Be=!1,revision:wt="main",legacy:xt=null}={}){const Mt=await ee(P,{progress_callback:K,config:ae,cache_dir:pe,local_files_only:Be,revision:wt,legacy:xt});return new this(...Mt)}_call(P,{text_pair:K=null,add_special_tokens:ae=!0,padding:pe=!1,truncation:Be=null,max_length:wt=null,return_tensor:xt=!0,return_token_type_ids:Mt=null}={}){const zt=Array.isArray(P);let er;if(zt){if(P.length===0)throw Error("text array must be non-empty");if(K!==null){if(Array.isArray(K)){if(P.length!==K.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");er=P.map((ir,qt)=>this._encode_plus(ir,{text_pair:K[qt],add_special_tokens:ae,return_token_type_ids:Mt}))}else er=P.map(ir=>this._encode_plus(ir,{add_special_tokens:ae,return_token_type_ids:Mt}))}else{if(P==null)throw Error("text may not be null or undefined");if(Array.isArray(K))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");er=[this._encode_plus(P,{text_pair:K,add_special_tokens:ae,return_token_type_ids:Mt})]}if(wt===null?pe==="max_length"?wt=this.model_max_length:wt=(0,Te.max)(er.map(ir=>ir.input_ids.length))[0]:Be||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),wt=Math.min(wt,this.model_max_length??1/0),pe||Be)for(let ir=0;irwt?Be&&rt(er[ir],wt):pe&&Pe(er[ir],wt,qt=>qt==="input_ids"?this.pad_token_id:0,this.padding_side));const zr={};if(xt){if(!(pe&&Be)&&er.some(qt=>{var pr;for(const mn of Object.keys(qt))if(qt[mn].length!==((pr=er[0][mn])==null?void 0:pr.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const ir=[er.length,er[0].input_ids.length];for(const qt of Object.keys(er[0]))zr[qt]=new Ce.Tensor("int64",BigInt64Array.from(er.flatMap(pr=>pr[qt]).map(BigInt)),ir)}else{for(const ir of Object.keys(er[0]))zr[ir]=er.map(qt=>qt[ir]);if(!zt)for(const ir of Object.keys(zr))zr[ir]=zr[ir][0]}return zr}_encode_text(P){return P===null?null:(this.added_tokens_regex?P.split(this.added_tokens_regex).filter(pe=>pe):[P]).map((pe,Be)=>{if(this.added_tokens.find(xt=>xt.content===pe)!==void 0)return pe;{if(this.remove_space===!0&&(pe=pe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(pe=se(pe)),this.normalizer!==null&&(pe=this.normalizer(pe)),pe.length===0)return[];const xt=this.pre_tokenizer!==null?this.pre_tokenizer(pe,{section_index:Be}):[pe];return this.model(xt)}}).flat()}_encode_plus(P,{text_pair:K=null,add_special_tokens:ae=!0,return_token_type_ids:pe=null}={}){const{tokens:Be,token_type_ids:wt}=this._tokenize_helper(P,{pair:K,add_special_tokens:ae}),xt=this.model.convert_tokens_to_ids(Be),Mt={input_ids:xt,attention_mask:new Array(xt.length).fill(1)};return(pe??this.return_token_type_ids)&&wt&&(Mt.token_type_ids=wt),Mt}_tokenize_helper(P,{pair:K=null,add_special_tokens:ae=!1}={}){const pe=this._encode_text(P),Be=this._encode_text(K);return this.post_processor?this.post_processor(pe,Be,{add_special_tokens:ae}):{tokens:(0,fe.mergeArrays)(pe??[],Be??[])}}tokenize(P,{pair:K=null,add_special_tokens:ae=!1}={}){return this._tokenize_helper(P,{pair:K,add_special_tokens:ae}).tokens}encode(P,{text_pair:K=null,add_special_tokens:ae=!0,return_token_type_ids:pe=null}={}){return this._encode_plus(P,{text_pair:K,add_special_tokens:ae,return_token_type_ids:pe}).input_ids}batch_decode(P,K={}){return P instanceof Ce.Tensor&&(P=P.tolist()),P.map(ae=>this.decode(ae,K))}decode(P,K={}){if(P instanceof Ce.Tensor&&(P=D(P)),!Array.isArray(P)||P.length===0||!(0,fe.isIntegralNumber)(P[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(P,K)}decode_single(P,{skip_special_tokens:K=!1,clean_up_tokenization_spaces:ae=null}){let pe=this.model.convert_ids_to_tokens(P);K&&(pe=pe.filter(wt=>!this.special_tokens.includes(wt)));let Be=this.decoder?this.decoder(pe):pe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Be=Be.replaceAll(this.decoder.end_of_word_suffix," "),K&&(Be=Be.trim())),(ae??this.clean_up_tokenization_spaces)&&(Be=H(Be)),Be}get_chat_template({chat_template:P=null,tools:K=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ae=this.chat_template;if(P!==null&&Object.hasOwn(ae,P))P=ae[P];else if(P===null)if(K!==null&&"tool_use"in ae)P=ae.tool_use;else if("default"in ae)P=ae.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(ae).sort()}.`)}else if(P===null)if(this.chat_template)P=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co./docs/transformers/main/en/chat_templating");return P}apply_chat_template(P,{tools:K=null,documents:ae=null,chat_template:pe=null,add_generation_prompt:Be=!1,tokenize:wt=!0,padding:xt=!1,truncation:Mt=!1,max_length:zt=null,return_tensor:er=!0,return_dict:zr=!1,tokenizer_kwargs:ir={},...qt}={}){if(pe=this.get_chat_template({chat_template:pe,tools:K}),typeof pe!="string")throw Error(`chat_template must be a string, but got ${typeof pe}`);let pr=this._compiled_template_cache.get(pe);pr===void 0&&(pr=new S.Template(pe),this._compiled_template_cache.set(pe,pr));const mn=Object.create(null);for(const Oe of _e){const Sn=this.getToken(Oe);Sn&&(mn[Oe]=Sn)}const ln=pr.render({messages:P,add_generation_prompt:Be,tools:K,documents:ae,...mn,...qt});if(wt){const Oe=this._call(ln,{add_special_tokens:!1,padding:xt,truncation:Mt,max_length:zt,return_tensor:er,...ir});return zr?Oe:Oe.input_ids}return ln}}class Je extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class gt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class mt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Et extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class _t extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Ft extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Nt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Rt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Gt extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Me extends we{}class Ze extends we{}class ot extends we{constructor(P,K){super(P,K);xe(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 Ht extends we{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class gr extends we{}class Lr extends we{}class mr extends we{}class yr extends we{constructor(_,P){super(_,P),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)),this.lang_to_token=K=>K}_build_translation_inputs(_,P,K){return Xn(this,_,P,K)}}class Tr extends yr{}class $n extends we{}class Rr extends we{constructor(_,P){var pe,Be;const K=".,!?…。,、।۔،",ae=(Be=(pe=_.pre_tokenizer)==null?void 0:pe.pretokenizers[0])==null?void 0:Be.pattern;ae&&ae.Regex===` ?[^(\\s|[${K}])]+`&&(ae.Regex=` ?[^\\s${K}]+`),super(_,P)}}const Hn="▁";class jn extends we{constructor(P,K){super(P,K);xe(this,"padding_side","left");this.legacy=K.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new cr({replacement:Hn,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(P){if(P===null)return null;if(this.legacy||P.length===0)return super._encode_text(P);let K=super._encode_text(Hn+P.replaceAll(Hn," "));return K.length>1&&K[0]===Hn&&this.special_tokens.includes(K[1])&&(K=K.slice(1)),K}}class Ys extends we{}class vs extends we{}class xs extends we{}class Ts extends we{}class Es extends we{}class Kn extends we{}class Js extends we{}class cs extends we{}class Ln extends we{}function Xn(be,_,P,K){if(!("language_codes"in be)||!Array.isArray(be.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in be)||!(be.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in be)||typeof be.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ae=K.src_lang,pe=K.tgt_lang;if(!be.language_codes.includes(pe))throw new Error(`Target language code "${pe}" is not valid. Must be one of: {${be.language_codes.join(", ")}}`);if(ae!==void 0){if(!be.language_codes.includes(ae))throw new Error(`Source language code "${ae}" is not valid. Must be one of: {${be.language_codes.join(", ")}}`);for(const Be of be.post_processor.config.single)if("SpecialToken"in Be&&be.languageRegex.test(Be.SpecialToken.id)){Be.SpecialToken.id=be.lang_to_token(ae);break}}return K.forced_bos_token_id=be.model.convert_tokens_to_ids([be.lang_to_token(pe)])[0],be._call(_,P)}class Vn extends we{constructor(_,P){super(_,P),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)),this.lang_to_token=K=>K}_build_translation_inputs(_,P,K){return Xn(this,_,P,K)}}class rs extends we{constructor(_,P){super(_,P),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(K=>this.languageRegex.test(K)).map(K=>K.slice(2,-2)),this.lang_to_token=K=>`__${K}__`}_build_translation_inputs(_,P,K){return Xn(this,_,P,K)}}class ps extends we{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(_,{return_timestamps:P=!1,return_language:K=!1,time_precision:ae=null,force_full_sequences:pe=!0}={}){if(ae===null)throw Error("Must specify time_precision");let Be=null;const wt=P==="word";function xt(){return{language:Be,timestamp:[null,null],text:""}}const Mt=[];let zt=xt(),er=0;const zr=this.timestamp_begin;let ir=[],qt=[],pr=!1,mn=null;const ln=new Set(this.all_special_ids);for(const Er of _){const sn=Er.tokens,xn=wt?Er.token_timestamps:null;let Qt=null,Tn=zr;if("stride"in Er){const[Cr,It,br]=Er.stride;if(er-=It,mn=Cr-br,It&&(Tn=It/ae+zr),br)for(let Gr=sn.length-1;Gr>=0;--Gr){const Xr=Number(sn[Gr]);if(Xr>=zr){if(Qt!==null&&(Xr-zr)*ae=zr){const br=(It-zr)*ae+er,Gr=(0,Te.round)(br,2);if(Qt!==null&&It>=Qt)pr=!0;else if(pr||ir.length>0&&It0?(ir.push(pn),wt&&qt.push(Ar)):ir.every(Cr=>Cr.length===0)&&(zt=xt(),ir=[],pn=[],qt=[],Ar=[])}if(ir.length>0){if(pe&&P)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[Er,sn]=this.findLongestCommonSequence(ir,qt),xn=this.decode(Er);zt.text=xn,wt&&(zt.words=this.collateWordTimestamps(Er,sn,Be)),Mt.push(zt)}let Oe=Object.create(null);const Sn=Mt.map(Er=>Er.text).join("");if(P||K){for(let Er=0;Er0;let wt=Be?[]:null,xt=Be?P[0]:null;for(let Mt=1;Mt<_.length;++Mt){const zt=_[Mt];let er=0,zr=[ae,ae,0,0];const ir=zt.length;for(let Er=1;ErGr===Ar[Xr]&&xt[sn+Xr]<=P[Mt][Tn+Xr]).length:Cr=Qt.filter((Gr,Xr)=>Gr===Ar[Xr]).length;const It=Er/1e4,br=Cr/Er+It;Cr>1&&br>er&&(er=br,zr=[sn,xn,Tn,pn])}const[qt,pr,mn,ln]=zr,Oe=Math.floor((pr+qt)/2),Sn=Math.floor((ln+mn)/2);pe.push(...K.slice(0,Oe)),K=zt.slice(Sn),ae=K.length,Be&&(wt.push(...xt.slice(0,Oe)),xt=P[Mt].slice(Sn))}return pe.push(...K),Be?(wt.push(...xt),[pe,wt]):[pe,[]]}collateWordTimestamps(_,P,K){const[ae,pe,Be]=this.combineTokensIntoWords(_,K),wt=[];for(let xt=0;xt=ae){const wt=((Be-ae)*K).toFixed(2);pe.push(`<|${wt}|>`),pe.push([])}else pe[pe.length-1].push(Be);return pe=pe.map(Be=>typeof Be=="string"?Be:super.decode(Be,P)),pe.join("")}splitTokensOnUnicode(_){const P=this.decode(_,{decode_with_timestamps:!0}),K="�",ae=[],pe=[],Be=[];let wt=[],xt=[],Mt=0;for(let zt=0;zt<_.length;++zt){const er=_[zt];wt.push(er),xt.push(zt);const zr=this.decode(wt,{decode_with_timestamps:!0});(!zr.includes(K)||P[Mt+zr.indexOf(K)]===K)&&(ae.push(zr),pe.push(wt),Be.push(xt),wt=[],xt=[],Mt+=zr.length)}return[ae,pe,Be]}splitTokensOnSpaces(_){const[P,K,ae]=this.splitTokensOnUnicode(_),pe=[],Be=[],wt=[],xt=new RegExp(`^[${B}]$`,"gu");for(let Mt=0;Mt=this.model.tokens_to_ids.get("<|endoftext|>"),qt=zt.startsWith(" "),pr=zt.trim(),mn=xt.test(pr);if(ir||qt||mn||pe.length===0)pe.push(zt),Be.push(er),wt.push(zr);else{const ln=pe.length-1;pe[ln]+=zt,Be[ln].push(...er),wt[ln].push(...zr)}}return[pe,Be,wt]}mergePunctuations(_,P,K,ae,pe){const Be=structuredClone(_),wt=structuredClone(P),xt=structuredClone(K);let Mt=Be.length-2,zt=Be.length-1;for(;Mt>=0;)Be[Mt].startsWith(" ")&&ae.includes(Be[Mt].trim())?(Be[zt]=Be[Mt]+Be[zt],wt[zt]=(0,fe.mergeArrays)(wt[Mt],wt[zt]),xt[zt]=(0,fe.mergeArrays)(xt[Mt],xt[zt]),Be[Mt]="",wt[Mt]=[],xt[Mt]=[]):zt=Mt,--Mt;for(Mt=0,zt=1;zter),wt.filter(er=>er.length>0),xt.filter(er=>er.length>0)]}get_decoder_prompt_ids({language:_=null,task:P=null,no_timestamps:K=!0}={}){const ae=[];if(_){const pe=(0,V.whisper_language_to_code)(_),Be=this.model.tokens_to_ids.get(`<|${pe}|>`);if(Be===void 0)throw new Error(`Unable to find language "${pe}" in model vocabulary. Please report this issue at ${A.GITHUB_ISSUE_URL}.`);ae.push(Be)}else ae.push(null);if(P){if(P=P.toLowerCase(),P!=="transcribe"&&P!=="translate")throw new Error(`Task "${P}" is not supported. Must be one of: ["transcribe", "translate"]`);const pe=this.model.tokens_to_ids.get(`<|${P}|>`);if(pe===void 0)throw new Error(`Unable to find task "${P}" in model vocabulary. Please report this issue at ${A.GITHUB_ISSUE_URL}.`);ae.push(pe)}else ae.push(null);if(K){const pe=this.model.tokens_to_ids.get("<|notimestamps|>");if(pe===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${A.GITHUB_ISSUE_URL}.`);ae.push(pe)}return ae.map((pe,Be)=>[Be+1,pe]).filter(pe=>pe[1]!==null)}}class hs extends we{}class Xt extends we{}class ns extends we{}class Cs extends we{constructor(_,P){super(_,P),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(K=>this.languageRegex.test(K)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(_){if(_===null)return null;const[P,...K]=_.trim().split(this.languageRegex);if(K.length===0)return super._encode_text(P);if(K.length===2){const[ae,pe]=K;return this.supported_language_codes.includes(ae)||console.warn(`Unsupported language code "${ae}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,fe.mergeArrays)([ae],super._encode_text(pe))}}}class $s extends we{}class fs extends we{}class Ss extends we{}class ks extends we{}class ms extends we{}class Ps extends we{constructor(_,P){super(_,P),this.decoder=new Ot({})}}class Wr extends we{}class vn{static async from_pretrained(_,{progress_callback:P=null,config:K=null,cache_dir:ae=null,local_files_only:pe=!1,revision:Be="main",legacy:wt=null}={}){var zr;const[xt,Mt]=await ee(_,{progress_callback:P,config:K,cache_dir:ae,local_files_only:pe,revision:Be,legacy:wt}),zt=((zr=Mt.tokenizer_class)==null?void 0:zr.replace(/Fast$/,""))??"PreTrainedTokenizer";let er=this.TOKENIZER_CLASS_MAPPING[zt];return er||(console.warn(`Unknown tokenizer class "${zt}", attempting to construct from base class.`),er=we),new er(xt,Mt)}}xe(vn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:gr,DistilBertTokenizer:Me,CamembertTokenizer:Ze,DebertaTokenizer:_t,DebertaV2Tokenizer:Ft,BertTokenizer:Je,HerbertTokenizer:Nt,ConvBertTokenizer:Rt,RoFormerTokenizer:Gt,XLMTokenizer:ot,ElectraTokenizer:Ht,MobileBertTokenizer:mt,SqueezeBertTokenizer:Et,AlbertTokenizer:gt,GPT2Tokenizer:Lr,BartTokenizer:mr,MBartTokenizer:yr,MBart50Tokenizer:Tr,RobertaTokenizer:$n,WhisperTokenizer:ps,CodeGenTokenizer:hs,CLIPTokenizer:Xt,SiglipTokenizer:ns,MarianTokenizer:Cs,BloomTokenizer:Rr,NllbTokenizer:Vn,M2M100Tokenizer:rs,LlamaTokenizer:jn,CodeLlamaTokenizer:Ys,XLMRobertaTokenizer:vs,MPNetTokenizer:xs,FalconTokenizer:Ts,GPTNeoXTokenizer:Es,EsmTokenizer:Kn,Wav2Vec2CTCTokenizer:$s,BlenderbotTokenizer:fs,BlenderbotSmallTokenizer:Ss,SpeechT5Tokenizer:ks,NougatTokenizer:ms,VitsTokenizer:Ps,Qwen2Tokenizer:Js,GemmaTokenizer:cs,Grok1Tokenizer:Ln,CohereTokenizer:Wr,PreTrainedTokenizer:we})},"./src/utils/audio.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{hamming:()=>V,hanning:()=>S,mel_filter_bank:()=>H,read_audio:()=>Ce,spectrogram:()=>I,window_function:()=>B});var O=N("./src/utils/hub.js"),fe=N("./src/utils/maths.js"),ye=N("./src/utils/core.js"),Te=N("./src/utils/tensor.js");async function Ce(k,ue){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co./docs/transformers.js/guides/node-audio-processing.");const ve=await(await(0,O.getFile)(k)).arrayBuffer(),$e=new AudioContext({sampleRate:ue});typeof ue>"u"&&console.warn(`No sampling rate provided, using default of ${$e.sampleRate}Hz.`);const Ie=await $e.decodeAudioData(ve);let Ae;if(Ie.numberOfChannels===2){const tt=Math.sqrt(2),Xe=Ie.getChannelData(0),dt=Ie.getChannelData(1);Ae=new Float32Array(Xe.length);for(let ge=0;ge2595*Math.log10(1+k/700),kaldi:k=>1127*Math.log(1+k/700),slaney:(k,ue=1e3,ve=15,$e=27/Math.log(6.4))=>k>=ue?ve+Math.log(k/ue)*$e:3*k/200};function ee(k,ue="htk"){const ve=A[ue];if(!ve)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?ve(k):k.map($e=>ve($e))}const ne={htk:k=>700*(10**(k/2595)-1),kaldi:k=>700*(Math.exp(k/1127)-1),slaney:(k,ue=1e3,ve=15,$e=Math.log(6.4)/27)=>k>=ve?ue*Math.exp($e*(k-ve)):200*k/3};function me(k,ue="htk"){const ve=ne[ue];if(!ve)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?ve(k):k.map($e=>ve($e))}function ce(k,ue){const ve=Float64Array.from({length:ue.length-1},(tt,Xe)=>ue[Xe+1]-ue[Xe]),$e=Array.from({length:k.length},()=>new Array(ue.length));for(let tt=0;ttnew Array(k.length));for(let tt=0;ttk+$e*Ae)}function H(k,ue,ve,$e,Ie,Ae=null,tt="htk",Xe=!1){if(Ae!==null&&Ae!=="slaney")throw new Error('norm must be one of null or "slaney"');const dt=ee(ve,tt),ge=ee($e,tt),G=D(dt,ge,ue+2);let de=me(G,tt),Se;if(Xe){const He=Ie/(k*2);Se=ee(Float64Array.from({length:k},(ct,nt)=>nt*He),tt),de=G}else Se=D(0,Math.floor(Ie/2),k);const Z=ce(Se,de);if(Ae!==null&&Ae==="slaney")for(let He=0;HeIe)throw Error(`frame_length (${ve}) may not be larger than fft_length (${Ie})`);if(Re!==ve)throw new Error(`Length of the window (${Re}) must equal frame_length (${ve})`);if($e<=0)throw new Error("hop_length must be greater than zero");if(Ae===null&&G!==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(Xe!=="reflect")throw new Error(`pad_mode="${Xe}" not implemented yet.`);const q=Math.floor((Ie-1)/2)+1;k=te(k,q,q)}let re=Math.floor(1+Math.floor((k.length-ve)/$e));lt!==null&&rere?st&&(qe=Ne):qe=je=Ne);const Ue=new fe.FFT(Ie),Ke=new Float64Array(Ie),ut=new Float64Array(Ue.outputBufferSize),yt=new Float32Array(ke*qe);for(let q=0;q=1;--he)Ke[he]-=ge*Ke[he-1];Ke[0]*=1-ge}for(let he=0;heMath.pow(Xe,.85));break;default:throw new Error(`Unknown window type ${ue}.`)}if(ve&&(tt=tt.subarray(0,k)),$e===null)return tt;if(k>$e)throw new Error(`Length of the window (${k}) may not be larger than frame_length (${$e})`);return tt}},"./src/utils/constants.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{GITHUB_ISSUE_URL:()=>O});const O="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{calculateDimensions:()=>j,calculateReflectOffset:()=>ee,dispatchCallback:()=>O,escapeRegExp:()=>ye,isIntegralNumber:()=>Ce,isTypedArray:()=>Te,len:()=>me,mergeArrays:()=>V,pick:()=>ne,pop:()=>S,product:()=>A,reverseDictionary:()=>fe});function O(ce,D){ce&&ce(D)}function fe(ce){return Object.fromEntries(Object.entries(ce).map(([D,H])=>[H,D]))}function ye(ce){return ce.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Te(ce){var D,H,te;return((te=(H=(D=ce==null?void 0:ce.prototype)==null?void 0:D.__proto__)==null?void 0:H.constructor)==null?void 0:te.name)==="TypedArray"}function Ce(ce){return Number.isInteger(ce)||typeof ce=="bigint"}function j(ce){const D=[];let H=ce;for(;Array.isArray(H);)D.push(H.length),H=H[0];return D}function S(ce,D,H=void 0){const te=ce[D];if(te!==void 0)return delete ce[D],te;if(H===void 0)throw Error(`Key ${D} does not exist in object.`);return H}function V(...ce){return Array.prototype.concat.apply([],ce)}function A(...ce){return ce.reduce((D,H)=>D.flatMap(te=>H.map(se=>[te,se])))}function ee(ce,D){return Math.abs((ce+D)%(2*D)-D)}function ne(ce,D){return Object.assign({},...D.map(H=>{if(ce[H]!==void 0)return{[H]:ce[H]}}))}function me(ce){let D=0;for(const H of ce)++D;return D}},"./src/utils/data-structures.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{CharTrie:()=>fe,PriorityQueue:()=>O,TokenLattice:()=>Te});class O{constructor(S=(A,ee)=>A>ee,V=1/0){this._heap=[],this._comparator=S,this._maxSize=V}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...S){return this.extend(S)}extend(S){for(const V of S)if(this.size0&&this._swap(0,V),this._heap.pop(),this._siftDown(),S}replace(S){const V=this.peek();return this._heap[0]=S,this._siftDown(),V}_parent(S){return(S+1>>>1)-1}_left(S){return(S<<1)+1}_right(S){return S+1<<1}_greater(S,V){return this._comparator(this._heap[S],this._heap[V])}_swap(S,V){const A=this._heap[S];this._heap[S]=this._heap[V],this._heap[V]=A}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(S){for(;S>0&&this._greater(S,this._parent(S));)this._swap(S,this._parent(S)),S=this._parent(S)}_siftDown(){let S=0;for(;this._left(S)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const ee=new Ce(this.bosTokenId,0,0,0,0),ne=new Ce(this.eosTokenId,1,this.len,0,0);this.nodes.push(ee.clone()),this.nodes.push(ne.clone()),this.beginNodes[this.len].push(ne),this.endNodes[0].push(ee)}insert(S,V,A,ee){const ne=this.nodes.length,me=new Ce(ee,ne,S,V,A);this.beginNodes[S].push(me),this.endNodes[S+V].push(me),this.nodes.push(me)}viterbi(){const S=this.len;let V=0;for(;V<=S;){if(this.beginNodes[V].length==0)return[];for(let ce of this.beginNodes[V]){ce.prev=null;let D=0,H=null;for(let te of this.endNodes[V]){const se=te.backtraceScore+ce.score;(H===null||se>D)&&(H=te.clone(),D=se)}if(H!==null)ce.prev=H,ce.backtraceScore=D;else return[]}++V}const A=[],ne=this.beginNodes[S][0].prev;if(ne===null)return[];let me=ne.clone();for(;me.prev!==null;)A.push(me.clone()),me=me.clone().prev.clone();return A.reverse(),A}piece(S){return this.chars.slice(S.pos,S.pos+S.length).join("")}tokens(){return this.viterbi().map(V=>this.piece(V))}tokenIds(){return this.viterbi().map(V=>V.tokenId)}}class Ce{constructor(S,V,A,ee,ne){this.tokenId=S,this.nodeId=V,this.pos=A,this.length=ee,this.score=ne,this.prev=null,this.backtraceScore=0}clone(){const S=new Ce(this.tokenId,this.nodeId,this.pos,this.length,this.score);return S.prev=this.prev,S.backtraceScore=this.backtraceScore,S}}},"./src/utils/devices.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{DEVICE_TYPES:()=>O});const O=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":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{DATA_TYPES:()=>Te,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Ce,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>j,isWebGpuFp16Supported:()=>ye});var O=N("./src/env.js"),fe=N("./src/utils/devices.js");const ye=function(){let S;return async function(){if(S===void 0)if(!O.apis.IS_WEBGPU_AVAILABLE)S=!1;else try{S=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{S=!1}return S}}(),Te=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Ce=Object.freeze({[fe.DEVICE_TYPES.wasm]:Te.q8}),j=Object.freeze({[Te.fp32]:"",[Te.fp16]:"_fp16",[Te.int8]:"_int8",[Te.uint8]:"_uint8",[Te.q8]:"_quantized",[Te.q4]:"_q4",[Te.q4f16]:"_q4f16",[Te.bnb4]:"_bnb4"})},"./src/utils/generic.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{Callable:()=>O});const O=class{constructor(){let fe=function(...ye){return fe._call(...ye)};return Object.setPrototypeOf(fe,new.target.prototype)}_call(...fe){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{getFile:()=>V,getModelFile:()=>ce,getModelJSON:()=>D});var O=N("?7a2c"),fe=N("?a42a"),ye=N("./src/env.js"),Te=N("./src/utils/core.js");const Ce={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class j{constructor(X){if(this.filePath=X,this.headers=new Headers,this.exists=O.existsSync(X),this.exists){this.status=200,this.statusText="OK";let R=O.statSync(X);this.headers.set("content-length",R.size.toString()),this.updateContentType();let I=this;this.body=new ReadableStream({start(B){I.arrayBuffer().then(k=>{B.enqueue(new Uint8Array(k)),B.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const X=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Ce[X]??"application/octet-stream")}clone(){let X=new j(this.filePath);return X.exists=this.exists,X.status=this.status,X.statusText=this.statusText,X.headers=new Headers(this.headers),X}async arrayBuffer(){return(await O.promises.readFile(this.filePath)).buffer}async blob(){const X=await O.promises.readFile(this.filePath);return new Blob([X],{type:this.headers.get("content-type")})}async text(){return await O.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function S(se,X=null,R=null){let I;try{I=new URL(se)}catch{return!1}return!(X&&!X.includes(I.protocol)||R&&!R.includes(I.hostname))}async function V(se){var X;if(ye.env.useFS&&!S(se,["http:","https:","blob:"]))return new j(se);if(typeof process<"u"&&((X=process==null?void 0:process.release)==null?void 0:X.name)==="node"){const R=!!(Cn!=null&&Cn.TESTING_REMOTELY),I=ye.env.version,B=new Headers;if(B.set("User-Agent",`transformers.js/${I}; is_ci/${R};`),S(se,["http:","https:"],["huggingface.co","hf.co"])){const ue=(Cn==null?void 0:Cn.HF_TOKEN)??(Cn==null?void 0:Cn.HF_ACCESS_TOKEN);ue&&B.set("Authorization",`Bearer ${ue}`)}return fetch(se,{headers:B})}else return fetch(se)}const A={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 ee(se,X,R){if(!R)return null;const I=A[se]??`Error (${se}) occurred while trying to load file`;throw Error(`${I}: "${X}".`)}class ne{constructor(X){this.path=X}async match(X){let R=fe.join(this.path,X),I=new j(R);if(I.exists)return I}async put(X,R){const I=Buffer.from(await R.arrayBuffer());let B=fe.join(this.path,X);try{await O.promises.mkdir(fe.dirname(B),{recursive:!0}),await O.promises.writeFile(B,I)}catch(k){console.warn("An error occurred while writing the file to cache:",k)}}}async function me(se,...X){for(let R of X)try{let I=await se.match(R);if(I)return I}catch{continue}}async function ce(se,X,R=!0,I={}){if(!ye.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(!ye.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,Te.dispatchCallback)(I.progress_callback,{status:"initiate",name:se,file:X});let B;if(!B&&ye.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{B=await caches.open("transformers-cache")}catch(Se){console.warn("An error occurred while opening the browser cache:",Se)}}if(!B&&ye.env.useFSCache&&(B=new ne(I.cache_dir??ye.env.cacheDir)),!B&&ye.env.useCustomCache){if(!ye.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ye.env.customCache.match||!ye.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=ye.env.customCache}const k=I.revision??"main";let ue=te(se,X),ve=te(ye.env.localModelPath,ue),$e=te(ye.env.remoteHost,ye.env.remotePathTemplate.replaceAll("{model}",se).replaceAll("{revision}",encodeURIComponent(k)),X),Ie=k==="main"?ue:te(se,k,X),Ae,tt=B instanceof ne?Ie:$e,Xe=!1,dt;B&&(dt=await me(B,ve,tt));const ge=dt!==void 0;if(dt===void 0){if(ye.env.allowLocalModels)if(S(ue,["http:","https:"])){if(I.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ue}.`);if(!ye.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ue}.`)}else try{dt=await V(ve),Ae=ve}catch(Z){console.warn(`Unable to load from local path "${ve}": "${Z}"`)}if(dt===void 0||dt.status===404){if(I.local_files_only||!ye.env.allowRemoteModels){if(R)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ve}".`);return null}if(dt=await V($e),dt.status!==200)return ee(dt.status,$e,R);Ae=tt}Xe=B&&typeof Response<"u"&&dt instanceof Response&&dt.status===200}(0,Te.dispatchCallback)(I.progress_callback,{status:"download",name:se,file:X});const G={status:"progress",name:se,file:X};let de;return I.progress_callback?ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(de=new Uint8Array(await dt.arrayBuffer()),(0,Te.dispatchCallback)(I.progress_callback,{...G,progress:100,loaded:de.length,total:de.length})):de=await H(dt,Se=>{(0,Te.dispatchCallback)(I.progress_callback,{...G,...Se})}):de=new Uint8Array(await dt.arrayBuffer()),Xe&&Ae&&await B.match(Ae)===void 0&&await B.put(Ae,new Response(de,{headers:dt.headers})).catch(Se=>{console.warn(`Unable to add response to browser cache: ${Se}.`)}),(0,Te.dispatchCallback)(I.progress_callback,{status:"done",name:se,file:X}),de}async function D(se,X,R=!0,I={}){let B=await ce(se,X,R,I);if(B===null)return{};let ue=new TextDecoder("utf-8").decode(B);return JSON.parse(ue)}async function H(se,X){const R=se.headers.get("Content-Length");R===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let I=parseInt(R??"0"),B=new Uint8Array(I),k=0;const ue=se.body.getReader();async function ve(){const{done:$e,value:Ie}=await ue.read();if($e)return;let Ae=k+Ie.length;if(Ae>I){I=Ae;let Xe=new Uint8Array(I);Xe.set(B),B=Xe}B.set(Ie,k),k=Ae;const tt=k/I*100;return X({progress:tt,loaded:k,total:I}),ve()}return await ve(),B}function te(...se){return se=se.map((X,R)=>(R&&(X=X.replace(new RegExp("^/"),"")),R!==se.length-1&&(X=X.replace(new RegExp("/$"),"")),X)),se.join("/")}},"./src/utils/image.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{RawImage:()=>me});var O=N("./src/utils/hub.js"),fe=N("./src/env.js"),ye=N("./src/utils/tensor.js"),Te=N("?2b25");const Ce=typeof self<"u",j=Ce&&self.constructor.name==="DedicatedWorkerGlobalScope";let S,V,A;if(Ce)S=(ce,D)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ce,D)},A=self.createImageBitmap,V=self.ImageData;else if(Te)A=async ce=>{const H=(await ce.metadata()).channels,{data:te,info:se}=await ce.rotate().raw().toBuffer({resolveWithObject:!0}),X=new me(new Uint8ClampedArray(te),se.width,se.height,se.channels);return H!==void 0&&H!==se.channels&&X.convert(H),X};else throw new Error("Unable to load image processing library.");const ee={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},ne=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class me{constructor(D,H,te,se){this.data=D,this.width=H,this.height=te,this.channels=se}get size(){return[this.width,this.height]}static async read(D){if(D instanceof me)return D;if(typeof D=="string"||D instanceof URL)return await this.fromURL(D);throw new Error(`Unsupported input type: ${typeof D}`)}static fromCanvas(D){if(!Ce)throw new Error("fromCanvas() is only supported in browser environments.");const te=D.getContext("2d").getImageData(0,0,D.width,D.height).data;return new me(te,D.width,D.height,4)}static async fromURL(D){const H=await(0,O.getFile)(D);if(H.status!==200)throw new Error(`Unable to read image from "${D}" (${H.status} ${H.statusText})`);const te=await H.blob();return this.fromBlob(te)}static async fromBlob(D){if(Ce){const H=await A(D),te=S(H.width,H.height).getContext("2d");return te.drawImage(H,0,0),new this(te.getImageData(0,0,H.width,H.height).data,H.width,H.height,4)}else{const H=Te(await D.arrayBuffer());return await A(H)}}static fromTensor(D,H="CHW"){if(D.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${D.dims.length} dimensions.`);if(H==="CHW")D=D.transpose(1,2,0);else if(H!=="HWC")throw new Error(`Unsupported channel format: ${H}`);if(!(D.data instanceof Uint8ClampedArray||D.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${D.type}`);switch(D.dims[2]){case 1:case 2:case 3:case 4:return new me(D.data,D.dims[1],D.dims[0],D.dims[2]);default:throw new Error(`Unsupported number of channels: ${D.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const D=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let H=0,te=0;H=0?B=te:ue=-te,se>=0?k=se:ve=-se,I.drawImage(R,B,k,D,H,ue,ve,D,H),new me(I.getImageData(0,0,D,H).data,D,H,4).convert(X)}else{let X=this.toSharp();if(te>=0&&se>=0)X=X.extract({left:Math.floor(te),top:Math.floor(se),width:D,height:H});else if(te<=0&&se<=0){const R=Math.floor(-se),I=Math.floor(-te);X=X.extend({top:R,left:I,right:D-this.width-I,bottom:H-this.height-R})}else{let R=[0,0],I=0;se<0?(R[0]=Math.floor(-se),R[1]=H-this.height-R[0]):I=Math.floor(se);let B=[0,0],k=0;te<0?(B[0]=Math.floor(-te),B[1]=D-this.width-B[0]):k=Math.floor(te),X=X.extend({top:R[0],bottom:R[1],left:B[0],right:B[1]}).extract({left:k,top:I,width:D,height:H})}return await A(X)}}async toBlob(D="image/png",H=1){if(!Ce)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:D,quality:H})}toTensor(D="CHW"){let H=new ye.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(D!=="HWC")if(D==="CHW")H=H.permute(2,0,1);else throw new Error(`Unsupported channel format: ${D}`);return H}toCanvas(){if(!Ce)throw new Error("toCanvas() is only supported in browser environments.");const D=this.clone().rgba(),H=S(D.width,D.height),te=new V(D.data,D.width,D.height);return H.getContext("2d").putImageData(te,0,0),H}_update(D,H,te,se=null){return this.data=D,this.width=H,this.height=te,se!==null&&(this.channels=se),this}clone(){return new me(this.data.slice(),this.width,this.height,this.channels)}convert(D){if(this.channels===D)return this;switch(D){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(D){if(Ce){if(j)throw new Error("Unable to save an image from a Web Worker.");const H=D.split(".").pop().toLowerCase(),te=ne.get(H)??"image/png",se=await this.toBlob(te),X=URL.createObjectURL(se),R=document.createElement("a");R.href=X,R.download=D,R.click(),R.remove()}else{if(fe.env.useFS)return await this.toSharp().toFile(D);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Ce)throw new Error("toSharp() is only supported in server-side environments.");return Te(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{FFT:()=>ce,bankers_round:()=>te,cos_sim:()=>j,dot:()=>Ce,dynamic_time_warping:()=>se,interpolate_data:()=>O,log_softmax:()=>Te,magnitude:()=>S,max:()=>A,medianFilter:()=>D,min:()=>V,permute_data:()=>fe,round:()=>H,softmax:()=>ye});function O(X,[R,I,B],[k,ue],ve="bilinear",$e=!1){const Ie=ue/B,Ae=k/I,tt=new X.constructor(k*ue*R),Xe=I*B,dt=k*ue;for(let ge=0;ge=0;--$e)k[$e]=Ie,B[$e]=R[I[$e]],Ie*=B[$e];const ue=I.map(($e,Ie)=>k[I.indexOf(Ie)]),ve=new X.constructor(X.length);for(let $e=0;$e=0;--Ae)Ie+=tt%R[Ae]*ue[Ae],tt=Math.floor(tt/R[Ae]);ve[Ie]=X[$e]}return[ve,B]}function ye(X){const R=A(X)[0],I=X.map(ue=>Math.exp(ue-R)),B=I.reduce((ue,ve)=>ue+ve,0);return I.map(ue=>ue/B)}function Te(X){const R=A(X)[0];let I=0;for(let ue=0;ueue-R-B)}function Ce(X,R){let I=0;for(let B=0;BR+I*I,0))}function V(X){if(X.length===0)throw Error("Array must not be empty");let R=X[0],I=0;for(let B=1;BR&&(R=X[B],I=B);return[Number(R),I]}function ee(X){return X>0&&(X&X-1)===0}class ne{constructor(R){if(this.size=R|0,this.size<=1||!ee(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=R<<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<>>k&3)<>>1);for(let k=0;k>>1]=R[k];return B}toComplexArray(R,I){const B=I||this.createComplexArray();for(let k=0;k>>1],B[k+1]=0;return B}transform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._transform4(R,I,1)}realTransform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._realTransform4(R,I,1)}inverseTransform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._transform4(R,I,-1);for(let B=0;B>=2;ve>=2;ve>>=2){$e=k/ve<<1;const dt=$e>>>2;for(Ie=0;Ie>>1,ve>>>1)}else for(Ie=0,Ae=0;Ie>>1,ve>>>1,B)}const Xe=this.table;for(ve>>=2;ve>=2;ve>>=2){$e=k/ve<<1;const ge=$e>>>1,G=ge>>>1,de=G>>>1;for(Ie=0;Ie>>1;for(let ge=2;ge>1;++tt){const Xe=(tt+1-R)**2/2,dt=Math.sqrt(Ie**2+Ae**2)**Xe,ge=Xe*Math.atan2(Ae,Ie),G=2*tt;ue[G]=dt*Math.cos(ge),ue[G+1]=dt*Math.sin(ge),ve[G]=ue[G],ve[G+1]=-ue[G+1]}this._slicedChirpBuffer=ue.subarray(I,B),this._f=new ne(k>>1),this._f.transform(this._chirpBuffer,ve)}_transform(R,I,B){const k=this._buffer1,ue=this._buffer2,ve=this._outBuffer1,$e=this._outBuffer2,Ie=this._chirpBuffer,Ae=this._slicedChirpBuffer,tt=this._a;if(B)for(let Xe=0;Xe>1,G=I[ge];k[Xe]=G*Ae[Xe],k[dt]=G*Ae[dt]}else for(let Xe=0;Xe=X.length&&(Ie=2*(X.length-1)-Ie),B[ve++]=X[Ie]}B.sort(),I[ue]=B[k]}return I}function H(X,R){const I=Math.pow(10,R);return Math.round(X*I)/I}function te(X){const R=Math.round(X);return Math.abs(X)%1===.5?R%2===0?R:R-1:R}function se(X){const R=X.length,I=X[0].length,B=[R+1,I+1],k=Array.from({length:B[0]},()=>Array(B[1]).fill(1/0));k[0][0]=0;const ue=Array.from({length:B[0]},()=>Array(B[1]).fill(-1));for(let tt=1;tt0||$e>0;)switch(Ie.push(ve-1),Ae.push($e-1),ue[ve][$e]){case 0:--ve,--$e;break;case 1:--ve;break;case 2:--$e;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ve}, ${$e}]. Please file a bug report.`)}return Ie.reverse(),Ae.reverse(),[Ie,Ae]}},"./src/utils/tensor.js":($t,Ee,N)=>{N.r(Ee),N.d(Ee,{Tensor:()=>Ce,cat:()=>X,full:()=>ve,full_like:()=>$e,interpolate:()=>V,interpolate_4d:()=>A,layer_norm:()=>D,matmul:()=>ee,mean:()=>B,mean_pooling:()=>ce,ones:()=>Ie,ones_like:()=>Ae,permute:()=>S,quantize_embeddings:()=>dt,rfft:()=>ne,stack:()=>R,std_mean:()=>I,topk:()=>me,zeros:()=>tt,zeros_like:()=>Xe});var O=N("./src/utils/maths.js"),fe=N("./src/backends/onnx.js"),ye=N("./src/ops/registry.js");const Te=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class Ce{constructor(...G){xe(this,"ort_tensor");return(0,fe.isONNXTensor)(G[0])?this.ort_tensor=G[0]:this.ort_tensor=new fe.Tensor(G[0],G[1],G[2]),new Proxy(this,{get:(de,Se)=>{if(typeof Se=="string"){let Z=Number(Se);if(Number.isInteger(Z))return de._getitem(Z)}return de[Se]},set:(de,Se,Z)=>de[Se]=Z})}get dims(){return this.ort_tensor.dims}set dims(G){this.ort_tensor.dims=G}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[G,...de]=this.dims;if(de.length>0){const Se=de.reduce((Z,He)=>Z*He);for(let Z=0;Z0){const Z=Se.reduce((He,ct)=>He*ct);return this._subarray(G,Z,Se)}else return new Ce(this.type,[this.data[G]],Se)}indexOf(G){const de=this.data;for(let Se=0;SeRe)throw new Error(`Invalid slice: ${st}`);const re=[Math.max(Pt,0),Math.min(Re,this.dims[Ne])];Se.push(re),de.push(re[1]-re[0])}else throw new Error(`Invalid slice: ${st}`)}const Z=Se.map(([Ne,st])=>st-Ne),He=Z.reduce((Ne,st)=>Ne*st),ct=this.data,nt=new ct.constructor(He),lt=this.stride();for(let Ne=0;Ne=0;--Pt){const re=Z[Pt];st+=(Re%re+Se[Pt][0])*lt[Pt],Re=Math.floor(Re/re)}nt[Ne]=ct[st]}return new Ce(this.type,nt,de)}permute(...G){return S(this,G)}transpose(...G){return this.permute(...G)}sum(G=null,de=!1){return this.norm(1,G,de)}norm(G="fro",de=null,Se=!1){if(G==="fro")G=2;else if(typeof G=="string")throw Error(`Unsupported norm: ${G}`);const Z=this.data;if(de===null){let nt=Z.reduce((lt,Ne)=>lt+Ne**G,0)**(1/G);return new Ce(this.type,[nt],[])}de=se(de,this.dims.length);const He=this.dims.slice();He[de]=1;const ct=new Z.constructor(Z.length/this.dims[de]);for(let nt=0;nt=0;--Ne){const Re=this.dims[Ne];if(Ne!==de){const re=st%Re;lt+=re*Pt,Pt*=He[Ne]}st=Math.floor(st/Re)}ct[lt]+=Z[nt]**G}if(G!==1)for(let nt=0;nt=0;--lt){const Pt=this.dims[lt];if(lt!==de){const Re=Ne%Pt;nt+=Re*st,st*=this.dims[lt]}Ne=Math.floor(Ne/Pt)}Z[ct]/=He[nt]}return this}normalize(G=2,de=1){return this.clone().normalize_(G,de)}stride(){return k(this.dims)}squeeze(G=null){return new Ce(this.type,this.data,H(this.dims,G))}squeeze_(G=null){return this.dims=H(this.dims,G),this}unsqueeze(G=null){return new Ce(this.type,this.data,te(this.dims,G))}unsqueeze_(G=null){return this.dims=te(this.dims,G),this}flatten_(G=0,de=-1){de=(de+this.dims.length)%this.dims.length;let Se=this.dims.slice(0,G),Z=this.dims.slice(G,de+1),He=this.dims.slice(de+1);return this.dims=[...Se,Z.reduce((ct,nt)=>ct*nt,1),...He],this}flatten(G=0,de=-1){return this.clone().flatten_(G,de)}view(...G){let de=-1;for(let Z=0;Znt!==de?He*ct:He,1);G[de]=Se.length/Z}return new Ce(this.type,Se,G)}neg_(){const G=this.data;for(let de=0;deHe*ct);if(de!==Se)throw Error(`cannot reshape array of size ${de} into shape (${G})`);let Z=ge;for(let He=G.length-1;He>=0;He--)Z=Z.reduce((ct,nt)=>{let lt=ct[ct.length-1];return lt.lengthde!==1):typeof G=="number"?ge[G]===1&&ge.splice(G,1):Array.isArray(G)&&(ge=ge.filter((de,Se)=>de!==1||!G.includes(Se))),ge}function te(ge,G){return G=se(G,ge.length+1),ge=ge.slice(),ge.splice(G,0,1),ge}function se(ge,G,de=null,Se=!0){if(Se&&(ge<-G||ge>=G))throw new Error(`IndexError: index ${ge} is out of bounds for dimension${de===null?"":" "+de} with size ${G}`);return ge<0&&(ge=(ge%G+G)%G),ge}function X(ge,G=0){G=se(G,ge[0].dims.length);const de=ge[0].dims.slice();de[G]=ge.reduce((ct,nt)=>ct+nt.dims[G],0);const Se=de.reduce((ct,nt)=>ct*nt,1),Z=new ge[0].data.constructor(Se),He=ge[0].type;if(G===0){let ct=0;for(const nt of ge){const lt=nt.data;Z.set(lt,ct),ct+=lt.length}}else{let ct=0;for(let nt=0;nt=0;--Re){const je=Ne[Re];let qe=re%je;Re===G&&(qe+=ct),Pt+=qe*ke,ke*=de[Re],re=Math.floor(re/je)}Z[Pt]=lt[st]}ct+=Ne[G]}}return new Ce(He,Z,de)}function R(ge,G=0){return X(ge.map(de=>de.unsqueeze(G)),G)}function I(ge,G=null,de=1,Se=!1){const Z=ge.data,He=ge.dims;if(G===null){const Re=Z.reduce((qe,Ue)=>qe+Ue,0)/Z.length,re=Math.sqrt(Z.reduce((qe,Ue)=>qe+(Ue-Re)**2,0)/(Z.length-de)),ke=new Ce(ge.type,[Re],[]);return[new Ce(ge.type,[re],[]),ke]}G=se(G,He.length);const ct=B(ge,G,Se),nt=ct.data,lt=He.slice();lt[G]=1;const Ne=new Z.constructor(Z.length/He[G]);for(let Pt=0;Pt=0;--re){const qe=He[re];if(re!==G){const Ue=ke%qe;Re+=Ue*je,je*=lt[re]}ke=Math.floor(ke/qe)}Ne[Re]+=(Z[Pt]-nt[Re])**2}for(let Pt=0;Ptlt+Ne,0);return new Ce(ge.type,[nt/Se.length],[])}const Z=ge.dims;G=se(G,Z.length);const He=Z.slice();He[G]=1;const ct=new Se.constructor(Se.length/Z[G]);for(let nt=0;nt=0;--Ne){const Re=Z[Ne];if(Ne!==G){const re=st%Re;lt+=re*Pt,Pt*=He[Ne]}st=Math.floor(st/Re)}ct[lt]+=Se[nt]}if(Z[G]!==1)for(let nt=0;nt=0;--de)G[de]=Se,Se*=ge[de];return G}function ue(ge,G,de,Se){const Z=ge.reduce((He,ct)=>He*ct,1);return new Ce(de,new Se(Z).fill(G),ge)}function ve(ge,G){let de,Se;if(typeof G=="number")de="float32",Se=Float32Array;else if(typeof G=="bigint")de="int64",Se=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof G}`);return ue(ge,G,de,Se)}function $e(ge,G){return ve(ge.dims,G)}function Ie(ge){return ue(ge,1n,"int64",BigInt64Array)}function Ae(ge){return Ie(ge.dims)}function tt(ge){return ue(ge,0n,"int64",BigInt64Array)}function Xe(ge){return tt(ge.dims)}function dt(ge,G){if(ge.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ge.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(G))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=G==="binary",Se=de?"int8":"uint8",Z=de?Int8Array:Uint8Array,He=ge.data,ct=new Z(He.length/8);for(let nt=0;nt0?1:0,Ne=Math.floor(nt/8),st=nt%8;ct[Ne]|=lt<<7-st,de&&st===0&&(ct[Ne]-=128)}return new Ce(Se,ct,[ge.dims[0],ge.dims[1]/8])}}},Qs={};function qr($t){var Ee=Qs[$t];if(Ee!==void 0)return Ee.exports;var N=Qs[$t]={exports:{}};return ts[$t](N,N.exports,qr),N.exports}qr.m=ts,(()=>{var $t=Object.getPrototypeOf?N=>Object.getPrototypeOf(N):N=>N.__proto__,Ee;qr.t=function(N,O){if(O&1&&(N=this(N)),O&8||typeof N=="object"&&N&&(O&4&&N.__esModule||O&16&&typeof N.then=="function"))return N;var fe=Object.create(null);qr.r(fe);var ye={};Ee=Ee||[null,$t({}),$t([]),$t($t)];for(var Te=O&2&&N;typeof Te=="object"&&!~Ee.indexOf(Te);Te=$t(Te))Object.getOwnPropertyNames(Te).forEach(Ce=>ye[Ce]=()=>N[Ce]);return ye.default=()=>N,qr.d(fe,ye),fe}})(),qr.d=($t,Ee)=>{for(var N in Ee)qr.o(Ee,N)&&!qr.o($t,N)&&Object.defineProperty($t,N,{enumerable:!0,get:Ee[N]})},qr.o=($t,Ee)=>Object.prototype.hasOwnProperty.call($t,Ee),qr.r=$t=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty($t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty($t,"__esModule",{value:!0})},(()=>{var $t;if(typeof self.location.href=="string"&&($t=self.location.href),!$t)throw new Error("Automatic publicPath is not supported in this browser");$t=$t.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),qr.p=$t})(),qr.b=new URL("./",self.location.href);var c={};/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/qr.r(c),qr.d(c,{ASTFeatureExtractor:()=>Zt.ASTFeatureExtractor,ASTForAudioClassification:()=>b.ASTForAudioClassification,ASTModel:()=>b.ASTModel,ASTPreTrainedModel:()=>b.ASTPreTrainedModel,AlbertForMaskedLM:()=>b.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>b.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>b.AlbertForSequenceClassification,AlbertModel:()=>b.AlbertModel,AlbertPreTrainedModel:()=>b.AlbertPreTrainedModel,AlbertTokenizer:()=>nr.AlbertTokenizer,AudioClassificationPipeline:()=>Hr.AudioClassificationPipeline,AutoConfig:()=>mc.AutoConfig,AutoModel:()=>b.AutoModel,AutoModelForAudioClassification:()=>b.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>b.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>b.AutoModelForCTC,AutoModelForCausalLM:()=>b.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>b.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>b.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>b.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>b.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>b.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>b.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>b.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>b.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>b.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>b.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>b.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>b.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>b.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>b.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>b.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>b.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>b.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>b.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>b.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>b.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>b.AutoModelForVision2Seq,AutoModelForXVector:()=>b.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>b.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Zt.AutoProcessor,AutoTokenizer:()=>nr.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>Hr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>b.BartForConditionalGeneration,BartForSequenceClassification:()=>b.BartForSequenceClassification,BartModel:()=>b.BartModel,BartPretrainedModel:()=>b.BartPretrainedModel,BartTokenizer:()=>nr.BartTokenizer,BaseModelOutput:()=>b.BaseModelOutput,BaseStreamer:()=>_c.BaseStreamer,BeitFeatureExtractor:()=>Zt.BeitFeatureExtractor,BeitForImageClassification:()=>b.BeitForImageClassification,BeitModel:()=>b.BeitModel,BeitPreTrainedModel:()=>b.BeitPreTrainedModel,BertForMaskedLM:()=>b.BertForMaskedLM,BertForQuestionAnswering:()=>b.BertForQuestionAnswering,BertForSequenceClassification:()=>b.BertForSequenceClassification,BertForTokenClassification:()=>b.BertForTokenClassification,BertModel:()=>b.BertModel,BertPreTrainedModel:()=>b.BertPreTrainedModel,BertTokenizer:()=>nr.BertTokenizer,BitImageProcessor:()=>Zt.BitImageProcessor,BlenderbotForConditionalGeneration:()=>b.BlenderbotForConditionalGeneration,BlenderbotModel:()=>b.BlenderbotModel,BlenderbotPreTrainedModel:()=>b.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>b.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>b.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>b.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>nr.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>nr.BlenderbotTokenizer,BloomForCausalLM:()=>b.BloomForCausalLM,BloomModel:()=>b.BloomModel,BloomPreTrainedModel:()=>b.BloomPreTrainedModel,BloomTokenizer:()=>nr.BloomTokenizer,CLIPFeatureExtractor:()=>Zt.CLIPFeatureExtractor,CLIPImageProcessor:()=>Zt.CLIPImageProcessor,CLIPModel:()=>b.CLIPModel,CLIPPreTrainedModel:()=>b.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>b.CLIPSegForImageSegmentation,CLIPSegModel:()=>b.CLIPSegModel,CLIPSegPreTrainedModel:()=>b.CLIPSegPreTrainedModel,CLIPTextModel:()=>b.CLIPTextModel,CLIPTextModelWithProjection:()=>b.CLIPTextModelWithProjection,CLIPTokenizer:()=>nr.CLIPTokenizer,CLIPVisionModel:()=>b.CLIPVisionModel,CLIPVisionModelWithProjection:()=>b.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>b.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>b.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>b.CamembertForSequenceClassification,CamembertForTokenClassification:()=>b.CamembertForTokenClassification,CamembertModel:()=>b.CamembertModel,CamembertPreTrainedModel:()=>b.CamembertPreTrainedModel,CamembertTokenizer:()=>nr.CamembertTokenizer,CausalLMOutput:()=>b.CausalLMOutput,CausalLMOutputWithPast:()=>b.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Zt.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>b.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>b.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>b.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Zt.ClapFeatureExtractor,ClapModel:()=>b.ClapModel,ClapPreTrainedModel:()=>b.ClapPreTrainedModel,ClapTextModelWithProjection:()=>b.ClapTextModelWithProjection,CodeGenForCausalLM:()=>b.CodeGenForCausalLM,CodeGenModel:()=>b.CodeGenModel,CodeGenPreTrainedModel:()=>b.CodeGenPreTrainedModel,CodeGenTokenizer:()=>nr.CodeGenTokenizer,CodeLlamaTokenizer:()=>nr.CodeLlamaTokenizer,CohereForCausalLM:()=>b.CohereForCausalLM,CohereModel:()=>b.CohereModel,CoherePreTrainedModel:()=>b.CoherePreTrainedModel,CohereTokenizer:()=>nr.CohereTokenizer,ConvBertForMaskedLM:()=>b.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>b.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>b.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>b.ConvBertForTokenClassification,ConvBertModel:()=>b.ConvBertModel,ConvBertPreTrainedModel:()=>b.ConvBertPreTrainedModel,ConvBertTokenizer:()=>nr.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Zt.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>b.ConvNextForImageClassification,ConvNextImageProcessor:()=>Zt.ConvNextImageProcessor,ConvNextModel:()=>b.ConvNextModel,ConvNextPreTrainedModel:()=>b.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>b.ConvNextV2ForImageClassification,ConvNextV2Model:()=>b.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>b.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Zt.DPTFeatureExtractor,DPTForDepthEstimation:()=>b.DPTForDepthEstimation,DPTImageProcessor:()=>Zt.DPTImageProcessor,DPTModel:()=>b.DPTModel,DPTPreTrainedModel:()=>b.DPTPreTrainedModel,DebertaForMaskedLM:()=>b.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>b.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>b.DebertaForSequenceClassification,DebertaForTokenClassification:()=>b.DebertaForTokenClassification,DebertaModel:()=>b.DebertaModel,DebertaPreTrainedModel:()=>b.DebertaPreTrainedModel,DebertaTokenizer:()=>nr.DebertaTokenizer,DebertaV2ForMaskedLM:()=>b.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>b.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>b.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>b.DebertaV2ForTokenClassification,DebertaV2Model:()=>b.DebertaV2Model,DebertaV2PreTrainedModel:()=>b.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>nr.DebertaV2Tokenizer,DecisionTransformerModel:()=>b.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>b.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>Zt.DeiTFeatureExtractor,DeiTForImageClassification:()=>b.DeiTForImageClassification,DeiTModel:()=>b.DeiTModel,DeiTPreTrainedModel:()=>b.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>b.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>b.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>Hr.DepthEstimationPipeline,DetrFeatureExtractor:()=>Zt.DetrFeatureExtractor,DetrForObjectDetection:()=>b.DetrForObjectDetection,DetrForSegmentation:()=>b.DetrForSegmentation,DetrModel:()=>b.DetrModel,DetrObjectDetectionOutput:()=>b.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>b.DetrPreTrainedModel,DetrSegmentationOutput:()=>b.DetrSegmentationOutput,Dinov2ForImageClassification:()=>b.Dinov2ForImageClassification,Dinov2Model:()=>b.Dinov2Model,Dinov2PreTrainedModel:()=>b.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>b.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>b.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>b.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>b.DistilBertForTokenClassification,DistilBertModel:()=>b.DistilBertModel,DistilBertPreTrainedModel:()=>b.DistilBertPreTrainedModel,DistilBertTokenizer:()=>nr.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>Hr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Zt.DonutFeatureExtractor,DonutSwinModel:()=>b.DonutSwinModel,DonutSwinPreTrainedModel:()=>b.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>b.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Zt.EfficientNetImageProcessor,EfficientNetModel:()=>b.EfficientNetModel,EfficientNetPreTrainedModel:()=>b.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>b.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>b.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>b.ElectraForSequenceClassification,ElectraForTokenClassification:()=>b.ElectraForTokenClassification,ElectraModel:()=>b.ElectraModel,ElectraPreTrainedModel:()=>b.ElectraPreTrainedModel,ElectraTokenizer:()=>nr.ElectraTokenizer,EosTokenCriteria:()=>eo.EosTokenCriteria,EsmForMaskedLM:()=>b.EsmForMaskedLM,EsmForSequenceClassification:()=>b.EsmForSequenceClassification,EsmForTokenClassification:()=>b.EsmForTokenClassification,EsmModel:()=>b.EsmModel,EsmPreTrainedModel:()=>b.EsmPreTrainedModel,EsmTokenizer:()=>nr.EsmTokenizer,FFT:()=>An.FFT,FalconForCausalLM:()=>b.FalconForCausalLM,FalconModel:()=>b.FalconModel,FalconPreTrainedModel:()=>b.FalconPreTrainedModel,FalconTokenizer:()=>nr.FalconTokenizer,FastViTForImageClassification:()=>b.FastViTForImageClassification,FastViTModel:()=>b.FastViTModel,FastViTPreTrainedModel:()=>b.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>Hr.FeatureExtractionPipeline,FeatureExtractor:()=>Zt.FeatureExtractor,FillMaskPipeline:()=>Hr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>b.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>b.Florence2PreTrainedModel,Florence2Processor:()=>Zt.Florence2Processor,GLPNFeatureExtractor:()=>Zt.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>b.GLPNForDepthEstimation,GLPNModel:()=>b.GLPNModel,GLPNPreTrainedModel:()=>b.GLPNPreTrainedModel,GPT2LMHeadModel:()=>b.GPT2LMHeadModel,GPT2Model:()=>b.GPT2Model,GPT2PreTrainedModel:()=>b.GPT2PreTrainedModel,GPT2Tokenizer:()=>nr.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>b.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>b.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>b.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>b.GPTJForCausalLM,GPTJModel:()=>b.GPTJModel,GPTJPreTrainedModel:()=>b.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>b.GPTNeoForCausalLM,GPTNeoModel:()=>b.GPTNeoModel,GPTNeoPreTrainedModel:()=>b.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>b.GPTNeoXForCausalLM,GPTNeoXModel:()=>b.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>b.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>nr.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>b.Gemma2ForCausalLM,Gemma2Model:()=>b.Gemma2Model,Gemma2PreTrainedModel:()=>b.Gemma2PreTrainedModel,GemmaForCausalLM:()=>b.GemmaForCausalLM,GemmaModel:()=>b.GemmaModel,GemmaPreTrainedModel:()=>b.GemmaPreTrainedModel,GemmaTokenizer:()=>nr.GemmaTokenizer,Grok1Tokenizer:()=>nr.Grok1Tokenizer,GroupViTModel:()=>b.GroupViTModel,GroupViTPreTrainedModel:()=>b.GroupViTPreTrainedModel,HerbertTokenizer:()=>nr.HerbertTokenizer,HieraForImageClassification:()=>b.HieraForImageClassification,HieraModel:()=>b.HieraModel,HieraPreTrainedModel:()=>b.HieraPreTrainedModel,HubertForCTC:()=>b.HubertForCTC,HubertForSequenceClassification:()=>b.HubertForSequenceClassification,HubertModel:()=>b.HubertModel,HubertPreTrainedModel:()=>b.HubertPreTrainedModel,ImageClassificationPipeline:()=>Hr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>Hr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Zt.ImageFeatureExtractor,ImageMattingOutput:()=>b.ImageMattingOutput,ImageSegmentationPipeline:()=>Hr.ImageSegmentationPipeline,ImageToImagePipeline:()=>Hr.ImageToImagePipeline,ImageToTextPipeline:()=>Hr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>eo.InterruptableStoppingCriteria,JAISLMHeadModel:()=>b.JAISLMHeadModel,JAISModel:()=>b.JAISModel,JAISPreTrainedModel:()=>b.JAISPreTrainedModel,LlamaForCausalLM:()=>b.LlamaForCausalLM,LlamaModel:()=>b.LlamaModel,LlamaPreTrainedModel:()=>b.LlamaPreTrainedModel,LlamaTokenizer:()=>nr.LlamaTokenizer,LlavaForConditionalGeneration:()=>b.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>b.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>b.LongT5ForConditionalGeneration,LongT5Model:()=>b.LongT5Model,LongT5PreTrainedModel:()=>b.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>b.M2M100ForConditionalGeneration,M2M100Model:()=>b.M2M100Model,M2M100PreTrainedModel:()=>b.M2M100PreTrainedModel,M2M100Tokenizer:()=>nr.M2M100Tokenizer,MBart50Tokenizer:()=>nr.MBart50Tokenizer,MBartForCausalLM:()=>b.MBartForCausalLM,MBartForConditionalGeneration:()=>b.MBartForConditionalGeneration,MBartForSequenceClassification:()=>b.MBartForSequenceClassification,MBartModel:()=>b.MBartModel,MBartPreTrainedModel:()=>b.MBartPreTrainedModel,MBartTokenizer:()=>nr.MBartTokenizer,MPNetForMaskedLM:()=>b.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>b.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>b.MPNetForSequenceClassification,MPNetForTokenClassification:()=>b.MPNetForTokenClassification,MPNetModel:()=>b.MPNetModel,MPNetPreTrainedModel:()=>b.MPNetPreTrainedModel,MPNetTokenizer:()=>nr.MPNetTokenizer,MT5ForConditionalGeneration:()=>b.MT5ForConditionalGeneration,MT5Model:()=>b.MT5Model,MT5PreTrainedModel:()=>b.MT5PreTrainedModel,MarianMTModel:()=>b.MarianMTModel,MarianModel:()=>b.MarianModel,MarianPreTrainedModel:()=>b.MarianPreTrainedModel,MarianTokenizer:()=>nr.MarianTokenizer,MaskFormerFeatureExtractor:()=>Zt.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>b.MaskFormerForInstanceSegmentation,MaskFormerModel:()=>b.MaskFormerModel,MaskFormerPreTrainedModel:()=>b.MaskFormerPreTrainedModel,MaskedLMOutput:()=>b.MaskedLMOutput,MaxLengthCriteria:()=>eo.MaxLengthCriteria,MistralForCausalLM:()=>b.MistralForCausalLM,MistralModel:()=>b.MistralModel,MistralPreTrainedModel:()=>b.MistralPreTrainedModel,MobileBertForMaskedLM:()=>b.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>b.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>b.MobileBertForSequenceClassification,MobileBertModel:()=>b.MobileBertModel,MobileBertPreTrainedModel:()=>b.MobileBertPreTrainedModel,MobileBertTokenizer:()=>nr.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>Zt.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>b.MobileNetV1ForImageClassification,MobileNetV1Model:()=>b.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>b.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Zt.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>b.MobileNetV2ForImageClassification,MobileNetV2Model:()=>b.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>b.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Zt.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>b.MobileNetV3ForImageClassification,MobileNetV3Model:()=>b.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>b.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Zt.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>b.MobileNetV4ForImageClassification,MobileNetV4Model:()=>b.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>b.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Zt.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>b.MobileViTForImageClassification,MobileViTImageProcessor:()=>Zt.MobileViTImageProcessor,MobileViTModel:()=>b.MobileViTModel,MobileViTPreTrainedModel:()=>b.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>b.MobileViTV2ForImageClassification,MobileViTV2Model:()=>b.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>b.MobileViTV2PreTrainedModel,ModelOutput:()=>b.ModelOutput,Moondream1ForConditionalGeneration:()=>b.Moondream1ForConditionalGeneration,MptForCausalLM:()=>b.MptForCausalLM,MptModel:()=>b.MptModel,MptPreTrainedModel:()=>b.MptPreTrainedModel,MusicgenForCausalLM:()=>b.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>b.MusicgenForConditionalGeneration,MusicgenModel:()=>b.MusicgenModel,MusicgenPreTrainedModel:()=>b.MusicgenPreTrainedModel,NllbTokenizer:()=>nr.NllbTokenizer,NomicBertModel:()=>b.NomicBertModel,NomicBertPreTrainedModel:()=>b.NomicBertPreTrainedModel,NougatImageProcessor:()=>Zt.NougatImageProcessor,NougatTokenizer:()=>nr.NougatTokenizer,OPTForCausalLM:()=>b.OPTForCausalLM,OPTModel:()=>b.OPTModel,OPTPreTrainedModel:()=>b.OPTPreTrainedModel,ObjectDetectionPipeline:()=>Hr.ObjectDetectionPipeline,OpenELMForCausalLM:()=>b.OpenELMForCausalLM,OpenELMModel:()=>b.OpenELMModel,OpenELMPreTrainedModel:()=>b.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Zt.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>b.OwlViTForObjectDetection,OwlViTModel:()=>b.OwlViTModel,OwlViTPreTrainedModel:()=>b.OwlViTPreTrainedModel,OwlViTProcessor:()=>Zt.OwlViTProcessor,Owlv2ForObjectDetection:()=>b.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Zt.Owlv2ImageProcessor,Owlv2Model:()=>b.Owlv2Model,Owlv2PreTrainedModel:()=>b.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>b.Phi3ForCausalLM,Phi3Model:()=>b.Phi3Model,Phi3PreTrainedModel:()=>b.Phi3PreTrainedModel,PhiForCausalLM:()=>b.PhiForCausalLM,PhiModel:()=>b.PhiModel,PhiPreTrainedModel:()=>b.PhiPreTrainedModel,Pipeline:()=>Hr.Pipeline,PreTrainedModel:()=>b.PreTrainedModel,PreTrainedTokenizer:()=>nr.PreTrainedTokenizer,PretrainedConfig:()=>mc.PretrainedConfig,PretrainedMixin:()=>b.PretrainedMixin,Processor:()=>Zt.Processor,PvtForImageClassification:()=>b.PvtForImageClassification,PvtImageProcessor:()=>Zt.PvtImageProcessor,PvtModel:()=>b.PvtModel,PvtPreTrainedModel:()=>b.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>Zt.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>b.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>b.PyAnnoteModel,PyAnnotePreTrainedModel:()=>b.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Zt.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>b.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>Hr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>b.Qwen2ForCausalLM,Qwen2Model:()=>b.Qwen2Model,Qwen2PreTrainedModel:()=>b.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>nr.Qwen2Tokenizer,RTDetrForObjectDetection:()=>b.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Zt.RTDetrImageProcessor,RTDetrModel:()=>b.RTDetrModel,RTDetrObjectDetectionOutput:()=>b.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>b.RTDetrPreTrainedModel,RawImage:()=>vf.RawImage,ResNetForImageClassification:()=>b.ResNetForImageClassification,ResNetModel:()=>b.ResNetModel,ResNetPreTrainedModel:()=>b.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>b.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>b.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>b.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>b.RoFormerForTokenClassification,RoFormerModel:()=>b.RoFormerModel,RoFormerPreTrainedModel:()=>b.RoFormerPreTrainedModel,RoFormerTokenizer:()=>nr.RoFormerTokenizer,RobertaForMaskedLM:()=>b.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>b.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>b.RobertaForSequenceClassification,RobertaForTokenClassification:()=>b.RobertaForTokenClassification,RobertaModel:()=>b.RobertaModel,RobertaPreTrainedModel:()=>b.RobertaPreTrainedModel,RobertaTokenizer:()=>nr.RobertaTokenizer,SamImageProcessor:()=>Zt.SamImageProcessor,SamImageSegmentationOutput:()=>b.SamImageSegmentationOutput,SamModel:()=>b.SamModel,SamPreTrainedModel:()=>b.SamPreTrainedModel,SamProcessor:()=>Zt.SamProcessor,SapiensFeatureExtractor:()=>Zt.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>b.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>b.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>b.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>b.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Zt.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Zt.SegformerFeatureExtractor,SegformerForImageClassification:()=>b.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>b.SegformerForSemanticSegmentation,SegformerModel:()=>b.SegformerModel,SegformerPreTrainedModel:()=>b.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>b.Seq2SeqLMOutput,SequenceClassifierOutput:()=>b.SequenceClassifierOutput,SiglipImageProcessor:()=>Zt.SiglipImageProcessor,SiglipModel:()=>b.SiglipModel,SiglipPreTrainedModel:()=>b.SiglipPreTrainedModel,SiglipTextModel:()=>b.SiglipTextModel,SiglipTokenizer:()=>nr.SiglipTokenizer,SiglipVisionModel:()=>b.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Zt.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>b.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>b.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>b.SpeechT5HifiGan,SpeechT5Model:()=>b.SpeechT5Model,SpeechT5PreTrainedModel:()=>b.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Zt.SpeechT5Processor,SpeechT5Tokenizer:()=>nr.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>b.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>b.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>b.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>b.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>b.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>nr.SqueezeBertTokenizer,StableLmForCausalLM:()=>b.StableLmForCausalLM,StableLmModel:()=>b.StableLmModel,StableLmPreTrainedModel:()=>b.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>b.Starcoder2ForCausalLM,Starcoder2Model:()=>b.Starcoder2Model,Starcoder2PreTrainedModel:()=>b.Starcoder2PreTrainedModel,StoppingCriteria:()=>eo.StoppingCriteria,StoppingCriteriaList:()=>eo.StoppingCriteriaList,SummarizationPipeline:()=>Hr.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>b.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Zt.Swin2SRImageProcessor,Swin2SRModel:()=>b.Swin2SRModel,Swin2SRPreTrainedModel:()=>b.Swin2SRPreTrainedModel,SwinForImageClassification:()=>b.SwinForImageClassification,SwinModel:()=>b.SwinModel,SwinPreTrainedModel:()=>b.SwinPreTrainedModel,T5ForConditionalGeneration:()=>b.T5ForConditionalGeneration,T5Model:()=>b.T5Model,T5PreTrainedModel:()=>b.T5PreTrainedModel,T5Tokenizer:()=>nr.T5Tokenizer,TableTransformerForObjectDetection:()=>b.TableTransformerForObjectDetection,TableTransformerModel:()=>b.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>b.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>b.TableTransformerPreTrainedModel,Tensor:()=>on.Tensor,Text2TextGenerationPipeline:()=>Hr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>Hr.TextClassificationPipeline,TextGenerationPipeline:()=>Hr.TextGenerationPipeline,TextStreamer:()=>_c.TextStreamer,TextToAudioPipeline:()=>Hr.TextToAudioPipeline,TokenClassificationPipeline:()=>Hr.TokenClassificationPipeline,TokenClassifierOutput:()=>b.TokenClassifierOutput,TokenizerModel:()=>nr.TokenizerModel,TrOCRForCausalLM:()=>b.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>b.TrOCRPreTrainedModel,TranslationPipeline:()=>Hr.TranslationPipeline,UniSpeechForCTC:()=>b.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>b.UniSpeechForSequenceClassification,UniSpeechModel:()=>b.UniSpeechModel,UniSpeechPreTrainedModel:()=>b.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>b.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>b.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>b.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>b.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>b.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>Zt.ViTFeatureExtractor,ViTForImageClassification:()=>b.ViTForImageClassification,ViTImageProcessor:()=>Zt.ViTImageProcessor,ViTMAEModel:()=>b.ViTMAEModel,ViTMAEPreTrainedModel:()=>b.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>b.ViTMSNForImageClassification,ViTMSNModel:()=>b.ViTMSNModel,ViTMSNPreTrainedModel:()=>b.ViTMSNPreTrainedModel,ViTModel:()=>b.ViTModel,ViTPreTrainedModel:()=>b.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>b.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>b.VitMatteForImageMatting,VitMatteImageProcessor:()=>Zt.VitMatteImageProcessor,VitMattePreTrainedModel:()=>b.VitMattePreTrainedModel,VitsModel:()=>b.VitsModel,VitsModelOutput:()=>b.VitsModelOutput,VitsPreTrainedModel:()=>b.VitsPreTrainedModel,VitsTokenizer:()=>nr.VitsTokenizer,Wav2Vec2BertForCTC:()=>b.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>b.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>b.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>b.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>nr.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Zt.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>b.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>b.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>b.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>b.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>b.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Zt.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>b.WavLMForAudioFrameClassification,WavLMForCTC:()=>b.WavLMForCTC,WavLMForSequenceClassification:()=>b.WavLMForSequenceClassification,WavLMForXVector:()=>b.WavLMForXVector,WavLMModel:()=>b.WavLMModel,WavLMPreTrainedModel:()=>b.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Zt.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>b.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>b.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Zt.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>b.WhisperForConditionalGeneration,WhisperModel:()=>b.WhisperModel,WhisperPreTrainedModel:()=>b.WhisperPreTrainedModel,WhisperProcessor:()=>Zt.WhisperProcessor,WhisperTextStreamer:()=>_c.WhisperTextStreamer,WhisperTokenizer:()=>nr.WhisperTokenizer,XLMForQuestionAnswering:()=>b.XLMForQuestionAnswering,XLMForSequenceClassification:()=>b.XLMForSequenceClassification,XLMForTokenClassification:()=>b.XLMForTokenClassification,XLMModel:()=>b.XLMModel,XLMPreTrainedModel:()=>b.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>b.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>b.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>b.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>b.XLMRobertaForTokenClassification,XLMRobertaModel:()=>b.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>b.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>nr.XLMRobertaTokenizer,XLMTokenizer:()=>nr.XLMTokenizer,XLMWithLMHeadModel:()=>b.XLMWithLMHeadModel,XVectorOutput:()=>b.XVectorOutput,YolosFeatureExtractor:()=>Zt.YolosFeatureExtractor,YolosForObjectDetection:()=>b.YolosForObjectDetection,YolosModel:()=>b.YolosModel,YolosObjectDetectionOutput:()=>b.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>b.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>Hr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>Hr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>Hr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>Hr.ZeroShotObjectDetectionPipeline,bankers_round:()=>An.bankers_round,cat:()=>on.cat,cos_sim:()=>An.cos_sim,dot:()=>An.dot,dynamic_time_warping:()=>An.dynamic_time_warping,env:()=>Mf.env,full:()=>on.full,full_like:()=>on.full_like,getKeyValueShapes:()=>mc.getKeyValueShapes,hamming:()=>yi.hamming,hanning:()=>yi.hanning,interpolate:()=>on.interpolate,interpolate_4d:()=>on.interpolate_4d,interpolate_data:()=>An.interpolate_data,is_chinese_char:()=>nr.is_chinese_char,layer_norm:()=>on.layer_norm,log_softmax:()=>An.log_softmax,magnitude:()=>An.magnitude,matmul:()=>on.matmul,max:()=>An.max,mean:()=>on.mean,mean_pooling:()=>on.mean_pooling,medianFilter:()=>An.medianFilter,mel_filter_bank:()=>yi.mel_filter_bank,min:()=>An.min,ones:()=>on.ones,ones_like:()=>on.ones_like,permute:()=>on.permute,permute_data:()=>An.permute_data,pipeline:()=>Hr.pipeline,quantize_embeddings:()=>on.quantize_embeddings,read_audio:()=>yi.read_audio,rfft:()=>on.rfft,round:()=>An.round,softmax:()=>An.softmax,spectrogram:()=>yi.spectrogram,stack:()=>on.stack,std_mean:()=>on.std_mean,topk:()=>on.topk,window_function:()=>yi.window_function,zeros:()=>on.zeros,zeros_like:()=>on.zeros_like});var Mf=qr("./src/env.js"),Hr=qr("./src/pipelines.js"),b=qr("./src/models.js"),nr=qr("./src/tokenizers.js"),Zt=qr("./src/processors.js"),mc=qr("./src/configs.js"),yi=qr("./src/utils/audio.js"),vf=qr("./src/utils/image.js"),on=qr("./src/utils/tensor.js"),An=qr("./src/utils/maths.js"),_c=qr("./src/generation/streamers.js"),eo=qr("./src/generation/stopping_criteria.js");c.ASTFeatureExtractor,c.ASTForAudioClassification,c.ASTModel,c.ASTPreTrainedModel,c.AlbertForMaskedLM,c.AlbertForQuestionAnswering,c.AlbertForSequenceClassification,c.AlbertModel,c.AlbertPreTrainedModel,c.AlbertTokenizer,c.AudioClassificationPipeline,c.AutoConfig,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC;var xf=c.AutoModelForCausalLM;c.AutoModelForDepthEstimation,c.AutoModelForDocumentQuestionAnswering,c.AutoModelForImageClassification,c.AutoModelForImageFeatureExtraction,c.AutoModelForImageMatting,c.AutoModelForImageSegmentation,c.AutoModelForImageToImage,c.AutoModelForMaskGeneration,c.AutoModelForMaskedLM,c.AutoModelForNormalEstimation,c.AutoModelForObjectDetection,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation,c.AutoModelForVision2Seq,c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection,c.AutoProcessor;var Tf=c.AutoTokenizer;c.AutomaticSpeechRecognitionPipeline,c.BartForConditionalGeneration,c.BartForSequenceClassification,c.BartModel,c.BartPretrainedModel,c.BartTokenizer,c.BaseModelOutput,c.BaseStreamer,c.BeitFeatureExtractor,c.BeitForImageClassification,c.BeitModel,c.BeitPreTrainedModel,c.BertForMaskedLM,c.BertForQuestionAnswering,c.BertForSequenceClassification,c.BertForTokenClassification,c.BertModel,c.BertPreTrainedModel,c.BertTokenizer,c.BitImageProcessor,c.BlenderbotForConditionalGeneration,c.BlenderbotModel,c.BlenderbotPreTrainedModel,c.BlenderbotSmallForConditionalGeneration,c.BlenderbotSmallModel,c.BlenderbotSmallPreTrainedModel,c.BlenderbotSmallTokenizer,c.BlenderbotTokenizer,c.BloomForCausalLM,c.BloomModel,c.BloomPreTrainedModel,c.BloomTokenizer,c.CLIPFeatureExtractor,c.CLIPImageProcessor,c.CLIPModel,c.CLIPPreTrainedModel,c.CLIPSegForImageSegmentation,c.CLIPSegModel,c.CLIPSegPreTrainedModel,c.CLIPTextModel,c.CLIPTextModelWithProjection,c.CLIPTokenizer,c.CLIPVisionModel,c.CLIPVisionModelWithProjection,c.CamembertForMaskedLM,c.CamembertForQuestionAnswering,c.CamembertForSequenceClassification,c.CamembertForTokenClassification,c.CamembertModel,c.CamembertPreTrainedModel,c.CamembertTokenizer,c.CausalLMOutput,c.CausalLMOutputWithPast,c.ChineseCLIPFeatureExtractor,c.ChineseCLIPModel,c.ChineseCLIPPreTrainedModel,c.ClapAudioModelWithProjection,c.ClapFeatureExtractor,c.ClapModel,c.ClapPreTrainedModel,c.ClapTextModelWithProjection,c.CodeGenForCausalLM,c.CodeGenModel,c.CodeGenPreTrainedModel,c.CodeGenTokenizer,c.CodeLlamaTokenizer,c.CohereForCausalLM,c.CohereModel,c.CoherePreTrainedModel,c.CohereTokenizer,c.ConvBertForMaskedLM,c.ConvBertForQuestionAnswering,c.ConvBertForSequenceClassification,c.ConvBertForTokenClassification,c.ConvBertModel,c.ConvBertPreTrainedModel,c.ConvBertTokenizer,c.ConvNextFeatureExtractor,c.ConvNextForImageClassification,c.ConvNextImageProcessor,c.ConvNextModel,c.ConvNextPreTrainedModel,c.ConvNextV2ForImageClassification,c.ConvNextV2Model,c.ConvNextV2PreTrainedModel,c.DPTFeatureExtractor,c.DPTForDepthEstimation,c.DPTImageProcessor,c.DPTModel,c.DPTPreTrainedModel,c.DebertaForMaskedLM,c.DebertaForQuestionAnswering,c.DebertaForSequenceClassification,c.DebertaForTokenClassification,c.DebertaModel,c.DebertaPreTrainedModel,c.DebertaTokenizer,c.DebertaV2ForMaskedLM,c.DebertaV2ForQuestionAnswering,c.DebertaV2ForSequenceClassification,c.DebertaV2ForTokenClassification,c.DebertaV2Model,c.DebertaV2PreTrainedModel,c.DebertaV2Tokenizer,c.DecisionTransformerModel,c.DecisionTransformerPreTrainedModel,c.DeiTFeatureExtractor,c.DeiTForImageClassification,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrModel,c.DetrObjectDetectionOutput,c.DetrPreTrainedModel,c.DetrSegmentationOutput,c.Dinov2ForImageClassification,c.Dinov2Model,c.Dinov2PreTrainedModel,c.DistilBertForMaskedLM,c.DistilBertForQuestionAnswering,c.DistilBertForSequenceClassification,c.DistilBertForTokenClassification,c.DistilBertModel,c.DistilBertPreTrainedModel,c.DistilBertTokenizer,c.DocumentQuestionAnsweringPipeline,c.DonutFeatureExtractor,c.DonutSwinModel,c.DonutSwinPreTrainedModel,c.EfficientNetForImageClassification,c.EfficientNetImageProcessor,c.EfficientNetModel,c.EfficientNetPreTrainedModel,c.ElectraForMaskedLM,c.ElectraForQuestionAnswering,c.ElectraForSequenceClassification,c.ElectraForTokenClassification,c.ElectraModel,c.ElectraPreTrainedModel,c.ElectraTokenizer,c.EosTokenCriteria,c.EsmForMaskedLM,c.EsmForSequenceClassification,c.EsmForTokenClassification,c.EsmModel,c.EsmPreTrainedModel,c.EsmTokenizer,c.FFT,c.FalconForCausalLM,c.FalconModel,c.FalconPreTrainedModel,c.FalconTokenizer,c.FastViTForImageClassification,c.FastViTModel,c.FastViTPreTrainedModel,c.FeatureExtractionPipeline,c.FeatureExtractor,c.FillMaskPipeline,c.Florence2ForConditionalGeneration,c.Florence2PreTrainedModel,c.Florence2Processor,c.GLPNFeatureExtractor,c.GLPNForDepthEstimation,c.GLPNModel,c.GLPNPreTrainedModel,c.GPT2LMHeadModel,c.GPT2Model,c.GPT2PreTrainedModel,c.GPT2Tokenizer,c.GPTBigCodeForCausalLM,c.GPTBigCodeModel,c.GPTBigCodePreTrainedModel,c.GPTJForCausalLM,c.GPTJModel,c.GPTJPreTrainedModel,c.GPTNeoForCausalLM,c.GPTNeoModel,c.GPTNeoPreTrainedModel,c.GPTNeoXForCausalLM,c.GPTNeoXModel,c.GPTNeoXPreTrainedModel,c.GPTNeoXTokenizer,c.Gemma2ForCausalLM,c.Gemma2Model,c.Gemma2PreTrainedModel,c.GemmaForCausalLM,c.GemmaModel,c.GemmaPreTrainedModel,c.GemmaTokenizer,c.Grok1Tokenizer,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline;var Ef=c.InterruptableStoppingCriteria;c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaPreTrainedModel,c.LongT5ForConditionalGeneration,c.LongT5Model,c.LongT5PreTrainedModel,c.M2M100ForConditionalGeneration,c.M2M100Model,c.M2M100PreTrainedModel,c.M2M100Tokenizer,c.MBart50Tokenizer,c.MBartForCausalLM,c.MBartForConditionalGeneration,c.MBartForSequenceClassification,c.MBartModel,c.MBartPreTrainedModel,c.MBartTokenizer,c.MPNetForMaskedLM,c.MPNetForQuestionAnswering,c.MPNetForSequenceClassification,c.MPNetForTokenClassification,c.MPNetModel,c.MPNetPreTrainedModel,c.MPNetTokenizer,c.MT5ForConditionalGeneration,c.MT5Model,c.MT5PreTrainedModel,c.MarianMTModel,c.MarianModel,c.MarianPreTrainedModel,c.MarianTokenizer,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4Model,c.MobileNetV4PreTrainedModel,c.MobileViTFeatureExtractor,c.MobileViTForImageClassification,c.MobileViTImageProcessor,c.MobileViTModel,c.MobileViTPreTrainedModel,c.MobileViTV2ForImageClassification,c.MobileViTV2Model,c.MobileViTV2PreTrainedModel,c.ModelOutput,c.Moondream1ForConditionalGeneration,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.PhiForCausalLM,c.PhiModel,c.PhiPreTrainedModel,c.Pipeline,c.PreTrainedModel,c.PreTrainedTokenizer,c.PretrainedConfig,c.PretrainedMixin,c.Processor,c.PvtForImageClassification,c.PvtImageProcessor,c.PvtModel,c.PvtPreTrainedModel,c.PyAnnoteFeatureExtractor,c.PyAnnoteForAudioFrameClassification,c.PyAnnoteModel,c.PyAnnotePreTrainedModel,c.PyAnnoteProcessor,c.QuestionAnsweringModelOutput,c.QuestionAnsweringPipeline,c.Qwen2ForCausalLM,c.Qwen2Model,c.Qwen2PreTrainedModel,c.Qwen2Tokenizer,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel,c.RawImage,c.ResNetForImageClassification,c.ResNetModel,c.ResNetPreTrainedModel,c.RoFormerForMaskedLM,c.RoFormerForQuestionAnswering,c.RoFormerForSequenceClassification,c.RoFormerForTokenClassification,c.RoFormerModel,c.RoFormerPreTrainedModel,c.RoFormerTokenizer,c.RobertaForMaskedLM,c.RobertaForQuestionAnswering,c.RobertaForSequenceClassification,c.RobertaForTokenClassification,c.RobertaModel,c.RobertaPreTrainedModel,c.RobertaTokenizer,c.SamImageProcessor,c.SamImageSegmentationOutput,c.SamModel,c.SamPreTrainedModel,c.SamProcessor,c.SapiensFeatureExtractor,c.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerModel,c.SegformerPreTrainedModel,c.Seq2SeqLMOutput,c.SequenceClassifierOutput,c.SiglipImageProcessor,c.SiglipModel,c.SiglipPreTrainedModel,c.SiglipTextModel,c.SiglipTokenizer,c.SiglipVisionModel,c.SpeechT5FeatureExtractor,c.SpeechT5ForSpeechToText,c.SpeechT5ForTextToSpeech,c.SpeechT5HifiGan,c.SpeechT5Model,c.SpeechT5PreTrainedModel,c.SpeechT5Processor,c.SpeechT5Tokenizer,c.SqueezeBertForMaskedLM,c.SqueezeBertForQuestionAnswering,c.SqueezeBertForSequenceClassification,c.SqueezeBertModel,c.SqueezeBertPreTrainedModel,c.SqueezeBertTokenizer,c.StableLmForCausalLM,c.StableLmModel,c.StableLmPreTrainedModel,c.Starcoder2ForCausalLM,c.Starcoder2Model,c.Starcoder2PreTrainedModel,c.StoppingCriteria,c.StoppingCriteriaList,c.SummarizationPipeline,c.Swin2SRForImageSuperResolution,c.Swin2SRImageProcessor,c.Swin2SRModel,c.Swin2SRPreTrainedModel,c.SwinForImageClassification,c.SwinModel,c.SwinPreTrainedModel,c.T5ForConditionalGeneration,c.T5Model,c.T5PreTrainedModel,c.T5Tokenizer,c.TableTransformerForObjectDetection,c.TableTransformerModel,c.TableTransformerObjectDetectionOutput,c.TableTransformerPreTrainedModel,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline;var Cf=c.TextStreamer;c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TrOCRForCausalLM,c.TrOCRPreTrainedModel,c.TranslationPipeline,c.UniSpeechForCTC,c.UniSpeechForSequenceClassification,c.UniSpeechModel,c.UniSpeechPreTrainedModel,c.UniSpeechSatForAudioFrameClassification,c.UniSpeechSatForCTC,c.UniSpeechSatForSequenceClassification,c.UniSpeechSatModel,c.UniSpeechSatPreTrainedModel,c.ViTFeatureExtractor,c.ViTForImageClassification,c.ViTImageProcessor,c.ViTMAEModel,c.ViTMAEPreTrainedModel,c.ViTMSNForImageClassification,c.ViTMSNModel,c.ViTMSNPreTrainedModel,c.ViTModel,c.ViTPreTrainedModel,c.VisionEncoderDecoderModel,c.VitMatteForImageMatting,c.VitMatteImageProcessor,c.VitMattePreTrainedModel,c.VitsModel,c.VitsModelOutput,c.VitsPreTrainedModel,c.VitsTokenizer,c.Wav2Vec2BertForCTC,c.Wav2Vec2BertForSequenceClassification,c.Wav2Vec2BertModel,c.Wav2Vec2BertPreTrainedModel,c.Wav2Vec2CTCTokenizer,c.Wav2Vec2FeatureExtractor,c.Wav2Vec2ForAudioFrameClassification,c.Wav2Vec2ForCTC,c.Wav2Vec2ForSequenceClassification,c.Wav2Vec2Model,c.Wav2Vec2PreTrainedModel,c.Wav2Vec2ProcessorWithLM,c.WavLMForAudioFrameClassification,c.WavLMForCTC,c.WavLMForSequenceClassification,c.WavLMForXVector,c.WavLMModel,c.WavLMPreTrainedModel,c.WeSpeakerFeatureExtractor,c.WeSpeakerResNetModel,c.WeSpeakerResNetPreTrainedModel,c.WhisperFeatureExtractor,c.WhisperForConditionalGeneration,c.WhisperModel,c.WhisperPreTrainedModel,c.WhisperProcessor,c.WhisperTextStreamer,c.WhisperTokenizer,c.XLMForQuestionAnswering,c.XLMForSequenceClassification,c.XLMForTokenClassification,c.XLMModel,c.XLMPreTrainedModel,c.XLMRobertaForMaskedLM,c.XLMRobertaForQuestionAnswering,c.XLMRobertaForSequenceClassification,c.XLMRobertaForTokenClassification,c.XLMRobertaModel,c.XLMRobertaPreTrainedModel,c.XLMRobertaTokenizer,c.XLMTokenizer,c.XLMWithLMHeadModel,c.XVectorOutput,c.YolosFeatureExtractor,c.YolosForObjectDetection,c.YolosModel,c.YolosObjectDetectionOutput,c.YolosPreTrainedModel,c.ZeroShotAudioClassificationPipeline,c.ZeroShotClassificationPipeline,c.ZeroShotImageClassificationPipeline,c.ZeroShotObjectDetectionPipeline,c.bankers_round,c.cat,c.cos_sim,c.dot,c.dynamic_time_warping,c.env,c.full,c.full_like,c.getKeyValueShapes,c.hamming,c.hanning,c.interpolate,c.interpolate_4d,c.interpolate_data,c.is_chinese_char,c.layer_norm,c.log_softmax,c.magnitude,c.matmul,c.max,c.mean,c.mean_pooling,c.medianFilter,c.mel_filter_bank,c.min,c.ones,c.ones_like,c.permute,c.permute_data,c.pipeline,c.quantize_embeddings,c.read_audio,c.rfft,c.round,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;class gc{static async getInstance(Ee=null){return this.tokenizer??(this.tokenizer=Tf.from_pretrained(this.model_id,{progress_callback:Ee})),this.model??(this.model=xf.from_pretrained(this.model_id,{device:"webgpu",use_external_data_format:!0,progress_callback:Ee})),Promise.all([this.tokenizer,this.model])}}xe(gc,"model_id","onnx-community/Llama-3.2-1B-Instruct-q4f16");const fd=new Ef;async function $f($t){const[Ee,N]=await gc.getInstance(),O=Ee.apply_chat_template($t,{add_generation_prompt:!0,return_dict:!0});let fe,ye=0,Te;const Ce=()=>{fe??(fe=performance.now()),ye++>0&&(Te=ye/(performance.now()-fe)*1e3)},j=ee=>{self.postMessage({status:"update",output:ee,tps:Te,numTokens:ye})},S=new Cf(Ee,{skip_prompt:!0,skip_special_tokens:!0,callback_function:j,token_callback_function:Ce});self.postMessage({status:"start"});const V=await N.generate({...O,max_new_tokens:1024,streamer:S,stopping_criteria:fd}),A=Ee.batch_decode(V,{skip_special_tokens:!0});self.postMessage({status:"complete",output:A})}async function Sf(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch($t){self.postMessage({status:"error",data:$t.toString()})}}async function kf(){self.postMessage({status:"loading",data:"Loading model..."});const[$t,Ee]=await gc.getInstance(O=>{self.postMessage(O)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const N=$t("a");await Ee.generate({...N,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async $t=>{const{type:Ee,data:N}=$t.data;switch(Ee){case"check":Sf();break;case"load":kf();break;case"generate":fd.reset(),$f(N);break;case"interrupt":fd.interrupt();break;case"reset":fd.reset();break}})})();