var eg=Object.defineProperty;var tg=(nr,Gr,ei)=>Gr in nr?eg(nr,Gr,{enumerable:!0,configurable:!0,writable:!0,value:ei}):nr[Gr]=ei;var _e=(nr,Gr,ei)=>tg(nr,typeof Gr!="symbol"?Gr+"":Gr,ei);(function(){"use strict";var nr={},Gr={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Le,A,r)=>{Le.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Le,A,r)=>{r.r(A),r.d(A,{Environment:()=>Ze,Interpreter:()=>at,Template:()=>gt,parse:()=>se,tokenize:()=>M});var _=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",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"}),I=Object.freeze({set:_.Set,for:_.For,in:_.In,is:_.Is,if:_.If,else:_.Else,endif:_.EndIf,elif:_.ElseIf,endfor:_.EndFor,and:_.And,or:_.Or,not:_.Not,"not in":_.NotIn,macro:_.Macro,endmacro:_.EndMacro,true:_.BooleanLiteral,false:_.BooleanLiteral,none:_.NullLiteral,True:_.BooleanLiteral,False:_.BooleanLiteral,None:_.NullLiteral}),N=class{constructor(F,ne){this.value=F,this.type=ne}};function X(F){return/\w/.test(F)}function j(F){return/[0-9]/.test(F)}var g=[["{%",_.OpenStatement],["%}",_.CloseStatement],["{{",_.OpenExpression],["}}",_.CloseExpression],["(",_.OpenParen],[")",_.CloseParen],["{",_.OpenCurlyBracket],["}",_.CloseCurlyBracket],["[",_.OpenSquareBracket],["]",_.CloseSquareBracket],[",",_.Comma],[".",_.Dot],[":",_.Colon],["|",_.Pipe],["<=",_.ComparisonBinaryOperator],[">=",_.ComparisonBinaryOperator],["==",_.ComparisonBinaryOperator],["!=",_.ComparisonBinaryOperator],["<",_.ComparisonBinaryOperator],[">",_.ComparisonBinaryOperator],["+",_.AdditiveBinaryOperator],["-",_.AdditiveBinaryOperator],["*",_.MultiplicativeBinaryOperator],["/",_.MultiplicativeBinaryOperator],["%",_.MultiplicativeBinaryOperator],["=",_.Equals]],b=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function y(F,ne={}){return F.endsWith(` `)&&(F=F.slice(0,-1)),F=F.replace(/{#.*?#}/gs,"{##}"),ne.lstrip_blocks&&(F=F.replace(/^[ \t]*({[#%])/gm,"$1")),ne.trim_blocks&&(F=F.replace(/([#%]})\n/g,"$1")),F.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function M(F,ne={}){var rt,mt,Ot;const K=[],de=y(F,ne);let Oe=0;const Qe=xt=>{let Ft="";for(;xt(de[Oe]);){if(de[Oe]==="\\"){if(++Oe,Oe>=de.length)throw new SyntaxError("Unexpected end of input");const At=de[Oe++],rs=b.get(At);if(rs===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);Ft+=rs;continue}if(Ft+=de[Oe++],Oe>=de.length)throw new SyntaxError("Unexpected end of input")}return Ft};e:for(;Oe0){K.push(new N(At,_.Text));continue}}Qe(At=>/\s/.test(At));const Ft=de[Oe];if(Ft==="-"||Ft==="+"){const At=(mt=K.at(-1))==null?void 0:mt.type;if(At===_.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${Ft}`);switch(At){case _.Identifier:case _.NumericLiteral:case _.BooleanLiteral:case _.NullLiteral:case _.StringLiteral:case _.CloseParen:case _.CloseSquareBracket:break;default:{++Oe;const rs=Qe(j);K.push(new N(`${Ft}${rs}`,rs.length>0?_.NumericLiteral:_.UnaryOperator));continue}}}for(const[At,rs]of g)if(de.slice(Oe,Oe+At.length)===At){K.push(new N(At,rs)),Oe+=At.length;continue e}if(Ft==="'"||Ft==='"'){++Oe;const At=Qe(rs=>rs!==Ft);K.push(new N(At,_.StringLiteral)),++Oe;continue}if(j(Ft)){const At=Qe(j);K.push(new N(At,_.NumericLiteral));continue}if(X(Ft)){const At=Qe(X),rs=Object.hasOwn(I,At)?I[At]:_.Identifier;rs===_.In&&((Ot=K.at(-1))==null?void 0:Ot.type)===_.Not?(K.pop(),K.push(new N("not in",_.NotIn))):K.push(new N(At,rs));continue}throw new SyntaxError(`Unexpected character: ${Ft}`)}return K}var v=class{constructor(){_e(this,"type","Statement")}},L=class extends v{constructor(ne){super();_e(this,"type","Program");this.body=ne}},H=class extends v{constructor(ne,K,de){super();_e(this,"type","If");this.test=ne,this.body=K,this.alternate=de}},re=class extends v{constructor(ne,K,de,Oe){super();_e(this,"type","For");this.loopvar=ne,this.iterable=K,this.body=de,this.defaultBlock=Oe}},oe=class extends v{constructor(ne,K){super();_e(this,"type","Set");this.assignee=ne,this.value=K}},z=class extends v{constructor(ne,K,de){super();_e(this,"type","Macro");this.name=ne,this.args=K,this.body=de}},V=class extends v{constructor(){super(...arguments);_e(this,"type","Expression")}},Y=class extends V{constructor(ne,K,de){super();_e(this,"type","MemberExpression");this.object=ne,this.property=K,this.computed=de}},D=class extends V{constructor(ne,K){super();_e(this,"type","CallExpression");this.callee=ne,this.args=K}},$=class extends V{constructor(ne){super();_e(this,"type","Identifier");this.value=ne}},w=class extends V{constructor(ne){super();_e(this,"type","Literal");this.value=ne}},C=class extends w{constructor(){super(...arguments);_e(this,"type","NumericLiteral")}},T=class extends w{constructor(){super(...arguments);_e(this,"type","StringLiteral")}},ee=class extends w{constructor(){super(...arguments);_e(this,"type","BooleanLiteral")}},J=class extends w{constructor(){super(...arguments);_e(this,"type","NullLiteral")}},le=class extends w{constructor(){super(...arguments);_e(this,"type","ArrayLiteral")}},ce=class extends w{constructor(){super(...arguments);_e(this,"type","TupleLiteral")}},ge=class extends w{constructor(){super(...arguments);_e(this,"type","ObjectLiteral")}},Ce=class extends V{constructor(ne,K,de){super();_e(this,"type","BinaryExpression");this.operator=ne,this.left=K,this.right=de}},Te=class extends V{constructor(ne,K){super();_e(this,"type","FilterExpression");this.operand=ne,this.filter=K}},ze=class extends V{constructor(ne,K){super();_e(this,"type","SelectExpression");this.iterable=ne,this.test=K}},qe=class extends V{constructor(ne,K,de){super();_e(this,"type","TestExpression");this.operand=ne,this.negate=K,this.test=de}},Ue=class extends V{constructor(ne,K){super();_e(this,"type","UnaryExpression");this.operator=ne,this.argument=K}},ut=class extends V{constructor(ne=void 0,K=void 0,de=void 0){super();_e(this,"type","SliceExpression");this.start=ne,this.stop=K,this.step=de}},ue=class extends V{constructor(ne,K){super();_e(this,"type","KeywordArgumentExpression");this.key=ne,this.value=K}};function se(F){const ne=new L([]);let K=0;function de(ot,pt){const It=F[K++];if(!It||It.type!==ot)throw new Error(`Parser Error: ${pt}. ${It.type} !== ${ot}.`);return It}function Oe(){switch(F[K].type){case _.Text:return mt();case _.OpenStatement:return Ot();case _.OpenExpression:return xt();default:throw new SyntaxError(`Unexpected token type: ${F[K].type}`)}}function Qe(...ot){return K+ot.length<=F.length&&ot.some((pt,It)=>pt!==F[K+It].type)}function rt(...ot){return K+ot.length<=F.length&&ot.every((pt,It)=>pt===F[K+It].type)}function mt(){return new T(de(_.Text,"Expected text token").value)}function Ot(){de(_.OpenStatement,"Expected opening statement token");let ot;switch(F[K].type){case _.Set:++K,ot=Ft(),de(_.CloseStatement,"Expected closing statement token");break;case _.If:++K,ot=At(),de(_.OpenStatement,"Expected {% token"),de(_.EndIf,"Expected endif token"),de(_.CloseStatement,"Expected %} token");break;case _.Macro:++K,ot=rs(),de(_.OpenStatement,"Expected {% token"),de(_.EndMacro,"Expected endmacro token"),de(_.CloseStatement,"Expected %} token");break;case _.For:++K,ot=Os(),de(_.OpenStatement,"Expected {% token"),de(_.EndFor,"Expected endfor token"),de(_.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${F[K].type}`)}return ot}function xt(){de(_.OpenExpression,"Expected opening expression token");const ot=ks();return de(_.CloseExpression,"Expected closing expression token"),ot}function Ft(){const ot=ks();if(rt(_.Equals)){++K;const pt=Ft();return new oe(ot,pt)}return ot}function At(){var us,Mr,ts,br,cr,Xr,Lr,vr;const ot=ks();de(_.CloseStatement,"Expected closing statement token");const pt=[],It=[];for(;!(((us=F[K])==null?void 0:us.type)===_.OpenStatement&&(((Mr=F[K+1])==null?void 0:Mr.type)===_.ElseIf||((ts=F[K+1])==null?void 0:ts.type)===_.Else||((br=F[K+1])==null?void 0:br.type)===_.EndIf));)pt.push(Oe());if(((cr=F[K])==null?void 0:cr.type)===_.OpenStatement&&((Xr=F[K+1])==null?void 0:Xr.type)!==_.EndIf)if(++K,rt(_.ElseIf))de(_.ElseIf,"Expected elseif token"),It.push(At());else for(de(_.Else,"Expected else token"),de(_.CloseStatement,"Expected closing statement token");!(((Lr=F[K])==null?void 0:Lr.type)===_.OpenStatement&&((vr=F[K+1])==null?void 0:vr.type)===_.EndIf);)It.push(Oe());return new H(ot,pt,It)}function rs(){const ot=or();if(ot.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const pt=Fr();de(_.CloseStatement,"Expected closing statement token");const It=[];for(;Qe(_.OpenStatement,_.EndMacro);)It.push(Oe());return new z(ot,pt,It)}function ws(ot=!1){const pt=ot?or:ks,It=[pt()],us=rt(_.Comma);for(;us&&(++K,It.push(pt()),!!rt(_.Comma)););return us?new ce(It):It[0]}function Os(){const ot=ws(!0);if(!(ot instanceof $||ot instanceof ce))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ot.type} instead`);de(_.In,"Expected `in` keyword following loop variable");const pt=ks();de(_.CloseStatement,"Expected closing statement token");const It=[];for(;Qe(_.OpenStatement,_.EndFor)&&Qe(_.OpenStatement,_.Else);)It.push(Oe());const us=[];if(rt(_.OpenStatement,_.Else))for(++K,++K,de(_.CloseStatement,"Expected closing statement token");Qe(_.OpenStatement,_.EndFor);)us.push(Oe());return new re(ot,pt,It,us)}function ks(){return qs()}function qs(){const ot=ir();if(rt(_.If)){++K;const pt=ir();if(rt(_.Else)){++K;const It=ir();return new H(pt,[ot],[It])}else return new ze(ot,pt)}return ot}function ir(){let ot=Kr();for(;rt(_.Or);){const pt=F[K];++K;const It=Kr();ot=new Ce(pt,ot,It)}return ot}function Kr(){let ot=Or();for(;rt(_.And);){const pt=F[K];++K;const It=Or();ot=new Ce(pt,ot,It)}return ot}function Or(){let ot;for(;rt(_.Not);){const pt=F[K];++K;const It=Or();ot=new Ue(pt,It)}return ot??mn()}function mn(){let ot=zt();for(;rt(_.ComparisonBinaryOperator)||rt(_.In)||rt(_.NotIn);){const pt=F[K];++K;const It=zt();ot=new Ce(pt,ot,It)}return ot}function zt(){let ot=dr();for(;rt(_.AdditiveBinaryOperator);){const pt=F[K];++K;const It=dr();ot=new Ce(pt,ot,It)}return ot}function Hr(){const ot=Zs();return rt(_.OpenParen)?kr(ot):ot}function kr(ot){let pt=new D(ot,Fr());return rt(_.OpenParen)&&(pt=kr(pt)),pt}function Fr(){de(_.OpenParen,"Expected opening parenthesis for arguments list");const ot=Sr();return de(_.CloseParen,"Expected closing parenthesis for arguments list"),ot}function Sr(){const ot=[];for(;!rt(_.CloseParen);){let pt=ks();if(rt(_.Equals)){if(++K,!(pt instanceof $))throw new SyntaxError("Expected identifier for keyword argument");const It=ks();pt=new ue(pt,It)}ot.push(pt),rt(_.Comma)&&++K}return ot}function Dr(){const ot=[];let pt=!1;for(;!rt(_.CloseSquareBracket);)rt(_.Colon)?(ot.push(void 0),++K,pt=!0):(ot.push(ks()),rt(_.Colon)&&(++K,pt=!0));if(ot.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(pt){if(ot.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ut(...ot)}return ot[0]}function Zs(){let ot=or();for(;rt(_.Dot)||rt(_.OpenSquareBracket);){const pt=F[K];++K;let It;const us=pt.type!==_.Dot;if(us)It=Dr(),de(_.CloseSquareBracket,"Expected closing square bracket");else if(It=or(),It.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ot=new Y(ot,It,us)}return ot}function dr(){let ot=$r();for(;rt(_.MultiplicativeBinaryOperator);){const pt=F[K];++K;const It=$r();ot=new Ce(pt,ot,It)}return ot}function $r(){let ot=qr();for(;rt(_.Is);){++K;const pt=rt(_.Not);pt&&++K;let It=or();if(It instanceof ee?It=new $(It.value.toString()):It instanceof J&&(It=new $("none")),!(It instanceof $))throw new SyntaxError("Expected identifier for the test");ot=new qe(ot,pt,It)}return ot}function qr(){let ot=Hr();for(;rt(_.Pipe);){++K;let pt=or();if(!(pt instanceof $))throw new SyntaxError("Expected identifier for the filter");rt(_.OpenParen)&&(pt=kr(pt)),ot=new Te(ot,pt)}return ot}function or(){const ot=F[K];switch(ot.type){case _.NumericLiteral:return++K,new C(Number(ot.value));case _.StringLiteral:return++K,new T(ot.value);case _.BooleanLiteral:return++K,new ee(ot.value.toLowerCase()==="true");case _.NullLiteral:return++K,new J(null);case _.Identifier:return++K,new $(ot.value);case _.OpenParen:{++K;const pt=ws();if(F[K].type!==_.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${F[K].type} instead`);return++K,pt}case _.OpenSquareBracket:{++K;const pt=[];for(;!rt(_.CloseSquareBracket);)pt.push(ks()),rt(_.Comma)&&++K;return++K,new le(pt)}case _.OpenCurlyBracket:{++K;const pt=new Map;for(;!rt(_.CloseCurlyBracket);){const It=ks();de(_.Colon,"Expected colon between key and value in object literal");const us=ks();pt.set(It,us),rt(_.Comma)&&++K}return++K,new ge(pt)}default:throw new SyntaxError(`Unexpected token: ${ot.type}`)}}for(;K=0?(ne=(ne??(ne=0))<0?Math.max(F.length+ne,0):Math.min(ne,F.length),K=(K??(K=F.length))<0?Math.max(F.length+K,0):Math.min(K,F.length)):(ne=(ne??(ne=F.length-1))<0?Math.max(F.length+ne,-1):Math.min(ne,F.length-1),K=(K??(K=-1))<-1?Math.max(F.length+K,-1):Math.min(K,F.length-1));const Qe=[];for(let rt=ne;Oe*rtne.toUpperCase())}var et=class{constructor(F=void 0){_e(this,"type","RuntimeValue");_e(this,"value");_e(this,"builtins",new Map);this.value=F}__bool__(){return new Je(!!this.value)}},Xe=class extends et{constructor(){super(...arguments);_e(this,"type","NumericValue")}},ie=class extends et{constructor(){super(...arguments);_e(this,"type","StringValue");_e(this,"builtins",new Map([["upper",new je(()=>new ie(this.value.toUpperCase()))],["lower",new je(()=>new ie(this.value.toLowerCase()))],["strip",new je(()=>new ie(this.value.trim()))],["title",new je(()=>new ie(Be(this.value)))],["length",new Xe(this.value.length)],["rstrip",new je(()=>new ie(this.value.trimEnd()))],["lstrip",new je(()=>new ie(this.value.trimStart()))]]))}},Je=class extends et{constructor(){super(...arguments);_e(this,"type","BooleanValue")}},Fe=class extends et{constructor(){super(...arguments);_e(this,"type","ObjectValue");_e(this,"builtins",new Map([["get",new je(([ne,K])=>{if(!(ne instanceof ie))throw new Error(`Object key must be a string: got ${ne.type}`);return this.value.get(ne.value)??K??new Ve})],["items",new je(()=>new ve(Array.from(this.value.entries()).map(([ne,K])=>new ve([new ie(ne),K]))))]]))}__bool__(){return new Je(this.value.size>0)}},pe=class extends Fe{constructor(){super(...arguments);_e(this,"type","KeywordArgumentsValue")}},ve=class extends et{constructor(){super(...arguments);_e(this,"type","ArrayValue");_e(this,"builtins",new Map([["length",new Xe(this.value.length)]]))}__bool__(){return new Je(this.value.length>0)}},Re=class extends ve{constructor(){super(...arguments);_e(this,"type","TupleValue")}},je=class extends et{constructor(){super(...arguments);_e(this,"type","FunctionValue")}},Ve=class extends et{constructor(){super(...arguments);_e(this,"type","NullValue")}},Ne=class extends et{constructor(){super(...arguments);_e(this,"type","UndefinedValue")}},Ze=class{constructor(F){_e(this,"variables",new Map([["namespace",new je(F=>{if(F.length===0)return new Fe(new Map);if(F.length!==1||!(F[0]instanceof Fe))throw new Error("`namespace` expects either zero arguments or a single object argument");return F[0]})]]));_e(this,"tests",new Map([["boolean",F=>F.type==="BooleanValue"],["callable",F=>F instanceof je],["odd",F=>{if(F.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${F.type}`);return F.value%2!==0}],["even",F=>{if(F.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${F.type}`);return F.value%2===0}],["false",F=>F.type==="BooleanValue"&&!F.value],["true",F=>F.type==="BooleanValue"&&F.value],["none",F=>F.type==="NullValue"],["string",F=>F.type==="StringValue"],["number",F=>F.type==="NumericValue"],["integer",F=>F.type==="NumericValue"&&Number.isInteger(F.value)],["iterable",F=>F.type==="ArrayValue"||F.type==="StringValue"],["mapping",F=>F.type==="ObjectValue"],["lower",F=>{const ne=F.value;return F.type==="StringValue"&&ne===ne.toLowerCase()}],["upper",F=>{const ne=F.value;return F.type==="StringValue"&&ne===ne.toUpperCase()}],["none",F=>F.type==="NullValue"],["defined",F=>F.type!=="UndefinedValue"],["undefined",F=>F.type==="UndefinedValue"],["equalto",(F,ne)=>F.value===ne.value],["eq",(F,ne)=>F.value===ne.value]]));this.parent=F}set(F,ne){return this.declareVariable(F,ht(ne))}declareVariable(F,ne){if(this.variables.has(F))throw new SyntaxError(`Variable already declared: ${F}`);return this.variables.set(F,ne),ne}setVariable(F,ne){return this.variables.set(F,ne),ne}resolve(F){if(this.variables.has(F))return this;if(this.parent)return this.parent.resolve(F);throw new Error(`Unknown variable: ${F}`)}lookupVariable(F){try{return this.resolve(F).variables.get(F)??new Ne}catch{return new Ne}}},at=class{constructor(F){_e(this,"global");this.global=F??new Ze}run(F){return this.evaluate(F,this.global)}evaluateBinaryExpression(F,ne){const K=this.evaluate(F.left,ne);switch(F.operator.value){case"and":return K.__bool__().value?this.evaluate(F.right,ne):K;case"or":return K.__bool__().value?K:this.evaluate(F.right,ne)}const de=this.evaluate(F.right,ne);switch(F.operator.value){case"==":return new Je(K.value==de.value);case"!=":return new Je(K.value!=de.value)}if(K instanceof Ne||de instanceof Ne)throw new Error("Cannot perform operation on undefined values");if(K instanceof Ve||de instanceof Ve)throw new Error("Cannot perform operation on null values");if(K instanceof Xe&&de instanceof Xe)switch(F.operator.value){case"+":return new Xe(K.value+de.value);case"-":return new Xe(K.value-de.value);case"*":return new Xe(K.value*de.value);case"/":return new Xe(K.value/de.value);case"%":return new Xe(K.value%de.value);case"<":return new Je(K.value":return new Je(K.value>de.value);case">=":return new Je(K.value>=de.value);case"<=":return new Je(K.value<=de.value)}else if(K instanceof ve&&de instanceof ve)switch(F.operator.value){case"+":return new ve(K.value.concat(de.value))}else if(de instanceof ve){const Oe=de.value.find(Qe=>Qe.value===K.value)!==void 0;switch(F.operator.value){case"in":return new Je(Oe);case"not in":return new Je(!Oe)}}if(K instanceof ie||de instanceof ie)switch(F.operator.value){case"+":return new ie(K.value.toString()+de.value.toString())}if(K instanceof ie&&de instanceof ie)switch(F.operator.value){case"in":return new Je(de.value.includes(K.value));case"not in":return new Je(!de.value.includes(K.value))}if(K instanceof ie&&de instanceof Fe)switch(F.operator.value){case"in":return new Je(de.value.has(K.value));case"not in":return new Je(!de.value.has(K.value))}throw new SyntaxError(`Unknown operator "${F.operator.value}" between ${K.type} and ${de.type}`)}evaluateArguments(F,ne){const K=[],de=new Map;for(const Oe of F)if(Oe.type==="KeywordArgumentExpression"){const Qe=Oe;de.set(Qe.key.value,this.evaluate(Qe.value,ne))}else{if(de.size>0)throw new Error("Positional arguments must come before keyword arguments");K.push(this.evaluate(Oe,ne))}return[K,de]}evaluateFilterExpression(F,ne){const K=this.evaluate(F.operand,ne);if(F.filter.type==="Identifier"){const de=F.filter;if(de.value==="tojson")return new ie(dt(K));if(K instanceof ve)switch(de.value){case"list":return K;case"first":return K.value[0];case"last":return K.value[K.value.length-1];case"length":return new Xe(K.value.length);case"reverse":return new ve(K.value.reverse());case"sort":return new ve(K.value.sort((Oe,Qe)=>{if(Oe.type!==Qe.type)throw new Error(`Cannot compare different types: ${Oe.type} and ${Qe.type}`);switch(Oe.type){case"NumericValue":return Oe.value-Qe.value;case"StringValue":return Oe.value.localeCompare(Qe.value);default:throw new Error(`Cannot compare type: ${Oe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${de.value}`)}else if(K instanceof ie)switch(de.value){case"length":return new Xe(K.value.length);case"upper":return new ie(K.value.toUpperCase());case"lower":return new ie(K.value.toLowerCase());case"title":return new ie(Be(K.value));case"capitalize":return new ie(K.value.charAt(0).toUpperCase()+K.value.slice(1));case"trim":return new ie(K.value.trim());case"indent":return new ie(K.value.split(` `).map((Oe,Qe)=>Qe===0||Oe.length===0?Oe:" "+Oe).join(` `));case"string":return K;default:throw new Error(`Unknown StringValue filter: ${de.value}`)}else if(K instanceof Xe)switch(de.value){case"abs":return new Xe(Math.abs(K.value));default:throw new Error(`Unknown NumericValue filter: ${de.value}`)}else if(K instanceof Fe)switch(de.value){case"items":return new ve(Array.from(K.value.entries()).map(([Oe,Qe])=>new ve([new ie(Oe),Qe])));case"length":return new Xe(K.value.size);default:throw new Error(`Unknown ObjectValue filter: ${de.value}`)}throw new Error(`Cannot apply filter "${de.value}" to type: ${K.type}`)}else if(F.filter.type==="CallExpression"){const de=F.filter;if(de.callee.type!=="Identifier")throw new Error(`Unknown filter: ${de.callee.type}`);const Oe=de.callee.value;if(Oe==="tojson"){const[,Qe]=this.evaluateArguments(de.args,ne),rt=Qe.get("indent")??new Ve;if(!(rt instanceof Xe||rt instanceof Ve))throw new Error("If set, indent must be a number");return new ie(dt(K,rt.value))}if(K instanceof ve){switch(Oe){case"selectattr":case"rejectattr":{const Qe=Oe==="selectattr";if(K.value.some(At=>!(At instanceof Fe)))throw new Error(`\`${Oe}\` can only be applied to array of objects`);if(de.args.some(At=>At.type!=="StringLiteral"))throw new Error(`arguments of \`${Oe}\` must be strings`);const[rt,mt,Ot]=de.args.map(At=>this.evaluate(At,ne));let xt;if(mt){const At=ne.tests.get(mt.value);if(!At)throw new Error(`Unknown test: ${mt.value}`);xt=At}else xt=(...At)=>At[0].__bool__().value;const Ft=K.value.filter(At=>{const rs=At.value.get(rt.value),ws=rs?xt(rs,Ot):!1;return Qe?ws:!ws});return new ve(Ft)}case"map":{const[,Qe]=this.evaluateArguments(de.args,ne);if(Qe.has("attribute")){const rt=Qe.get("attribute");if(!(rt instanceof ie))throw new Error("attribute must be a string");const mt=Qe.get("default"),Ot=K.value.map(xt=>{if(!(xt instanceof Fe))throw new Error("items in map must be an object");return xt.value.get(rt.value)??mt??new Ne});return new ve(Ot)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Oe}`)}else if(K instanceof ie){switch(Oe){case"indent":{const[Qe,rt]=this.evaluateArguments(de.args,ne),mt=Qe.at(0)??rt.get("width")??new Xe(4);if(!(mt instanceof Xe))throw new Error("width must be a number");const Ot=Qe.at(1)??rt.get("first")??new Je(!1),xt=Qe.at(2)??rt.get("blank")??new Je(!1),Ft=K.value.split(` `),At=" ".repeat(mt.value),rs=Ft.map((ws,Os)=>!Ot.value&&Os===0||!xt.value&&ws.length===0?ws:At+ws);return new ie(rs.join(` `))}}throw new Error(`Unknown StringValue filter: ${Oe}`)}else throw new Error(`Cannot apply filter "${Oe}" to type: ${K.type}`)}throw new Error(`Unknown filter: ${F.filter.type}`)}evaluateTestExpression(F,ne){const K=this.evaluate(F.operand,ne),de=ne.tests.get(F.test.value);if(!de)throw new Error(`Unknown test: ${F.test.value}`);const Oe=de(K);return new Je(F.negate?!Oe:Oe)}evaluateUnaryExpression(F,ne){const K=this.evaluate(F.argument,ne);switch(F.operator.value){case"not":return new Je(!K.value);default:throw new SyntaxError(`Unknown operator: ${F.operator.value}`)}}evalProgram(F,ne){return this.evaluateBlock(F.body,ne)}evaluateBlock(F,ne){let K="";for(const de of F){const Oe=this.evaluate(de,ne);Oe.type!=="NullValue"&&Oe.type!=="UndefinedValue"&&(K+=Oe.value)}return new ie(K)}evaluateIdentifier(F,ne){return ne.lookupVariable(F.value)}evaluateCallExpression(F,ne){const[K,de]=this.evaluateArguments(F.args,ne);de.size>0&&K.push(new pe(de));const Oe=this.evaluate(F.callee,ne);if(Oe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Oe.type}`);return Oe.value(K,ne)}evaluateSliceExpression(F,ne,K){if(!(F instanceof ve||F instanceof ie))throw new Error("Slice object must be an array or string");const de=this.evaluate(ne.start,K),Oe=this.evaluate(ne.stop,K),Qe=this.evaluate(ne.step,K);if(!(de instanceof Xe||de instanceof Ne))throw new Error("Slice start must be numeric or undefined");if(!(Oe instanceof Xe||Oe instanceof Ne))throw new Error("Slice stop must be numeric or undefined");if(!(Qe instanceof Xe||Qe instanceof Ne))throw new Error("Slice step must be numeric or undefined");return F instanceof ve?new ve(xe(F.value,de.value,Oe.value,Qe.value)):new ie(xe(Array.from(F.value),de.value,Oe.value,Qe.value).join(""))}evaluateMemberExpression(F,ne){const K=this.evaluate(F.object,ne);let de;if(F.computed){if(F.property.type==="SliceExpression")return this.evaluateSliceExpression(K,F.property,ne);de=this.evaluate(F.property,ne)}else de=new ie(F.property.value);let Oe;if(K instanceof Fe){if(!(de instanceof ie))throw new Error(`Cannot access property with non-string: got ${de.type}`);Oe=K.value.get(de.value)??K.builtins.get(de.value)}else if(K instanceof ve||K instanceof ie)if(de instanceof Xe)Oe=K.value.at(de.value),K instanceof ie&&(Oe=new ie(K.value.at(de.value)));else if(de instanceof ie)Oe=K.builtins.get(de.value);else throw new Error(`Cannot access property with non-string/non-number: got ${de.type}`);else{if(!(de instanceof ie))throw new Error(`Cannot access property with non-string: got ${de.type}`);Oe=K.builtins.get(de.value)}return Oe instanceof et?Oe:new Ne}evaluateSet(F,ne){const K=this.evaluate(F.value,ne);if(F.assignee.type==="Identifier"){const de=F.assignee.value;ne.setVariable(de,K)}else if(F.assignee.type==="MemberExpression"){const de=F.assignee,Oe=this.evaluate(de.object,ne);if(!(Oe instanceof Fe))throw new Error("Cannot assign to member of non-object");if(de.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Oe.value.set(de.property.value,K)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(F.assignee)}`);return new Ve}evaluateIf(F,ne){const K=this.evaluate(F.test,ne);return this.evaluateBlock(K.__bool__().value?F.body:F.alternate,ne)}evaluateFor(F,ne){const K=new Ze(ne);let de,Oe;if(F.iterable.type==="SelectExpression"){const xt=F.iterable;Oe=this.evaluate(xt.iterable,K),de=xt.test}else Oe=this.evaluate(F.iterable,K);if(!(Oe instanceof ve))throw new Error(`Expected iterable type in for loop: got ${Oe.type}`);const Qe=[],rt=[];for(let xt=0;xtws.setVariable(F.loopvar.value,At);else if(F.loopvar.type==="TupleLiteral"){const ws=F.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const Os=At;if(ws.value.length!==Os.value.length)throw new Error(`Too ${ws.value.length>Os.value.length?"few":"many"} items to unpack`);rs=ks=>{for(let qs=0;qs0?Qe[xt-1]:new Ne],["nextitem",xt{var rt;const Oe=new Ze(de);K=K.slice();let Qe;((rt=K.at(-1))==null?void 0:rt.type)==="KeywordArgumentsValue"&&(Qe=K.pop());for(let mt=0;mtthis.evaluate(K,ne)));case"TupleLiteral":return new Re(F.value.map(K=>this.evaluate(K,ne)));case"ObjectLiteral":{const K=new Map;for(const[de,Oe]of F.value){const Qe=this.evaluate(de,ne);if(!(Qe instanceof ie))throw new Error(`Object keys must be strings: got ${Qe.type}`);K.set(Qe.value,this.evaluate(Oe,ne))}return new Fe(K)}case"Identifier":return this.evaluateIdentifier(F,ne);case"CallExpression":return this.evaluateCallExpression(F,ne);case"MemberExpression":return this.evaluateMemberExpression(F,ne);case"UnaryExpression":return this.evaluateUnaryExpression(F,ne);case"BinaryExpression":return this.evaluateBinaryExpression(F,ne);case"FilterExpression":return this.evaluateFilterExpression(F,ne);case"TestExpression":return this.evaluateTestExpression(F,ne);default:throw new SyntaxError(`Unknown node type: ${F.type}`)}}};function ht(F){switch(typeof F){case"number":return new Xe(F);case"string":return new ie(F);case"boolean":return new Je(F);case"undefined":return new Ne;case"object":return F===null?new Ve:Array.isArray(F)?new ve(F.map(ht)):new Fe(new Map(Object.entries(F).map(([ne,K])=>[ne,ht(K)])));case"function":return new je((ne,K)=>{const de=F(...ne.map(Oe=>Oe.value))??null;return ht(de)});default:throw new Error(`Cannot convert to runtime value: ${F}`)}}function dt(F,ne,K){const de=K??0;switch(F.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(F.value);case"ArrayValue":case"ObjectValue":{const Oe=ne?" ".repeat(ne):"",Qe=` `+Oe.repeat(de),rt=Qe+Oe;if(F.type==="ArrayValue"){const mt=F.value.map(Ot=>dt(Ot,ne,de+1));return ne?`[${rt}${mt.join(`,${rt}`)}${Qe}]`:`[${mt.join(", ")}]`}else{const mt=Array.from(F.value.entries()).map(([Ot,xt])=>{const Ft=`"${Ot}": ${dt(xt,ne,de+1)}`;return ne?`${rt}${Ft}`:Ft});return ne?`{${mt.join(",")}${Qe}}`:`{${mt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${F.type}`)}}var gt=class{constructor(F){_e(this,"parsed");const ne=M(F,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=se(ne)}render(F){const ne=new Ze;ne.set("false",!1),ne.set("true",!0),ne.set("raise_exception",Oe=>{throw new Error(Oe)}),ne.set("range",he);for(const[Oe,Qe]of Object.entries(F))ne.set(Oe,Qe);return new at(ne).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Le,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>N,resolveBackendAndExecutionProviders:()=>j});const _=new Map,I=[],N=(g,b,y)=>{if(b&&typeof b.init=="function"&&typeof b.createInferenceSessionHandler=="function"){const M=_.get(g);if(M===void 0)_.set(g,{backend:b,priority:y});else{if(M.priority>y)return;if(M.priority===y&&M.backend!==b)throw new Error(`cannot register backend "${g}" using priority ${y}`)}if(y>=0){const v=I.indexOf(g);v!==-1&&I.splice(v,1);for(let L=0;L{const b=_.get(g);if(!b)return"backend not found.";if(b.initialized)return b.backend;if(b.aborted)return b.error;{const y=!!b.initPromise;try{return y||(b.initPromise=b.backend.init(g)),await b.initPromise,b.initialized=!0,b.backend}catch(M){return y||(b.error=`${M}`,b.aborted=!0),b.error}finally{delete b.initPromise}}},j=async g=>{const b=g.executionProviders||[],y=b.map(oe=>typeof oe=="string"?oe:oe.name),M=y.length===0?I:y;let v;const L=[],H=new Set;for(const oe of M){const z=await X(oe);typeof z=="string"?L.push({name:oe,err:z}):(v||(v=z),v===z&&H.add(oe))}if(!v)throw new Error(`no available backend found. ERR: ${L.map(oe=>`[${oe.name}] ${oe.err}`).join(", ")}`);for(const{name:oe,err:z}of L)y.includes(oe)&&console.warn(`removing requested execution provider "${oe}" from session options because it is not available: ${z}`);const re=b.filter(oe=>H.has(typeof oe=="string"?oe:oe.name));return[v,new Proxy(g,{get:(oe,z)=>z==="executionProviders"?re:Reflect.get(oe,z)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Le,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>_.registerBackend});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Le,A,r)=>{r.r(A),r.d(A,{env:()=>N});var _=r("./node_modules/onnxruntime-common/dist/esm/version.js");let I="warning";const N={wasm:{},webgl:{},webgpu:{},versions:{common:_.version},set logLevel(X){if(X!==void 0){if(typeof X!="string"||["verbose","info","warning","error","fatal"].indexOf(X)===-1)throw new Error(`Unsupported logging level: ${X}`);I=X}},get logLevel(){return I}};Object.defineProperty(N,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Le,A,r)=>{r.r(A),r.d(A,{env:()=>I});var _=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const I=_.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Le,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>N.InferenceSession,TRACE:()=>j.TRACE,TRACE_FUNC_BEGIN:()=>j.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>j.TRACE_FUNC_END,Tensor:()=>X.Tensor,TrainingSession:()=>g.TrainingSession,env:()=>I.env,registerBackend:()=>_.registerBackend});var _=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),I=r("./node_modules/onnxruntime-common/dist/esm/env.js"),N=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),X=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),r("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var j=r("./node_modules/onnxruntime-common/dist/esm/trace.js");r("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),r("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var g=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Le,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>X});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),I=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),N=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class X{constructor(g){this.handler=g}async run(g,b,y){(0,N.TRACE_FUNC_BEGIN)();const M={};let v={};if(typeof g!="object"||g===null||g instanceof I.Tensor||Array.isArray(g))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let L=!0;if(typeof b=="object"){if(b===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(b instanceof I.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(b)){if(b.length===0)throw new TypeError("'fetches' cannot be an empty array.");L=!1;for(const oe of b){if(typeof oe!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(oe)===-1)throw new RangeError(`'fetches' contains invalid output name: ${oe}.`);M[oe]=null}if(typeof y=="object"&&y!==null)v=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else{let oe=!1;const z=Object.getOwnPropertyNames(b);for(const V of this.outputNames)if(z.indexOf(V)!==-1){const Y=b[V];(Y===null||Y instanceof I.Tensor)&&(oe=!0,L=!1,M[V]=Y)}if(oe){if(typeof y=="object"&&y!==null)v=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else v=b}}else if(typeof b<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const oe of this.inputNames)if(typeof g[oe]>"u")throw new Error(`input '${oe}' is missing in 'feeds'.`);if(L)for(const oe of this.outputNames)M[oe]=null;const H=await this.handler.run(g,M,v),re={};for(const oe in H)if(Object.hasOwnProperty.call(H,oe)){const z=H[oe];z instanceof I.Tensor?re[oe]=z:re[oe]=new I.Tensor(z.type,z.data,z.dims)}return(0,N.TRACE_FUNC_END)(),re}async release(){return this.handler.dispose()}static async create(g,b,y,M){(0,N.TRACE_FUNC_BEGIN)();let v,L={};if(typeof g=="string"){if(v=g,typeof b=="object"&&b!==null)L=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof Uint8Array){if(v=g,typeof b=="object"&&b!==null)L=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&g instanceof SharedArrayBuffer){const z=g;let V=0,Y=g.byteLength;if(typeof b=="object"&&b!==null)L=b;else if(typeof b=="number"){if(V=b,!Number.isSafeInteger(V))throw new RangeError("'byteOffset' must be an integer.");if(V<0||V>=z.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${z.byteLength}).`);if(Y=g.byteLength-V,typeof y=="number"){if(Y=y,!Number.isSafeInteger(Y))throw new RangeError("'byteLength' must be an integer.");if(Y<=0||V+Y>z.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${z.byteLength-V}].`);if(typeof M=="object"&&M!==null)L=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else if(typeof y<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof b<"u")throw new TypeError("'options' must be an object.");v=new Uint8Array(z,V,Y)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[H,re]=await(0,_.resolveBackendAndExecutionProviders)(L),oe=await H.createInferenceSessionHandler(v,re);return(0,N.TRACE_FUNC_END)(),new X(oe)}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":(Le,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>I});var _=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const I=_.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Le,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Le,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Le,A,r)=>{r.r(A),r.d(A,{tensorToDataURL:()=>_,tensorToImageData:()=>I});const _=(N,X)=>{const j=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);j.width=N.dims[3],j.height=N.dims[2];const g=j.getContext("2d");if(g!=null){let b,y;(X==null?void 0:X.tensorLayout)!==void 0&&X.tensorLayout==="NHWC"?(b=N.dims[2],y=N.dims[3]):(b=N.dims[3],y=N.dims[2]);const M=(X==null?void 0:X.format)!==void 0?X.format:"RGB",v=X==null?void 0:X.norm;let L,H;v===void 0||v.mean===void 0?L=[255,255,255,255]:typeof v.mean=="number"?L=[v.mean,v.mean,v.mean,v.mean]:(L=[v.mean[0],v.mean[1],v.mean[2],0],v.mean[3]!==void 0&&(L[3]=v.mean[3])),v===void 0||v.bias===void 0?H=[0,0,0,0]:typeof v.bias=="number"?H=[v.bias,v.bias,v.bias,v.bias]:(H=[v.bias[0],v.bias[1],v.bias[2],0],v.bias[3]!==void 0&&(H[3]=v.bias[3]));const re=y*b;let oe=0,z=re,V=re*2,Y=-1;M==="RGBA"?(oe=0,z=re,V=re*2,Y=re*3):M==="RGB"?(oe=0,z=re,V=re*2):M==="RBG"&&(oe=0,V=re,z=re*2);for(let D=0;D{const j=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let g;if(j!=null){let b,y,M;(X==null?void 0:X.tensorLayout)!==void 0&&X.tensorLayout==="NHWC"?(b=N.dims[2],y=N.dims[1],M=N.dims[3]):(b=N.dims[3],y=N.dims[2],M=N.dims[1]);const v=X!==void 0&&X.format!==void 0?X.format:"RGB",L=X==null?void 0:X.norm;let H,re;L===void 0||L.mean===void 0?H=[255,255,255,255]:typeof L.mean=="number"?H=[L.mean,L.mean,L.mean,L.mean]:(H=[L.mean[0],L.mean[1],L.mean[2],255],L.mean[3]!==void 0&&(H[3]=L.mean[3])),L===void 0||L.bias===void 0?re=[0,0,0,0]:typeof L.bias=="number"?re=[L.bias,L.bias,L.bias,L.bias]:(re=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(re[3]=L.bias[3]));const oe=y*b;if(X!==void 0&&(X.format!==void 0&&M===4&&X.format!=="RGBA"||M===3&&X.format!=="RGB"&&X.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const z=4;let V=0,Y=1,D=2,$=3,w=0,C=oe,T=oe*2,ee=-1;v==="RGBA"?(w=0,C=oe,T=oe*2,ee=oe*3):v==="RGB"?(w=0,C=oe,T=oe*2):v==="RBG"&&(w=0,T=oe,C=oe*2),g=j.createImageData(b,y);for(let J=0;J{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Le,A,r)=>{r.r(A),r.d(A,{bufferToTensor:()=>I,tensorFromGpuBuffer:()=>j,tensorFromImage:()=>N,tensorFromMLTensor:()=>g,tensorFromPinnedBuffer:()=>b,tensorFromTexture:()=>X});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const I=(y,M)=>{if(y===void 0)throw new Error("Image buffer must be defined");if(M.height===void 0||M.width===void 0)throw new Error("Image height and width must be defined");if(M.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:v,width:L}=M,H=M.norm??{mean:255,bias:0};let re,oe;typeof H.mean=="number"?re=[H.mean,H.mean,H.mean,H.mean]:re=[H.mean[0],H.mean[1],H.mean[2],H.mean[3]??255],typeof H.bias=="number"?oe=[H.bias,H.bias,H.bias,H.bias]:oe=[H.bias[0],H.bias[1],H.bias[2],H.bias[3]??0];const z=M.format!==void 0?M.format:"RGBA",V=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",Y=v*L,D=V==="RGBA"?new Float32Array(Y*4):new Float32Array(Y*3);let $=4,w=0,C=1,T=2,ee=3,J=0,le=Y,ce=Y*2,ge=-1;z==="RGB"&&($=3,w=0,C=1,T=2,ee=-1),V==="RGBA"?ge=Y*3:V==="RBG"?(J=0,ce=Y,le=Y*2):V==="BGR"&&(ce=0,le=Y,J=Y*2);for(let Te=0;Te{const v=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,L=typeof ImageData<"u"&&y instanceof ImageData,H=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,re=typeof y=="string";let oe,z=M??{};const V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Y=D=>typeof HTMLCanvasElement<"u"&&D instanceof HTMLCanvasElement||D instanceof OffscreenCanvas?D.getContext("2d"):null;if(v){const D=V();D.width=y.width,D.height=y.height;const $=Y(D);if($!=null){let w=y.height,C=y.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(w=M.resizedHeight,C=M.resizedWidth),M!==void 0){if(z=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");z.tensorFormat="RGBA",z.height=w,z.width=C}else z.tensorFormat="RGBA",z.height=w,z.width=C;$.drawImage(y,0,0),oe=$.getImageData(0,0,C,w).data}else throw new Error("Can not access image data")}else if(L){let D,$;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?(D=M.resizedHeight,$=M.resizedWidth):(D=y.height,$=y.width),M!==void 0&&(z=M),z.format="RGBA",z.height=D,z.width=$,M!==void 0){const w=V();w.width=$,w.height=D;const C=Y(w);if(C!=null)C.putImageData(y,0,0),oe=C.getImageData(0,0,$,D).data;else throw new Error("Can not access image data")}else oe=y.data}else if(H){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const D=V();D.width=y.width,D.height=y.height;const $=Y(D);if($!=null){const w=y.height,C=y.width;return $.drawImage(y,0,0,C,w),oe=$.getImageData(0,0,C,w).data,z.height=w,z.width=C,I(oe,z)}else throw new Error("Can not access image data")}else{if(re)return new Promise((D,$)=>{const w=V(),C=Y(w);if(!y||!C)return $();const T=new Image;T.crossOrigin="Anonymous",T.src=y,T.onload=()=>{w.width=T.width,w.height=T.height,C.drawImage(T,0,0,w.width,w.height);const ee=C.getImageData(0,0,w.width,w.height);z.height=w.height,z.width=w.width,D(I(ee.data,z))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(oe!==void 0)return I(oe,z);throw new Error("Input data provided is not supported - aborted tensor creation")},X=(y,M)=>{const{width:v,height:L,download:H,dispose:re}=M,oe=[1,L,v,4];return new _.Tensor({location:"texture",type:"float32",texture:y,dims:oe,download:H,dispose:re})},j=(y,M)=>{const{dataType:v,dims:L,download:H,dispose:re}=M;return new _.Tensor({location:"gpu-buffer",type:v??"float32",gpuBuffer:y,dims:L,download:H,dispose:re})},g=(y,M)=>{const{dataType:v,dims:L,download:H,dispose:re}=M;return new _.Tensor({location:"ml-tensor",type:v??"float32",mlTensor:y,dims:L,download:H,dispose:re})},b=(y,M,v)=>new _.Tensor({location:"cpu-pinned",type:y,data:M,dims:v??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Le,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Le,A,r)=>{r.r(A),r.d(A,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>I,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>_,checkTypedArray:()=>X});const _=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),I=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let N=!1;const X=()=>{if(!N){N=!0;const j=typeof BigInt64Array<"u"&&BigInt64Array.from,g=typeof BigUint64Array<"u"&&BigUint64Array.from,b=typeof Float16Array<"u"&&Float16Array.from;j&&(_.set("int64",BigInt64Array),I.set(BigInt64Array,"int64")),g&&(_.set("uint64",BigUint64Array),I.set(BigUint64Array,"uint64")),b?(_.set("float16",Float16Array),I.set(Float16Array,"float16")):_.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Le,A,r)=>{r.r(A),r.d(A,{Tensor:()=>j});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),I=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),N=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),X=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class j{constructor(b,y,M){(0,N.checkTypedArray)();let v,L;if(typeof b=="object"&&"location"in b)switch(this.dataLocation=b.location,v=b.type,L=b.dims,b.location){case"cpu-pinned":{const re=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(!re)throw new TypeError(`unsupported type "${v}" to create tensor from pinned buffer`);if(!(b.data instanceof re))throw new TypeError(`buffer should be of type ${re.name}`);this.cpuData=b.data;break}case"texture":{if(v!=="float32")throw new TypeError(`unsupported type "${v}" to create tensor from texture`);this.gpuTextureData=b.texture,this.downloader=b.download,this.disposer=b.dispose;break}case"gpu-buffer":{if(v!=="float32"&&v!=="float16"&&v!=="int32"&&v!=="int64"&&v!=="uint32"&&v!=="uint8"&&v!=="bool"&&v!=="uint4"&&v!=="int4")throw new TypeError(`unsupported type "${v}" to create tensor from gpu buffer`);this.gpuBufferData=b.gpuBuffer,this.downloader=b.download,this.disposer=b.dispose;break}case"ml-tensor":{if(v!=="float32"&&v!=="float16"&&v!=="int32"&&v!=="int64"&&v!=="uint32"&&v!=="uint64"&&v!=="int8"&&v!=="uint8"&&v!=="bool")throw new TypeError(`unsupported type "${v}" to create tensor from MLTensor`);this.mlTensorData=b.mlTensor,this.downloader=b.download,this.disposer=b.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let re,oe;if(typeof b=="string")if(v=b,oe=M,b==="string"){if(!Array.isArray(y))throw new TypeError("A string tensor's data must be a string array.");re=y}else{const z=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(z===void 0)throw new TypeError(`Unsupported tensor type: ${b}.`);if(Array.isArray(y)){if(b==="float16"&&z===Uint16Array||b==="uint4"||b==="int4")throw new TypeError(`Creating a ${b} tensor from number array is not supported. Please use ${z.name} as data.`);b==="uint64"||b==="int64"?re=z.from(y,BigInt):re=z.from(y)}else if(y instanceof z)re=y;else if(y instanceof Uint8ClampedArray)if(b==="uint8")re=Uint8Array.from(y);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${v} tensor's data must be type of ${z}`)}else if(oe=y,Array.isArray(b)){if(b.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const z=typeof b[0];if(z==="string")v="string",re=b;else if(z==="boolean")v="bool",re=Uint8Array.from(b);else throw new TypeError(`Invalid element type of data array: ${z}.`)}else if(b instanceof Uint8ClampedArray)v="uint8",re=Uint8Array.from(b);else{const z=N.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(b.constructor);if(z===void 0)throw new TypeError(`Unsupported type for tensor data: ${b.constructor}.`);v=z,re=b}if(oe===void 0)oe=[re.length];else if(!Array.isArray(oe))throw new TypeError("A tensor's dims must be a number array");L=oe,this.cpuData=re,this.dataLocation="cpu"}const H=(0,X.calculateSize)(L);if(this.cpuData&&H!==this.cpuData.length&&!((v==="uint4"||v==="int4")&&Math.ceil(H/2)===this.cpuData.length))throw new Error(`Tensor's size(${H}) does not match data length(${this.cpuData.length}).`);this.type=v,this.dims=L,this.size=H}static async fromImage(b,y){return(0,I.tensorFromImage)(b,y)}static fromTexture(b,y){return(0,I.tensorFromTexture)(b,y)}static fromGpuBuffer(b,y){return(0,I.tensorFromGpuBuffer)(b,y)}static fromMLTensor(b,y){return(0,I.tensorFromMLTensor)(b,y)}static fromPinnedBuffer(b,y,M){return(0,I.tensorFromPinnedBuffer)(b,y,M)}toDataURL(b){return(0,_.tensorToDataURL)(this,b)}toImageData(b){return(0,_.tensorToImageData)(this,b)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(b){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const y=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=y,b&&this.disposer&&(this.disposer(),this.disposer=void 0),y}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(b){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,X.tensorReshape)(this,b)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Le,A,r)=>{r.r(A),r.d(A,{calculateSize:()=>I,tensorReshape:()=>N});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const I=X=>{let j=1;for(let g=0;g{switch(X.location){case"cpu":return new _.Tensor(X.type,X.data,j);case"cpu-pinned":return new _.Tensor({location:"cpu-pinned",data:X.data,type:X.type,dims:j});case"texture":return new _.Tensor({location:"texture",texture:X.texture,type:X.type,dims:j});case"gpu-buffer":return new _.Tensor({location:"gpu-buffer",gpuBuffer:X.gpuBuffer,type:X.type,dims:j});case"ml-tensor":return new _.Tensor({location:"ml-tensor",mlTensor:X.mlTensor,type:X.type,dims:j});default:throw new Error(`tensorReshape: tensor location ${X.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Le,A,r)=>{r.r(A),r.d(A,{Tensor:()=>I});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const I=_.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Le,A,r)=>{r.r(A),r.d(A,{TRACE:()=>I,TRACE_FUNC_BEGIN:()=>X,TRACE_FUNC_END:()=>j});var _=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const I=(g,b)=>{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||console.timeStamp(`${g}::ORT::${b}`)},N=(g,b)=>{var v;const y=((v=new Error().stack)==null?void 0:v.split(/\r\n|\r|\n/g))||[];let M=!1;for(let L=0;L{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||N("BEGIN",g)},j=g=>{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||N("END",g)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Le,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>X});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),I=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const N="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class X{constructor(g,b,y){this.handler=g,this.hasOptimizerModel=b,this.hasEvalModel=y}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(g,b){const y=g.evalModel||"",M=g.optimizerModel||"",v=b||{},[L,H]=await(0,_.resolveBackendAndExecutionProviders)(v);if(L.createTrainingSessionHandler){const re=await L.createTrainingSessionHandler(g.checkpointState,g.trainModel,y,M,H);return new X(re,!!g.optimizerModel,!!g.evalModel)}else throw new Error(N)}typeNarrowingForRunStep(g,b,y,M,v){const L={};let H={};if(typeof y!="object"||y===null||y instanceof I.Tensor||Array.isArray(y))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let re=!0;if(typeof M=="object"){if(M===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(M instanceof I.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(M)){if(M.length===0)throw new TypeError("'fetches' cannot be an empty array.");re=!1;for(const oe of M){if(typeof oe!="string")throw new TypeError("'fetches' must be a string array or an object.");if(b.indexOf(oe)===-1)throw new RangeError(`'fetches' contains invalid output name: ${oe}.`);L[oe]=null}if(typeof v=="object"&&v!==null)H=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else{let oe=!1;const z=Object.getOwnPropertyNames(M);for(const V of b)if(z.indexOf(V)!==-1){const Y=M[V];(Y===null||Y instanceof I.Tensor)&&(oe=!0,re=!1,L[V]=Y)}if(oe){if(typeof v=="object"&&v!==null)H=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else H=M}}else if(typeof M<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const oe of g)if(typeof y[oe]>"u")throw new Error(`input '${oe}' is missing in 'feeds'.`);if(re)for(const oe of b)L[oe]=null;return[L,H]}convertHandlerReturnTypeToMapOfTensors(g){const b={};for(const y in g)if(Object.hasOwnProperty.call(g,y)){const M=g[y];M instanceof I.Tensor?b[y]=M:b[y]=new I.Tensor(M.type,M.data,M.dims)}return b}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(g,b,y){const[M,v]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,g,b,y),L=await this.handler.runTrainStep(g,M,v);return this.convertHandlerReturnTypeToMapOfTensors(L)}async runOptimizerStep(g){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(g||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(g,b,y){if(this.hasEvalModel){const[M,v]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,g,b,y),L=await this.handler.runEvalStep(g,M,v);return this.convertHandlerReturnTypeToMapOfTensors(L)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(g=!0){return this.handler.getParametersSize(g)}async loadParametersBuffer(g,b=!0){const y=await this.getParametersSize(b);if(g.length!==4*y)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(g,b)}async getContiguousParameters(g=!0){return this.handler.getContiguousParameters(g)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Le,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>I});var _=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const I=_.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Le,A,r)=>{r.r(A),r.d(A,{version:()=>_});const _="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs":(Le,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>dt,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>Ve,TRACE_FUNC_END:()=>Ne,Tensor:()=>pe,default:()=>Df,env:()=>T,registerBackend:()=>H});/*! * ONNX Runtime Web v1.21.0-dev.20241205-d27fecd3d3 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var _=Object.defineProperty,I=Object.getOwnPropertyDescriptor,N=Object.getOwnPropertyNames,X=Object.prototype.hasOwnProperty,j=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),g=(e,t)=>()=>(e&&(t=e(e=0)),t),b=(e,t)=>{for(var s in t)_(e,s,{get:t[s],enumerable:!0})},y=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of N(t))!X.call(e,i)&&i!==s&&_(e,i,{get:()=>t[i],enumerable:!(n=I(t,i))||n.enumerable});return e},M=e=>y(_({},"__esModule",{value:!0}),e),v,L,H,re,oe,z=g(()=>{v=new Map,L=[],H=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=v.get(e);if(n===void 0)v.set(e,{backend:t,priority:s});else{if(n.priority>s)return;if(n.priority===s&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let i=L.indexOf(e);i!==-1&&L.splice(i,1);for(let a=0;a{let t=v.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return s||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},oe=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?L:s,i,a=[],o=new Set;for(let p of n){let h=await re(p);typeof h=="string"?a.push({name:p,err:h}):(i||(i=h),i===h&&o.add(p))}if(!i)throw new Error(`no available backend found. ERR: ${a.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of a)s.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let d=t.filter(p=>o.has(typeof p=="string"?p:p.name));return[i,new Proxy(e,{get:(p,h)=>h==="executionProviders"?d:Reflect.get(p,h)})]}}),V=g(()=>{z()}),Y,D=g(()=>{Y="1.21.0-dev.20241205-6ed77cc374"}),$,w,C=g(()=>{D(),$="warning",w={wasm:{},webgl:{},webgpu:{},versions:{common:Y},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}`);$=e}},get logLevel(){return $}},Object.defineProperty(w,"logLevel",{enumerable:!0})}),T,ee=g(()=>{C(),T=w}),J,le,ce=g(()=>{J=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let i,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,p,h;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],0],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?h=[0,0,0,0]:typeof d.bias=="number"?h=[d.bias,d.bias,d.bias,d.bias]:(h=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(h[3]=d.bias[3]));let k=a*i,S=0,u=k,B=k*2,R=-1;o==="RGBA"?(S=0,u=k,B=k*2,R=k*3):o==="RGB"?(S=0,u=k,B=k*2):o==="RBG"&&(S=0,B=k,u=k*2);for(let U=0;U{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let i,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,k;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?k=[0,0,0,0]:typeof p.bias=="number"?k=[p.bias,p.bias,p.bias,p.bias]:(k=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(k[3]=p.bias[3]));let S=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,B=0,R=1,U=2,Z=3,te=0,Q=S,fe=S*2,me=-1;d==="RGBA"?(te=0,Q=S,fe=S*2,me=S*3):d==="RGB"?(te=0,Q=S,fe=S*2):d==="RBG"&&(te=0,fe=S,Q=S*2),n=s.createImageData(i,a);for(let Me=0;Me{Fe(),ge=(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:s,width:n}=t,i=t.norm??{mean:255,bias:0},a,o;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=s*n,k=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),S=4,u=0,B=1,R=2,U=3,Z=0,te=h,Q=h*2,fe=-1;d==="RGB"&&(S=3,u=0,B=1,R=2,U=-1),p==="RGBA"?fe=h*3:p==="RBG"?(Z=0,Q=h,te=h*2):p==="BGR"&&(Q=0,te=h,Z=h*2);for(let me=0;me{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,d=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=k=>typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||k instanceof OffscreenCanvas?k.getContext("2d"):null;if(s){let k=p();k.width=e.width,k.height=e.height;let S=h(k);if(S!=null){let u=e.height,B=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(u=t.resizedHeight,B=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=u,d.width=B}else d.tensorFormat="RGBA",d.height=u,d.width=B;S.drawImage(e,0,0),o=S.getImageData(0,0,B,u).data}else throw new Error("Can not access image data")}else if(n){let k,S;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,S=t.resizedWidth):(k=e.height,S=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=k,d.width=S,t!==void 0){let u=p();u.width=S,u.height=k;let B=h(u);if(B!=null)B.putImageData(e,0,0),o=B.getImageData(0,0,S,k).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let k=p();k.width=e.width,k.height=e.height;let S=h(k);if(S!=null){let u=e.height,B=e.width;return S.drawImage(e,0,0,B,u),o=S.getImageData(0,0,B,u).data,d.height=u,d.width=B,ge(o,d)}else throw new Error("Can not access image data")}else{if(a)return new Promise((k,S)=>{let u=p(),B=h(u);if(!e||!B)return S();let R=new Image;R.crossOrigin="Anonymous",R.src=e,R.onload=()=>{u.width=R.width,u.height=R.height,B.drawImage(R,0,0,u.width,u.height);let U=B.getImageData(0,0,u.width,u.height);d.height=u.height,d.width=u.width,k(ge(U.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ge(o,d);throw new Error("Input data provided is not supported - aborted tensor creation")},Te=(e,t)=>{let{width:s,height:n,download:i,dispose:a}=t,o=[1,n,s,4];return new Je({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:a})},ze=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:a}=t;return new Je({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:i,dispose:a})},qe=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:a}=t;return new Je({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:i,dispose:a})},Ue=(e,t,s)=>new Je({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),ue,se,he,xe,Be=g(()=>{ue=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"]]),he=!1,xe=()=>{if(!he){he=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(ue.set("int64",BigInt64Array),se.set(BigInt64Array,"int64")),t&&(ue.set("uint64",BigUint64Array),se.set(BigUint64Array,"uint64")),s?(ue.set("float16",Float16Array),se.set(Float16Array,"float16")):ue.set("float16",Uint16Array)}}}),et,Xe,ie=g(()=>{Fe(),et=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Je(e.type,e.data,t);case"cpu-pinned":return new Je({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Je({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Je({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Je({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Je,Fe=g(()=>{ce(),ut(),Be(),ie(),Je=class{constructor(e,t,s){xe();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let o=ue.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,d;if(typeof e=="string")if(n=e,d=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let p=ue.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?o=p.from(t,BigInt):o=p.from(t)}else if(t instanceof p)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=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 ${p}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof e[0];if(p==="string")n="string",o=e;else if(p==="boolean")n="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let p=se.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,o=e}if(d===void 0)d=[o.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");i=d,this.cpuData=o,this.dataLocation="cpu"}let a=et(i);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=a}static async fromImage(e,t){return Ce(e,t)}static fromTexture(e,t){return Te(e,t)}static fromGpuBuffer(e,t){return ze(e,t)}static fromMLTensor(e,t){return qe(e,t)}static fromPinnedBuffer(e,t,s){return Ue(e,t,s)}toDataURL(e){return J(this,e)}toImageData(e){return le(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xe(this,e)}}}),pe,ve=g(()=>{Fe(),pe=Je}),Re,je,Ve,Ne,Ze=g(()=>{C(),Re=(e,t)=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||console.timeStamp(`${e}::ORT::${t}`)},je=(e,t)=>{var i;let s=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||je("BEGIN",e)},Ne=e=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||je("END",e)}}),at,ht=g(()=>{z(),ve(),Ze(),at=class hf{constructor(t){this.handler=t}async run(t,s,n){Ve();let i={},a={};if(typeof t!="object"||t===null||t instanceof pe||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof pe)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.");o=!1;for(let h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);i[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,k=Object.getOwnPropertyNames(s);for(let S of this.outputNames)if(k.indexOf(S)!==-1){let u=s[S];(u===null||u instanceof pe)&&(h=!0,o=!1,i[S]=u)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(o)for(let h of this.outputNames)i[h]=null;let d=await this.handler.run(t,i,a),p={};for(let h in d)if(Object.hasOwnProperty.call(d,h)){let k=d[h];k instanceof pe?p[h]=k:p[h]=new pe(k.type,k.data,k.dims)}return Ne(),p}async release(){return this.handler.dispose()}static async create(t,s,n,i){Ve();let a,o={};if(typeof t=="string"){if(a=t,typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let k=t,S=0,u=t.byteLength;if(typeof s=="object"&&s!==null)o=s;else if(typeof s=="number"){if(S=s,!Number.isSafeInteger(S))throw new RangeError("'byteOffset' must be an integer.");if(S<0||S>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(u=t.byteLength-S,typeof n=="number"){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||S+u>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-S}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(k,S,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,p]=await oe(o),h=await d.createInferenceSessionHandler(a,p);return Ne(),new hf(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),dt,gt=g(()=>{ht(),dt=at}),F=g(()=>{}),ne=g(()=>{}),K=g(()=>{}),de=g(()=>{}),Oe={};b(Oe,{InferenceSession:()=>dt,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>Ve,TRACE_FUNC_END:()=>Ne,Tensor:()=>pe,env:()=>T,registerBackend:()=>H});var Qe=g(()=>{V(),ee(),gt(),ve(),F(),ne(),Ze(),K(),de()}),rt=g(()=>{}),mt={};b(mt,{default:()=>Ft});var Ot,xt,Ft,At=g(()=>{var e;Oh(),It(),Sr(),Ot="ort-wasm-proxy-worker",xt=((e=globalThis.self)==null?void 0:e.name)===Ot,xt&&(self.onmessage=t=>{let{type:s,in:n}=t.data;try{switch(s){case"init-wasm":ot(n.wasm).then(()=>{Gp(n).then(()=>{postMessage({type:s})},i=>{postMessage({type:s,err:i})})},i=>{postMessage({type:s,err:i})});break;case"init-ep":{let{epName:i,env:a}=n;Kp(a,i).then(()=>{postMessage({type:s})},o=>{postMessage({type:s,err:o})});break}case"copy-from":{let{buffer:i}=n,a=Mp(i);postMessage({type:s,out:a});break}case"create":{let{model:i,options:a}=n;Hp(i,a).then(o=>{postMessage({type:s,out:o})},o=>{postMessage({type:s,err:o})});break}case"release":qp(n),postMessage({type:s});break;case"run":{let{sessionId:i,inputIndices:a,inputs:o,outputIndices:d,options:p}=n;Qp(i,a,o,d,new Array(d.length).fill(null),p).then(h=>{h.some(k=>k[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:h},Jp([...o,...h]))},h=>{postMessage({type:s,err:h})});break}case"end-profiling":Yp(n),postMessage({type:s});break;default:}}catch(i){postMessage({type:s,err:i})}}),Ft=xt?null:t=>new Worker(t??ir,{type:"module",name:Ot})}),rs={};b(rs,{default:()=>ks});var ws,Os,ks,qs=g(()=>{var e;Os=(ws=self.location.href,async function(t={}){function s(){return jt.buffer!=Gt.buffer&&Ts(),Gt}function n(){return jt.buffer!=Gt.buffer&&Ts(),Cs}function i(){return jt.buffer!=Gt.buffer&&Ts(),nt}function a(){return jt.buffer!=Gt.buffer&&Ts(),Pt}function o(){return jt.buffer!=Gt.buffer&&Ts(),ps}function d(){return jt.buffer!=Gt.buffer&&Ts(),zs}function p(){return jt.buffer!=Gt.buffer&&Ts(),yr}function h(){return jt.buffer!=Gt.buffer&&Ts(),Ii}var k,S,u=Object.assign({},t),B=new Promise((l,m)=>{k=l,S=m}),R=typeof window=="object",U=typeof importScripts=="function",Z=U&&self.name=="em-pthread";u.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(u.Fb||(u.Fb=new Map)).set(l,m)},u.unmountExternalData=()=>{delete u.Fb};var te=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let Q=()=>{let l=(x,O,G)=>(...we)=>{let Ke=cn,st=O==null?void 0:O();we=x(...we);let bt=O==null?void 0:O();return st!==bt&&(x=bt,G(st),O=G=null),cn!=Ke?new Promise((St,Wt)=>{wh={resolve:St,reject:Wt}}):we},m=x=>async(...O)=>{var G;try{if(u.Gb)throw Error("Session already started");let we=u.Gb={hc:O[0],errors:[]},Ke=await x(...O);if(u.Gb!==we)throw Error("Session mismatch");(G=u.Hb)==null||G.flush();let st=we.errors;if(0St),0u._OrtCreateSession,x=>u._OrtCreateSession=x),u._OrtRun=m(l(u._OrtRun,()=>u._OrtRun,x=>u._OrtRun=x)),u._OrtRunWithBinding=m(l(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,x=>u._OrtRunWithBinding=x)),u._OrtBindInput=l(u._OrtBindInput,()=>u._OrtBindInput,x=>u._OrtBindInput=x),Q=void 0};u.jsepInit=(l,m)=>{if(Q==null||Q(),l==="webgpu"){[u.Hb,u.Vb,u.Zb,u.Ob,u.Yb,u.kb,u.$b,u.cc,u.Wb,u.Xb,u.ac]=m;let x=u.Hb;u.jsepRegisterBuffer=(O,G,we,Ke)=>x.registerBuffer(O,G,we,Ke),u.jsepGetBuffer=O=>x.getBuffer(O),u.jsepCreateDownloader=(O,G,we)=>x.createDownloader(O,G,we),u.jsepOnCreateSession=O=>{x.onCreateSession(O)},u.jsepOnReleaseSession=O=>{x.onReleaseSession(O)},u.jsepOnRunStart=O=>x.onRunStart(O),u.dc=(O,G)=>{x.upload(O,G)}}else if(l==="webnn"){[u.Hb,u.bc,u.Pb,u.jsepEnsureTensor,u.ec,u.jsepDownloadTensor]=m,u.jsepReleaseTensorId=u.Pb;let x=u.Hb;u.jsepOnRunStart=O=>x.onRunStart(O),u.jsepRegisterMLContext=(O,G)=>{x.registerMLContext(O,G)},u.jsepOnReleaseSession=O=>{x.onReleaseSession(O)},u.jsepCreateMLTensorDownloader=(O,G)=>x.createMLTensorDownloader(O,G),u.jsepRegisterMLTensor=(O,G,we)=>x.registerMLTensor(O,G,we),u.jsepCreateMLContext=O=>x.createMLContext(O),u.jsepRegisterMLConstant=(O,G,we,Ke,st)=>x.registerMLConstant(O,G,we,Ke,st,u.Fb)}};var fe,me,Me=Object.assign({},u),$e="./this.program",Ae=(l,m)=>{throw m},Ge="";(R||U)&&(U?Ge=self.location.href:typeof document<"u"&&document.currentScript&&(Ge=document.currentScript.src),ws&&(Ge=ws),Ge=Ge.startsWith("blob:")?"":Ge.substr(0,Ge.replace(/[?#].*/,"").lastIndexOf("/")+1),U&&(me=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),fe=(l,m,x)=>{var O=new XMLHttpRequest;O.open("GET",l,!0),O.responseType="arraybuffer",O.onload=()=>{O.status==200||O.status==0&&O.response?m(O.response):x()},O.onerror=x,O.send(null)});var lt,Et=console.log.bind(console),Kt=console.error.bind(console),Yt=Et,kt=Kt;if(Object.assign(u,Me),Me=null,Z){let l=function(m){try{var x=m.data,O=x.cmd;if(O==="load"){let G=[];self.onmessage=we=>G.push(we),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let we of G)l(we);self.onmessage=l};for(let we of x.handlers)u[we]&&!u[we].proxy||(u[we]=(...Ke)=>{postMessage({Nb:"callHandler",pc:we,args:Ke})},we=="print"&&(Yt=u[we]),we=="printErr"&&(kt=u[we]));jt=x.wasmMemory,Ts(),Jt(x.wasmModule)}else if(O==="run"){vh(x.pthread_ptr,0,0,1,0,0),_h(x.pthread_ptr),Bf(),rm(),$t||(ef(),$t=!0);try{Rf(x.start_routine,x.arg)}catch(G){if(G!="unwind")throw G}}else O==="cancel"?Da()&&Fp(-1):x.target!=="setimmediate"&&(O==="checkMailbox"?$t&&xp():O&&(kt(`worker: received unknown command ${O}`),kt(x)))}catch(G){throw tf(),G}};var Jt,$t=!1;kt=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:Da()})},u.instantiateWasm=(m,x)=>new Promise(O=>{Jt=G=>{G=new WebAssembly.Instance(G,Jh()),x(G),O()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}u.wasmBinary&&(lt=u.wasmBinary);var jt,bs,Ht,Gt,Cs,nt,Pt,ps,zs,yr,Vs,ln,Ii,As=!1;function Ts(){var l=jt.buffer;u.HEAP8=Gt=new Int8Array(l),u.HEAP16=nt=new Int16Array(l),u.HEAPU8=Cs=new Uint8Array(l),u.HEAPU16=Pt=new Uint16Array(l),u.HEAP32=ps=new Int32Array(l),u.HEAPU32=zs=new Uint32Array(l),u.HEAPF32=yr=new Float32Array(l),u.HEAPF64=Ii=new Float64Array(l),u.HEAP64=Vs=new BigInt64Array(l),u.HEAPU64=ln=new BigUint64Array(l)}if(!Z){if(!((jt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof te))throw kt("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");Ts()}var qn=[],vc=[],rh=[],Tc=0,xc=null;function Hh(){if(--Tc==0&&xc){var l=xc;xc=null,l()}}function Xn(l){throw kt(l="Aborted("+l+")"),As=!0,Ht=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),S(l),l}var nh,qh=l=>l.startsWith("data:application/octet-stream;base64,"),Xh=l=>l.startsWith("file://");function Qh(l){if(l==nh&<)return new Uint8Array(lt);if(me)return me(l);throw"both async and sync fetching of the wasm failed"}function Yh(l,m,x){return function(O){if(!lt&&(R||U)){if(typeof fetch=="function"&&!Xh(O))return fetch(O,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${O}'`;return G.arrayBuffer()}).catch(()=>Qh(O));if(fe)return new Promise((G,we)=>{fe(O,Ke=>G(new Uint8Array(Ke)),we)})}return Promise.resolve().then(()=>Qh(O))}(l).then(O=>WebAssembly.instantiate(O,m)).then(x,O=>{kt(`failed to asynchronously prepare wasm: ${O}`),Xn(O)})}function Jh(){return{a:{O:zf,Aa:Lf,b:jf,aa:am,B:dm,qa:cm,Y:hm,_:mm,ra:fm,oa:_m,ha:gm,na:wm,L:ym,Z:Mm,W:bm,pa:vm,X:Tm,va:Uf,F:Wf,Q:Vf,P:Kf,E:qf,u:Xf,q:Qf,G:Yf,A:n_,R:i_,ua:o_,ka:a_,U:l_,ba:u_,H:d_,ja:_h,ta:c_,t:p_,Ba:h_,x:__,n:g_,l:y_,c:mh,o:M_,j:T_,w:x_,p:E_,f:P_,s:C_,m:k_,e:S_,k:$_,i:A_,h:I_,d:O_,ea:F_,fa:D_,ga:L_,ca:zm,da:Bm,T:z_,g:B_,D:R_,I:N_,M:j_,y:U_,sa:W_,V:V_,v:Nm,z:G_,N:K_,S:H_,za:q_,ya:X_,la:Wm,ma:Vm,$:uh,C:Gm,K:Km,ia:Hm,J:qm,a:jt,xa:lh,wa:Ym,r:J_}}}var ih={874308:(l,m,x,O,G)=>{if(u===void 0||!u.Fb)return 1;if((l=Bs(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=u.Fb.get(l)))return 2;if(m=Number(m>>>0),x=Number(x>>>0),O=Number(O>>>0),m+x>l.byteLength)return 3;try{let we=l.subarray(m,m+x);switch(G){case 0:n().set(we,O>>>0);break;case 1:u.dc(O,we);break;default:return 4}return 0}catch{return 4}},875023:(l,m,x)=>{u.ec(l,n().subarray(m>>>0,m+x>>>0))},875086:()=>u.bc(),875127:l=>{u.Pb(l)},875163:()=>{u.Wb()},875194:()=>{u.Xb()},875223:()=>{u.ac()},875248:l=>u.Vb(l),875281:l=>u.Zb(l),875313:(l,m,x)=>{u.Ob(Number(l),Number(m),Number(x),!0)},875376:(l,m,x)=>{u.Ob(Number(l),Number(m),Number(x))},875433:()=>typeof wasmOffsetConverter<"u",875490:l=>{u.kb("Abs",l,void 0)},875541:l=>{u.kb("Neg",l,void 0)},875592:l=>{u.kb("Floor",l,void 0)},875645:l=>{u.kb("Ceil",l,void 0)},875697:l=>{u.kb("Reciprocal",l,void 0)},875755:l=>{u.kb("Sqrt",l,void 0)},875807:l=>{u.kb("Exp",l,void 0)},875858:l=>{u.kb("Erf",l,void 0)},875909:l=>{u.kb("Sigmoid",l,void 0)},875964:(l,m,x)=>{u.kb("HardSigmoid",l,{alpha:m,beta:x})},876043:l=>{u.kb("Log",l,void 0)},876094:l=>{u.kb("Sin",l,void 0)},876145:l=>{u.kb("Cos",l,void 0)},876196:l=>{u.kb("Tan",l,void 0)},876247:l=>{u.kb("Asin",l,void 0)},876299:l=>{u.kb("Acos",l,void 0)},876351:l=>{u.kb("Atan",l,void 0)},876403:l=>{u.kb("Sinh",l,void 0)},876455:l=>{u.kb("Cosh",l,void 0)},876507:l=>{u.kb("Asinh",l,void 0)},876560:l=>{u.kb("Acosh",l,void 0)},876613:l=>{u.kb("Atanh",l,void 0)},876666:l=>{u.kb("Tanh",l,void 0)},876718:l=>{u.kb("Not",l,void 0)},876769:(l,m,x)=>{u.kb("Clip",l,{min:m,max:x})},876838:l=>{u.kb("Clip",l,void 0)},876890:(l,m)=>{u.kb("Elu",l,{alpha:m})},876948:l=>{u.kb("Gelu",l,void 0)},877e3:l=>{u.kb("Relu",l,void 0)},877052:(l,m)=>{u.kb("LeakyRelu",l,{alpha:m})},877116:(l,m)=>{u.kb("ThresholdedRelu",l,{alpha:m})},877186:(l,m)=>{u.kb("Cast",l,{to:m})},877244:l=>{u.kb("Add",l,void 0)},877295:l=>{u.kb("Sub",l,void 0)},877346:l=>{u.kb("Mul",l,void 0)},877397:l=>{u.kb("Div",l,void 0)},877448:l=>{u.kb("Pow",l,void 0)},877499:l=>{u.kb("Equal",l,void 0)},877552:l=>{u.kb("Greater",l,void 0)},877607:l=>{u.kb("GreaterOrEqual",l,void 0)},877669:l=>{u.kb("Less",l,void 0)},877721:l=>{u.kb("LessOrEqual",l,void 0)},877780:(l,m,x,O,G)=>{u.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},877955:(l,m,x,O,G)=>{u.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878129:(l,m,x,O,G)=>{u.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878303:(l,m,x,O,G)=>{u.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878478:(l,m,x,O,G)=>{u.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878652:(l,m,x,O,G)=>{u.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878825:(l,m,x,O,G)=>{u.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878998:(l,m,x,O,G)=>{u.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},879175:(l,m,x,O,G)=>{u.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},879355:(l,m,x,O,G)=>{u.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!x,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},879535:l=>{u.kb("Where",l,void 0)},879588:(l,m,x)=>{u.kb("Transpose",l,{perm:m?Array.from(o().subarray(Number(m)>>>0,Number(x)>>>0)):[]})},879712:(l,m,x,O)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:Bs(x),format:O?"NHWC":"NCHW"})},879845:(l,m,x,O)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:Bs(x),format:O?"NHWC":"NCHW"})},879978:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We,ls)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[x],group:O,kernelShape:[G],pads:[we,Ke],strides:[st],wIsConst:()=>!!s()[St>>>0],outputPadding:Wt?Array.from(o().subarray(Number(Wt)>>>0,Number(hs)>>>0)):[],outputShape:Ms?Array.from(o().subarray(Number(Ms)>>>0,Number(We)>>>0)):[],activation:Bs(ls)})},880411:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We)=>{u.kb("ConvTranspose",l,{format:st?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(x)>>>0,2+(Number(x)>>>0)>>>0)),group:O,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Ke)>>>0,2+(Number(Ke)>>>0)>>>0)),wIsConst:()=>!!s()[bt>>>0],outputPadding:St?Array.from(o().subarray(Number(St)>>>0,Number(Wt)>>>0)):[],outputShape:hs?Array.from(o().subarray(Number(hs)>>>0,Number(Ms)>>>0)):[],activation:Bs(We)})},881072:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We,ls)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[x],group:O,kernelShape:[G],pads:[we,Ke],strides:[st],wIsConst:()=>!!s()[St>>>0],outputPadding:Wt?Array.from(o().subarray(Number(Wt)>>>0,Number(hs)>>>0)):[],outputShape:Ms?Array.from(o().subarray(Number(Ms)>>>0,Number(We)>>>0)):[],activation:Bs(ls)})},881505:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We)=>{u.kb("ConvTranspose",l,{format:st?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(x)>>>0,2+(Number(x)>>>0)>>>0)),group:O,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Ke)>>>0,2+(Number(Ke)>>>0)>>>0)),wIsConst:()=>!!s()[bt>>>0],outputPadding:St?Array.from(o().subarray(Number(St)>>>0,Number(Wt)>>>0)):[],outputShape:hs?Array.from(o().subarray(Number(hs)>>>0,Number(Ms)>>>0)):[],activation:Bs(We)})},882166:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882257:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We)=>{u.kb("AveragePool",l,{format:We?"NHWC":"NCHW",auto_pad:m,ceil_mode:x,count_include_pad:O,storage_order:G,dilations:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],pads:St?Array.from(o().subarray(Number(St)>>>0,Number(Wt)>>>0)):[],strides:hs?Array.from(o().subarray(Number(hs)>>>0,Number(Ms)>>>0)):[]})},882736:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882827:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We)=>{u.kb("AveragePool",l,{format:We?"NHWC":"NCHW",auto_pad:m,ceil_mode:x,count_include_pad:O,storage_order:G,dilations:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],pads:St?Array.from(o().subarray(Number(St)>>>0,Number(Wt)>>>0)):[],strides:hs?Array.from(o().subarray(Number(hs)>>>0,Number(Ms)>>>0)):[]})},883306:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883393:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We)=>{u.kb("MaxPool",l,{format:We?"NHWC":"NCHW",auto_pad:m,ceil_mode:x,count_include_pad:O,storage_order:G,dilations:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],pads:St?Array.from(o().subarray(Number(St)>>>0,Number(Wt)>>>0)):[],strides:hs?Array.from(o().subarray(Number(hs)>>>0,Number(Ms)>>>0)):[]})},883868:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883955:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We)=>{u.kb("MaxPool",l,{format:We?"NHWC":"NCHW",auto_pad:m,ceil_mode:x,count_include_pad:O,storage_order:G,dilations:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],pads:St?Array.from(o().subarray(Number(St)>>>0,Number(Wt)>>>0)):[],strides:hs?Array.from(o().subarray(Number(hs)>>>0,Number(Ms)>>>0)):[]})},884430:(l,m,x,O,G)=>{u.kb("Gemm",l,{alpha:m,beta:x,transA:O,transB:G})},884534:l=>{u.kb("MatMul",l,void 0)},884588:(l,m,x,O)=>{u.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!x,axis:O})},884696:(l,m,x,O)=>{u.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!x,axis:O})},884804:(l,m)=>{u.kb("Softmax",l,{axis:m})},884867:(l,m)=>{u.kb("Concat",l,{axis:m})},884927:(l,m,x,O,G)=>{u.kb("Split",l,{axis:m,numOutputs:x,splitSizes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},885083:l=>{u.kb("Expand",l,void 0)},885137:(l,m)=>{u.kb("Gather",l,{axis:Number(m)})},885208:(l,m)=>{u.kb("GatherElements",l,{axis:Number(m)})},885287:(l,m)=>{u.kb("GatherND",l,{batch_dims:Number(m)})},885366:(l,m,x,O,G,we,Ke,st,bt,St,Wt)=>{u.kb("Resize",l,{antialias:m,axes:x?Array.from(o().subarray(Number(x)>>>0,Number(O)>>>0)):[],coordinateTransformMode:Bs(G),cubicCoeffA:we,excludeOutside:Ke,extrapolationValue:st,keepAspectRatioPolicy:Bs(bt),mode:Bs(St),nearestMode:Bs(Wt)})},885728:(l,m,x,O,G,we,Ke)=>{u.kb("Slice",l,{starts:m?Array.from(o().subarray(Number(m)>>>0,Number(x)>>>0)):[],ends:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[],axes:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[]})},885992:l=>{u.kb("Tile",l,void 0)},886044:(l,m,x)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:x?"NHWC":"NCHW"})},886158:(l,m,x)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:x?"NHWC":"NCHW"})},886272:l=>{u.kb("Range",l,void 0)},886325:(l,m)=>{u.kb("Einsum",l,{equation:Bs(m)})},886406:(l,m,x,O,G)=>{u.kb("Pad",l,{mode:m,value:x,pads:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},886549:(l,m,x,O,G,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:x,spatial:!!G,trainingMode:!!O,format:we?"NHWC":"NCHW"})},886718:(l,m,x,O,G,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:x,spatial:!!G,trainingMode:!!O,format:we?"NHWC":"NCHW"})},886887:(l,m,x)=>{u.kb("CumSum",l,{exclusive:Number(m),reverse:Number(x)})},886984:(l,m,x)=>{u.kb("DequantizeLinear",l,{axis:m,blockSize:x})},887074:(l,m,x,O,G)=>{u.kb("GridSample",l,{align_corners:m,mode:Bs(x),padding_mode:Bs(O),format:G?"NHWC":"NCHW"})},887244:(l,m,x,O,G)=>{u.kb("GridSample",l,{align_corners:m,mode:Bs(x),padding_mode:Bs(O),format:G?"NHWC":"NCHW"})},887414:(l,m)=>{u.kb("ScatterND",l,{reduction:Bs(m)})},887499:(l,m,x,O,G,we,Ke,st,bt)=>{u.kb("Attention",l,{numHeads:m,isUnidirectional:x,maskFilterValue:O,scale:G,doRotary:we,qkvHiddenSizes:Ke?Array.from(o().subarray(Number(st)>>>0,Number(st)+Ke>>>0)):[],pastPresentShareBuffer:!!bt})},887771:l=>{u.kb("BiasAdd",l,void 0)},887826:l=>{u.kb("BiasSplitGelu",l,void 0)},887887:l=>{u.kb("FastGelu",l,void 0)},887943:(l,m,x,O,G,we,Ke,st,bt,St,Wt,hs,Ms,We,ls,Rs)=>{u.kb("Conv",l,{format:hs?"NHWC":"NCHW",auto_pad:m,dilations:x?Array.from(o().subarray(Number(x)>>>0,Number(O)>>>0)):[],group:G,kernel_shape:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],pads:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],strides:St?Array.from(o().subarray(Number(St)>>>0,Number(Wt)>>>0)):[],w_is_const:()=>!!s()[Number(Ms)>>>0],activation:Bs(We),activation_params:ls?Array.from(p().subarray(Number(ls)>>>0,Number(Rs)>>>0)):[]})},888527:l=>{u.kb("Gelu",l,void 0)},888579:(l,m,x,O,G,we,Ke,st,bt)=>{u.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:x,scale:O,softcap:G,doRotary:we,rotaryInterleaved:Ke,smoothSoftmax:st,localWindowSize:bt})},888796:(l,m,x,O)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:x,simplified:!!O})},888907:(l,m,x,O)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:x,simplified:!!O})},889018:(l,m,x,O,G,we)=>{u.kb("MatMulNBits",l,{k:m,n:x,accuracyLevel:O,bits:G,blockSize:we})},889145:(l,m,x,O,G,we)=>{u.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:x,maskFilterValue:O,scale:G,doRotary:we})},889304:(l,m)=>{u.kb("QuickGelu",l,{alpha:m})},889368:(l,m,x,O,G)=>{u.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:x,rotaryEmbeddingDim:O,scale:G})},889507:(l,m,x)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!x})},889609:(l,m,x)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!x})},889711:(l,m,x,O)=>{u.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:x,blockSize:O})},889832:l=>{u.$b(l)},889866:(l,m)=>u.cc(Number(l),Number(m),u.Gb.hc,u.Gb.errors)};function Lf(l,m,x){return Im(async()=>{await u.Yb(Number(l),Number(m),Number(x))})}function zf(){return typeof wasmOffsetConverter<"u"}function oh(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var ah=l=>{l.terminate(),l.onmessage=()=>{}},Zh=l=>{Qn.length==0&&(im(),nm(Qn[0]));var m=Qn.pop();if(!m)return 6;Fi.push(m),un[l.Bb]=m,m.Bb=l.Bb;var x={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(x,l.nc),0},Oi=0,Is=(l,m,...x)=>{for(var O=2*x.length,G=Eh(),we=xh(8*O),Ke=we>>>3,st=0;st>>0]=bt)}return l=sf(l,0,O,we,m),Dp(G),l};function lh(l){if(Z)return Is(0,1,l);if(Ht=l,!(0{if(Ht=l,Z)throw em(l),"unwind";lh(l)},Qn=[],Fi=[],tm=[],un={},sm=l=>{var m=l.Bb;delete un[m],Qn.push(l),Fi.splice(Fi.indexOf(l),1),l.Bb=0,Th(m)};function rm(){tm.forEach(l=>l())}var nm=l=>new Promise(m=>{l.onmessage=G=>{var we=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=Da()){var Ke=un[G.targetThread];Ke?Ke.postMessage(G,G.transferList):kt(`Internal error! Worker sent a message "${we}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else we==="checkMailbox"?xp():we==="spawnThread"?Zh(G):we==="cleanupThread"?sm(un[G.thread]):we==="killThread"?(G=G.thread,we=un[G],delete un[G],ah(we),Th(G),Fi.splice(Fi.indexOf(we),1),we.Bb=0):we==="cancelThread"?un[G.thread].postMessage({cmd:"cancel"}):we==="loaded"?(l.loaded=!0,m(l)):we==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):we==="callHandler"?u[G.handler](...G.args):we&&kt(`worker sent an unknown command ${we}`)},l.onerror=G=>{throw kt(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var x,O=[];for(x of[])u.hasOwnProperty(x)&&O.push(x);l.postMessage({cmd:"load",handlers:O,wasmMemory:jt,wasmModule:bs})});function im(){var l=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Qn.push(l)}var Tp=l=>{for(;0{var l=Da(),m=d()[l+52>>>2>>>0];l=d()[l+56>>>2>>>0],nf(m,m-l),Dp(m)},Rf=(l,m)=>{Oi=0,l=of(l,m),0>>=0);throw m>>>=0,x>>>=0,d()[O.Kb+16>>>2>>>0]=0,d()[O.Kb+4>>>2>>>0]=m,d()[O.Kb+8>>>2>>>0]=x,l}function om(l,m,x,O){return Z?Is(2,1,l,m,x,O):am(l,m,x,O)}function am(l,m,x,O){if(l>>>=0,m>>>=0,x>>>=0,O>>>=0,te===void 0)return kt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return Z&&G.length===0?om(l,m,x,O):(l={ic:x,Bb:l,Rb:O,nc:G},Z?(l.Nb="spawnThread",postMessage(l,G),0):Zh(l))}var lm=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,um=(l,m,x)=>{var O=(m>>>=0)+x;for(x=m;l[x]&&!(x>=O);)++x;if(16(G=(240&G)==224?(15&G)<<12|we<<6|Ke:(7&G)<<18|we<<12|Ke<<6|63&l[m++])?O+=String.fromCharCode(G):(G-=65536,O+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else O+=String.fromCharCode(G)}return O},Bs=(l,m)=>(l>>>=0)?um(n(),l,m):"";function dm(l,m,x){return Z?Is(3,1,l,m,x):0}function cm(l,m){if(Z)return Is(4,1,l,m)}var dh=l=>{for(var m=0,x=0;x=O?m++:2047>=O?m+=2:55296<=O&&57343>=O?(m+=4,++x):m+=3}return m},pm=(l,m,x,O)=>{if(!(0>>=0;O=x+O-1;for(var we=0;we=Ke&&(Ke=65536+((1023&Ke)<<10)|1023&l.charCodeAt(++we)),127>=Ke){if(x>=O)break;m[x++>>>0]=Ke}else{if(2047>=Ke){if(x+1>=O)break;m[x++>>>0]=192|Ke>>6}else{if(65535>=Ke){if(x+2>=O)break;m[x++>>>0]=224|Ke>>12}else{if(x+3>=O)break;m[x++>>>0]=240|Ke>>18,m[x++>>>0]=128|Ke>>12&63}m[x++>>>0]=128|Ke>>6&63}m[x++>>>0]=128|63&Ke}}return m[x>>>0]=0,x-G},Oa=(l,m,x)=>pm(l,n(),m,x);function hm(l,m){if(Z)return Is(5,1,l,m)}function mm(l,m,x){if(Z)return Is(6,1,l,m,x)}function fm(l,m,x){return Z?Is(7,1,l,m,x):0}function _m(l,m){if(Z)return Is(8,1,l,m)}function gm(l,m,x){if(Z)return Is(9,1,l,m,x)}function wm(l,m,x,O){if(Z)return Is(10,1,l,m,x,O)}function ym(l,m,x,O){if(Z)return Is(11,1,l,m,x,O)}function Mm(l,m,x,O){if(Z)return Is(12,1,l,m,x,O)}function bm(l){if(Z)return Is(13,1,l)}function vm(l,m){if(Z)return Is(14,1,l,m)}function Tm(l,m,x){if(Z)return Is(15,1,l,m,x)}var xm,Yn,Uf=()=>{Xn("")},dn=l=>{for(var m="";n()[l>>>0];)m+=xm[n()[l++>>>0]];return m},ch={},ph={};function kn(l,m,x={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(O,G,we={}){var Ke=G.name;if(!O)throw new Yn(`type "${Ke}" must have a positive integer typeid pointer`);if(ph.hasOwnProperty(O)){if(we.Tb)return;throw new Yn(`Cannot register type '${Ke}' twice`)}ph[O]=G,ch.hasOwnProperty(O)&&(G=ch[O],delete ch[O],G.forEach(st=>st()))}(l,m,x)}var Em=(l,m,x)=>{switch(m){case 1:return x?O=>s()[O>>>0]:O=>n()[O>>>0];case 2:return x?O=>i()[O>>>1>>>0]:O=>a()[O>>>1>>>0];case 4:return x?O=>o()[O>>>2>>>0]:O=>d()[O>>>2>>>0];case 8:return x?O=>Vs[O>>>3]:O=>ln[O>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function Wf(l,m,x){x>>>=0,kn(l>>>=0,{name:m=dn(m>>>0),fromWireType:O=>O,toWireType:function(O,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(O=typeof G)=="object"||O==="array"||O==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:Jn,readValueFromPointer:Em(m,x,m.indexOf("u")==-1),Eb:null})}var Jn=8;function Vf(l,m,x,O){kn(l>>>=0,{name:m=dn(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,we){return we?x:O},argPackAdvance:Jn,readValueFromPointer:function(G){return this.fromWireType(n()[G>>>0])},Eb:null})}var hh=[],Sn=[];function mh(l){9<(l>>>=0)&&--Sn[l+1]==0&&(Sn[l]=void 0,hh.push(l))}var Cr=l=>{if(!l)throw new Yn("Cannot use deleted val. handle = "+l);return Sn[l]},Ir=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=hh.pop()||Sn.length;return Sn[m]=l,Sn[m+1]=1,m}};function fh(l){return this.fromWireType(d()[l>>>2>>>0])}var Gf={name:"emscripten::val",fromWireType:l=>{var m=Cr(l);return mh(l),m},toWireType:(l,m)=>Ir(m),argPackAdvance:Jn,readValueFromPointer:fh,Eb:null};function Kf(l){return kn(l>>>0,Gf)}var Hf=(l,m)=>{switch(m){case 4:return function(x){return this.fromWireType(p()[x>>>2>>>0])};case 8:return function(x){return this.fromWireType(h()[x>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function qf(l,m,x){x>>>=0,kn(l>>>=0,{name:m=dn(m>>>0),fromWireType:O=>O,toWireType:(O,G)=>G,argPackAdvance:Jn,readValueFromPointer:Hf(m,x),Eb:null})}function Xf(l,m,x,O,G){if(l>>>=0,x>>>=0,m=dn(m>>>0),G===-1&&(G=4294967295),G=st=>st,O===0){var we=32-8*x;G=st=>st<>>we}var Ke=m.includes("unsigned")?function(st,bt){return bt>>>0}:function(st,bt){return bt};kn(l,{name:m,fromWireType:G,toWireType:Ke,argPackAdvance:Jn,readValueFromPointer:Em(m,x,O!==0),Eb:null})}function Qf(l,m,x){function O(we){var Ke=d()[we>>>2>>>0];return we=d()[we+4>>>2>>>0],new G(s().buffer,we,Ke)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];kn(l>>>=0,{name:x=dn(x>>>0),fromWireType:O,argPackAdvance:Jn,readValueFromPointer:O},{Tb:!0})}function Yf(l,m){l>>>=0;var x=(m=dn(m>>>0))==="std::string";kn(l,{name:m,fromWireType:function(O){var G=d()[O>>>2>>>0],we=O+4;if(x)for(var Ke=we,st=0;st<=G;++st){var bt=we+st;if(st==G||n()[bt>>>0]==0){if(Ke=Bs(Ke,bt-Ke),St===void 0)var St=Ke;else St+="\0",St+=Ke;Ke=bt+1}}else{for(St=Array(G),st=0;st>>0]);St=St.join("")}return pn(O),St},toWireType:function(O,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var we=typeof G=="string";if(!(we||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new Yn("Cannot pass non-string to std::string");var Ke=x&&we?dh(G):G.length,st=Op(4+Ke+1),bt=st+4;if(d()[st>>>2>>>0]=Ke,x&&we)Oa(G,bt,Ke+1);else if(we)for(we=0;we>>0]=St}else for(we=0;we>>0]=G[we];return O!==null&&O.push(pn,st),st},argPackAdvance:Jn,readValueFromPointer:fh,Eb(O){pn(O)}})}var Pm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Jf=(l,m)=>{for(var x=l>>1,O=x+m/2;!(x>=O)&&a()[x>>>0];)++x;if(32<(x<<=1)-l&&Pm)return Pm.decode(n().slice(l,x));for(x="",O=0;!(O>=m/2);++O){var G=i()[l+2*O>>>1>>>0];if(G==0)break;x+=String.fromCharCode(G)}return x},Zf=(l,m,x)=>{if(x??(x=2147483647),2>x)return 0;var O=m;x=(x-=2)<2*l.length?x/2:l.length;for(var G=0;G>>1>>>0]=we,m+=2}return i()[m>>>1>>>0]=0,m-O},e_=l=>2*l.length,t_=(l,m)=>{for(var x=0,O="";!(x>=m/4);){var G=o()[l+4*x>>>2>>>0];if(G==0)break;++x,65536<=G?(G-=65536,O+=String.fromCharCode(55296|G>>10,56320|1023&G)):O+=String.fromCharCode(G)}return O},s_=(l,m,x)=>{if(m>>>=0,x??(x=2147483647),4>x)return 0;var O=m;x=O+x-4;for(var G=0;G=we&&(we=65536+((1023&we)<<10)|1023&l.charCodeAt(++G)),o()[m>>>2>>>0]=we,(m+=4)+4>x)break}return o()[m>>>2>>>0]=0,m-O},r_=l=>{for(var m=0,x=0;x=O&&++x,m+=4}return m};function n_(l,m,x){if(l>>>=0,m>>>=0,x=dn(x>>>=0),m===2)var O=Jf,G=Zf,we=e_,Ke=st=>a()[st>>>1>>>0];else m===4&&(O=t_,G=s_,we=r_,Ke=st=>d()[st>>>2>>>0]);kn(l,{name:x,fromWireType:st=>{for(var bt,St=d()[st>>>2>>>0],Wt=st+4,hs=0;hs<=St;++hs){var Ms=st+4+hs*m;hs!=St&&Ke(Ms)!=0||(Wt=O(Wt,Ms-Wt),bt===void 0?bt=Wt:(bt+="\0",bt+=Wt),Wt=Ms+m)}return pn(st),bt},toWireType:(st,bt)=>{if(typeof bt!="string")throw new Yn(`Cannot pass non-string to C++ string type ${x}`);var St=we(bt),Wt=Op(4+St+m);return d()[Wt>>>2>>>0]=St/m,G(bt,Wt+4,St+m),st!==null&&st.push(pn,Wt),Wt},argPackAdvance:Jn,readValueFromPointer:fh,Eb(st){pn(st)}})}function i_(l,m){kn(l>>>=0,{Ub:!0,name:m=dn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var o_=()=>1;function a_(l){vh(l>>>0,!U,1,!R,131072,!1),rm()}var Cm=l=>{if(!As)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(o(),l>>>2,l).value.then(xp),l+=128,Atomics.store(o(),l>>>2,1))}var xp=()=>{var l=Da();l&&(_h(l),Cm(rf))};function l_(l,m){(l>>>=0)==m>>>0?setTimeout(xp):Z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=un[l])&&l.postMessage({cmd:"checkMailbox"})}var gh=[];function u_(l,m,x,O,G){for(m>>>=0,O/=2,gh.length=O,x=G>>>0>>>3,G=0;G>>0];return(m?ih[m]:Z_[l])(...gh)}function d_(l){l>>>=0,Z?postMessage({cmd:"cleanupThread",thread:l}):sm(un[l])}function c_(l){}var Ep=(l,m)=>{var x=ph[l];if(x===void 0)throw l=Zm(l),x=dn(l),pn(l),new Yn(`${m} has unknown type ${x}`);return x},km=(l,m,x)=>{var O=[];return l=l.toWireType(O,x),O.length&&(d()[m>>>2>>>0]=Ir(O)),l};function p_(l,m,x){return m>>>=0,x>>>=0,l=Cr(l>>>0),m=Ep(m,"emval::as"),km(m,x,l)}function h_(l,m){return m>>>=0,l=Cr(l>>>0),(m=Ep(m,"emval::as")).toWireType(null,l)}var Pp=l=>{try{l()}catch(m){Xn(m)}},Zn=0,cn=null,Sm=0,Cp=[],$m={},Am={},m_=0,wh=null,f_=[];function Im(l){return function(m){if(!As){if(Zn===0){var x=!1,O=!1;m((G=0)=>{if(!As&&(Sm=G,x=!0,O)){Zn=2,Pp(()=>uf(cn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var we=function(){var bt=o()[cn+8>>>2>>>0];return bt=Nt[Am[bt]],--Oi,bt()}()}catch(bt){we=bt,G=!0}var Ke=!1;if(!cn){var st=wh;st&&(wh=null,(G?st.reject:st.resolve)(we),Ke=!0)}if(G&&!Ke)throw we}}),O=!0,x||(Zn=1,cn=function(){var G=Op(65548),we=G+12;d()[G>>>2>>>0]=we,d()[G+4>>>2>>>0]=we+65536,we=Cp[0];var Ke=$m[we];return Ke===void 0&&(Ke=m_++,$m[we]=Ke,Am[Ke]=we),we=Ke,o()[G+8>>>2>>>0]=we,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Pp(()=>af(cn)))}else Zn===2?(Zn=0,Pp(df),pn(cn),cn=null,f_.forEach(Cm)):Xn(`invalid state: ${Zn}`);return Sm}}(m=>{l().then(m)})}function __(l){return l>>>=0,Im(()=>(l=Cr(l)).then(Ir))}var kp=[];function g_(l,m,x,O){return x>>>=0,O>>>=0,(l=kp[l>>>0])(null,m=Cr(m>>>0),x,O)}var w_={},Sp=l=>{var m=w_[l];return m===void 0?dn(l):m};function y_(l,m,x,O,G){return x>>>=0,O>>>=0,G>>>=0,(l=kp[l>>>0])(m=Cr(m>>>0),m[x=Sp(x)],O,G)}var Om=()=>typeof globalThis=="object"?globalThis:Function("return this")();function M_(l){return(l>>>=0)==0?Ir(Om()):(l=Sp(l),Ir(Om()[l]))}var b_=l=>{var m=kp.length;return kp.push(l),m},v_=(l,m)=>{for(var x=Array(l),O=0;O>>2>>>0],"parameter "+O);return x},Fm=(l,m)=>Object.defineProperty(m,"name",{value:l});function T_(l,m,x){var O=(m=v_(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { `,we=0,Ke=[];x===0&&Ke.push("obj");for(var st=["retType"],bt=[O],St=0;StWt.name).join(", ")}) => ${O.name}>`,b_(Fm(x,l))}function x_(l){return l=Sp(l>>>0),Ir(u[l])}function E_(l,m){return m>>>=0,l=Cr(l>>>0),m=Cr(m),Ir(l[m])}function P_(l){9<(l>>>=0)&&(Sn[l+1]+=1)}function C_(){return Ir([])}function k_(l){l=Cr(l>>>0);for(var m=Array(l.length),x=0;x>>0))}function $_(){return Ir({})}function A_(l){for(var m=Cr(l>>>=0);m.length;){var x=m.pop();m.pop()(x)}mh(l)}function I_(l,m,x){m>>>=0,x>>>=0,l=Cr(l>>>0),m=Cr(m),x=Cr(x),l[m]=x}function O_(l,m){return m>>>=0,l=(l=Ep(l>>>0,"_emval_take_value")).readValueFromPointer(m),Ir(l)}function F_(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),o()[m>>>2>>>0]=l.getUTCSeconds(),o()[m+4>>>2>>>0]=l.getUTCMinutes(),o()[m+8>>>2>>>0]=l.getUTCHours(),o()[m+12>>>2>>>0]=l.getUTCDate(),o()[m+16>>>2>>>0]=l.getUTCMonth(),o()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,o()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[m+28>>>2>>>0]=l}var Fa=l=>l%4==0&&(l%100!=0||l%400==0),Dm=[0,31,60,91,121,152,182,213,244,274,305,335],Lm=[0,31,59,90,120,151,181,212,243,273,304,334];function D_(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),o()[m>>>2>>>0]=l.getSeconds(),o()[m+4>>>2>>>0]=l.getMinutes(),o()[m+8>>>2>>>0]=l.getHours(),o()[m+12>>>2>>>0]=l.getDate(),o()[m+16>>>2>>>0]=l.getMonth(),o()[m+20>>>2>>>0]=l.getFullYear()-1900,o()[m+24>>>2>>>0]=l.getDay();var x=(Fa(l.getFullYear())?Dm:Lm)[l.getMonth()]+l.getDate()-1|0;o()[m+28>>>2>>>0]=x,o()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),x=new Date(l.getFullYear(),6,1).getTimezoneOffset();var O=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(x!=O&&l.getTimezoneOffset()==Math.min(O,x)),o()[m+32>>>2>>>0]=l}function L_(l){l>>>=0;var m=new Date(o()[l+20>>>2>>>0]+1900,o()[l+16>>>2>>>0],o()[l+12>>>2>>>0],o()[l+8>>>2>>>0],o()[l+4>>>2>>>0],o()[l>>>2>>>0],0),x=o()[l+32>>>2>>>0],O=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),we=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Ke=Math.min(we,G);return 0>x?o()[l+32>>>2>>>0]=+(G!=we&&Ke==O):0>>2>>>0]=m.getDay(),x=(Fa(m.getFullYear())?Dm:Lm)[m.getMonth()]+m.getDate()-1|0,o()[l+28>>>2>>>0]=x,o()[l>>>2>>>0]=m.getSeconds(),o()[l+4>>>2>>>0]=m.getMinutes(),o()[l+8>>>2>>>0]=m.getHours(),o()[l+12>>>2>>>0]=m.getDate(),o()[l+16>>>2>>>0]=m.getMonth(),o()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function zm(l,m,x,O,G,we,Ke){return Z?Is(16,1,l,m,x,O,G,we,Ke):-52}function Bm(l,m,x,O,G,we){if(Z)return Is(17,1,l,m,x,O,G,we)}function z_(l,m,x,O){l>>>=0,m>>>=0,x>>>=0,O>>>=0;var G=new Date().getFullYear(),we=new Date(G,0,1),Ke=new Date(G,6,1);G=we.getTimezoneOffset();var st=Ke.getTimezoneOffset(),bt=Math.max(G,st);d()[l>>>2>>>0]=60*bt,o()[m>>>2>>>0]=+(G!=st),we=(l=St=>St.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(we),Ke=l(Ke),st{yh.length=0;for(var x;x=n()[l++>>>0];){var O=x!=105;m+=(O&=x!=112)&&m%8?4:0,yh.push(x==112?d()[m>>>2>>>0]:x==106?Vs[m>>>3]:x==105?o()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=O?8:4}return yh};function B_(l,m,x){return l>>>=0,m=Rm(m>>>0,x>>>0),ih[l](...m)}function R_(l,m,x){return l>>>=0,m=Rm(m>>>0,x>>>0),ih[l](...m)}var N_=()=>{},j_=()=>Date.now();function U_(l,m){return kt(Bs(l>>>0,m>>>0))}var Nm,W_=()=>{throw Oi+=1,"unwind"};function V_(){return 4294901760}Nm=()=>performance.timeOrigin+performance.now();var G_=()=>navigator.hardwareConcurrency;function K_(){return Xn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function H_(l){l>>>=0;var m=n().length;if(l<=m||4294901760=x;x*=2){var O=m*(1+.2/x);O=Math.min(O,l+100663296);var G=Math;O=Math.max(l,O);e:{G=(G.min.call(G,4294901760,O+(65536-O%65536)%65536)-jt.buffer.byteLength+65535)/65536;try{jt.grow(G),Ts();var we=1;break e}catch{}we=void 0}if(we)return!0}return!1}var $p=()=>(Xn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Ec={},jm=l=>{l.forEach(m=>{$p()})};function q_(){var l=Error().stack.toString().split(` `);return l[0]=="Error"&&l.shift(),jm(l),Ec.Qb=$p(),Ec.fc=l,Ec.Qb}function X_(l,m,x){if(l>>>=0,m>>>=0,Ec.Qb==l)var O=Ec.fc;else(O=Error().stack.toString().split(` `))[0]=="Error"&&O.shift(),jm(O);for(var G=3;O[G]&&$p()!=l;)++G;for(l=0;l>>2>>>0]=$p();return l}var Mh,bh={},Um=()=>{if(!Mh){var l,m={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",_:$e};for(l in bh)bh[l]===void 0?delete m[l]:m[l]=bh[l];var x=[];for(l in m)x.push(`${l}=${m[l]}`);Mh=x}return Mh};function Wm(l,m){if(Z)return Is(18,1,l,m);l>>>=0,m>>>=0;var x=0;return Um().forEach((O,G)=>{var we=m+x;for(G=d()[l+4*G>>>2>>>0]=we,we=0;we>>0]=O.charCodeAt(we);s()[G>>>0]=0,x+=O.length+1}),0}function Vm(l,m){if(Z)return Is(19,1,l,m);l>>>=0,m>>>=0;var x=Um();d()[l>>>2>>>0]=x.length;var O=0;return x.forEach(G=>O+=G.length+1),d()[m>>>2>>>0]=O,0}function Gm(l){return Z?Is(20,1,l):52}function Km(l,m,x,O){return Z?Is(21,1,l,m,x,O):52}function Hm(l,m,x,O){return Z?Is(22,1,l,m,x,O):70}var Q_=[null,[],[]];function qm(l,m,x,O){if(Z)return Is(23,1,l,m,x,O);m>>>=0,x>>>=0,O>>>=0;for(var G=0,we=0;we>>2>>>0],st=d()[m+4>>>2>>>0];m+=8;for(var bt=0;bt>>0],Wt=Q_[l];St===0||St===10?((l===1?Yt:kt)(um(Wt,0)),Wt.length=0):Wt.push(St)}G+=st}return d()[O>>>2>>>0]=G,0}var Xm=[31,29,31,30,31,30,31,31,30,31,30,31],Qm=[31,28,31,30,31,30,31,31,30,31,30,31],Y_=(l,m)=>{s().set(l,m>>>0)};function Ym(l,m,x,O){function G(We,ls,Rs){for(We=typeof We=="number"?We.toString():We||"";We.lengthpf?-1:0Di-We.getDate())){We.setDate(We.getDate()+ls);break}ls-=Di-We.getDate()+1,We.setDate(1),11>Rs?We.setMonth(Rs+1):(We.setMonth(0),We.setFullYear(We.getFullYear()+1))}return Rs=new Date(We.getFullYear()+1,0,4),ls=st(new Date(We.getFullYear(),0,4)),Rs=st(Rs),0>=Ke(ls,We)?0>=Ke(Rs,We)?We.getFullYear()+1:We.getFullYear():We.getFullYear()-1}l>>>=0,m>>>=0,x>>>=0,O>>>=0;var St=d()[O+40>>>2>>>0];for(var Wt in O={lc:o()[O>>>2>>>0],kc:o()[O+4>>>2>>>0],Ib:o()[O+8>>>2>>>0],Mb:o()[O+12>>>2>>>0],Jb:o()[O+16>>>2>>>0],Db:o()[O+20>>>2>>>0],vb:o()[O+24>>>2>>>0],Cb:o()[O+28>>>2>>>0],sc:o()[O+32>>>2>>>0],jc:o()[O+36>>>2>>>0],mc:St?Bs(St):""},x=Bs(x),St={"%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"})x=x.replace(new RegExp(Wt,"g"),St[Wt]);var hs="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ms="January February March April May June July August September October November December".split(" ");for(Wt in St={"%a":We=>hs[We.vb].substring(0,3),"%A":We=>hs[We.vb],"%b":We=>Ms[We.Jb].substring(0,3),"%B":We=>Ms[We.Jb],"%C":We=>we((We.Db+1900)/100|0,2),"%d":We=>we(We.Mb,2),"%e":We=>G(We.Mb,2," "),"%g":We=>bt(We).toString().substring(2),"%G":bt,"%H":We=>we(We.Ib,2),"%I":We=>((We=We.Ib)==0?We=12:12{for(var ls=0,Rs=0;Rs<=We.Jb-1;ls+=(Fa(We.Db+1900)?Xm:Qm)[Rs++]);return we(We.Mb+ls,3)},"%m":We=>we(We.Jb+1,2),"%M":We=>we(We.kc,2),"%n":()=>` `,"%p":We=>0<=We.Ib&&12>We.Ib?"AM":"PM","%S":We=>we(We.lc,2),"%t":()=>" ","%u":We=>We.vb||7,"%U":We=>we(Math.floor((We.Cb+7-We.vb)/7),2),"%V":We=>{var ls=Math.floor((We.Cb+7-(We.vb+6)%7)/7);if(2>=(We.vb+371-We.Cb-2)%7&&ls++,ls)ls==53&&((Rs=(We.vb+371-We.Cb)%7)==4||Rs==3&&Fa(We.Db)||(ls=1));else{ls=52;var Rs=(We.vb+7-We.Cb-1)%7;(Rs==4||Rs==5&&Fa(We.Db%400-1))&&ls++}return we(ls,2)},"%w":We=>We.vb,"%W":We=>we(Math.floor((We.Cb+7-(We.vb+6)%7)/7),2),"%y":We=>(We.Db+1900).toString().substring(2),"%Y":We=>We.Db+1900,"%z":We=>{var ls=0<=(We=We.jc);return We=Math.abs(We)/60,(ls?"+":"-")+("0000"+(We/60*100+We%60)).slice(-4)},"%Z":We=>We.mc,"%%":()=>"%"},x=x.replace(/%%/g,"\0\0"),St)x.includes(Wt)&&(x=x.replace(new RegExp(Wt,"g"),St[Wt](O)));return Wt=function(We){var ls=Array(dh(We)+1);return pm(We,ls,0,ls.length),ls}(x=x.replace(/\0\0/g,"%")),Wt.length>m?0:(Y_(Wt,l),Wt.length-1)}function J_(l,m,x,O){return Ym(l>>>0,m>>>0,x>>>0,O>>>0)}Z||function(){for(var l=u.numThreads-1;l--;)im();qn.unshift(()=>{Tc++,function(m){Z?m():Promise.all(Qn.map(nm)).then(m)}(()=>Hh())})}();for(var Jm=Array(256),Ap=0;256>Ap;++Ap)Jm[Ap]=String.fromCharCode(Ap);xm=Jm,Yn=u.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},u.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},Sn.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>Sn.length/2-5-hh.length;var Z_=[lh,em,om,dm,cm,hm,mm,fm,_m,gm,wm,ym,Mm,bm,vm,Tm,zm,Bm,Wm,Vm,Gm,Km,Hm,qm],Nt=function(){function l(x,O){return Nt=x.exports,Nt=function(){var G=Nt,we={};for(let[Ke,st]of Object.entries(G))we[Ke]=typeof st=="function"?(...bt)=>{Cp.push(Ke);try{return st(...bt)}finally{As||(Cp.pop(),cn&&Zn===1&&Cp.length===0&&(Zn=0,Oi+=1,Pp(lf),typeof Fibers<"u"&&Fibers.tc()))}}:st;return we}(),Nt=function(){var G=Nt,we=st=>bt=>st(bt)>>>0,Ke=st=>()=>st()>>>0;return(G=Object.assign({},G)).Da=we(G.Da),G.gb=Ke(G.gb),G.ib=we(G.ib),G.emscripten_main_runtime_thread_id=Ke(G.emscripten_main_runtime_thread_id),G.tb=we(G.tb),G.ub=Ke(G.ub),G}(),tm.push(Nt.jb),vc.unshift(Nt.Ca),bs=O,Hh(),Nt}var m=Jh();if(Tc++,u.instantiateWasm)try{return u.instantiateWasm(m,l)}catch(x){kt(`Module.instantiateWasm callback failed with error: ${x}`),S(x)}return nh||(nh=u.locateFile?qh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ge):Ge+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(x,O){var G=nh;return lt||typeof WebAssembly.instantiateStreaming!="function"||qh(G)||Xh(G)||typeof fetch!="function"?Yh(G,x,O):fetch(G,{credentials:"same-origin"}).then(we=>WebAssembly.instantiateStreaming(we,x).then(O,function(Ke){return kt(`wasm streaming compile failed: ${Ke}`),kt("falling back to ArrayBuffer instantiation"),Yh(G,x,O)}))}(m,function(x){l(x.instance,x.module)}).catch(S),{}}(),Zm=l=>(Zm=Nt.Da)(l),ef=()=>(ef=Nt.Ea)();u._OrtInit=(l,m)=>(u._OrtInit=Nt.Fa)(l,m),u._OrtGetLastError=(l,m)=>(u._OrtGetLastError=Nt.Ga)(l,m),u._OrtCreateSessionOptions=(l,m,x,O,G,we,Ke,st,bt,St)=>(u._OrtCreateSessionOptions=Nt.Ha)(l,m,x,O,G,we,Ke,st,bt,St),u._OrtAppendExecutionProvider=(l,m)=>(u._OrtAppendExecutionProvider=Nt.Ia)(l,m),u._OrtAddFreeDimensionOverride=(l,m,x)=>(u._OrtAddFreeDimensionOverride=Nt.Ja)(l,m,x),u._OrtAddSessionConfigEntry=(l,m,x)=>(u._OrtAddSessionConfigEntry=Nt.Ka)(l,m,x),u._OrtReleaseSessionOptions=l=>(u._OrtReleaseSessionOptions=Nt.La)(l),u._OrtCreateSession=(l,m,x)=>(u._OrtCreateSession=Nt.Ma)(l,m,x),u._OrtReleaseSession=l=>(u._OrtReleaseSession=Nt.Na)(l),u._OrtGetInputOutputCount=(l,m,x)=>(u._OrtGetInputOutputCount=Nt.Oa)(l,m,x),u._OrtGetInputName=(l,m)=>(u._OrtGetInputName=Nt.Pa)(l,m),u._OrtGetOutputName=(l,m)=>(u._OrtGetOutputName=Nt.Qa)(l,m),u._OrtFree=l=>(u._OrtFree=Nt.Ra)(l),u._OrtCreateTensor=(l,m,x,O,G,we)=>(u._OrtCreateTensor=Nt.Sa)(l,m,x,O,G,we),u._OrtGetTensorData=(l,m,x,O,G)=>(u._OrtGetTensorData=Nt.Ta)(l,m,x,O,G),u._OrtReleaseTensor=l=>(u._OrtReleaseTensor=Nt.Ua)(l),u._OrtCreateRunOptions=(l,m,x,O)=>(u._OrtCreateRunOptions=Nt.Va)(l,m,x,O),u._OrtAddRunConfigEntry=(l,m,x)=>(u._OrtAddRunConfigEntry=Nt.Wa)(l,m,x),u._OrtReleaseRunOptions=l=>(u._OrtReleaseRunOptions=Nt.Xa)(l),u._OrtCreateBinding=l=>(u._OrtCreateBinding=Nt.Ya)(l),u._OrtBindInput=(l,m,x)=>(u._OrtBindInput=Nt.Za)(l,m,x),u._OrtBindOutput=(l,m,x,O)=>(u._OrtBindOutput=Nt._a)(l,m,x,O),u._OrtClearBoundOutputs=l=>(u._OrtClearBoundOutputs=Nt.$a)(l),u._OrtReleaseBinding=l=>(u._OrtReleaseBinding=Nt.ab)(l),u._OrtRunWithBinding=(l,m,x,O,G)=>(u._OrtRunWithBinding=Nt.bb)(l,m,x,O,G),u._OrtRun=(l,m,x,O,G,we,Ke,st)=>(u._OrtRun=Nt.cb)(l,m,x,O,G,we,Ke,st),u._OrtEndProfiling=l=>(u._OrtEndProfiling=Nt.db)(l),u._JsepOutput=(l,m,x)=>(u._JsepOutput=Nt.eb)(l,m,x),u._JsepGetNodeName=l=>(u._JsepGetNodeName=Nt.fb)(l);var Ip,Da=()=>(Da=Nt.gb)(),pn=u._free=l=>(pn=u._free=Nt.hb)(l),Op=u._malloc=l=>(Op=u._malloc=Nt.ib)(l),vh=(l,m,x,O,G,we)=>(vh=Nt.lb)(l,m,x,O,G,we),tf=()=>(tf=Nt.mb)(),sf=(l,m,x,O,G)=>(sf=Nt.nb)(l,m,x,O,G),Th=l=>(Th=Nt.ob)(l),Fp=l=>(Fp=Nt.pb)(l),rf=()=>(rf=Nt.qb)(),nf=(l,m)=>(nf=Nt.rb)(l,m),Dp=l=>(Dp=Nt.sb)(l),xh=l=>(xh=Nt.tb)(l),Eh=()=>(Eh=Nt.ub)(),of=u.dynCall_ii=(l,m)=>(of=u.dynCall_ii=Nt.wb)(l,m),af=l=>(af=Nt.xb)(l),lf=()=>(lf=Nt.yb)(),uf=l=>(uf=Nt.zb)(l),df=()=>(df=Nt.Ab)();function cf(){0Eh(),u.stackRestore=l=>Dp(l),u.stackAlloc=l=>xh(l),u.setValue=function(l,m,x="i8"){switch(x.endsWith("*")&&(x="*"),x){case"i1":case"i8":s()[l>>>0]=m;break;case"i16":i()[l>>>1>>>0]=m;break;case"i32":o()[l>>>2>>>0]=m;break;case"i64":Vs[l>>>3]=BigInt(m);break;case"float":p()[l>>>2>>>0]=m;break;case"double":h()[l>>>3>>>0]=m;break;case"*":d()[l>>>2>>>0]=m;break;default:Xn(`invalid type for setValue: ${x}`)}},u.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return s()[l>>>0];case"i16":return i()[l>>>1>>>0];case"i32":return o()[l>>>2>>>0];case"i64":return Vs[l>>>3];case"float":return p()[l>>>2>>>0];case"double":return h()[l>>>3>>>0];case"*":return d()[l>>>2>>>0];default:Xn(`invalid type for getValue: ${m}`)}},u.UTF8ToString=Bs,u.stringToUTF8=Oa,u.lengthBytesUTF8=dh,xc=function l(){Ip||cf(),Ip||(xc=l)},cf(),u.PTR_SIZE=4,B}),ks=Os,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&Os()}),ir,Kr,Or,mn,zt,Hr,kr,Fr,Sr=g(()=>{var e,t;rt(),ir=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),Kr=typeof location>"u"?void 0:location.origin,Or=(s,n)=>{try{let i=n??ir;return(i?new URL(s,i):new URL(s)).origin===Kr}catch{return!1}},mn=async s=>{let n=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},zt=(At(),M(mt)).default,Hr=async()=>{if(!ir)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Or(ir))return[void 0,zt()];let s=await mn(ir);return[s,zt(s)]},kr=(qs(),M(rs)).default,Fr=async(s,n,i)=>[void 0,kr]}),Dr,Zs,dr,$r,qr,or,ot,pt,It=g(()=>{Sr(),Zs=!1,dr=!1,$r=!1,qr=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},or=()=>{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}},ot=async e=>{if(Zs)return Promise.resolve();if(dr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if($r)throw new Error("previous call to 'initializeWebAssembly()' failed.");dr=!0;let t=e.initTimeout,s=e.numThreads;if(!or())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=qr();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", 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=s=1);let i=e.wasmPaths,a=typeof i=="string"?i:void 0,o=i==null?void 0:i.mjs,d=(o==null?void 0:o.href)??o,p=i==null?void 0:i.wasm,h=(p==null?void 0:p.href)??p,k=e.wasmBinary,[S,u]=await Fr(d,a,s>1),B=!1,R=[];if(t>0&&R.push(new Promise(U=>{setTimeout(()=>{B=!0,U()},t)})),R.push(new Promise((U,Z)=>{let te={numThreads:s};k?te.wasmBinary=k:(h||a)&&(te.locateFile=(Q,fe)=>h??(a??fe)+Q),u(te).then(Q=>{dr=!1,Zs=!0,Dr=Q,U(),S&&URL.revokeObjectURL(S)},Q=>{dr=!1,$r=!0,Z(Q)})})),await Promise.race(R),B)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},pt=()=>{if(Zs&&Dr)return Dr;throw new Error("WebAssembly is not initialized yet.")}}),us,Mr,ts,br=g(()=>{It(),us=(e,t)=>{let s=pt(),n=s.lengthBytesUTF8(e)+1,i=s._malloc(n);return s.stringToUTF8(e,i,n),t.push(i),i},Mr=(e,t,s,n)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([i,a])=>{let o=t?t+i:i;if(typeof a=="object")Mr(a,o+".",s,n);else if(typeof a=="string"||typeof a=="number")n(o,a.toString());else if(typeof a=="boolean")n(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},ts=e=>{let t=pt(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetLastError(i,i+n);let a=Number(t.getValue(i,n===4?"i32":"i64")),o=t.getValue(i+n,"*"),d=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(s)}}}),cr,Xr=g(()=>{It(),br(),cr=e=>{let t=pt(),s=0,n=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(i.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=us(e.tag,n)),s=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),s===0&&ts("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Mr(e.extra,"",new WeakSet,(o,d)=>{let p=us(o,n),h=us(d,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&ts(`Can't set a run config entry: ${o} - ${d}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(o=>t._free(o)),a}}}),Lr,vr,An,zr,In,si=g(()=>{It(),br(),Lr=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}`)}},vr=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},An=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(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},zr=(e,t,s)=>{for(let n of t){let i=typeof n=="string"?n:n.name;switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let o=n==null?void 0:n.deviceType;if(o){let d=us("deviceType",s),p=us(o,s);pt()._OrtAddSessionConfigEntry(e,d,p)!==0&&ts(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(i="JS",typeof n!="string"){let o=n;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let d=us("preferredLayout",s),p=us(o.preferredLayout,s);pt()._OrtAddSessionConfigEntry(e,d,p)!==0&&ts(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=us(i,s);pt()._OrtAppendExecutionProvider(e,a)!==0&&ts(`Can't append execution provider: ${i}.`)}},In=e=>{let t=pt(),s=0,n=[],i=e||{};An(i);try{let a=Lr(i.graphOptimizationLevel??"all"),o=vr(i.executionMode??"sequential"),d=typeof i.logId=="string"?us(i.logId,n):0,p=i.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=i.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let k=typeof i.optimizedModelFilePath=="string"?us(i.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,d,p,h,k),s===0&&ts("Can't create session options."),i.executionProviders&&zr(s,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let S=us("enableGraphCapture",n),u=us(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,S,u)!==0&&ts(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[S,u]of Object.entries(i.freeDimensionOverrides)){if(typeof S!="string")throw new Error(`free dimension override name must be a string: ${S}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let B=us(S,n);t._OrtAddFreeDimensionOverride(s,B,u)!==0&&ts(`Can't set a free dimension override: ${S} - ${u}.`)}return i.extra!==void 0&&Mr(i.extra,"",new WeakSet,(S,u)=>{let B=us(S,n),R=us(u,n);t._OrtAddSessionConfigEntry(s,B,R)!==0&&ts(`Can't set a session config entry: ${S} - ${u}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&ts("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Br,Tr,er,fn,Qr,_n,Yr,gn,Bt=g(()=>{Br=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}`)}},Tr=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}`)}},er=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((i,a)=>i*a,1);return s>0?Math.ceil(n*s):void 0},fn=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}`)}},Qr=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}`)}},_n=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Yr=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",gn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),wn,On=g(()=>{rt(),wn=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 s=t.headers.get("Content-Length"),n=s?parseInt(s,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(d){if(d instanceof RangeError){let p=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw d}let o=0;for(;;){let{done:d,value:p}=await i.read();if(d)break;let h=p.byteLength;new Uint8Array(a,o,h).set(p),o+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Fn,Dn,Rr,Ln,yn,zn,is,tr=g(()=>{Bt(),Fn=["V","I","W","E","F"],Dn=(e,t)=>{console.log(`[${Fn[e]},${new Date().toISOString()}]${t}`)},yn=(e,t)=>{Rr=e,Ln=t},zn=(e,t)=>{let s=Qr(e),n=Qr(Rr);s>=n&&Dn(s,typeof t=="function"?t():t)},is=(...e)=>{Ln&&zn(...e)}}),Mn,Bn=g(()=>{Bt(),Mn=(e,t)=>new(fn(t))(e)}),Jr=g(()=>{}),bn,Ee,E,q,ae,ye,Pe,He,ct,wt=g(()=>{tr(),Jr(),bn=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]]),Ee=[],E=e=>Math.ceil(Number(e)/16)*16,q=e=>{for(let t=0;tae++,Pe=async(e,t,s,n)=>{let i=E(s),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let d=a.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(d,0,s)),p}else return new Uint8Array(d.slice(0,s))}finally{a.destroy()}},He=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of bn)Ee.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,i=t.byteLength,a=E(i),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(Number(o.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=d.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,i)),d.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(d,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([h.finish()]),d.destroy(),is("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)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(s.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=E(s.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(s.gpuData.buffer,0,n.gpuData.buffer,0,i)}registerExternalBuffer(e,t,s){let n;if(s){if(n=s[0],e===s[1])return is("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else n=ye();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),is("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),is("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=q(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let d=(i?this.freeBuffers:this.freeUniformBuffers).get(s);d?d.length>0?n=d.pop():n=this.backend.device.createBuffer({size:s,usage:t}):n=this.backend.device.createBuffer({size:s,usage:t})}else n=this.backend.device.createBuffer({size:s,usage:t});let o={id:ye(),type:0,buffer:n};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),is("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return is("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await Pe(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=bn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(is("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ct=(...e)=>new He(...e)}),_t,it,Ct=g(()=>{_t=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}},it=e=>new _t(e)}),ms,ns,Se,ys,Fs,Xs,Js,Dt=g(()=>{ms=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},ns=class{static calcShape(e,t,s=!1){let n=e.length,i=t.length;if(n===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),o=new Array(a);if(s){if(n<2||i<2)return;let d=ms.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(d===void 0)return;[o[a-2],o[a-1]]=d}for(let d=s?3:1;d<=a;d++){let p=n-d<0?1:e[n-d],h=i-d<0?1:t[i-d];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)o[a-d]=Math.max(p,h);else{if(k>1)return;o[a-d]=0}}return o}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let i=1;i<=s;i++)if(e[s-i]!==1&&e[s-i]!==t[n-i])return!1;return!0}},Se=class Lp{static size(t){return Lp.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let n=t.length;if(n===0)return[];let i=new Array(n),a=n-1;for(;a>=0;){if(t[a]%s===0){i[a]=t[a]/s;break}if(s%t[a]!==0)throw new Error("cannot convert shape");i[a]=1,s/=t[a],a--}for(a--;a>=0;a--)i[a]=t[a];return i}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Lp.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Lp.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,n){let i=1;for(let a=s;a=0;--i)n[i]=n[i+1]*t[i+1];return n}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(n=>this.normalizeAxis(n,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(n=>t[n]):t.slice().reverse()}static padShape(t,s){let n=t.length;return t.map((i,a)=>i+s[a]+s[a+n])}static areEqual(t,s){return t.length!==s.length?!1:t.every((n,i)=>n===s[i])}},ys=class Pc{static adjustPoolAttributes(t,s,n,i,a,o){if(!t&&n.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let d=0;d=n.length?n.push(s[d+2]):n[d]=s[d+2];for(let d=0;d=n[d]||o[d+n.length]>=n[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,n,i,a,o,d){if(d){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{Bt(),Dt(),Ns=64,xr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(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}`)}},es=(e,t=1)=>{let s=xr(e,t);return typeof s=="string"?s:s[0]},_s=(e,t=1)=>{let s=xr(e,t);return typeof s=="string"?s:s[1]},Tt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:Se.computeStrides(s)})}),t},os=e=>e%4===0?4:e%2===0?2:1,Er=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,Ds=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,Gs=(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,Mt=(e,t,s,n)=>e.startsWith("uniforms.")&&s>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}]`:s>1?`${e}[${t}]`:e,Ss=(e,t,s,n,i)=>{let a=typeof s=="number",o=a?s:s.length,d=[...new Array(o).keys()],p=o<2?"u32":o<=4?`vec${o}`:`array`,h=xr(t,i),k=typeof h=="string"?h:h[1],S=typeof h=="string"?h:h[0],u={indices:p,value:k,storage:S,tensor:t},B=nt=>typeof nt=="string"?nt:`${nt}u`,R={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},U=a?"uniforms.":"",Z=`${U}${e}_shape`,te=`${U}${e}_strides`,Q="";for(let nt=0;nt ${u.indices} { var indices: ${u.indices}; var current = offset; ${Q} return indices; }`,me=nt=>(R.offsetToIndices=!0,o<2?nt:`o2i_${e}(${nt})`),Me=[];if(o>=2)for(let nt=o-1;nt>=0;nt--)Me.push(`${Mt(te,nt,o)} * (indices[${nt}])`);let $e=o<2?"":` fn i2o_${e}(indices: ${u.indices}) -> u32 { return ${Me.join("+")}; }`,Ae=nt=>(R.indicesToOffset=!0,o<2?nt:`i2o_${e}(${nt})`),Ge=(...nt)=>o===0?"0u":`${u.indices}(${nt.map(B).join(",")})`,lt=(nt,Pt)=>o<2?`${nt}`:`${Mt(nt,Pt,o)}`,Et=(nt,Pt,ps)=>o<2?`${nt}=${ps};`:`${Mt(nt,Pt,o)}=${ps};`,Kt={},Yt=(nt,Pt)=>{R.broadcastedIndicesToOffset=!0;let ps=`${Pt.name}broadcastedIndicesTo${e}Offset`;if(ps in Kt)return`${ps}(${nt})`;let zs=[];for(let yr=o-1;yr>=0;yr--){let Vs=Pt.indicesGet("outputIndices",yr+Pt.rank-o);zs.push(`${lt(te,yr)} * (${Vs} % ${lt(Z,yr)})`)}return Kt[ps]=`fn ${ps}(outputIndices: ${Pt.type.indices}) -> u32 { return ${zs.length>0?zs.join("+"):"0u"}; }`,`${ps}(${nt})`},kt=(nt,Pt)=>(()=>{if(u.storage===u.value)return`${e}[${nt}]=${Pt};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${nt}]=vec2(u32(${Pt}), select(0u, 0xFFFFFFFFu, ${Pt} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${nt}]=vec2(u32(${Pt}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${nt}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Pt}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Jt=nt=>(()=>{if(u.storage===u.value)return`${e}[${nt}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${nt}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${nt}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${nt}] & 0xFFu), bool(${e}[${nt}] & 0xFF00u), bool(${e}[${nt}] & 0xFF0000u), bool(${e}[${nt}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),$t=o<2?"":` fn get_${e}ByIndices(indices: ${u.indices}) -> ${k} { return ${Jt(`i2o_${e}(indices)`)}; }`,jt=o<2?"":(()=>{let nt=d.map(ps=>`d${ps}: u32`).join(", "),Pt=d.map(ps=>`d${ps}`).join(", ");return` fn get_${e}(${nt}) -> ${k} { return get_${e}ByIndices(${Ge(Pt)}); }`})(),bs=(...nt)=>{if(nt.length!==o)throw new Error(`indices length must be ${o}`);let Pt=nt.map(B).join(",");return o===0?Jt("0u"):o===1?Jt(Pt[0]):(R.get=!0,R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}(${Pt})`)},Ht=nt=>o<2?Jt(nt):(R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}ByIndices(${nt})`),Gt=o<2?"":` fn set_${e}ByIndices(indices: ${u.indices}, value: ${k}) { ${kt(`i2o_${e}(indices)`,"value")} }`,Cs=o<2?"":(()=>{let nt=d.map(ps=>`d${ps}: u32`).join(", "),Pt=d.map(ps=>`d${ps}`).join(", ");return` fn set_${e}(${nt}, value: ${k}) { set_${e}ByIndices(${Ge(Pt)}, value); }`})();return{impl:()=>{let nt=[],Pt=!1;return R.offsetToIndices&&(nt.push(fe),Pt=!0),R.indicesToOffset&&(nt.push($e),Pt=!0),R.broadcastedIndicesToOffset&&(Object.values(Kt).forEach(ps=>nt.push(ps)),Pt=!0),R.set&&(nt.push(Cs),Pt=!0),R.setByIndices&&(nt.push(Gt),Pt=!0),R.get&&(nt.push(jt),Pt=!0),R.getByIndices&&(nt.push($t),Pt=!0),!a&&Pt&&nt.unshift(`const ${Z} = ${u.indices}(${s.join(",")});`,`const ${te} = ${u.indices}(${Se.computeStrides(s).join(",")});`),nt.join(` `)},type:u,offsetToIndices:me,indicesToOffset:Ae,broadcastedIndicesToOffset:Yt,indices:Ge,indicesGet:lt,indicesSet:Et,set:(...nt)=>{if(nt.length!==o+1)throw new Error(`indices length must be ${o}`);let Pt=nt[o];if(typeof Pt!="string")throw new Error("value must be string");let ps=nt.slice(0,o).map(B).join(",");return o===0?kt("0u",Pt):o===1?kt(ps[0],Pt):(R.set=!0,R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}(${ps}, ${Pt})`)},setByOffset:kt,setByIndices:(nt,Pt)=>o<2?kt(nt,Pt):(R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}ByIndices(${nt}, ${Pt});`),get:bs,getByOffset:Jt,getByIndices:Ht,usage:n,name:e,strides:te,shape:Z,rank:o}},De=(e,t,s,n=1)=>Ss(e,t,s,"input",n),yt=(e,t,s,n=1)=>Ss(e,t,s,"output",n),sr=(e,t,s)=>Ss(e,t,s,"atomicOutput",1),Zr=(e,t,s,n=1)=>Ss(e,t,s,"internal",n),ri=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=Ns){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,o=i?`let global_idx = global_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${n}) fn main(${a}) { ${o} `}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 s=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":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,s=1){return this.uniforms.push({name:e,type:t,length:s}),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:s,length:n}of this.uniforms)if(n&&n>4)s==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let i=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${i}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},La=(e,t)=>new ri(e,t)}),za,zi,Bi,Ba,Ra,Ri,ar,Na,Ni,Nr=g(()=>{Bt(),Dt(),Ct(),Xt(),za=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},zi=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Bi=(e,t)=>Se.sortBasedOnPerm(e,zi(e.length,t)),Ba=(e,t,s,n)=>{let i=`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`;for(let a=0;a{let s=[],n=[];for(let i=0;i{let s=0;for(let n=0;n{let s=e.dataType,n=e.dims.length,i=zi(n,t),a=Bi(e.dims,i),o=e.dims,d=a,p=n<2||Ri(i,e.dims),h;if(p)return h=R=>{let U=De("input",s,o,4),Z=yt("output",s,d,4);return` ${R.registerUniform("output_size","u32").declareVariables(U,Z)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let R=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64/4)},programUniforms:[{type:12,data:Math.ceil(R/4)}]}},getShaderSource:h};let{newShape:k,newPerm:S}=Ra(e.dims,i),u=Se.areEqual(S,[2,3,1]),B=Se.areEqual(S,[3,1,2]);if(k.length===2||u||B){o=u?[k[0],k[1]*k[2]]:B?[k[0]*k[1],k[2]]:k,d=[o[1],o[0]];let R=16;return h=U=>{let Z=De("a",s,o.length),te=yt("output",s,d.length);return` ${U.registerUniform("output_size","u32").declareVariables(Z,te)} var tile : array, ${R}>; ${U.mainStart([R,R,1])} let stride = (uniforms.output_shape[1] - 1) / ${R} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${R}u + local_id.x; let input_row = workgroup_id_x * ${R}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${Z.getByIndices(`${Z.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${R}u + local_id.x; let output_row = workgroup_id_y * ${R}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${te.setByIndices(`${te.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let U=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d[1]/R),y:Math.ceil(d[0]/R)},programUniforms:[{type:12,data:U},...Tt(o,d)]}},getShaderSource:h}}return h=R=>{let U=De("a",s,o.length),Z=yt("output",s,d.length);return` ${R.registerUniform("output_size","u32").declareVariables(U,Z)} ${Ba(i,n,U,Z)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${Z.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${Z.setByOffset("global_idx",U.getByIndices("aIndices"))} }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let R=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...Tt(o,d)]}},getShaderSource:h}},Na=(e,t)=>{za(e.inputs),e.compute(ar(e.inputs[0],t.perm))},Ni=e=>it({perm:e.perm})}),ni,ja,Ua,Wa,Va,Ga,Ka,Ha,ji,qa,lr,en,Xa,Ic,Qa,Oc,Ya,Ui,Ja,Za,el,Fc=g(()=>{Bt(),Dt(),Xt(),ai(),Nr(),ni={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"},ja={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"},Ua={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Wa={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Va=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let a=0;ae[a]);return[s,i]},Ka=(e,t)=>{let s=e.length+t.length,n=[],i=0;for(let a=0;a{for(let s=0;s{let s=[];if(!Ha(e,t)){for(let n=0;ns.push(n))}return s},qa=(e,t,s,n,i,a,o)=>{let d=s[0].dims,p=Se.size(a),h=Se.size(o),k=De("_A",s[0].dataType,d),S=yt("output",i,a),u=64;p===1&&(u=256);let B=` var aBestValues : array; `,R=U=>` ${U.registerUniform("reduceSize","u32").declareVariables(k,S)} ${B} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${U.mainStart(u)} let outputIndex = global_idx / ${u}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${Ua[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${u}) { let candidate = f32(${k.getByOffset("offset + k")}); bestValue = ${ni[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${u}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${ja[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${S.setByOffset("outputIndex",`${n==="mean"?`${S.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${S.type.storage}(${Wa[n]})`}`)}; } }`;return{name:e,shaderCache:{hint:`${t};${u}`,inputDependencies:["type"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},lr=(e,t,s,n)=>{let i=e.inputs.length===1?s:Wi(e.inputs,s),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((B,R)=>R));let o=Se.normalizeAxes(a,e.inputs[0].dims.length),d=o,p=e.inputs[0],h=ji(d,e.inputs[0].dims.length);h.length>0&&(p=e.compute(ar(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],d=Va(d.length,p.dims.length));let[k,S]=Ga(p.dims,d),u=k;i.keepDims&&(u=Ka(k,o)),e.compute(qa(t,i.cacheKey,[p],n,e.inputs[0].dataType,u,S),{inputs:[p]})},en=(e,t)=>{lr(e,"ReduceMeanShared",t,"mean")},Xa=(e,t)=>{lr(e,"ReduceL1Shared",t,"l1")},Ic=(e,t)=>{lr(e,"ReduceL2Shared",t,"l2")},Qa=(e,t)=>{lr(e,"ReduceLogSumExpShared",t,"logSumExp")},Oc=(e,t)=>{lr(e,"ReduceMaxShared",t,"max")},Ya=(e,t)=>{lr(e,"ReduceMinShared",t,"min")},Ui=(e,t)=>{lr(e,"ReduceProdShared",t,"prod")},Ja=(e,t)=>{lr(e,"ReduceSumShared",t,"sum")},Za=(e,t)=>{lr(e,"ReduceSumSquareShared",t,"sumSquare")},el=(e,t)=>{lr(e,"ReduceLogSumShared",t,"logSum")}}),pr,ii,oi,Wi,hr,Vi,tl,sl,Gi,rl,nl,Ki,il,ol,Hi,mr,al,qi,ll,ul,Xi,dl,cl,Qi,pl,hl,ai=g(()=>{Bt(),Dt(),Ct(),Xt(),Fc(),pr=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.")},ii=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],oi=(e,t,s,n,i,a,o=!1,d=!1)=>{let p=[],h=s[0].dims,k=h.length,S=Se.normalizeAxes(i,k),u=!d&&S.length===0;h.forEach((U,Z)=>{u||S.indexOf(Z)>=0?o&&p.push(1):p.push(U)});let B=p.length,R=Se.size(p);return{name:e,shaderCache:t,getShaderSource:U=>{let Z=[],te=De("_A",s[0].dataType,k),Q=yt("output",a,B),fe=n(te,Q,S),me=fe[2];for(let Me=0,$e=0;Me=0?(o&&$e++,me=`for(var j${Me}: u32 = 0; j${Me} < ${h[Me]}; j${Me}++) { ${fe[2].includes("last_index")?`let last_index = j${Me};`:""} ${te.indicesSet("input_indices",Me,`j${Me}`)} ${me} }`):(Z.push(`${te.indicesSet("input_indices",Me,Q.indicesGet("output_indices",$e))};`),$e++);return` ${U.registerUniform("output_size","u32").declareVariables(te,Q)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${te.type.indices}; let output_indices = ${Q.offsetToIndices("global_idx")}; ${Z.join(` `)} ${fe[0]} // init ops for reduce max/min ${fe[1]} ${me} ${fe[3]} ${fe.length===4?Q.setByOffset("global_idx","value"):fe.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...Tt(h,p)]})}},Wi=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),it({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},hr=(e,t,s,n)=>{let i=e.inputs,a=i.length===1?s:Wi(i,s);e.compute(oi(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?ii:n,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Vi=(e,t)=>{pr(e.inputs),hr(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},tl=(e,t)=>{pr(e.inputs),hr(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},sl=(e,t)=>{pr(e.inputs),hr(e,"ReduceL2",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Gi=(e,t)=>{pr(e.inputs),hr(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},rl=(e,t)=>{pr(e.inputs),hr(e,"ReduceMax",t,(s,n,i)=>{let a=[];for(let o=0;o=0||i.length===0)&&a.push(s.indicesSet("input_indices",o,0));return[`${a.join(` `)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},nl=(e,t)=>{pr(e.inputs),hr(e,"ReduceMean",t,(s,n,i)=>{let a=1;for(let o=0;o=0||i.length===0)&&(a*=e.inputs[0].dims[o]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Ki=(e,t)=>{pr(e.inputs),hr(e,"ReduceMin",t,(s,n,i)=>{let a=[];for(let o=0;o=0||i.length===0)&&a.push(`input_indices[${o}] = 0;`);return[`${a.join(` `)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},il=(e,t)=>{pr(e.inputs),hr(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},ol=(e,t)=>{pr(e.inputs),hr(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Hi=(e,t)=>{pr(e.inputs),hr(e,"ReduceSumSquare",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},mr=(e,t,s)=>{if(t.length===0)return s;let n=1,i=1;for(let a=0;a1024},al=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?nl(e,t):en(e,t)},qi=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?tl(e,t):Xa(e,t)},ll=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?sl(e,t):Ic(e,t)},ul=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gi(e,t):Qa(e,t)},Xi=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?rl(e,t):Oc(e,t)},dl=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ki(e,t):Ya(e,t)},cl=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?il(e,t):Ui(e,t)},Qi=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ol(e,t):Ja(e,t)},pl=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hi(e,t):Za(e,t)},hl=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vi(e,t):el(e,t)}}),Yi,ml,Ji,Zi,Dc=g(()=>{Bt(),Ct(),ai(),Yi=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.")},ml=(e,t)=>{Yi(e.inputs);let s=(n,i,a)=>{let o=[];for(let d=0;d=0||a.length===0)&&o.push(`input_indices[${d}] = 0;`);return[`${o.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(oi("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Ji=(e,t)=>{Yi(e.inputs);let s=(n,i,a)=>{let o=[];for(let d=0;d=0||a.length===0)&&o.push(`input_indices[${d}] = 0;`);return[`${o.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(oi("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Zi=e=>it(e)}),eo,li,fl,to,_l,Rn,so,gl,ro=g(()=>{Bt(),Dt(),Jr(),Xt(),eo=(e,t)=>{let s=e[0],n=e[1],i=e[2],a=e[3],o=e[4],d=e[5];if(o&&d)throw new Error("Attention cannot have both past and attention_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=s.dims[0],h=s.dims[1],k=s.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==k)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let S=i.dims[0]/3,u=S,B=u;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let fe of t.qkvHiddenSizes)if(fe%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");S=t.qkvHiddenSizes[0],u=t.qkvHiddenSizes[1],B=t.qkvHiddenSizes[2]}let R=h;if(S!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==S+u+B)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let U=0;if(o){if(u!==B)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==u/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(U=o.dims[3])}let Z=R+U,te=-1,Q=0;if(a)throw new Error("Mask not supported");if(o)throw new Error("past is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(d.dims[0]!==p||d.dims[1]!==t.numHeads||d.dims[2]!==h||d.dims[3]!==Z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:U,kvSequenceLength:R,totalSequenceLength:Z,maxSequenceLength:te,inputHiddenSize:k,hiddenSize:S,vHiddenSize:B,headSize:Math.floor(S/t.numHeads),vHeadSize:Math.floor(B/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:Q,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},li=(e,t,s)=>t&&e?` let total_sequence_length_input = u32(${t.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; var past_sequence_length: u32 = 0; if (is_first_prompt == false) { past_sequence_length = total_sequence_length - sequence_length; } `:` ${s?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; `,fl=(e,t,s,n,i,a,o,d)=>{let p=os(o?1:a),h=64,k=a/p;k{let Q=yt("x",e.dataType,e.dims,p),fe=[Q],me=o?De("seq_lens",o.dataType,o.dims):void 0;me&&fe.push(me);let Me=d?De("total_sequence_length_input",d.dataType,d.dims):void 0;Me&&fe.push(Me);let $e=_s(e.dataType),Ae=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${te.registerUniforms(Ae).declareVariables(...fe)} ${te.mainStart([h,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; ${li(me,Me,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${o?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; var thread_max_vector = ${R}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${R}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(p){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: ${p}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${h}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${R}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${R}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(p){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: ${p}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${h}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${Q.type.value}(${$e}(1.0) / ${$e}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${R}(x[offset + i]); x[offset + i] = ${Q.type.value}(exp(f32input - max_value) / sum); } } ${o?` for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${Q.type.value}(${$e}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${B};${p}`,inputDependencies:U},getShaderSource:Z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/h),y:i,z:t*s},programUniforms:u})}},to=(e,t,s,n,i,a,o,d,p)=>{let h=o+a.kvSequenceLength,k=[a.batchSize,a.numHeads,a.sequenceLength,h],S=e>1&&n,u=a.kvNumHeads?a.kvNumHeads:a.numHeads,B=S?[a.batchSize,u,h,a.headSize]:void 0,R=a.nReps?a.nReps:1,U=a.scale===0?1/Math.sqrt(a.headSize):a.scale,Z=os(a.headSize),te=a.headSize/Z,Q=12,fe={x:Math.ceil(h/Q),y:Math.ceil(a.sequenceLength/Q),z:a.batchSize*a.numHeads},me=[{type:12,data:a.sequenceLength},{type:12,data:te},{type:12,data:h},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:U},{type:12,data:o},{type:12,data:a.kvSequenceLength},{type:12,data:R}],Me=S&&n&&Se.size(n.dims)>0,$e=["type","type"];Me&&$e.push("type"),i&&$e.push("type"),d&&$e.push("type"),p&&$e.push("type");let Ae=[{dims:k,dataType:t.dataType,gpuDataType:0}];S&&Ae.push({dims:B,dataType:t.dataType,gpuDataType:0});let Ge=lt=>{let Et=De("q",t.dataType,t.dims,Z),Kt=De("key",s.dataType,s.dims,Z),Yt=[Et,Kt];if(Me){let Gt=De("past_key",n.dataType,n.dims,Z);Yt.push(Gt)}i&&Yt.push(De("attention_bias",i.dataType,i.dims));let kt=d?De("seq_lens",d.dataType,d.dims):void 0;kt&&Yt.push(kt);let Jt=p?De("total_sequence_length_input",p.dataType,p.dims):void 0;Jt&&Yt.push(Jt);let $t=yt("output",t.dataType,k),jt=[$t];S&&jt.push(yt("present_key",t.dataType,B,Z));let bs=_s(1,Z),Ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${Q}u; var tileQ: array<${Et.type.storage}, ${Q*Q}>; var tileK: array<${Et.type.storage}, ${Q*Q}>; ${lt.registerUniforms(Ht).declareVariables(...Yt,...jt)} ${lt.mainStart([Q,Q,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${R===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${R===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; ${li(kt,Jt,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${Me&&S?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${S?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} var value = ${bs}(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; ${Me&&S?` if (n + local_id.y < past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; }`:` if (n + local_id.y < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; }`} ${S?`if (n + local_id.y < present_sequence_length) { present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${bs}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { let headOffset = workgroup_id.z * uniforms.M * uniforms.N; let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(Z){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${Z}`)}})()}; output[outputIdx] = ${$t.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${Z};${i!==void 0};${n!==void 0};${e}`,inputDependencies:$e},getRunData:()=>({outputs:Ae,dispatchGroup:fe,programUniforms:me}),getShaderSource:Ge}},_l=(e,t,s,n,i,a,o=void 0,d=void 0)=>{let p=a+i.kvSequenceLength,h=i.nReps?i.nReps:1,k=i.vHiddenSize*h,S=e>1&&n,u=i.kvNumHeads?i.kvNumHeads:i.numHeads,B=S?[i.batchSize,u,p,i.headSize]:void 0,R=[i.batchSize,i.sequenceLength,k],U=12,Z={x:Math.ceil(i.vHeadSize/U),y:Math.ceil(i.sequenceLength/U),z:i.batchSize*i.numHeads},te=[{type:12,data:i.sequenceLength},{type:12,data:p},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:k},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:h}],Q=S&&n&&Se.size(n.dims)>0,fe=["type","type"];Q&&fe.push("type"),o&&fe.push("type"),d&&fe.push("type");let me=[{dims:R,dataType:t.dataType,gpuDataType:0}];S&&me.push({dims:B,dataType:t.dataType,gpuDataType:0});let Me=$e=>{let Ae=De("probs",t.dataType,t.dims),Ge=De("v",s.dataType,s.dims),lt=[Ae,Ge];Q&<.push(De("past_value",n.dataType,n.dims));let Et=o?De("seq_lens",o.dataType,o.dims):void 0;o&<.push(Et);let Kt=d?De("total_sequence_length_input",d.dataType,d.dims):void 0;d&<.push(Kt);let Yt=[yt("output",t.dataType,R)];S&&Yt.push(yt("present_value",t.dataType,B));let kt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${U}u; var tileQ: array<${Ae.type.value}, ${U*U}>; var tileV: array<${Ae.type.value}, ${U*U}>; ${$e.registerUniforms(kt).declareVariables(...lt,...Yt)} ${$e.mainStart([U,U,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${h===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; ${li(Et,Kt,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${Q&&S?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${S?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} var value = ${Ae.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; ${Q&&S?` if (w + local_id.y < past_sequence_length) { tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; } `:` if (w + local_id.y < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; }`} ${S?` if (w + local_id.y < present_sequence_length) { present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + headIdx * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:fe},getRunData:()=>({outputs:me,dispatchGroup:Z,programUniforms:te}),getShaderSource:Me}},Rn=(e,t,s,n,i,a,o,d,p,h,k=void 0,S=void 0)=>{let u=Math.min(e.outputCount,1+(o?1:0)+(d?1:0)),B=u>1?h.pastSequenceLength:0,R=B+h.kvSequenceLength,U=p&&Se.size(p.dims)>0?p:void 0,Z=[t,s];u>1&&o&&Se.size(o.dims)>0&&Z.push(o),U&&Z.push(U),k&&Z.push(k),S&&Z.push(S);let te=e.compute(to(u,t,s,o,U,h,B,k,S),{inputs:Z,outputs:u>1?[-1,1]:[-1]})[0];e.compute(fl(te,h.batchSize,h.numHeads,B,h.sequenceLength,R,k,S),{inputs:k&&S?[te,k,S]:[te],outputs:[]});let Q=[te,n];u>1&&d&&Se.size(d.dims)>0&&Q.push(d),k&&Q.push(k),S&&Q.push(S),e.compute(_l(u,te,n,d,h,B,k,S),{inputs:Q,outputs:u>1?[0,2]:[0]})},so=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,o=12,d={x:Math.ceil(t.headSize/o),y:Math.ceil(t.sequenceLength/o),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:i},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],k=S=>{let u=yt("output_q",p[0].dataType,s),B=yt("output_k",p[0].dataType,s),R=yt("output_v",p[0].dataType,s),U=De("input",p[0].dataType,p[0].dims),Z=De("weight",p[1].dataType,p[1].dims),te=De("bias",p[2].dataType,p[2].dims),Q=U.type.storage,fe=[{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 = ${o}u; var tileInput: array<${Q}, ${o*o}>; var tileWeightQ: array<${Q}, ${o*o}>; var tileWeightK: array<${Q}, ${o*o}>; var tileWeightV: array<${Q}, ${o*o}>; ${S.registerUniforms(fe).declareVariables(U,Z,te,u,B,R)} ${S.mainStart([o,o,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 = ${Q}(0); var valueK = ${Q}(0); var valueV = ${Q}(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:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:d,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},gl=(e,t)=>{let s=eo(e.inputs,t),[n,i,a]=so(e,s);return Rn(e,n,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),no,wl,yl,io,Lc=g(()=>{Qe(),Bt(),Dt(),Ct(),Xt(),no=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,i,a)=>{let o=i.length;if(o!==n.length)throw new Error(`${a}: num dimensions != ${o}`);i.forEach((d,p)=>{if(d!==n[p])throw new Error(`${a}: dim[${p}] 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);s(e[1].dims,n,"Invalid input scale"),s(e[2].dims,n,"Invalid input B"),s(e[3].dims,n,"Invalid input mean"),s(e[4].dims,n,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},wl=(e,t)=>{let{epsilon:s,spatial:n,format:i}=t,a=e[0].dims,o=n?os(a[a.length-1]):1,d=i==="NHWC"&&a.length>1?o:1,p=Se.size(a)/o,h=n,k=h?a.length:a,S=De("x",e[0].dataType,e[0].dims,o),u=De("scale",e[1].dataType,e[1].dims,d),B=De("bias",e[2].dataType,e[2].dims,d),R=De("inputMean",e[3].dataType,e[3].dims,d),U=De("inputVar",e[4].dataType,e[4].dims,d),Z=yt("y",e[0].dataType,k,o),te=()=>{let fe="";if(n)fe=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")fe=` ${Z.indicesSet("outputIndices","0","0")} let cOffset = ${Z.indicesToOffset("outputIndices")};`;else{fe=`var cIndices = ${u.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let me=1;me` const epsilon = ${s}; ${fe.registerUniform("outputSize","u32").declareVariables(S,u,B,R,U,Z)} ${fe.mainStart()} ${fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${Z.offsetToIndices(`global_idx * ${o}`)}; ${te()} let scale = ${u.getByOffset("cOffset")}; let bias = ${B.getByOffset("cOffset")}; let inputMean = ${R.getByOffset("cOffset")}; let inputVar = ${U.getByOffset("cOffset")}; let x = ${S.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${Z.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${o}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:Q,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...Tt(a)]:[{type:12,data:p}]})}},yl=e=>it(e),io=(e,t)=>{let{inputs:s,outputCount:n}=e,i=yl({...t,outputCount:n});if(T.webgpu.validateInputContent&&no(s,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(wl(s,i))}}),Ml,oo,bl,zc=g(()=>{Dt(),Xt(),Ml=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")},oo=e=>{let t=e[0].dims,s=e[0].dims[2],n=Se.size(t)/4,i=e[0].dataType,a=De("input",i,t,4),o=De("bias",i,[s],4),d=De("residual",i,t,4),p=yt("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` const channels = ${s}u / 4; ${h.declareVariables(a,o,d,p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${a.getByOffset("global_idx")} + ${o.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; ${p.setByOffset("global_idx","value")} }`}},bl=e=>{Ml(e.inputs),e.compute(oo(e.inputs))}}),ao,ds,vl,lo,Tl,xl,uo,El,Pl,co,Cl,kl,Sl,$l,po,Al,Nn,ho,ui,Il,mo,Ol,Fl,fo,Dl,Ll,_o,zl,Bl,go,Rl,Nl,wo,jl,Ul,yo,Wl,di,Mo,Vl,Gl,Kl,bo,Hl,ql,vo=g(()=>{Bt(),Dt(),Ct(),Xt(),ao=(e,t,s,n,i,a,o)=>{let d=Math.ceil(t/4),p="";typeof i=="string"?p=`${i}(a)`:p=i("a");let h=De("inputData",s,[d],4),k=yt("outputData",n,[d],4),S=[{name:"vec_size",type:"u32"}];return o&&S.push(...o),` ${e.registerUniforms(S).declareVariables(h,k)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${k.setByOffset("global_idx",p)} }`},ds=(e,t,s,n,i,a=e.dataType,o,d)=>{let p=[{type:12,data:Math.ceil(Se.size(e.dims)/4)}];return o&&p.push(...o),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:h=>ao(h,Se.size(e.dims),e.dataType,a,s,n,d),getRunData:h=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Se.size(h[0].dims)/64/4)},programUniforms:p})}},vl=e=>{e.compute(ds(e.inputs[0],"Abs","abs"))},lo=e=>{e.compute(ds(e.inputs[0],"Acos","acos"))},Tl=e=>{e.compute(ds(e.inputs[0],"Acosh","acosh"))},xl=e=>{e.compute(ds(e.inputs[0],"Asin","asin"))},uo=e=>{e.compute(ds(e.inputs[0],"Asinh","asinh"))},El=e=>{e.compute(ds(e.inputs[0],"Atan","atan"))},Pl=e=>{e.compute(ds(e.inputs[0],"Atanh","atanh"))},co=e=>it(e),Cl=(e,t)=>{let s;switch(t.to){case 10:s="vec4";break;case 1:s="vec4";break;case 12:s="vec4";break;case 6:s="vec4";break;case 9:s="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ds(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},kl=e=>{let t,s,n=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,s=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,s=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return it({min:t,max:s})},Sl=(e,t)=>{let s=t||kl(e.inputs),n=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},$l=e=>{e.compute(ds(e.inputs[0],"Ceil","ceil"))},po=e=>{e.compute(ds(e.inputs[0],"Cos","cos"))},Al=e=>{e.compute(ds(e.inputs[0],"Cosh","cosh"))},Nn=e=>it(e),ho=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` const elu_alpha_ = ${s}(${t.alpha}); fn elu_f32(a: ${s}) -> ${s} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,t.cacheKey))},ui=(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)); }`,Il=e=>{let t=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,ui(t)))},mo=e=>{e.compute(ds(e.inputs[0],"Exp","exp"))},Ol=e=>{e.compute(ds(e.inputs[0],"Floor","floor"))},Fl=e=>{let t=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,ui(t)))},fo=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${t.alpha});`,t.cacheKey))},Dl=e=>{e.compute(ds(e.inputs[0],"Not",t=>`!${t}`))},Ll=e=>{e.compute(ds(e.inputs[0],"Neg",t=>`-${t}`))},_o=e=>{e.compute(ds(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},zl=e=>{let t=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},Bl=e=>{e.compute(ds(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},go=e=>it(e),Rl=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"HardSigmoid",n=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${n} + vec4<${s}>(${t.beta})))`,void 0,t.cacheKey))},Nl=e=>{e.compute(ds(e.inputs[0],"Sin","sin"))},wo=e=>{e.compute(ds(e.inputs[0],"Sinh","sinh"))},jl=e=>{e.compute(ds(e.inputs[0],"Sqrt","sqrt"))},Ul=e=>{e.compute(ds(e.inputs[0],"Tan","tan"))},yo=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Wl=e=>{e.compute(ds(e.inputs[0],"Tanh",yo))},di=(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 ${yo("v")}; } `,Mo=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Vl=e=>{let t=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"FastGelu",Mo,di(t),void 0,e.inputs[0].dataType))},Gl=(e,t)=>{let s=_s(e.inputs[0].dataType);return e.compute(ds(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${s}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`,t.cacheKey)),0},Kl=e=>{e.compute(ds(e.inputs[0],"Log","log"))},bo=(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; } `,Hl=e=>`quick_gelu_impl(${e})`,ql=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"QuickGelu",Hl,bo(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Xl,To,Ql,Bc=g(()=>{Dt(),Xt(),vo(),Xl=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")},To=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=De("input",e[0].dataType,e[0].dims,4),n=De("bias",e[0].dataType,[e[0].dims[2]],4),i=yt("output",e[0].dataType,t,4),a=Se.size(t)/4,o=es(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:d=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${d.declareVariables(s,n,i)} ${ui(o)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(a)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${i.setByOffset("global_idx","valueLeft * geluRight")} }`}},Ql=e=>{Xl(e.inputs),e.compute(To(e.inputs))}}),Yl,Jl,ur,Zl,eu,xo,tu,su,Eo,ru,nu,Po,iu,Rc=g(()=>{Bt(),Dt(),Xt(),Yl=(e,t,s,n,i,a,o,d,p,h,k,S)=>{let u,B;typeof d=="string"?u=B=(Q,fe)=>`${d}((${Q}),(${fe}))`:typeof d=="function"?u=B=d:(u=d.scalar,B=d.vector);let R=yt("outputData",k,n.length,4),U=De("aData",p,t.length,4),Z=De("bData",h,s.length,4),te;if(i)if(a){let Q=Se.size(t)===1,fe=Se.size(s)===1,me=t.length>0&&t[t.length-1]%4===0,Me=s.length>0&&s[s.length-1]%4===0;Q||fe?te=R.setByOffset("global_idx",B(Q?`${U.type.value}(${U.getByOffset("0")}.x)`:U.getByOffset("global_idx"),fe?`${Z.type.value}(${Z.getByOffset("0")}.x)`:Z.getByOffset("global_idx"))):te=` let outputIndices = ${R.offsetToIndices("global_idx * 4u")}; let offsetA = ${U.broadcastedIndicesToOffset("outputIndices",R)}; let offsetB = ${Z.broadcastedIndicesToOffset("outputIndices",R)}; ${R.setByOffset("global_idx",B(o||me?U.getByOffset("offsetA / 4u"):`${U.type.value}(${U.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||Me?Z.getByOffset("offsetB / 4u"):`${Z.type.value}(${Z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else te=R.setByOffset("global_idx",B(U.getByOffset("global_idx"),Z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let Q=(fe,me,Me="")=>{let $e=`aData[indexA${me}][componentA${me}]`,Ae=`bData[indexB${me}][componentB${me}]`;return` let outputIndices${me} = ${R.offsetToIndices(`global_idx * 4u + ${me}u`)}; let offsetA${me} = ${U.broadcastedIndicesToOffset(`outputIndices${me}`,R)}; let offsetB${me} = ${Z.broadcastedIndicesToOffset(`outputIndices${me}`,R)}; let indexA${me} = offsetA${me} / 4u; let indexB${me} = offsetB${me} / 4u; let componentA${me} = offsetA${me} % 4u; let componentB${me} = offsetB${me} % 4u; ${fe}[${me}] = ${Me}(${u($e,Ae)}); `};k===9?te=` var data = vec4(0); ${Q("data",0,"u32")} ${Q("data",1,"u32")} ${Q("data",2,"u32")} ${Q("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:te=` ${Q("outputData[global_idx]",0)} ${Q("outputData[global_idx]",1)} ${Q("outputData[global_idx]",2)} ${Q("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(U,Z,R)} ${S??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${te} }`},Jl=(e,t,s,n,i,a,o=s.dataType)=>{let d=s.dims.map(U=>Number(U)??1),p=n.dims.map(U=>Number(U)??1),h=!Se.areEqual(d,p),k=d,S=Se.size(d),u=!1,B=!1,R=[h];if(h){let U=ns.calcShape(d,p,!1);if(!U)throw new Error("Can't perform binary op on the given tensors");k=U.slice(),S=Se.size(k);let Z=Se.size(d)===1,te=Se.size(p)===1,Q=d.length>0&&d[d.length-1]%4===0,fe=p.length>0&&p[p.length-1]%4===0;R.push(Z),R.push(te),R.push(Q),R.push(fe);let me=1;for(let Me=1;MeU.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:U=>Yl(U,d,p,k,u,h,B,i,s.dataType,n.dataType,o,a),getRunData:()=>({outputs:[{dims:k,dataType:o}],dispatchGroup:{x:Math.ceil(S/64/4)},programUniforms:[{type:12,data:Math.ceil(Se.size(k)/4)},...Tt(d,p,k)]})}},ur=(e,t,s,n,i,a)=>{e.compute(Jl(t,i??"",e.inputs[0],e.inputs[1],s,n,a))},Zl=e=>{ur(e,"Add",(t,s)=>`${t}+${s}`)},eu=e=>{ur(e,"Div",(t,s)=>`${t}/${s}`)},xo=e=>{ur(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},tu=e=>{ur(e,"Mul",(t,s)=>`${t}*${s}`)},su=e=>{let t=De("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ur(e,"Pow",{scalar:(s,n)=>`pow_custom(${s},${n})`,vector:(s,n)=>`pow_vector_custom(${s},${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)); } `)},Eo=e=>{ur(e,"Sub",(t,s)=>`${t}-${s}`)},ru=e=>{ur(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},nu=e=>{ur(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},Po=e=>{ur(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},iu=e=>{ur(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),Co,ou,au,ci,lu,uu,du=g(()=>{Bt(),Dt(),Ct(),Xt(),Co=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],i=n.dataType,a=n.dims.length;e.forEach((o,d)=>{if(d!==s){if(o.dataType!==i)throw new Error("input tensors should be one type");if(o.dims.length!==a)throw new Error("input tensors should have the same shape");o.dims.forEach((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},ou=(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; }`,au=(e,t)=>{let s=e.length,n=[];for(let i=0;i{let i=Se.size(s),a=new Array(e.length),o=new Array(e.length),d=0,p=[],h=[],k=[{type:12,data:i}];for(let U=0;U`uniforms.sizeInConcatAxis${U}`).join(","),R=U=>` ${(()=>{U.registerUniform("outputSize","u32");for(let Z=0;Z(${B}); ${u} -= sizeInConcatAxis[inputIndex - 1u]; } ${au(o,S)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:k}),getShaderSource:R}},lu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=Se.normalizeAxis(t.axis,n.length);Co(s,i);let a=n.slice();a[i]=s.reduce((d,p)=>d+(p.dims.length>i?p.dims[i]:0),0);let o=s.filter(d=>Se.size(d.dims)>0);e.compute(ci(o,i,a,s[0].dataType),{inputs:o})},uu=e=>it({axis:e.axis})}),jr,tn,Ur,ko,sn=g(()=>{Bt(),Dt(),jr=(e,t,s="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}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(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}`)}},tn=(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})},Ur=(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"})},ko=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[s,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:s,beta:n}}else if(t==="Clip"){let[s,n]=(e==null?void 0:e.activation_params)||[Xs,Js];return{activation:t,clipMax:n,clipMin:s}}else if(t==="LeakyRelu"){let[s]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:s}}return{activation:t}}}),Ks,So,$o=g(()=>{Ks=(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.`)}},So=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),cu,Nc=g(()=>{cu=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)); } `}),vn,Ao,Io=g(()=>{Bt(),Dt(),Xt(),sn(),vn=(e,t,s,n,i)=>{let a=n-s;return` ${Array.from({length:s}).map((o,d)=>` if (${Mt(t.shape,d,t.rank)} != 1) { ${t.indicesSet(e,d,Mt(i,d+a,n))} } else { ${t.indicesSet(e,d,0)} }`).join("")} `},Ao=(e,t,s,n,i=!1,a)=>{let o=e[0].dims,d=e[1].dims,p=o[o.length-2],h=d[d.length-1],k=o[o.length-1],S=os(h),u=os(k),B=os(p),R=Se.size(s)/S/B,U=e.length>2,Z=n?n.slice(0,-2):s.slice(0,-2),te=[Se.size(Z),p,h],Q=[{type:12,data:R},{type:12,data:p},{type:12,data:h},{type:12,data:k}];tn(t,Q),Q.push(...Tt(Z,o,d)),U&&Q.push(...Tt(e[2].dims)),Q.push(...Tt(te));let fe=me=>{let Me=Zr("batch_dims",e[0].dataType,Z.length),$e=De("a",e[0].dataType,o.length,u),Ae=De("b",e[1].dataType,d.length,S),Ge=yt("output",e[0].dataType,te.length,S),lt=es(Ge.type.tensor),Et=jr(t,Ge.type.value,lt),Kt=[$e,Ae],Yt="";if(U){let $t=i?S:1;Kt.push(De("bias",e[2].dataType,e[2].dims.length,$t)),Yt=`${i?`value += bias[col / ${$t}];`:`value += ${Ge.type.value}(bias[row + i]);`}`}let kt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ur(t,kt);let Jt=()=>{let $t=`var a_data: ${$e.type.value};`;for(let jt=0;jt; for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { ${Jt()} } for (var i = 0u; i < ${B}u; i++) { var value = values[i]; ${Yt} ${Et} let cur_indices = ${Ge.type.indices}(batch, row + i, col); let offset = ${Ge.indicesToOffset("cur_indices")}; ${Ge.setByOffset(`offset / ${S}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${S};${u};${B};${i}`,inputDependencies:U?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:Q}),getShaderSource:fe}}}),Oo,pu,Fo,pi,hu,Do,Lo,hi,zo=g(()=>{Bt(),Dt(),Xt(),sn(),Io(),$o(),Oo=(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":""}); `,pu=(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];"} }`,Fo=(e,t,s="f32",n,i=!1,a=32,o=!1,d=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=i?p:a,S=i?a:p,u=k/t[0],B=a/t[1];if(!((i&&u===4&&e[1]===4||!i&&(u===3||u===4))&&k%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${u} must be 3 or 4. tileAWidth ${k} 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, ${k/u}>, ${S}>; var mm_Bsub: array, ${h/e[0]}>, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${u}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${o?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${p}; let num_tiles = ${o?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${o?`i32(globalId.z) * ${d}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${B}; 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; ${Oo(i,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${pu(i,u)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},pi=(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":""}); `,hu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Do=(e,t,s="f32",n,i=!1,a=32,o=!1,d=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],S=i?h:a,u=i?a:h;if(!(u%t[1]===0&&S%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${S} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let B=u/t[1],R=S/t[0],U=a/t[1],Z=p?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${h}; let globalColStart = i32(workgroupId.x) * ${k}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${S}; inputCol = inputCol + ${t[0]}) { ${pi(i,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${k}; 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<${s}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${h}; let tileRowA = i32(localId.y) * ${B}; let tileColA = i32(localId.x) * ${R}; let tileRowB = i32(localId.y) * ${U}; // 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 < ${B}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${R}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${pi(i,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${U}; 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<${s}, 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) { ${hu(i)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${u}>; var mm_Bsub : array, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${o?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${o?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${o?`i32(globalId.z) * ${d}`:"0"}; var acc : array, rowPerThread>; ${Z} } `},Lo=(e,t,s,n,i=!1)=>{let[a,o,d,p]=n,h=es(n[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Ks(e,h)} { var value = ${Ks(e,h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${o.type.indices}; ${vn("aIndices",o,o.rank-2,a.rank,"batchIndices")} ${o.indicesSet("aIndices",o.rank-2,"u32(row)")} ${o.indicesSet("aIndices",o.rank-1,"u32(colIn)")} value = ${o.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Ks(e,h)} { var value = ${Ks(e,h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${d.type.indices}; ${vn("bIndices",d,d.rank-2,a.rank,"batchIndices")} ${d.indicesSet("bIndices",d.rank-2,"u32(row)")} ${d.indicesSet("bIndices",d.rank-1,"u32(colIn)")} value = ${d.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ks(e,h)}) { 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 + ${i?"bias[colIn]":`${Ks(e,h)}(bias[row])`};`:""} ${s} ${p.setByIndices("vec3(coords)","value")} } } `},hi=(e,t,s,n,i=!1,a)=>{let o=e[0].dims,d=e[1].dims,p=o.slice(0,-2),h=d.slice(0,-2),k=n?n.slice(0,-2):s.slice(0,-2),S=Se.size(k),u=o[o.length-2],B=o[o.length-1],R=d[d.length-1],U=B%4===0&&R%4===0,Z=u<=8?[4,1,1]:[4,4,1],te=[8,8,1],Q=[Math.ceil(R/te[0]/Z[0]),Math.ceil(u/te[1]/Z[1]),Math.ceil(S/te[2]/Z[2])],fe=U?4:1,me=[...p,u,B/fe],Me=me.length,$e=[...h,B,R/fe],Ae=$e.length,Ge=[S,u,R/fe],lt=[{type:6,data:u},{type:6,data:R},{type:6,data:B}];tn(t,lt),lt.push(...Tt(k,me,$e));let Et=["rank","rank"],Kt=e.length>2;Kt&&(lt.push(...Tt(e[2].dims)),Et.push("rank")),lt.push(...Tt(Ge));let Yt=kt=>{let Jt=k.length,$t=Zr("batchDims",e[0].dataType,Jt,1),jt=es(e[0].dataType),bs=De("a",e[0].dataType,Me,fe),Ht=De("b",e[1].dataType,Ae,fe),Gt=yt("result",e[0].dataType,Ge.length,fe),Cs=[bs,Ht];if(Kt){let yr=i?fe:1;Cs.push(De("bias",e[2].dataType,e[2].dims.length,yr))}let nt=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ur(t,nt);let Pt=es(Gt.type.tensor),ps=jr(t,Gt.type.value,Pt),zs=Lo(fe,Kt,ps,[$t,bs,Ht,Gt],i);return` ${kt.registerUniforms(nt).registerInternalVariables($t).declareVariables(...Cs,Gt)} ${zs} ${U?Fo(Z,te,jt,$t):Do(Z,te,jt,$t)} `};return{name:"MatMul",shaderCache:{hint:`${Z};${t.activation};${U};${i}`,inputDependencies:Et},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Q[0],y:Q[1],z:Q[2]},programUniforms:lt}),getShaderSource:Yt}}}),Bo,mu,jc=g(()=>{Bt(),tr(),Xt(),sn(),$o(),Nc(),zo(),Bo=(e,t,s,n,i=!1,a,o=4,d=4,p=4,h="f32")=>{let k=lt=>{switch(lt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${lt} is not supported.`)}},S=lt=>{switch(lt){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 ${lt} is not supported.`)}},u=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,B=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,R=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",U=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Z=e?"row":"col",te=e?"col":"row",Q=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${Z} / outWidth; let outCol = ${Z} % outWidth; let WRow = ${te} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${te} / 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 = ${te} % inChannels; var resData = ${Ks(o,h)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${R} && xCol >= 0 && xCol < ${U}) { ${u} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${k(o)} } return resData;`,fe=e?t&&n?` let col = colIn * ${o}; ${Q}`:` let col = colIn * ${o}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${Q} } return ${Ks(o,h)}(0.0);`:n&&s?` let col = colIn * ${o}; ${Q}`:` let col = colIn * ${o}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${Q} } return ${Ks(o,h)}(0.0);`,me=`${S(d)}`,Me=Ks(p,h),$e=Ks(e?o:d,h),Ae=Ks(e?d:o,h),Ge=jr(a,Me,h);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${$e} { ${e?fe:me} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ae} { ${e?me:fe} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Me}) { let col = colIn * ${p}; 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])"}; ${B} ${So(i)} ${Ge} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},mu=(e,t,s,n,i,a,o,d,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],S=s[0],u=h?s[2]:s[3],B=h?s[1]:s[2],R=h?s[3]:s[1],U=h&&(k%4===0||k%3===0)&&R%4===0,Z=h?R:u*B,te=h?u*B:R,Q=[8,8,1],fe=n<=8?[4,1,1]:[4,4,1],me=[Math.ceil(Z/Q[0]/fe[0]),Math.ceil(te/Q[1]/fe[1]),Math.ceil(S/Q[2]/fe[2])];is("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${me}`);let Me=U?h&&k%4!==0?3:4:1,$e=Q[1]*fe[1],Ae=Q[0]*fe[0],Ge=Math.max(Q[0]*Me,Q[1]),lt=n%$e===0,Et=i%Ae===0,Kt=a%Ge===0,Yt=U?[Me,4,4]:[1,1,1],kt=[{type:6,data:n},{type:6,data:i},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];tn(t,kt),kt.push(...Tt(e[0].dims,e[1].dims));let Jt=["rank","rank"];o&&(kt.push(...Tt(e[2].dims)),Jt.push("rank")),kt.push(...Tt(s));let $t=jt=>{let bs=[{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}];Ur(t,bs);let Ht=U?4:1,Gt=es(e[0].dataType),Cs=` fn setOutputAtIndex(flatIndex : i32, value : ${U?`vec4<${Gt}>`:Gt}) { result[flatIndex] = ${U?`vec4<${Gt}>`:Gt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${U?`vec4<${Gt}>`:Gt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${U?"/ 4":""}, value); }`,nt=De("x",e[0].dataType,e[0].dims.length,Me===3?1:Me),Pt=De("w",e[1].dataType,e[1].dims.length,Ht),ps=[nt,Pt],zs=yt("result",e[0].dataType,s.length,Ht);if(o){let yr=De("bias",e[2].dataType,e[2].dims.length,Ht);ps.push(yr),Cs+=` fn getBiasByOutputCoords(coords : vec4) -> ${U?`vec4<${Gt}>`:Gt} { return bias[coords.${h?"w":"y"}${U?"/ 4":""}]; }`}return` ${cu("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 }; ${jt.registerUniforms(bs).declareVariables(...ps,zs)} ${Cs} ${Bo(h,lt,Et,Kt,o,t,Yt[0],Yt[1],Yt[2],Gt)} ${U?Fo(fe,Q,Gt,void 0,!h,Ge):Do(fe,Q,Gt,void 0,!h,Ge,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Me};${U};${lt};${Et};${Kt};${$e};${Ae};${Ge}`,inputDependencies:Jt},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:me[0],y:me[1],z:me[2]},programUniforms:kt}),getShaderSource:$t}}}),Ro,No,jn,fu,jo,mi,_u,gu,Uc=g(()=>{Bt(),tr(),Dt(),Xt(),sn(),$o(),Ro=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,jn=(e,t)=>t<=1?e:e+(e-1)*(t-1),fu=(e,t,s,n=1)=>{let i=jn(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)},jo=(e,t,s,n,i)=>{i==null&&(i=fu(e,t[0],n[0]));let a=[0,0,0,s];for(let o=0;o<3;o++)e[o]+2*i>=t[o]&&(a[o]=Math.trunc((e[o]-t[o]+2*i)/n[o]+1));return a},mi=(e,t,s,n,i,a,o,d,p,h)=>{let k,S,u,B;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let R=jo([t,s,n,1],[d,p,h],1,[i,a,o],e);S=R[0],u=R[1],B=R[2]}else if(Array.isArray(e)){if(!e.every((U,Z,te)=>U===te[0]))throw Error(`Unsupported padding parameter: ${e}`);k={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let R=jo([t,s,n,1],[d,p,h],1,[i,a,o],e[0]);S=R[0],u=R[1],B=R[2]}else if(e==="SAME_UPPER"){S=Math.ceil(t/i),u=Math.ceil(s/a),B=Math.ceil(n/o);let R=(S-1)*i+d-t,U=(u-1)*a+p-s,Z=(B-1)*o+h-n,te=Math.floor(R/2),Q=R-te,fe=Math.floor(U/2),me=U-fe,Me=Math.floor(Z/2),$e=Z-Me;k={top:fe,bottom:me,left:Me,right:$e,front:te,back:Q}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:S,outHeight:u,outWidth:B}},_u=(e,t,s,n,i,a=!1,o="channelsLast")=>{let d,p,h,k,S;if(o==="channelsLast")[d,p,h,k,S]=e;else if(o==="channelsFirst")[d,S,p,h,k]=e;else throw new Error(`Unknown dataFormat ${o}`);let[u,,B,R,U]=t,[Z,te,Q]=No(s),[fe,me,Me]=No(n),$e=jn(B,fe),Ae=jn(R,me),Ge=jn(U,Me),{padInfo:lt,outDepth:Et,outHeight:Kt,outWidth:Yt}=mi(i,p,h,k,Z,te,Q,$e,Ae,Ge),kt=a?u*S:u,Jt=[0,0,0,0,0];return o==="channelsFirst"?Jt=[d,kt,Et,Kt,Yt]:o==="channelsLast"&&(Jt=[d,Et,Kt,Yt,kt]),{batchSize:d,dataFormat:o,inDepth:p,inHeight:h,inWidth:k,inChannels:S,outDepth:Et,outHeight:Kt,outWidth:Yt,outChannels:kt,padInfo:lt,strideDepth:Z,strideHeight:te,strideWidth:Q,filterDepth:B,filterHeight:R,filterWidth:U,effectiveFilterDepth:$e,effectiveFilterHeight:Ae,effectiveFilterWidth:Ge,dilationDepth:fe,dilationHeight:me,dilationWidth:Me,inShape:e,outShape:Jt,filterShape:t}},gu=(e,t,s,n,i,a)=>{let o=a==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let d=[64,1,1],p={x:s.map((Z,te)=>te)},h=[Math.ceil(Ro(p.x.map(Z=>s[Z]))/d[0]),1,1];is("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,S=Se.size(s),u=[{type:12,data:S},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];tn(t,u),u.push(...Tt(e[0].dims,e[1].dims));let B=["rank","rank"],R=e.length===3;R&&(u.push(...Tt(e[2].dims)),B.push("rank")),u.push(...Tt(s));let U=Z=>{let te=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Ur(t,te);let Q=1,fe=es(e[0].dataType),me=De("x",e[0].dataType,e[0].dims.length,k),Me=De("W",e[1].dataType,e[1].dims.length,Q),$e=[me,Me],Ae=yt("result",e[0].dataType,s.length,Q),Ge="";if(R){let Kt=De("bias",e[2].dataType,e[2].dims.length,Q);$e.push(Kt),Ge+=` fn getBiasByOutputCoords(coords : array) -> ${fe} { return bias[${o?Mt("coords",4,5):Mt("coords",1,5)}]; }`}let lt=Ks(k,fe),Et=jr(t,lt,fe);return` ${Ge} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${me.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${Me.getByIndices("aIndices")}; } ${Z.registerUniforms(te).declareVariables(...$e,Ae)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Ae.offsetToIndices("global_idx")}; let batch = ${Mt("coords",0,me.rank)}; let d2 = ${o?Mt("coords",me.rank-1,me.rank):Mt("coords",1,me.rank)}; let xFRCCorner = vec3(${o?Mt("coords",1,me.rank):Mt("coords",2,me.rank)}, ${o?Mt("coords",2,me.rank):Mt("coords",3,me.rank)}, ${o?Mt("coords",3,me.rank):Mt("coords",4,me.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${o?Mt("uniforms.x_shape",1,me.rank):Mt("uniforms.x_shape",2,me.rank)}; let xShapeZ = ${o?Mt("uniforms.x_shape",2,me.rank):Mt("uniforms.x_shape",3,me.rank)}; let xShapeW = ${o?Mt("uniforms.x_shape",3,me.rank):Mt("uniforms.x_shape",4,me.rank)}; let xShapeU = ${o?Mt("uniforms.x_shape",4,me.rank):Mt("uniforms.x_shape",1,me.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) { ${o?`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) { ${o?`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) { ${o?`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) { ${o?`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); } } } } ${R?"value = value + getBiasByOutputCoords(coords)":""}; ${Et} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${o};${k};${R}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:u}),getShaderSource:U}}}),wu,yu,Mu=g(()=>{Bt(),Dt(),Xt(),sn(),wu=(e,t,s,n)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",o=e[0].dims,d=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],k=h/t.group,S=p&&k>=4?os(h):1,u=Se.size(s)/S,B=[{type:12,data:u},{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:k}];tn(t,B),B.push(...Tt(o,[d[0],d[1],d[2],d[3]/S]));let R=i?["rank","rank","rank"]:["rank","rank"];B.push(...Tt([s[0],s[1],s[2],s[3]/S]));let U=Z=>{let te=yt("output",e[0].dataType,s.length,S),Q=es(te.type.tensor),fe=jr(t,te.type.value,Q),me=De("x",e[0].dataType,o.length),Me=De("w",e[1].dataType,d.length,S),$e=[me,Me];i&&$e.push(De("b",e[2].dataType,e[2].dims,S));let Ae=[{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"}];Ur(t,Ae);let Ge=p?` 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 = ${me.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${Me.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 = ${me.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${Me.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${Z.registerUniforms(Ae).declareVariables(...$e,te)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${te.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${p?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${S} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; var value: ${te.type.value} = ${te.type.value}(0); ${Ge} ${a} ${fe} ${te.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${S}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:B}),getShaderSource:U}},yu=(e,t,s,n)=>{let i=e.length>2,a=os(s[3]),o=os(s[2]),d=Se.size(s)/a/o,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],k=[s[0],s[1],s[2],s[3]/a],S=[{type:12,data:d},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];tn(t,S),S.push(...Tt(p,h,k));let u=(o-1)*t.strides[1]+h[1],B=R=>{let U=yt("output",e[0].dataType,k.length,a),Z=es(U.type.tensor),te=jr(t,U.type.value,Z),Q=De("x",e[0].dataType,p.length,a),fe=De("w",e[1].dataType,h.length,a),me=[Q,fe];i&&me.push(De("b",e[2].dataType,e[2].dims,a));let Me=i?"value += b[output_channel];":"",$e=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ur(t,$e),` ${R.registerUniforms($e).declareVariables(...me,U)} ${R.mainStart()} ${R.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] / ${o}u; let col = (index1 % width1) * ${o}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<${Q.type.value}, ${u}>; var values: array<${U.type.value}, ${o}>; 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 < ${h[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 < ${u}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${Q.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${Q.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${fe.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${o}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${o}u; i++) { var value = values[i]; ${Me} ${te} ${U.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${o};${u};${h[0]};${h[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:S}),getShaderSource:B}}}),bu,fi,Uo,_i,Wo,Vo,vu,Go,Ko,Wc=g(()=>{Dt(),jc(),Uc(),zo(),Mu(),sn(),Io(),Nr(),bu=(e,t,s,n,i,a)=>{let o=e[0],d=e.slice(a?1:2,a?3:4),p=d.length,h=t[0],k=t.slice(2).map((u,B)=>u+(u-1)*(s[B]-1)),S=d.map((u,B)=>u+n[B]+n[B+p]).map((u,B)=>Math.floor((u-k[B]+i[B])/i[B]));return S.splice(0,0,o),S.splice(a?3:1,0,h),S},fi=[2,3,1,0],Uo=(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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},_i=(e,t)=>{let s=e.kernelShape.slice();s.length{let t=ko(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,a=e.group,o=e.kernel_shape,d=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:i,group:a,kernelShape:o,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Vo=(e,t,s,n)=>{let i=s.format==="NHWC",a=bu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,i);if(s.group!==1){let $e=[t[0]];if(i){let Ae=e.kernelCustomData.wT??e.compute(ar(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ae),$e.push(Ae)}else $e.push(t[1]);t.length===3&&$e.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(yu($e,s,a,n),{inputs:$e}):e.compute(wu($e,s,a,n),{inputs:$e});return}let o=t.length===3,d=t[0].dims[i?1:2],p=t[0].dims[i?2:3],h=t[0].dims[i?3:1],k=t[1].dims[2],S=t[1].dims[3],u=a[i?1:2],B=a[i?2:3],R=a[i?3:1],U=i&&k===d&&S===p&&s.pads[0]===0&&s.pads[1]===0;if(U||k===1&&S===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let $e=a[0],Ae,Ge,lt,Et=[];if(i){let kt=e.kernelCustomData.wT??e.compute(ar(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=kt),U){let Jt=d*p*h;Ae=t[0].reshape([1,$e,Jt]),Ge=kt.reshape([1,Jt,R]),lt=[1,$e,R]}else Ae=t[0].reshape([$e,d*p,h]),Ge=kt.reshape([1,h,R]),lt=[$e,u*B,R];Et.push(Ae),Et.push(Ge)}else Ae=t[0].reshape([$e,h,d*p]),Ge=t[1].reshape([1,R,h]),lt=[$e,R,u*B],Et.push(Ge),Et.push(Ae);o&&Et.push(t[2]);let Kt=lt[2],Yt=Et[0].dims[Et[0].dims.length-1];Kt<8&&Yt<8?e.compute(Ao(Et,s,a,lt,i,n),{inputs:Et}):e.compute(hi(Et,s,a,lt,i,n),{inputs:Et});return}let Z=!0,te=e.kernelCustomData.wT??e.compute(ar(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=te);let Q=[t[0],te];o&&Q.push(t[2]);let fe=i?u*B:R,me=i?R:u*B,Me=k*S*h;e.compute(mu(Q,s,a,fe,me,Me,o,Z,n),{inputs:Q})},vu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),o=[1].concat(t.dilations),d=[1].concat(t.kernelShape),p=_i({...t,pads:i,strides:a,dilations:o,kernelShape:d},n);Vo(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Go=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",i=_i(s,t),a=s.autoPad==="NOTSET"?s.pads:s.autoPad,o=_u(t[0].dims,t[1].dims,s.strides,s.dilations,a,!1,n);e.compute(gu(t,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],n))},Ko=(e,t)=>{if(Uo(e.inputs,t),e.inputs[0].dims.length===3)vu(e,t);else if(e.inputs[0].dims.length===5)Go(e,e.inputs,t);else{let s=_i(t,e.inputs);Vo(e,e.inputs,s)}}}),Ho,Vc=g(()=>{Bt(),tr(),Dt(),Xt(),Ho=(e,t,s)=>{let n=e.length>2,i=t.outputShape,a=t.format==="NHWC",o=t.group,d=e[1].dims,p=d[2]/o,h=d[3],k=a?os(h):1,S=Se.size(i)/k,u=[Math.ceil(S/64),1,1];is("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let B=["rank","rank"],R=[t.strides[0],t.strides[1]],U=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],Z=[t.dilations[0],t.dilations[1]],te=[U[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),U[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],Q=[te[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),te[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],fe=[{type:12,data:S},{type:12,data:R},{type:12,data:U},{type:12,data:Z},{type:12,data:te},{type:6,data:Q},{type:12,data:p},{type:12,data:h},...Tt(e[0].dims,e[1].dims)];n&&(fe.push(...Tt(e[2].dims)),B.push("rank")),fe.push(...Tt(i));let me=Me=>{let $e=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:R.length},{name:"filter_dims",type:"u32",length:U.length},{name:"dilations",type:"u32",length:U.length},{name:"effective_filter_dims",type:"u32",length:te.length},{name:"pads",type:"i32",length:Q.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ae=es(e[0].dataType),Ge=a?1:2,lt=a?2:3,Et=a?3:1,Kt=De("W",e[1].dataType,e[1].dims.length,k),Yt=De("Dy",e[0].dataType,e[0].dims.length),kt=[Yt,Kt];n&&kt.push(De("bias",e[2].dataType,[i[Et]].length,k));let Jt=yt("result",e[0].dataType,i.length,k),$t=` let outputIndices = ${Jt.offsetToIndices(`global_idx * ${k}`)}; let batch = ${Jt.indicesGet("outputIndices",0)}; let d1 = ${Jt.indicesGet("outputIndices",Et)}; let r = ${Jt.indicesGet("outputIndices",Ge)}; let c = ${Jt.indicesGet("outputIndices",lt)}; 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 = ${Jt.type.value}(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 = (${Ae}(dyRCorner) + ${Ae}(wR)) / ${Ae}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${Ae}(uniforms.Dy_shape[${Ge}]) || 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 = (${Ae}(dyCCorner) + ${Ae}(wC)) / ${Ae}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${Ae}(uniforms.Dy_shape[${lt}]) || 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 = ${a?Yt.get("batch","idyR","idyC","inputChannel"):Yt.get("batch","inputChannel","idyR","idyC")}; let w_offset = ${Kt.indicesToOffset(`${Kt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; let wValue = ${Kt.getByOffset(`w_offset / ${k}`)}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd${n?` + bias[d1 / ${k}]`:""}; ${Jt.setByOffset("global_idx","value")}; `;return` ${Me.registerUniforms($e).declareVariables(...kt,Jt)} ${Me.mainStart()} ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${$t}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}`,inputDependencies:B},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:s?s(i):i,dataType:e[0].dataType}],programUniforms:fe}),getShaderSource:me}}}),Tu,qo,xu,Xo,Qo,Eu,Yo,Pu,Cu,Gc=g(()=>{Vc(),sn(),Nr(),Tu=(e,t,s,n,i,a)=>(e-1)*t+s+(n-1)*i+1-a,qo=(e,t,s,n,i)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(s[n]=a,s[i]=e-a):t==="SAME_LOWER"&&(s[n]=e-a,s[i]=a)},xu=(e,t,s,n,i,a,o,d,p,h)=>{let k=e.length-2,S=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((S,u)=>S*u,1)===0){s.length=0;for(let S=2;SS+u,0)===0){let S=t[0].dims.length-2;p=new Array(S).fill(1)}let h=e.strides.slice();if(h.reduce((S,u)=>S+u,0)===0){let S=t[0].dims.length-2;h=new Array(S).fill(1)}xu(d,s,p,e.autoPad,e.group,i,h,n,o,a);let k=Object.assign({},e);return Object.assign(k,{kernelShape:s,pads:i,outputPadding:o,outputShape:a,dilations:p,strides:h}),k},Qo=e=>{let t=ko(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,a=e.group,o=e.kernelShape,d=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,S=e.outputShape;return{autoPad:n,format:s,dilations:i,group:a,kernelShape:o,outputPadding:k,outputShape:S,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Eu=(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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((o,d)=>o+d,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((o,d)=>o+d,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((o,d)=>o+d,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((o,d)=>o+d,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Yo=(e,t,s,n)=>{let i=e.kernelCustomData.wT??e.compute(ar(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let a=[t[0],i];t.length===3&&a.push(t[2]),e.compute(Ho(a,s,n),{inputs:a})},Pu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let o=t.strides;(o.length===0||o[0]===0)&&(o=[1]);let d=t.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],o=[1].concat(o),a=[1].concat(a),i=[1].concat(i);let p=Xo({...t,pads:d,strides:o,dilations:a,kernelShape:i},n);Yo(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Cu=(e,t)=>{if(Eu(e.inputs,t),e.inputs[0].dims.length===3)Pu(e,t);else{let s=Xo(t,e.inputs);Yo(e,e.inputs,s)}}}),ku,Jo,Su,Kc=g(()=>{Bt(),Dt(),Ct(),Xt(),ku=(e,t,s,n)=>{let i=Se.size(t),a=t.length,o=De("input",e,a),d=yt("output",e,a),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=Se.normalizeAxis(p,a),k=S=>{let u=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,B=Mt("uniforms.input_shape","uniforms.axis",a),R=n.reverse?u+(n.exclusive?" + 1":""):"0",U=n.reverse?B:u+(n.exclusive?"":" + 1");return` ${S.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,d)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${d.offsetToIndices("global_idx")}; var sum = ${d.type.value}(0); let first : i32 = ${R}; let last : i32 = ${U}; for (var i : i32 = first; i < last; i++) { ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${o.getByIndices("inputIndices")}; } ${d.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:h},...Tt(t,t)]}),getShaderSource:k}},Jo=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(ku(n,s,i,t),{inputs:[0]})},Su=e=>{let t=e.exclusive===1,s=e.reverse===1;return it({exclusive:t,reverse:s})}}),Zo,$u,Au,Wr,Iu,Hc=g(()=>{Bt(),Dt(),Ct(),Xt(),Zo=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},$u=(e,t,s,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`);for(let a=0;a{let s,n,i,a,o,d,p=t.format==="NHWC",h=t.blocksize,k=t.mode==="DCR";p?([s,n,i,a]=e.dims,o=k?[s,n,i,h,h,a/h**2]:[s,n,i,a/h**2,h,h],d=k?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=k?[s,h,h,a/h**2,n,i]:[s,a/h**2,h,h,n,i],d=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let S=e.reshape(o),u=S.dims.length,B=e.dataType,R=De("a",B,u),U=yt("output",B,u),Z=te=>` ${te.registerUniform("output_size","u32").declareVariables(R,U)} ${$u(d,u,R,U)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${U.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${U.setByOffset("global_idx",R.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:te=>{let Q=p?[s,n*h,i*h,a/h**2]:[s,a/h**2,n*h,i*h],fe=Se.size(Q),me=S.dims,Me=Se.sortBasedOnPerm(me,d);return{outputs:[{dims:Q,dataType:te[0].dataType}],dispatchGroup:{x:Math.ceil(fe/64)},programUniforms:[{type:12,data:fe},...Tt(me,Me)]}},getShaderSource:Z}},Wr=(e,t)=>{Zo(e.inputs),e.compute(Au(e.inputs[0],t))},Iu=e=>it({blocksize:e.blocksize,mode:e.mode,format:e.format})}),gi,Un,wi,Ou,Fu,Du,Lu,Wn,zu,Bu,Ru,yi=g(()=>{Bt(),Dt(),Ct(),Xt(),gi="[a-zA-Z]|\\.\\.\\.",Un="("+gi+")+",wi="^"+Un+"$",Ou="("+Un+",)*"+Un,Fu="^"+Ou+"$",Du=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},Lu=class{constructor(e,t){var i;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,n]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(Fu)))throw new Error("Invalid LHS term");if(s.split(",").forEach((a,o)=>{let d=e[o].dims.slice();if(!a.match(RegExp(wi)))throw new Error("Invalid LHS term");let p=this.processTerm(a,!0,d,o);this.lhs.push(p)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,o])=>o.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Un)))throw new Error("Invalid RHS");(i=n.match(RegExp(gi,"g")))==null||i.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(a);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,s){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(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let i=s.length,a=!1,o=[],d=0;if(!e.match(RegExp(wi))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(gi,"g")),h=new Du(n);return p==null||p.forEach((k,S)=>{if(k==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let u=i-p.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(o=s.slice(d,d+u),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let B=0;Be+"_max",zu=(e,t,s,n)=>{let i=e.map(h=>h.length).map((h,k)=>De(`input${k}`,t,h)),a=Se.size(n),o=yt("output",t,n.length),d=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let k=[],S="var prod = 1.0;",u="var sum = 0.0;",B="sum += prod;",R=[],U=[],Z=[],te=[],Q=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((me,Me)=>{var $e;if(s.rhs.symbolToIndices.has(Me)){let Ae=($e=s.rhs.symbolToIndices.get(Me))==null?void 0:$e[0];Ae!==void 0&&s.lhs.forEach((Ge,lt)=>{if(me.inputIndices.includes(lt)){let Et=Ge.symbolToIndices.get(Me);if(Et===void 0)throw new Error("Invalid symbol error");Et.forEach(Kt=>{k.push(`${i[lt].indicesSet(`input${lt}Indices`,Kt,o.indicesGet("outputIndices",Ae))}`)})}})}else s.lhs.forEach((Ae,Ge)=>{if(me.inputIndices.includes(Ge)){let lt=Ae.symbolToIndices.get(Me);if(lt===void 0)throw new Error("Invalid symbol error");lt.forEach(Et=>{R.push(`${i[Ge].indicesSet(`input${Ge}Indices`,Et,`${Me}`)}`)}),te.push(`prod *= ${i[Ge].getByIndices(`input${Ge}Indices`)};`)}}),U.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${Wn(Me)}; ${Me}++) {`),Z.push("}")});let fe=Q?[...k,`let sum = ${i.map((me,Me)=>me.getByIndices(`input${Me}Indices`)).join(" * ")};`]:[...k,u,...U,...R,S,...te,B,...Z];return` ${h.registerUniforms(d.map(me=>({name:`${Wn(me)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${o.offsetToIndices("global_idx")}; ${i.map((me,Me)=>`var input${Me}Indices: ${i[Me].type.indices};`).join(` `)} ${fe.join(` `)}; ${o.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=d.filter(S=>s.symbolToInfo.has(S)).map(S=>{var u;return{type:12,data:((u=s.symbolToInfo.get(S))==null?void 0:u.dimValue)||0}});h.push({type:12,data:a});let k=e.map((S,u)=>[...Tt(S)]).reduce((S,u)=>S.concat(u),h);return k.push(...Tt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:k}},getShaderSource:p}},Bu=(e,t)=>{let s=new Lu(e.inputs,t.equation),n=s.outputDims,i=e.inputs.map((a,o)=>a.dims);e.compute(zu(i,e.inputs[0].dataType,s,n))},Ru=e=>{let t=e.equation.replace(/\s+/g,"");return it({equation:t})}}),Nu,ea,ju,Uu,Mi,qc=g(()=>{Bt(),Dt(),Xt(),Nu=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=s.length{let s=e.length-t.length,n=[];for(let i=0;ie.length>t.length?ea(e,t):ea(t,e),Uu=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=ju(t,s),i=e[0].dataType,a=i===9||Se.size(t)===1,o=i===9||t.length>0&&t[t.length-1]%4===0?4:1,d=a||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(Se.size(n)/d),h=S=>{let u=De("input",i,t.length,o),B=yt("output",i,n.length,d),R;if(i===9){let U=(Z,te,Q="")=>` let outputIndices${te} = ${B.offsetToIndices(`outputOffset + ${te}u`)}; let offset${te} = ${u.broadcastedIndicesToOffset(`outputIndices${te}`,B)}; let index${te} = offset${te} / 4u; let component${te} = offset${te} % 4u; ${Z}[${te}] = ${Q}(${u.getByOffset(`index${te}`)}[component${te}]); `;R=` let outputOffset = global_idx * ${d}; var data = vec4(0); ${U("data",0,"u32")} ${U("data",1,"u32")} ${U("data",2,"u32")} ${U("data",3,"u32")} ${B.setByOffset("global_idx","data")} }`}else R=` let outputIndices = ${B.offsetToIndices(`global_idx * ${d}`)}; let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",B)}; let data = ${B.type.value}(${u.getByOffset(`inputOffset / ${o}`)}); ${B.setByOffset("global_idx","data")} }`;return` ${S.registerUniform("vec_size","u32").declareVariables(u,B)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${R}`},k=[{type:12,data:p},...Tt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${o}${d}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},Mi=e=>{Nu(e.inputs),e.compute(Uu(e.inputs),{inputs:[0]})}}),Wu,Vu,Up=g(()=>{Bt(),Dt(),Xt(),vo(),Wu=e=>{let t=e[0].dataType,s=Se.size(e[0].dims),n=Se.size(e[1].dims),i=n%4===0,a=o=>{let d=De("x",t,[1],4),p=De("bias",t,[1],4),h=yt("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],S=B=>` let bias${B}_offset: u32 = (global_idx * 4 + ${B}) % uniforms.bias_size; let bias${B} = ${p.getByOffset(`bias${B}_offset / 4`)}[bias${B}_offset % 4];`,u=i?` let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${S(0)}${S(1)}${S(2)}${S(3)} let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(k).declareVariables(d,p,h)} ${di(_s(t))} ${o.mainStart(Ns)} ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${d.getByOffset("global_idx")}; ${u} let x_in = x + bias; ${h.setByOffset("global_idx",Mo("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:o=>({outputs:[{dims:o[0].dims,dataType:o[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(s/Ns/4)}})}},Vu=e=>{e.inputs.length<2||Se.size(e.inputs[1].dims)===0?Vl(e):e.compute(Wu(e.inputs))}}),Gu,Ku,Hu,Tn,Xc=g(()=>{Bt(),Dt(),Ct(),Xt(),Gu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ku=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,a=Se.normalizeAxis(t.axis,i),o=s.slice(0);o.splice(a,1,...n);let d=s[a],p=e[0].dataType===9?4:1,h=Math.ceil(Se.size(o)/p),k=[{type:12,data:h},{type:6,data:d},{type:12,data:a},...Tt(e[0].dims,e[1].dims,o)],S=u=>{let B=De("data",e[0].dataType,e[0].dims.length,p),R=De("inputIndices",e[1].dataType,e[1].dims.length),U=yt("output",e[0].dataType,o.length,p),Z=Q=>{let fe=n.length,me=`var indicesIndices${Q} = ${R.type.indices}(0);`;for(let Me=0;Me1?`indicesIndices${Q}[${Me}]`:`indicesIndices${Q}`} = ${o.length>1?`outputIndices${Q}[uniforms.axis + ${Me}]`:`outputIndices${Q}`};`;me+=` var idx${Q} = ${R.getByIndices(`indicesIndices${Q}`)}; if (idx${Q} < 0) { idx${Q} = idx${Q} + uniforms.axisDimLimit; } var dataIndices${Q} : ${B.type.indices}; `;for(let Me=0,$e=0;Me1?`dataIndices${Q}[${Me}]`:`dataIndices${Q}`} = u32(idx${Q});`,$e+=fe):(me+=`${i>1?`dataIndices${Q}[${Me}]`:`dataIndices${Q}`} = ${o.length>1?`outputIndices${Q}[${$e}]`:`outputIndices${Q}`};`,$e++);return me},te;if(e[0].dataType===9){let Q=(fe,me,Me="")=>` let outputIndices${me} = ${U.offsetToIndices(`outputOffset + ${me}u`)}; ${Z(me)}; let offset${me} = ${B.indicesToOffset(`dataIndices${me}`)}; let index${me} = offset${me} / 4u; let component${me} = offset${me} % 4u; ${fe}[${me}] = ${Me}(${B.getByOffset(`index${me}`)}[component${me}]); `;te=` let outputOffset = global_idx * ${p}; var value = vec4(0); ${Q("value",0,"u32")} ${Q("value",1,"u32")} ${Q("value",2,"u32")} ${Q("value",3,"u32")} ${U.setByOffset("global_idx","value")} `}else te=` let outputIndices = ${U.offsetToIndices("global_idx")}; ${Z("")}; let value = ${B.getByIndices("dataIndices")}; ${U.setByOffset("global_idx","value")}; `;return` ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(B,R,U)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${te} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:S}},Hu=e=>it({axis:e.axis}),Tn=(e,t)=>{let s=e.inputs;Gu(s),e.compute(Ku(e.inputs,t))}}),qu,Xu,Qu,Qc=g(()=>{Bt(),Dt(),Xt(),qu=(e,t,s,n,i,a,o,d,p)=>{let h=[{type:12,data:a},{type:12,data:n},{type:12,data:i},{type:12,data:s},{type:12,data:o},{type:12,data:d},{type:12,data:p}],k=[a];h.push(...Tt(t.dims,k));let S=u=>{let B=De("indices_data",t.dataType,t.dims.length),R=yt("input_slice_offsets_data",12,1,1),U=[B,R],Z=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:i.length},{name:"sizes_from_slice_dims_data",type:"u32",length:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${u.registerUniforms(Z).declareVariables(...U)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let batch_idx = global_idx / uniforms.num_slices_per_batch; let base_offset = batch_idx * uniforms.input_batch_stride; let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; var relative_slice_offset = 0; for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); let input_dim_idx = uniforms.batch_dims + dim_idx; if (index < 0) { ${i.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} } ${s.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${i.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:k,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:S},{inputs:[t],outputs:[-1]})[0]},Xu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=s[0].dataType,a=s[1].dims,o=a[a.length-1],d=Se.sizeToDimension(a,a.length-1),p=Se.sizeFromDimension(n,t.batchDims+o),h=Se.sizeToDimension(n,t.batchDims),k=Se.sizeFromDimension(n,t.batchDims),S=d/h,u=new Array(o),B=p;for(let me=0;men.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let Z=a.slice(0,-1).concat(n.slice(U)),te=Se.size(Z),Q=[{type:12,data:te},{type:12,data:p},...Tt(s[0].dims,R.dims,Z)],fe=me=>{let Me=De("data",s[0].dataType,s[0].dims.length),$e=De("slice_offsets",12,R.dims.length),Ae=yt("output",s[0].dataType,Z.length);return` ${me.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Me,$e,Ae)} ${me.mainStart()} ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:Z,dataType:i}],dispatchGroup:{x:Math.ceil(te/64)},programUniforms:Q}),getShaderSource:fe},{inputs:[s[0],R]})},Qu=e=>({batchDims:e.batch_dims,cacheKey:""})}),bi,Yc,Yu,Ju,Jc=g(()=>{Bt(),Dt(),Ct(),Xt(),bi=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=Se.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,i=e[0],a=e[2],o=e.length===4?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map((d,p)=>p===s?Math.ceil(d/n)===a.dims[p]:d===a.dims[p]).reduce((d,p)=>d&&p,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(o){if(o.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==a.dims.length||!o.dims.map((d,p)=>d===a.dims[p]).reduce((d,p)=>d&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Yc=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,a=Se.normalizeAxis(t.gatherAxis,i),o=Se.normalizeAxis(t.quantizeAxis,i),d=s.slice(0);d.splice(a,1,...n);let p=Se.size(d),h=e[2].dataType,k=e[0].dataType===22,S=[{type:12,data:p},{type:12,data:o},{type:12,data:a},{type:12,data:t.blockSize},...Tt(...e.map((B,R)=>B.dims),d)],u=B=>{let R=De("data",e[0].dataType,e[0].dims.length),U=De("inputIndices",e[1].dataType,e[1].dims.length),Z=De("scales",e[2].dataType,e[2].dims.length),te=e.length>3?De("zeroPoint",e[3].dataType,e[3].dims.length):void 0,Q=yt("output",h,d.length),fe=[R,U,Z];te&&fe.push(te);let me=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${B.registerUniforms(me).declareVariables(...fe,Q)} ${B.mainStart()} let output_indices = ${Q.offsetToIndices("global_idx")}; var indices_indices = ${U.type.indices}(0); ${n.length>1?` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${Q.indicesGet("output_indices","uniforms.gather_axis + i")}; ${U.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${Q.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${R.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${Q.indicesGet("output_indices","i")}; ${R.indicesSet("data_indices","i","index")}; } var index_from_indices = ${U.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${s[a]}; } ${R.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${d.length}; i++) { let index = ${Q.indicesGet("output_indices",`i + ${n.length} - 1`)}; ${R.indicesSet("data_indices","i","index")}; } let data_offset = ${R.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${R.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${Z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${Z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${Z.getByIndices("scale_indices")}; ${te?` let zero_point_indices = scale_indices; let zero_point_offset = ${te.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${te.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${_s(h)}(quantized_data - zero_point) * scale; ${Q.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((B,R)=>R!==1).map(B=>B.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(B,R)=>"rank")},getRunData:()=>({outputs:[{dims:d,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:S}),getShaderSource:u}},Yu=(e,t)=>{let s=e.inputs;bi(s,t),e.compute(Yc(e.inputs,t))},Ju=e=>it({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Zu,ed,ta,td,Zc=g(()=>{Bt(),Dt(),Ct(),Xt(),Zu=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.`)},ed=(e,t)=>{let s=e[0].dims,n=e[0].dataType,i=s.length,a=e[1].dims,o=e[1].dataType,d=Se.normalizeAxis(t.axis,i),p=s[d],h=a.slice(0),k=Se.size(h),S=De("input",n,i),u=De("indicesInput",o,a.length),B=yt("output",n,h.length),R=[{type:12,data:k},{type:6,data:p},{type:12,data:d}];return R.push(...Tt(s,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:R}),getShaderSource:U=>` ${U.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(S,u,B)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${B.offsetToIndices("global_idx")}; var idx = ${u.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${S.type.indices}(outputIndices); ${S.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${S.getByIndices("inputIndices")}; ${B.setByOffset("global_idx","value")}; }`}},ta=e=>it({axis:e.axis}),td=(e,t)=>{let s=e.inputs;Zu(s),e.compute(ed(e.inputs,t))}}),sa,sd,rd,ra,ep=g(()=>{Bt(),Dt(),Xt(),sa=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")},sd=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[i,a,o]=Fs.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),d=[i,a];if(!d)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(a/p),k=Math.ceil(i/p),S=!0,u=Se.size(d),B=[{type:12,data:S?h:u},{type:12,data:i},{type:12,data:a},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],R=["type","type"];e.length===3&&(B.push(...Tt(e[2].dims)),R.push("rank")),B.push(...Tt(d));let U=te=>{let Q="";t.transA&&t.transB?Q="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?Q="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?Q="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(Q="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let fe=t.alpha===1?"":"value *= uniforms.alpha;",me=De("a",e[0].dataType,e[0].dims),Me=De("b",e[1].dataType,e[1].dims),$e=me.type.value,Ae=null,Ge=[me,Me];e.length===3&&(Ae=De("c",e[2].dataType,e[2].dims.length),Ge.push(Ae));let lt=yt("output",e[0].dataType,d.length);Ge.push(lt);let Et=[{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` ${te.registerUniforms(Et).declareVariables(...Ge)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${$e}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${Q} } ${fe} ${Ae!=null?`let cOffset = ${Ae.broadcastedIndicesToOffset("vec2(m, n)",lt)}; value += ${$e}(uniforms.beta) * ${Ae.getByOffset("cOffset")};`:""} output[global_idx] = value; }`},Z=te=>{let Q=De("a",e[0].dataType,e[0].dims),fe=De("b",e[1].dataType,e[1].dims),me=null,Me=[Q,fe];e.length===3&&(me=De("c",e[2].dataType,e[2].dims.length),Me.push(me));let $e=yt("output",e[0].dataType,d.length);Me.push($e);let Ae=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],Ge="",lt="";t.transA&&t.transB?(lt=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${Q.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${fe.type.value}(0); } `,Ge="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(lt=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${Q.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${fe.type.value}(0); } `,Ge="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(lt=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${Q.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${fe.type.value}(0); } `,Ge="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(lt=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${Q.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${fe.type.value}(0); } `,Ge="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Et=t.alpha===1?"":"value *= uniforms.alpha;";return` ${te.registerUniforms(Ae).declareVariables(...Me)} var tile_a: array, ${p}>; var tile_b: array, ${p}>; ${te.mainStart([p,p,1])} let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; let num_tiles = (uniforms.K - 1) / ${p} + 1; var k_start = 0u; var value = ${$e.type.value}(0); for (var t: u32 = 0u; t < num_tiles; t++) { ${lt} k_start = k_start + ${p}; workgroupBarrier(); for (var k: u32 = 0u; k < ${p}; k++) { ${Ge} } workgroupBarrier(); } ${Et} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${me!=null?`let cOffset = ${me.broadcastedIndicesToOffset("vec2(m, n)",$e)}; value += ${$e.type.value}(uniforms.beta) * ${me.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } }`};return S?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:B}),getShaderSource:Z}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:B}),getShaderSource:U}},rd=e=>{let t=e.transA,s=e.transB,n=e.alpha,i=e.beta;return{transA:t,transB:s,alpha:n,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},ra=(e,t)=>{sa(e.inputs),e.compute(sd(e.inputs,t))}}),Pr,fr,rn,nn,nd,id,na,vi,tp,od,ad,ia,ld,ud,dd=g(()=>{Bt(),Dt(),Ct(),Xt(),[Pr,fr,rn,nn]=[0,1,2,3],nd=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},id=` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); var coeffs: vec4; coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } `,na=e=>` fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { var v: vec4; var coeffs = gs_get_cubic_coeffs(x); for (var i = 0; i < 4; i++) { v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; } coeffs = gs_get_cubic_coeffs(y); let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); return pixel; } `,vi=e=>` fn gs_denormalize(n: f32, length: i32) -> f32 { ${e.alignCorners===0?` // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] return ((n + 1.0) * f32(length) - 1.0) / 2.0; `:` // alignCorners: true => [-1, 1] to [0, length - 1] return (n + 1.0) / 2.0 * (f32(length - 1)); `} } `,tp=e=>` ${e.paddingMode==="reflection"?` fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { var dx = 0.0; var fx = f32(x); let range = x_max - x_min; if (fx < x_min) { dx = x_min - fx; let n = u32(dx / range); let r = dx - f32(n) * range; if (n % 2 == 0) { fx = x_min + r; } else { fx = x_max - r; } } else if (fx > x_max) { dx = fx - x_max; let n = u32(dx / range); let r = dx - f32(n) * range; if (n % 2 == 0) { fx = x_max - r; } else { fx = x_min + r; } } return u32(fx); }`:""} `,od=(e,t,s)=>` fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { var pixel = ${t}(0); var indices = vec4(0); indices[${Pr}] = batch; indices[${fr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { indices[${rn}] = u32(r); indices[${nn}] = u32(c); } `;case"border":return` indices[${rn}] = u32(clamp(r, 0, H - 1)); indices[${nn}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` indices[${rn}] = gs_reflect(r, border[1], border[3]); indices[${nn}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } `,ad=(e,t,s)=>(()=>{switch(s.mode){case"nearest":return` let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Pr}], indices[${fr}], border); `;case"bilinear":return` let x1 = i32(floor(x)); let y1 = i32(floor(y)); let x2 = x1 + 1; let y2 = y1 + 1; let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Pr}], indices[${fr}], border); let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Pr}], indices[${fr}], border); let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Pr}], indices[${fr}], border); let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Pr}], indices[${fr}], border); let dx2 = ${t}(f32(x2) - x); let dx1 = ${t}(x - f32(x1)); let dy2 = ${t}(f32(y2) - y); let dy1 = ${t}(y - f32(y1)); let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); `;case"bicubic":return` let x0 = i32(floor(x)) - 1; let y0 = i32(floor(y)) - 1; var p: mat4x4<${t}>; for (var h = 0; h < 4; h++) { for (var w = 0; w < 4; w++) { p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Pr}], indices[${fr}], border); } } let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); `;default:throw new Error(`mode ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,ia=(e,t)=>{let s=De("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=De("grid",e[1].dataType,n.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Pr,fr,rn,nn]=[0,3,1,2]);let o=yt("output",e[0].dataType,a.length),d=s.type.value,p=Se.size(a),h=[{type:12,data:p},...Tt(e[0].dims,n,a)],k=S=>` ${S.registerUniform("output_size","u32").declareVariables(s,i,o)} ${id} ${na(d)} ${vi(t)} ${tp(t)} ${od(s,d,t)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${rn}]); let W_in = i32(uniforms.x_shape[${nn}]); ${t.alignCorners===0?` let x_min = -0.5; let x_max = f32(W_in) - 0.5; let y_min = -0.5; let y_max = f32(H_in) - 0.5; `:` let x_min = 0.0; let x_max = f32(W_in) - 1.0; let y_min = 0.0; let y_max = f32(H_in) - 1.0; `}; let border = vec4(x_min, y_min, x_max, y_max); let indices = ${o.offsetToIndices("global_idx")}; var grid_indices = vec3(indices[${Pr}], indices[${rn}], indices[${nn}]); let nxy = ${i.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${ad(o,d,t)} }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:S=>{let u=Se.size(a);return{outputs:[{dims:a,dataType:S[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h}},getShaderSource:k}},ld=(e,t)=>{nd(e.inputs),e.compute(ia(e.inputs,t))},ud=e=>it({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Qs,cd,oa,pd,sp,xn,aa,hd=g(()=>{Bt(),Dt(),Ct(),Jr(),ro(),Xt(),Nr(),Qs=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,cd=(e,t)=>{let s=e[0],n=Qs(e,1),i=Qs(e,2),a=Qs(e,3),o=Qs(e,4),d=Qs(e,5),p=Qs(e,6),h=Qs(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let k=s.dims[0],S=s.dims[1],u=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],B=S,R=0,U=0,Z=Math.floor(u/t.numHeads);if(p&&h&&Se.size(p.dims)&&Se.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==k||p.dims[1]!==t.numHeads||p.dims[3]!==Z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==k||h.dims[1]!==t.numHeads||h.dims[3]!==Z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');R=p.dims[2],U=p.dims[2]}else if(p&&Se.size(p.dims)||h&&Se.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te;if(n&&Se.size(n.dims)>0){if(s.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(s.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]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');te=2,B=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==Z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');te=5,B=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==Z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');te=0,B=n.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}if(a&&Se.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let Q=R+B,fe=0;if(o&&Se.size(o.dims)>0){fe=8;let Ae=o.dims;throw Ae.length===1?Ae[0]===k?fe=1:Ae[0]===3*k+2&&(fe=3):Ae.length===2&&Ae[0]===k&&Ae[1]===Q&&(fe=5),fe===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let me=!1,Me=u;if(i&&Se.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(B!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Me=i.dims[2]}else{if(B!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Me=i.dims[1]*i.dims[3],me=!0}}let $e=!1;if(o&&Se.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(d&&Se.size(d.dims)>0){if(d.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(d.dims[0]!==k||d.dims[1]!==t.numHeads||d.dims[2]!==S||d.dims[3]!==Q)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:S,pastSequenceLength:R,kvSequenceLength:B,totalSequenceLength:Q,maxSequenceLength:U,inputHiddenSize:0,hiddenSize:u,vHiddenSize:Me,headSize:Z,vHeadSize:Math.floor(Me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:fe,scale:t.scale,broadcastResPosBias:$e,passPastInKv:me,qkvFormat:te}},oa=e=>it({...e}),pd=it({perm:[0,2,1,3]}),sp=(e,t,s,n,i,a,o)=>{let d=[n,i,a],p=Se.size(d),h=[{type:12,data:p},{type:12,data:o},{type:12,data:a}],k=S=>{let u=yt("qkv_with_bias",t.dataType,d),B=De("qkv",t.dataType,d),R=De("bias",s.dataType,d),U=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${S.registerUniforms(U).declareVariables(B,R,u)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:d,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,s],outputs:[-1]})[0]},xn=(e,t,s,n,i,a,o,d)=>{let p=a;if(o&&Se.size(o.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=sp(e,a,o,t,n,s*i,d),p=p.reshape([t,n,s,i]),s===1||n===1?p:e.compute(ar(p,pd.perm),{inputs:[p],outputs:[-1]})[0]}else return a.dims.length===3&&(p=a.reshape([t,n,s,i])),s===1||n===1?p:e.compute(ar(p,pd.perm),{inputs:[p],outputs:[-1]})[0]},aa=(e,t)=>{let s=cd(e.inputs,t),n=e.inputs[0],i=Qs(e.inputs,1),a=Qs(e.inputs,2),o=Qs(e.inputs,3),d=Qs(e.inputs,4),p=Qs(e.inputs,5),h=Qs(e.inputs,6),k=Qs(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let S=i&&a&&i.dims.length===4&&a.dims.length===4,u=xn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,o,0);if(S)return Rn(e,u,i,a,d,void 0,h,k,p,s);if(!i||!a)throw new Error("key and value must be provided");let B=xn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,i,o,s.hiddenSize),R=xn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,a,o,2*s.hiddenSize);Rn(e,u,B,R,d,void 0,h,k,p,s)}}),md,la,fd,_d,Ti,gd,wd,ua=g(()=>{Bt(),Dt(),Ct(),Xt(),md=e=>{if(!e||e.length<1)throw new Error("too few inputs")},la=(e,t)=>{let s=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>s.push(Number(i))),n=s.length),it({numOutputs:n,axis:t.axis,splitSizes:s})},fd=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Mt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,_d=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=Se.size(s),i=e[0].dataType,a=Se.normalizeAxis(t.axis,s.length),o=new Array(t.numOutputs),d=De("input",i,s.length),p=new Array(t.numOutputs),h=[],k=[],S=0,u=[{type:12,data:n}];for(let R=0;R` ${R.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(d,...o)} ${fd(p.length)} ${_d(o)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${d.offsetToIndices("global_idx")}; var index = ${d.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Mt("uniforms.size_in_split_axis","output_number - 1u",p.length)}; ${d.indicesSet("indices",a,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:B,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u})}},gd=(e,t)=>{md(e.inputs);let s=e.inputs.length===1?t:la(e.inputs,t);e.compute(Ti(e.inputs,s),{inputs:[0]})},wd=e=>{let t=e.axis,s=e.splitSizes,n=e.numOutputs<0?s.length:e.numOutputs;if(n!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return it({axis:t,numOutputs:n,splitSizes:s})}}),yd,Md,da,bd,rp=g(()=>{Ct(),ro(),hd(),ua(),Nr(),yd=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,p=s.dims[0],h=s.dims[1],k=s.dims.length===3?d?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],S=h,u=0,B=!n||n.dims.length===0,R=Math.floor(B?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);B&&(k=R*t.numHeads);let U=a&&a.dims.length!==0,Z=o&&o.dims.length!==0;if(U&&a.dims.length===4&&a.dims[0]===p&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===R)throw new Error("BSNH pastKey/pastValue is not supported");if(U&&Z){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=a.dims[2]}else if(U||Z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te=1;if(n&&n.dims.length>0){if(s.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(s.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(s.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');S=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==R)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');S=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==R)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');S=n.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}let Q=0,fe=!1,me=t.kvNumHeads?R*t.kvNumHeads:k;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(S!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');me=i.dims[2]}else{if(S!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');me=i.dims[1]*i.dims[3],fe=!0}}let Me=e.length>4?e[5]:void 0;if(Me&&Me.dims.length!==1&&Me.dims[0]!==p)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:p,sequenceLength:h,pastSequenceLength:u,kvSequenceLength:S,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:me,headSize:R,vHeadSize:Math.floor(me/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:Q,scale:t.scale,broadcastResPosBias:!1,passPastInKv:fe,qkvFormat:te}},Md=it({perm:[0,2,1,3]}),da=(e,t,s)=>{let n=t,i=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(n=t.reshape([s.batchSize,s.kvSequenceLength,i,s.headSize]),n=e.compute(ar(n,Md.perm),{inputs:[n],outputs:[-1]})[0]),n},bd=(e,t)=>{var Z;let s=yd(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((Z=e.inputs[1])==null?void 0:Z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,d=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,k=s.kvNumHeads?s.kvNumHeads:s.numHeads,S=it({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,k*s.headSize,k*s.headSize]}),[u,B,R]=!i&&!a?e.compute(Ti([n],S),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,a],U=xn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,u,void 0,0);Rn(e,U,da(e,B,s),da(e,R,s),void 0,void 0,o,d,void 0,s,p,h)}}),ca,vd,Td,xd,Ed=g(()=>{Bt(),Dt(),Nr(),Xt(),ca=(e,t,s,n,i,a,o,d)=>{let p=os(a),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,S=i*o,u=64;S===1&&(u=256);let B=[i,o,a/p],R=[i,o,2],U=["rank","type","type"],Z=[];Z.push(...Tt(B,R));let te=Q=>{let fe=De("x",t.dataType,3,p),me=De("scale",s.dataType,s.dims),Me=De("bias",n.dataType,n.dims),$e=yt("output",1,3,2),Ae=[fe,me,Me,$e];return` var workgroup_shared : array<${k}, ${u}>; const workgroup_size = ${u}u; ${Q.declareVariables(...Ae)} ${Q.mainStart(u)} 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 = ${h}(0); var squared_sum = ${h}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${h}(${fe.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${k}(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 = ${Gs("workgroup_shared[0][0]",p)} / f32(hight * ${p}); let squared_sum_final = ${Gs("workgroup_shared[0][1]",p)} / f32(hight * ${p}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${d})); 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:`${p};${d};${u}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:R,dataType:1}],dispatchGroup:{x:S},programUniforms:Z}),getShaderSource:te},{inputs:[t,s,n],outputs:[-1]})[0]},vd=(e,t,s)=>{let n=t[0].dims,i=n,a=2,o=n[0],d=n[1],p=Se.sizeFromDimension(n,a),h=os(p),k=Se.size(i)/h,S=ca(e,t[0],t[1],t[2],o,p,d,s.epsilon),u=[o,d,p/h],B=[o,d],R=["type","none"],U=Z=>{let te=De("x",t[0].dataType,u.length,h),Q=De("scale_shift",1,B.length,2),fe=yt("output",t[0].dataType,u.length,h),me=[te,Q,fe];return` ${Z.registerUniform("output_size","u32").declareVariables(...me)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${fe.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${Q.getByIndices("vec2(batch, channel)")}; let value = ${te.getByOffset("global_idx")} * ${fe.type.value}(scale_shift.x) + ${fe.type.value}(scale_shift.y); ${fe.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...Tt(u,B,u)]}),getShaderSource:U},{inputs:[t[0],S]})},Td=(e,t,s)=>{let n=t[0].dims,i=n,a=n[0],o=n[n.length-1],d=Se.sizeFromDimension(n,1)/o,p=os(o),h=Se.size(i)/p,k=[{type:12,data:d},{type:12,data:Math.floor(o/p)}],S=["type","type"],u=!1,B=[0,n.length-1];for(let te=0;ten[B[Q]])),U=ca(e,R,t[1],t[2],a,d,o,s.epsilon),Z=te=>{let Q=es(t[0].dataType),fe=p===1?"vec2f":`mat${p}x2f`,me=Ae=>{let Ge=Ae===0?"x":"y",lt=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${Q}(${lt}(scale.${Ge}))`;case 2:return`vec2<${Q}>(${lt}(scale[0].${Ge}, scale[1].${Ge}))`;case 4:return`vec4<${Q}>(${lt}(scale[0].${Ge}, scale[1].${Ge}, scale[2].${Ge}, scale[3].${Ge}))`;default:throw new Error(`Not supported compoents ${p}`)}},Me=De("input",t[0].dataType,t[0].dims,p),$e=yt("output",t[0].dataType,i,p);return` @group(0) @binding(0) var input : array<${Me.type.storage}>; @group(0) @binding(1) var scale_input : array<${fe}>; @group(0) @binding(2) var output : array<${$e.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${te.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], ${me(0)}, ${me(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:Z},{inputs:[t[0],U]})},xd=(e,t)=>{t.format==="NHWC"?Td(e,e.inputs,t):vd(e,e.inputs,t)}}),Pd,Cd,pa,np=g(()=>{Bt(),Dt(),Xt(),Pd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Cd=(e,t,s)=>{let n=t.simplified,i=e[0].dims,a=e[1],o=!n&&e[2],d=i,p=Se.normalizeAxis(t.axis,i.length),h=Se.sizeToDimension(i,p),k=Se.sizeFromDimension(i,p),S=Se.size(a.dims),u=o?Se.size(o.dims):0;if(S!==k||o&&u!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. Size of scale and bias (if provided) must match this. Got scale size of ${S} and bias size of ${u}`);let B=[];for(let Me=0;Me1,Q=s>2,fe=Me=>{let $e=es(e[0].dataType),Ae=[De("x",e[0].dataType,e[0].dims,R),De("scale",a.dataType,a.dims,R)];o&&Ae.push(De("bias",o.dataType,o.dims,R)),Ae.push(yt("output",e[0].dataType,d,R)),te&&Ae.push(yt("mean_data_output",1,B)),Q&&Ae.push(yt("inv_std_output",1,B));let Ge=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${Me.registerUniforms(Ge).declareVariables(...Ae)} ${Me.mainStart()} ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Er("f32",R)}; var mean_square_vector = ${Er("f32",R)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Ds($e,R,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Gs("mean_vector",R)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Gs("mean_square_vector",R)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Ds($e,R,"x[j + offset]")}; let f32scale = ${Ds($e,R,"scale[j]")}; output[j + offset] = ${Ae[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${o?`+ ${Ds($e,R,"bias[j]")}`:""} ); } ${te?"mean_data_output[global_idx] = mean":""}; ${Q?"inv_std_output[global_idx] = inv_std_dev":""}; }`},me=[{dims:d,dataType:e[0].dataType}];return te&&me.push({dims:B,dataType:1}),Q&&me.push({dims:B,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${R};${s};${n}`,inputDependencies:U},getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:Z}),getShaderSource:fe}},pa=(e,t)=>{Pd(e.inputs),e.compute(Cd(e.inputs,t,e.outputCount))}}),kd,gs,Wp=g(()=>{Dt(),Io(),zo(),kd=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.")},gs=e=>{kd(e.inputs);let t=ns.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let s=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(s<8&&n<8)e.compute(Ao(e.inputs,{activation:""},t));else{let i=t[t.length-2],a=Se.size(e.inputs[0].dims.slice(0,-2)),o=Se.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&i===1&&o===1){let d=e.inputs[0].reshape([1,a,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,a,s],k=[d,p];e.compute(hi(k,{activation:""},t,h),{inputs:k})}else e.compute(hi(e.inputs,{activation:""},t))}}}),ip,op,ha,Sd,$d,ap=g(()=>{Bt(),Dt(),Ct(),Xt(),ip=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,o=e[1];if(!Se.areEqual(o.dims,[t.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(Se.size(d)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(Se.size(p)!==h)throw new Error("zeroPoints input size error.")}},op=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],a=t.k,o=t.n,d=s.slice(0,n-2),p=Se.size(d),h=e[1].dims[2]/4,k=e[0].dataType,S=os(t.k),u=os(h),B=os(o),R=d.concat([i,o]),U=i>1&&o/B%2===0?2:1,Z=Se.size(R)/B/U,te=64,Q=[],fe=[p,i,a/S],me=Se.convertShape(e[1].dims).slice();me.splice(-1,1,h/u),Q.push(...Tt(fe)),Q.push(...Tt(me)),Q.push(...Tt(e[2].dims)),e.length===4&&Q.push(...Tt(Se.convertShape(e[3].dims)));let Me=[p,i,o/B];Q.push(...Tt(Me));let $e=Ae=>{let Ge=fe.length,lt=De("a",e[0].dataType,Ge,S),Et=De("b",12,me.length,u),Kt=De("scales",e[2].dataType,e[2].dims.length),Yt=[lt,Et,Kt],kt=e.length===4?De("zero_points",12,e[3].dims.length):void 0;kt&&Yt.push(kt);let Jt=Me.length,$t=yt("output",e[0].dataType,Jt,B),jt=es(e[0].dataType),bs=(()=>{switch(S){case 1:return`array<${jt}, 8>`;case 2:return`mat4x2<${jt}>`;case 4:return`mat2x4<${jt}>`;default:throw new Error(`${S}-component is not supported.`)}})(),Ht=()=>{let nt=` // reuse a data var input_offset = ${lt.indicesToOffset(`${lt.type.indices}(batch, row, word_offset)`)}; var a_data: ${bs}; for (var j: u32 = 0; j < ${8/S}; j++) { a_data[j] = ${lt.getByOffset("input_offset")}; input_offset++; } `;for(let Pt=0;Pt> 4) & b_mask); b_quantized_values = ${bs}(${Array.from({length:4},(ps,zs)=>`${jt}(b_value_lower[${zs}]), ${jt}(b_value_upper[${zs}])`).join(", ")}); b_dequantized_values = ${S===1?`${bs}(${Array.from({length:8},(ps,zs)=>`(b_quantized_values[${zs}] - ${kt?`zero_point${Pt}`:"zero_point"}) * scale${Pt}`).join(", ")});`:`(b_quantized_values - ${bs}(${Array(8).fill(`${kt?`zero_point${Pt}`:"zero_point"}`).join(",")})) * scale${Pt};`}; workgroup_shared[local_id.x * ${U} + ${Math.floor(Pt/B)}]${B>1?`[${Pt%B}]`:""} += ${Array.from({length:8/S},(ps,zs)=>`${S===1?`a_data[${zs}] * b_dequantized_values[${zs}]`:`dot(a_data[${zs}], b_dequantized_values[${zs}])`}`).join(" + ")}; `;return nt},Gt=()=>{let nt=` var col_index = col * ${B}; ${kt?` 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 = ${jt}(8);`} `;for(let Pt=0;Pt> 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 = ${kt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${Pt} = ${jt}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return nt},Cs=()=>{let nt=`col_index = col * ${B};`;for(let Pt=0;Pt; var b_value_upper: vec4; var b_quantized_values: ${bs}; var b_dequantized_values: ${bs};`,nt};return` var workgroup_shared: array<${$t.type.value}, ${U*te}>; ${Ae.declareVariables(...Yt,$t)} ${Ae.mainStart([te,1,1])} let output_indices = ${$t.offsetToIndices(`(global_idx / ${te}) * ${U}`)}; 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 += ${te}) { //process one block var word_offset: u32 = block * ${t.blockSize/S}; ${Gt()} for (var word: u32 = 0; word < ${h}; word += ${u}) { ${Cs()} for (var i: u32 = 0; i < ${u}; i++) { ${Ht()} word_offset += ${8/S}; } } } workgroupBarrier(); if (local_id.x < ${U}) { var output_value: ${$t.type.value} = ${$t.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${te}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${U}; } ${$t.setByIndices(`${$t.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${S};${u};${B};${U};${te}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:R,dataType:k}],dispatchGroup:{x:Z},programUniforms:Q}),getShaderSource:$e}},ha=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],a=t.k,o=t.n,d=s.slice(0,n-2),p=Se.size(d),h=e[1].dims[2]/4,k=e[0].dataType,S=os(t.k),u=os(h),B=d.concat([i,o]),R=128,U=o%8===0?8:o%4===0?4:1,Z=R/U,te=Z*u*8,Q=te/S,fe=te/t.blockSize,me=Se.size(B)/U,Me=[],$e=[p,i,a/S],Ae=Se.convertShape(e[1].dims).slice();Ae.splice(-1,1,h/u),Me.push(...Tt($e)),Me.push(...Tt(Ae)),Me.push(...Tt(e[2].dims)),e.length===4&&Me.push(...Tt(Se.convertShape(e[3].dims)));let Ge=[p,i,o];Me.push(...Tt(Ge));let lt=Et=>{let Kt=$e.length,Yt=De("a",e[0].dataType,Kt,S),kt=De("b",12,Ae.length,u),Jt=De("scales",e[2].dataType,e[2].dims.length),$t=[Yt,kt,Jt],jt=e.length===4?De("zero_points",12,e[3].dims.length):void 0;jt&&$t.push(jt);let bs=Ge.length,Ht=yt("output",e[0].dataType,bs),Gt=es(e[0].dataType),Cs=()=>{switch(S){case 1:return` let a_data0 = vec4<${Gt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Gt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${Gt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Gt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${S}-component is not supported.`)}};return` var sub_a: array<${Yt.type.value}, ${Q}>; var inter_results: array, ${U}>; ${Et.declareVariables(...$t,Ht)} ${Et.mainStart([Z,U,1])} let output_indices = ${Ht.offsetToIndices(`workgroup_index * ${U}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let n_blocks_per_col = uniforms.b_shape[1]; let num_tiles = (n_blocks_per_col - 1) / ${fe} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${Q}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${Q}; a_offset += ${R}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${Yt.getByIndices(`${Yt.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${Yt.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${fe} + local_id.x; ${jt?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${jt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Gt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Gt}(8);`} let scale = ${Jt.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${kt.getByIndices(`${kt.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/S}; for (var i: u32 = 0; i < ${u}; i++) { ${Cs()} let b_value = ${u===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${Gt}>(${Array.from({length:4},(nt,Pt)=>`${Gt}(b_value_lower[${Pt}]), ${Gt}(b_value_upper[${Pt}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Gt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(nt,Pt)=>`${`dot(a_data${Pt}, b_dequantized_values[${Pt}])`}`).join(" + ")}; word_offset += ${8/S}; } workgroupBarrier(); } if (local_idx < ${U}) { var output_value: ${Ht.type.value} = ${Ht.type.value}(0); for (var b = 0u; b < ${Z}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${Ht.setByIndices(`${Ht.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${S};${u};${Z};${U}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:k}],dispatchGroup:{x:me},programUniforms:Me}),getShaderSource:lt}},Sd=(e,t)=>{ip(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(ha(e.inputs,t)):e.compute(op(e.inputs,t))},$d=e=>it(e)}),Ad,ma,fa,lp,Id,Od,_a,up,dp,cp=g(()=>{Bt(),Dt(),Xt(),Ad=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].")}},ma=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Mt("uniforms.pads",i,s)}; if (k < 0) { break; } if (k >= i32(${Mt("uniforms.x_shape",i,t)})) { break; } offset += k * i32(${Mt("uniforms.x_strides",i,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `},fa=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Mt("uniforms.pads",i,s)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Mt("uniforms.x_shape",i,t)}) - 1); k = k % _2n_1; if(k >= i32(${Mt("uniforms.x_shape",i,t)})) { k = _2n_1 - k; } } offset += k * i32(${Mt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},lp=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Mt("uniforms.pads",i,s)}; if (k < 0) { k = 0; } if (k >= i32(${Mt("uniforms.x_shape",i,t)})) { k = i32(${Mt("uniforms.x_shape",i,t)}) - 1; } offset += k * i32(${Mt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},Id=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Mt("uniforms.pads",i,s)}; if (k < 0) { k += i32(${Mt("uniforms.x_shape",i,t)}]); } if (k >= i32(${Mt("uniforms.x_shape",i,t)})) { k -= i32(${Mt("uniforms.x_shape",i,t)}); } offset += k * i32(${Mt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},Od=(e,t,s)=>{switch(s.mode){case 0:return ma(e,t,s.pads.length);case 1:return fa(e,t,s.pads.length);case 2:return lp(e,t,s.pads.length);case 3:return Id(e,t,s.pads.length);default:throw new Error("Invalid mode")}},_a=(e,t)=>{let s=Se.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=Se.size(s),a=[{type:12,data:i},{type:6,data:t.pads}],o=e.length>=3&&e[2].data;t.mode===0&&a.push({type:o?e[2].dataType:1,data:t.value}),a.push(...Tt(e[0].dims,s));let d=["rank"],p=h=>{let k=yt("output",e[0].dataType,s.length),S=De("x",e[0].dataType,n.length),u=S.type.value,B=Od(k,n.length,t),R=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&R.push({name:"constant_value",type:o?u:"f32"}),` ${h.registerUniforms(R).declareVariables(S,k)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${k.offsetToIndices("global_idx")}; var value = ${u}(0); ${B} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${o}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(s)/64)},programUniforms:a}),getShaderSource:p}},up=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let d=e[3].getBigInt64Array();for(let p=0;pa[Number(p)]=Number(d));let o=[];return a.forEach(d=>o.push(d)),{mode:t.mode,value:n,pads:o}}else return t},dp=(e,t)=>{Ad(e.inputs);let s=up(e.inputs,t);e.compute(_a(e.inputs,s),{inputs:[0]})}}),Vn,ga,wa,ya,Ma,Fd,Dd,ba,va,Ld,zd,Bd,Rd,Nd,Ta,jd,Ud,Wd,pp,Vd=g(()=>{Qe(),Bt(),Dt(),Xt(),Vn=e=>{if(T.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},ga=(e,t,s)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),o=t.kernelShape.slice(),d=t.strides.slice(),p=a?t.dilations.slice():[],h=t.pads.slice();ys.adjustPoolAttributes(s,i,o,d,p,h);let k=ys.computePoolOutputShape(s,i,d,p,o,h,t.autoPad),S=Object.assign({},t);a?Object.assign(S,{kernelShape:o,strides:d,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(S,{kernelShape:o,strides:d,pads:h,cacheKey:t.cacheKey});let u=k.slice();return u.push(u.splice(1,1)[0]),[S,n?u:k]},wa=(e,t)=>{let s=t.format==="NHWC",n=Se.size(e),i=Se.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:i}],o=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let d=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],k=t.pads[t.pads.length-1],S=!!(h+k);a.push({type:12,data:d},{type:12,data:p},{type:12,data:h},{type:12,data:k}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(t.kernelShape.length===2){let B=t.kernelShape[t.kernelShape.length-2],R=t.strides[t.strides.length-2],U=t.pads[t.pads.length/2-2],Z=t.pads[t.pads.length-2];u=!!(U+Z),a.push({type:12,data:B},{type:12,data:R},{type:12,data:U},{type:12,data:Z}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,o,!0,S,u]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=Se.computeStrides(t.kernelShape);a.push({type:12,data:d},{type:12,data:t.pads},{type:12,data:t.strides}),o.push({name:"kernelStrides",type:"u32",length:d.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,k)=>h+k);return[a,o,!!p,!1,!1]}},ya=(e,t,s,n,i,a,o,d,p,h,k,S)=>{let u=i.format==="NHWC",B=t.type.value,R=yt("output",t.type.tensor,n);if(i.kernelShape.length<=2){let U="",Z="",te="",Q=s-(u?2:1);if(k?U=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${Q}] = indices[${Q}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${Q}] < 0 || xIndices[${Q}] >= uniforms.x_shape[${Q}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:U=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${Q}] = indices[${Q}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`,i.kernelShape.length===2){let fe=s-(u?3:2);S?Z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${fe}] = indices[${fe}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${fe}] < 0 || xIndices[${fe}] >= uniforms.x_shape[${fe}]) { pad += i32(uniforms.kw); continue; } `:Z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${fe}] = indices[${fe}] * uniforms.sh - uniforms.phStart + j; `,te=` } `}return` ${e.registerUniforms(p).declareVariables(t,R)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${R.offsetToIndices("global_idx")}; var xIndices = ${R.offsetToIndices("global_idx")}; var value = ${B}(${d}); var pad = 0; ${Z} ${U} ${te} ${o} output[global_idx] = value; }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let U=i.kernelShape.length,Z=i.pads.length,te="";return h?te=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:te=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} `,` ${e.registerUniforms(p).declareVariables(t,R)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${R.offsetToIndices("global_idx")}; var xIndices = ${R.offsetToIndices("global_idx")}; var offsets: array; var value = ${B}(${d}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${U-1}u; j++) { offsets[j] = offset / ${Mt("uniforms.kernelStrides","j",U)}; offset -= offsets[j] * ${Mt("uniforms.kernelStrides","j",U)}; } offsets[${U-1}] = offset; isPad = false; for (var j = ${s-U}u; j < ${s}u; j++) { xIndices[j] = indices[j] * ${Mt("uniforms.strides",`j - ${s-U}u`,U)} + offsets[j - ${s-U}u] - ${Mt("uniforms.pads","j - 2u",Z)}; ${te} } ${o} output[global_idx] = value; }`}},Ma=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Fd=e=>`${Ma(e)};${e.countIncludePad}`,Dd=e=>`${Ma(e)};${e.storageOrder};${e.dilations}`,ba=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}),va=(e,t,s,n)=>{let[i,a]=ga(t,n,s),o=De("x",t.dataType,t.dims.length),d=o.type.value,p="value += x_val;",h="";i.countIncludePad?h+=`value /= ${d}(uniforms.kernelSize);`:h+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[k,S,u,B,R]=wa(a,i);k.push(...Tt(t.dims,a));let U=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${u};${B};${R}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:k}),getShaderSource:Z=>ya(Z,o,t.dims.length,a.length,i,p,h,0,S,u,B,R)}},Ld=e=>{let t=e.count_include_pad!==0,s=ba(e);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...s,cacheKey:""};return{...n,cacheKey:Fd(n)}},zd=(e,t)=>{Vn(e.inputs),e.compute(va("AveragePool",e.inputs[0],!1,t))},Bd={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Rd=e=>{let t=e.format;return{format:t,...Bd,cacheKey:t}},Nd=(e,t)=>{Vn(e.inputs),e.compute(va("GlobalAveragePool",e.inputs[0],!0,t))},Ta=(e,t,s,n)=>{let[i,a]=ga(t,n,s),o=` value = max(x_val, value); `,d="",p=De("x",t.dataType,t.dims.length),h=["rank"],[k,S,u,B,R]=wa(a,i);return k.push(...Tt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${u};${B};${R}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:k}),getShaderSource:U=>ya(U,p,t.dims.length,a.length,i,o,d,t.dataType===10?-65504:-1e5,S,u,B,R)}},jd=(e,t)=>{Vn(e.inputs),e.compute(Ta("MaxPool",e.inputs[0],!1,t))},Ud=e=>{let t=e.storage_order,s=e.dilations,n=ba(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:s,...n,cacheKey:""};return{...i,cacheKey:Dd(i)}},Wd=e=>{let t=e.format;return{format:t,...Bd,cacheKey:t}},pp=(e,t)=>{Vn(e.inputs),e.compute(Ta("GlobalMaxPool",e.inputs[0],!0,t))}}),Gd,Kd,Hd,qd,hp=g(()=>{Bt(),Dt(),Ct(),Xt(),Gd=(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((s,n)=>s===e[2].dims[n]).reduce((s,n)=>s&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((i,a)=>a===t.axis||i===e[0].dims[a]).reduce((i,a)=>i&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let s=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(s/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Kd=(e,t)=>{let s=Se.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,a=e[0].dims,o=e[1].dataType,d=Se.size(a),p=n===3||n===2,h=p?[Math.ceil(Se.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,S=e.length>2?e[2]:void 0,u=S?p?[Math.ceil(Se.size(S.dims)/4)]:S.dims:void 0,B=k.length===0||k.length===1&&k[0]===1,R=B===!1&&k.length===1,U=os(d),Z=B&&(!p||U===4),te=Z?U:1,Q=Z&&!p?U:1,fe=De("input",p?12:n,h.length,Q),me=De("scale",o,k.length),Me=S?De("zero_point",p?12:n,u.length):void 0,$e=yt("output",o,a.length,te),Ae=[fe,me];Me&&Ae.push(Me);let Ge=[h,k];S&&Ge.push(u);let lt=[{type:12,data:d/te},{type:12,data:s},{type:12,data:t.blockSize},...Tt(...Ge,a)],Et=Kt=>{let Yt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${Kt.registerUniforms(Yt).declareVariables(...Ae,$e)} ${Kt.mainStart()} ${Kt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${$e.offsetToIndices("global_idx")}; // Set input x ${p?` let input = ${fe.getByOffset("global_idx / 4")}; let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${te===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${fe.getByOffset("global_idx")};`}; // Set scale input ${B?`let scale_value= ${me.getByOffset("0")}`:R?` let scale_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${me.getByOffset("scale_index")};`:` var scale_indices: ${me.type.indices} = output_indices; let index = ${me.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${me.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${me.getByIndices("scale_indices")};`}; // Set zero-point input ${Me?B?p?` let zero_point_input = ${Me.getByOffset("0")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Me.getByOffset("0")}`:R?p?` let zero_point_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${Me.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${Me.getByOffset("zero_point_index")};`:p?` let zero_point_offset = ${me.indicesToOffset("scale_indices")}; let zero_point_input = ${Me.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Me.getByIndices("scale_indices")};`:`let zero_point_value = ${p?i?"i32":"u32":fe.type.value}(0);`}; // Compute and write output ${$e.setByOffset("global_idx",`${$e.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:Me?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Et,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(d/te/64),y:1,z:1},programUniforms:lt})}},Hd=(e,t)=>{Gd(e.inputs,t),e.compute(Kd(e.inputs,t))},qd=e=>it({axis:e.axis,blockSize:e.blockSize})}),Xd,Qd,Yd,mp=g(()=>{Qe(),Bt(),Xt(),Xd=(e,t,s)=>{let n=e===t,i=et&&s>0;if(n||i||a)throw new Error("Range these inputs' contents are invalid.")},Qd=(e,t,s,n)=>{let i=Math.abs(Math.ceil((t-e)/s)),a=[i],o=i,d=[{type:12,data:o},{type:n,data:e},{type:n,data:s},...Tt(a)],p=h=>{let k=yt("output",n,a.length),S=k.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:S},{name:"delta",type:S}];return` ${h.registerUniforms(u).declareVariables(k)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${S}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:d})}},Yd=e=>{let t=0,s=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),T.webgpu.validateInputContent&&Xd(t,s,n),e.compute(Qd(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),Jd,Zd,ec,tc,fp=g(()=>{Bt(),Dt(),Ct(),Xt(),Jd=(e,t,s,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let i=`{ var oldValue = 0; loop { let newValueF32 =`,a=`; let newValue = bitcast(newValueF32); let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); if res.exchanged { break; } oldValue = res.old_value; } }`;switch(e){case"none":return`${t}=${s};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${s}));`:` ${i}bitcast<${n}>(oldValue) + (${s})${a}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${s}));`:` ${i}max(bitcast(oldValue), (${s}))${a}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${s}));`:`${i}min(bitcast<${n}>(oldValue), (${s}))${a}`;case"mul":return`${i}(bitcast<${n}>(oldValue) * (${s}))${a}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Zd=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s,a=1,o=Math.ceil(Se.size(n)/a),d=n[n.length-1],p=Se.sizeFromDimension(s,d),h=[{type:12,data:o},{type:12,data:d},{type:12,data:p},...Tt(e[1].dims,e[2].dims,i)],k=S=>{let u=De("indices",e[1].dataType,e[1].dims.length),B=De("updates",e[2].dataType,e[2].dims.length,a),R=t.reduction!=="none"&&t.reduction!==""?sr("output",e[0].dataType,i.length):yt("output",e[0].dataType,i.length,a);return` ${S.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(u,B,R)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var data_offset = 0u; let indices_start = uniforms.last_index_dimension * global_idx; let indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); ${e[0].dims.length===1?` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;`:` let element_count_dim = uniforms.output_strides[i - indices_start]; let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} if (index >= 0) { if (index >= i32(dim_value)) { index = i32(dim_value - 1); } } else { if (index < -i32(dim_value)) { index = 0; } else { index += i32(dim_value); } } data_offset += u32((u32(index) * element_count_dim)); } for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * global_idx + i]; ${Jd(t.reduction,"output[data_offset + i]","value",R.type.value)} } }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:h}),getShaderSource:k}},ec=e=>it({reduction:e.reduction}),tc=(e,t)=>{e.compute(Zd(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),sc,rc,nc,ic,oc,ac,lc,uc,dc,cc,pc,xa,hc,mc,_p,Qt,fc,Us,Ws,Ys=g(()=>{Bt(),Dt(),Ct(),Xt(),sc=(e,t)=>{if(e.every(s=>s>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")}},rc=(e,t,s)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(s).fill(1);return t.forEach((i,a)=>n[i]=e[a]),n},nc=(e,t,s,n,i,a)=>{let[o,d,p]=s>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(k=>a.push(k));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0){if(e[d].getFloat32Array().forEach(k=>n.push(k)),n.length!==0&&n.length!==h&&s>=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");sc(n,t),t.axes.length>0&&rc(n,t.axes,h).forEach((k,S)=>n[S]=k)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(k=>i.push(Number(k))),i.length!==0&&i.length!==h&&s>=18&&i.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof i<"u"&&n.length>0&&i.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},ic=(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`)}})()+"}",oc=(e,t,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{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`)}})()+"}",ac=(e,t,s)=>{let n=new Array(s).fill(0).concat(new Array(s).fill(1)),i=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,o)=>{n[a]=i[o],n[o+s]=i[t.length+o]}),n):i},lc=(e,t,s,n)=>{let i=[];if(s.length>0)if(n.length>0){if(e.forEach(a=>i.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,o)=>i[a]=s[o])}else s.forEach(a=>i.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((a,o)=>Math.round(a*t[o]))}return i},uc=(e,t,s)=>{let n=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return s.axes.length>0?(s.axes.forEach(a=>t[a]=n),s.axes.forEach(a=>i[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),i.forEach((a,o)=>i[o]=Math.round(a*t[o]))),i},dc=(e,t,s,n,i)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { var original_indices: array<${e.type.value}, ${s.length}>; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${Mt("uniforms.scales","i",n)}; var roi_low = ${Mt("uniforms.roi","i",i)}; var roi_hi = ${Mt("uniforms.roi",`i + ${t.length}`,i)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Mt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Mt("uniforms.output_shape","i",s.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,cc=(e,t,s,n,i,a,o)=>` 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 = ${Mt("uniforms.scales","i",i)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Mt("uniforms.roi","i",a)}; var roi_hi = ${Mt("uniforms.roi",`i + ${s.length}`,a)}; var input_shape_i = ${Mt("uniforms.input_shape","i",s.length)}; var output_shape_i = ${Mt("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${o} || (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; }`,pc=(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 >= ${Mt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,xa=(e,t,s,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",s,"batch")}; `:"",hc=(e,t,s,n,i)=>{let[a,o,d,p]=s.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(row, ${s[o]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(col, ${s[d]} - 1))`)}; ${xa(e,p,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${h} = originalIndices[${o}]; var col:${h} = originalIndices[${d}]; ${n?`if (row < 0 || row > (${s[o]} - 1) || col < 0 || col > (${s[d]} - 1)) { return ${i}; }`:""}; row = max(0, min(row, ${s[o]} - 1)); col = max(0, min(col, ${s[d]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; var batch: u32 = ${s.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${h} = getInputValue(batch, channel, row1, col1); var x12: ${h} = getInputValue(batch, channel, row1, col2); var x21: ${h} = getInputValue(batch, channel, row2, col1); var x22: ${h} = getInputValue(batch, channel, row2, col2); var dx1: ${h} = abs(row - ${h}(row1)); var dx2: ${h} = abs(${h}(row2) - row); var dy1: ${h} = abs(col - ${h}(col1)); var dy2: ${h} = abs(${h}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},mc=(e,t,s,n,i,a,o,d,p,h)=>{let k=s.length===2,[S,u]=k?[0,1]:[2,3],B=e.type.value,R=U=>{let Z=U===S?"row":"col";return` fn ${Z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${B} { var output_index = ${t.indicesGet("output_indices",U)}; var originalIdx: ${B} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[U]}, ${n[U]}, ${s[U]}, ${a[U]}, ${a[U]} + ${s.length}); var fractOriginalIdx: ${B} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${d} && (originalIdx < 0 || originalIdx > (${s[U]} - 1))) { return ${p}; } var data: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${Z}: ${B} = originalIdx + ${B}(i); if (${Z} < 0 || ${Z} >= ${s[U]}) { ${h?`coefs[i + 1] = 0.0; continue;`:d?`return ${p};`:`${Z} = max(0, min(${Z}, ${s[U]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",U,`u32(${Z})`)}; data[i + 1] = ${U===S?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${R(S)}; ${R(u)}; fn getCubicInterpolationCoefs(s: ${B}) -> array<${B}, 4> { var absS = abs(s); var coeffs: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${B} = 1.0 - absS; var twoMinusAbsS: ${B} = 2.0 - absS; var onePlusAbsS: ${B} = 1.0 + absS; coeffs[0] = ((${o} * onePlusAbsS - 5 * ${o}) * onePlusAbsS + 8 * ${o}) * onePlusAbsS - 4 * ${o}; coeffs[1] = ((${o} + 2) * absS - (${o} + 3)) * absS * absS + 1; coeffs[2] = ((${o} + 2) * oneMinusAbsS - (${o} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${o} * twoMinusAbsS - 5 * ${o}) * twoMinusAbsS + 8 * ${o}) * twoMinusAbsS - 4 * ${o}; return coeffs; } fn cubicInterpolation1D(x: array<${B}, 4>, coefs: array<${B}, 4>) -> ${B} { var coefsSum: ${B} = 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}) -> ${B} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},_p=(e,t,s,n,i)=>{let[a,o,d,p,h]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],k=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${k} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(depth, ${s[o]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(height, ${s[d]} - 1))`)}; ${e.indicesSet("input_indices",p,`max(0, min(width, ${s[p]} - 1))`)}; ${xa(e,h,a,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${k} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${k} = originalIndices[${o}]; var height:${k} = originalIndices[${d}]; var width:${k} = originalIndices[${p}]; ${n?`if (depth < 0 || depth > (${s[o]} - 1) || height < 0 || height > (${s[d]} - 1) || width < 0 || (width > ${s[p]} - 1)) { return ${i}; }`:""}; depth = max(0, min(depth, ${s[o]} - 1)); height = max(0, min(height, ${s[d]} - 1)); width = max(0, min(width, ${s[p]} - 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 = ${s.length>3?`u32(originalIndices[${h}])`:"0"}; var batch: u32 = ${s.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${k} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${k} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${k} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${k} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${k} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${k} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${k} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${k} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${k} = abs(depth - ${k}(depth1)); var dx2: ${k} = abs(${k}(depth2) - depth); var dy1: ${k} = abs(height - ${k}(height1)); var dy2: ${k} = abs(${k}(height2) - height); var dz1: ${k} = abs(width - ${k}(width1)); var dz2: ${k} = abs(${k}(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); }`},Qt=(e,t,s,n,i,a)=>{let o=e.dims,d=ac(a,t.axes,o.length),p=lc(o,n,i,t.axes),h=n.slice();n.length===0&&(h=o.map((Q,fe)=>Q===0?1:p[fe]/Q),t.keepAspectRatioPolicy!=="stretch"&&(p=uc(o,h,t)));let k=yt("output",e.dataType,p.length),S=De("input",e.dataType,o.length),u=Se.size(p),B=o.length===p.length&&o.every((Q,fe)=>Q===p[fe]),R=t.coordinateTransformMode==="tf_crop_and_resize",U=t.extrapolationValue,Z=S.type.value,te=Q=>` ${B?"":` ${ic(t.coordinateTransformMode,Z)}; ${(()=>{switch(t.mode){case"nearest":return` ${pc(S,o)}; ${oc(t.nearestMode,s,Z)}; ${cc(S,k,o,p,h.length,d.length,R)}; `;case"linear":return` ${dc(k,o,p,h.length,d.length)}; ${(()=>{if(o.length===2||o.length===4)return`${hc(S,k,o,R,U)}`;if(o.length===3||o.length===5)return`${_p(S,k,o,R,U)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(o.length===2||o.length===4)return`${mc(S,k,o,p,h,d,t.cubicCoeffA,R,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")}})()}; `} ${Q.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",d.length).declareVariables(S,k)} ${Q.mainStart()} ${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${B?"output[global_idx] = input[global_idx];":` let output_indices = ${k.offsetToIndices("global_idx")}; var input_indices: ${S.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${S.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${o.length===2||o.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}|${s}|${h.length>0?h:""}|${i.length>0?i:""}|${d.length>0?d:""}|${B}|${o}`,inputDependencies:["rank"]},getShaderSource:te,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:h},{type:1,data:d},...Tt(o,p)]})}},fc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Us=(e,t)=>{let s=[],n=[],i=[],a=fc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");nc(e.inputs,t,a,s,n,i),e.compute(Qt(e.inputs[0],t,a,s,n,i),{inputs:[0]})},Ws=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,o=e.extrapolationValue,d=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return it({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:a,extrapolationValue:o,keepAspectRatioPolicy:d,mode:p,nearestMode:h})}}),on,gp,_c,wp=g(()=>{Bt(),Dt(),Ct(),Xt(),on=(e,t)=>{let[s,n,i,a]=e,{numHeads:o,rotaryEmbeddingDim:d}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!Se.areEqual(n.dims,[])&&!Se.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Se.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>0&&o===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=s.dims[0],h=s.dims[s.dims.length-2],k=i.dims[0],S=Se.sizeFromDimension(s.dims,1)/h,u=d===0?i.dims[1]*2:S/o;if(d>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(u/2!==i.dims[1]&&d/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},gp=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:i,scale:a}=t,o=e[0].dims[0],d=Se.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=d/p,k=e[2].dims[1],S=i===0?k*2:h/n,u=new Array(o,p,h/S,S-k),B=Se.computeStrides(u),R=[{type:1,data:a},{type:12,data:u},{type:12,data:B},...e[0].dims.length===3?new Array({type:12,data:[d,h,S,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,S,p*S,1]}):[],...Tt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],U=Z=>{let te=De("input",e[0].dataType,e[0].dims.length),Q=De("position_ids",e[1].dataType,e[1].dims.length),fe=De("cos_cache",e[2].dataType,e[2].dims.length),me=De("sin_cache",e[3].dataType,e[3].dims.length),Me=yt("output",e[0].dataType,e[0].dims.length);return Z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:B.length},{name:"input_output_strides",type:"u32",length:B.length}]),` ${Z.declareVariables(te,Q,fe,me,Me)} ${Z.mainStart(Ns)} let half_rotary_emb_dim = uniforms.${fe.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${Z.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${Q.broadcastedIndicesToOffset("bsnh.xy",yt("",Q.type.tensor,2))}; let position_id = u32(${Q.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); let j = i + select(half_rotary_emb_dim, 1, ${s}); let re = ${te.getByOffset("i")} * ${fe.get("position_id","bsnh[3]")} - ${te.getByOffset("j")} * ${me.get("position_id","bsnh[3]")}; ${Me.setByOffset("i","re")} let im = ${te.getByOffset("i")} * ${me.get("position_id","bsnh[3]")} + ${te.getByOffset("j")} * ${fe.get("position_id","bsnh[3]")}; ${Me.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${Me.setByOffset("k",te.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:it({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:U,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(u)/Ns)},programUniforms:R})}},_c=(e,t)=>{on(e.inputs,t),e.compute(gp(e.inputs,t))}}),f,P,W,be=g(()=>{Bt(),Dt(),Xt(),f=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],n=e[2];if(t.dataType!==s.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(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(s.dims[s.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let o=e[3];if(o.dims.length!==1)throw new Error("Beta must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let o=e[4];if(o.dims.length!==1)throw new Error("Bias must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},P=(e,t,s,n)=>{let i=t.simplified,a=e[0].dims,o=Se.size(a),d=a,p=o,h=a.slice(-1)[0],k=n?a.slice(0,-1).concat(1):[],S=!i&&e.length>3,u=e.length>4,B=n&&s>1,R=n&&s>2,U=s>3,Z=64,te=os(h),Q=[{type:12,data:p},{type:12,data:te},{type:12,data:h},{type:1,data:t.epsilon}],fe=Me=>{let $e=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ae=[De("x",e[0].dataType,e[0].dims,te),De("skip",e[1].dataType,e[1].dims,te),De("gamma",e[2].dataType,e[2].dims,te)];S&&Ae.push(De("beta",e[3].dataType,e[3].dims,te)),u&&Ae.push(De("bias",e[4].dataType,e[4].dims,te)),Ae.push(yt("output",e[0].dataType,d,te)),B&&Ae.push(yt("mean_output",1,k)),R&&Ae.push(yt("inv_std_output",1,k)),U&&Ae.push(yt("input_skip_bias_sum",e[0].dataType,d,te));let Ge=es(e[0].dataType),lt=es(1,te);return` ${Me.registerUniforms($e).declareVariables(...Ae)} var sum_shared : array<${lt}, ${Z}>; var sum_squared_shared : array<${lt}, ${Z}>; ${Me.mainStart([Z,1,1])} let ix = local_id.x; let iy = global_id.x / ${Z}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${Z}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${Z-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${u?"bias[offset1d + i]":Ge+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${U?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Ds(Ge,te,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${Z}; for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { reduce_size = curr_size + (reduce_size & 1); if (ix < curr_size) { sum_shared[ix] += sum_shared[ix + reduce_size]; sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; } workgroupBarrier(); } let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; let mean = ${Gs("sum",te)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Gs("square_sum",te)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); ${B?"mean_output[global_idx] = mean;":""} ${R?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${i?"":`- ${Ge}(mean)`}) * ${Ge}(inv_std_dev) * gamma[offset1d + i] ${S?"+ beta[offset1d + i]":""}; } }`},me=[{dims:d,dataType:e[0].dataType}];return s>1&&me.push({dims:k,dataType:1}),s>2&&me.push({dims:k,dataType:1}),s>3&&me.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${te};${B};${R};${U}`,inputDependencies:e.map((Me,$e)=>"type")},getShaderSource:fe,getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:Q})}},W=(e,t)=>{f(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(P(e.inputs,t,e.outputCount,!1),{outputs:s})}}),Ie,ke,Ye,tt,ft,vt,Rt,Ut,Lt=g(()=>{Bt(),Dt(),Ct(),Xt(),Ie=(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((s,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`)})},ke=(e,t)=>{let s=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>s.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>s.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return s},Ye=(e,t)=>{if(e.length>1){let s=ke(e,1),n=ke(e,2),i=ke(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),it({starts:s,ends:n,axes:i})}else return t},tt=(e,t,s,n,i)=>{let a=e;return e<0&&(a+=s[n[t]]),i[t]<0?Math.max(0,Math.min(a,s[n[t]]-1)):Math.max(0,Math.min(a,s[n[t]]))},ft=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${s.length}; i >= 0; i--) { let input_shape_i = ${Mt("uniforms.input_shape","i",s.length)}; let steps_i = ${Mt("uniforms.steps","i",s.length)}; let signs_i = ${Mt("uniforms.signs","i",s.length)}; let starts_i = ${Mt("uniforms.starts","i",s.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; }`,vt=(e,t)=>{let s=e[0].dims,n=Se.size(s),i=t.axes.length>0?Se.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],a=ke(e,4);a.forEach(te=>te!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((te,Q)=>tt(te,Q,s,i,a)),d=t.ends.map((te,Q)=>tt(te,Q,s,i,a));if(i.length!==o.length||i.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==s.length)for(let te=0;teMath.sign(te));a.forEach((te,Q,fe)=>{if(te<0){let me=(d[Q]-o[Q])/te,Me=o[Q],$e=Me+me*a[Q];o[Q]=$e,d[Q]=Me,fe[Q]=-te}});let h=s.slice(0);i.forEach((te,Q)=>{h[te]=Math.ceil((d[te]-o[te])/a[te])});let k={dims:h,dataType:e[0].dataType},S=yt("output",e[0].dataType,h.length),u=De("input",e[0].dataType,e[0].dims.length),B=Se.size(h),R=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:a.length}],U=[{type:12,data:B},{type:12,data:o},{type:6,data:p},{type:12,data:a},...Tt(e[0].dims,h)],Z=te=>` ${te.registerUniforms(R).declareVariables(u,S)} ${ft(u,S,s)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${S.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${S.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${o.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:Z,getRunData:()=>({outputs:[k],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:U})}},Rt=(e,t)=>{Ie(e.inputs,t);let s=Ye(e.inputs,t);e.compute(vt(e.inputs,s),{inputs:[0]})},Ut=e=>{let t=e.starts,s=e.ends,n=e.axes;return it({starts:t,ends:s,axes:n})}}),Vt,Zt,ss,qt,as=g(()=>{Bt(),Dt(),Ct(),Nr(),Xt(),Vt=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Zt=(e,t)=>{let s=e.inputs[0],n=s.dims,i=Se.size(n),a=n.length,o=Se.normalizeAxis(t.axis,a),d=oGe),h[o]=a-1,h[a-1]=o,p=e.compute(ar(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let k=p.dims,S=k[a-1],u=i/S,B=os(S),R=S/B,U=64;u===1&&(U=256);let Z=(Ae,Ge)=>Ge===4?`max(max(${Ae}.x, ${Ae}.y), max(${Ae}.z, ${Ae}.w))`:Ge===2?`max(${Ae}.x, ${Ae}.y)`:Ge===3?`max(max(${Ae}.x, ${Ae}.y), ${Ae}.z)`:Ae,te=De("x",p.dataType,p.dims,B),Q=yt("result",p.dataType,p.dims,B),fe=te.type.value,me=es(p.dataType)==="f32"?`var threadMax = ${fe}(-3.402823e+38f);`:`var threadMax = ${fe}(-65504.0h);`,Me=Ae=>` var rowMaxShared : ${fe}; var rowSumShared : ${fe}; var threadShared : array<${fe}, ${U}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${fe} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${fe}) { let index = row * row_stride + col; result[index] = value; } ${Ae.registerUniform("packedCols","i32").declareVariables(te,Q)} ${Ae.mainStart(U)} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${U}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${me} 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 = ${fe}(${Z("threadShared[0]",B)}); } workgroupBarrier(); // find the rows sum var threadSum = ${fe}(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 = ${fe}(${Gs("threadShared[0]",B)}); } 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); } }`,$e=e.compute({name:"Softmax",shaderCache:{hint:`${B};${U}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:R}]}),getShaderSource:Me},{inputs:[p],outputs:[d?-1:0]})[0];d&&e.compute(ar($e,h),{inputs:[$e]})},ss=(e,t)=>{Vt(e.inputs),Zt(e,t)},qt=e=>it({axis:e.axis})}),xs,vs,cs,Es,$s,Hs=g(()=>{Bt(),Dt(),Xt(),xs=e=>Array.from(e.getBigInt64Array(),Number),vs=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(xs(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")},cs=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??xs(e[1]),i=cs(s,n),a=Se.size(i),o=e[0].dataType,d=De("input",o,s.length),p=yt("output",o,i.length),h=k=>` const inputShape = ${d.indices(...s)}; ${k.registerUniform("output_size","u32").declareVariables(d,p)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${p.offsetToIndices("global_idx")}; var input_indices: ${d.type.indices}; for (var i = 0; i < ${s.length}; i++) { let input_dim_i = ${d.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; ${d.indicesSet("input_indices","i","input_dim_value")} } ${p.setByOffset("global_idx",d.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...Tt(e[0].dims,i)]}),getShaderSource:h}},$s=e=>{vs(e.inputs),e.compute(Es(e.inputs),{inputs:[0]})}}),js,_r,En,gc=g(()=>{Bt(),Dt(),Xt(),js=(e,t,s,n,i)=>{let a=yt("output_data",i,s.length,4),o=De("a_data",t[1].dataType,t[1].dims.length,4),d=De("b_data",t[2].dataType,t[2].dims.length,4),p=De("c_data",t[0].dataType,t[0].dims.length,4),h,k=(S,u,B)=>`select(${u}, ${S}, ${B})`;if(!n)h=a.setByOffset("global_idx",k(o.getByOffset("global_idx"),d.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let S=(u,B,R="")=>{let U=`a_data[index_a${B}][component_a${B}]`,Z=`b_data[index_b${B}][component_b${B}]`,te=`bool(c_data[index_c${B}] & (0xffu << (component_c${B} * 8)))`;return` let output_indices${B} = ${a.offsetToIndices(`global_idx * 4u + ${B}u`)}; let offset_a${B} = ${o.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let offset_b${B} = ${d.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let offset_c${B} = ${p.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let index_a${B} = offset_a${B} / 4u; let index_b${B} = offset_b${B} / 4u; let index_c${B} = offset_c${B} / 4u; let component_a${B} = offset_a${B} % 4u; let component_b${B} = offset_b${B} % 4u; let component_c${B} = offset_c${B} % 4u; ${u}[${B}] = ${R}(${k(U,Z,te)}); `};i===9?h=` var data = vec4(0); ${S("data",0,"u32")} ${S("data",1,"u32")} ${S("data",2,"u32")} ${S("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` ${S("output_data[global_idx]",0)} ${S("output_data[global_idx]",1)} ${S("output_data[global_idx]",2)} ${S("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(p,o,d,a)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${h} }`},_r=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,i=e[1].dataType,a=!(Se.areEqual(t,s)&&Se.areEqual(s,n)),o=t,d=Se.size(t);if(a){let h=ns.calcShape(ns.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");o=h,d=Se.size(o)}let p=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>js(h,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:p},...Tt(n,t,s,o)]})}},En=e=>{e.compute(_r(e.inputs))}}),rr,Ar=g(()=>{Dc(),ro(),Lc(),zc(),Bc(),Rc(),du(),Wc(),Gc(),Kc(),Hc(),yi(),qc(),Up(),Xc(),Qc(),Jc(),Zc(),ep(),dd(),rp(),Ed(),np(),Wp(),ap(),hd(),cp(),Vd(),hp(),mp(),fp(),ai(),Ys(),wp(),be(),Lt(),as(),ua(),Hs(),Nr(),vo(),gc(),rr=new Map([["Abs",[vl]],["Acos",[lo]],["Acosh",[Tl]],["Add",[Zl]],["ArgMax",[Ji,Zi]],["ArgMin",[ml,Zi]],["Asin",[xl]],["Asinh",[uo]],["Atan",[El]],["Atanh",[Pl]],["Attention",[gl]],["AveragePool",[zd,Ld]],["BatchNormalization",[io]],["BiasAdd",[bl]],["BiasSplitGelu",[Ql]],["Cast",[Cl,co]],["Ceil",[$l]],["Clip",[Sl]],["Concat",[lu,uu]],["Conv",[Ko,Wo]],["ConvTranspose",[Cu,Qo]],["Cos",[po]],["Cosh",[Al]],["CumSum",[Jo,Su]],["DepthToSpace",[Wr,Iu]],["DequantizeLinear",[Hd,qd]],["Div",[eu]],["Einsum",[Bu,Ru]],["Elu",[ho,Nn]],["Equal",[xo]],["Erf",[Il]],["Exp",[mo]],["Expand",[Mi]],["FastGelu",[Vu]],["Floor",[Ol]],["FusedConv",[Ko,Wo]],["Gather",[Tn,Hu]],["GatherElements",[td,ta]],["GatherBlockQuantized",[Yu,Ju]],["GatherND",[Xu,Qu]],["Gelu",[Fl]],["Gemm",[ra,rd]],["GlobalAveragePool",[Nd,Rd]],["GlobalMaxPool",[pp,Wd]],["Greater",[ru]],["GreaterOrEqual",[Po]],["GridSample",[ld,ud]],["GroupQueryAttention",[bd]],["HardSigmoid",[Rl,go]],["InstanceNormalization",[xd]],["LayerNormalization",[pa]],["LeakyRelu",[fo,Nn]],["Less",[nu]],["LessOrEqual",[iu]],["Log",[Kl]],["MatMul",[gs]],["MatMulNBits",[Sd,$d]],["MaxPool",[jd,Ud]],["Mul",[tu]],["MultiHeadAttention",[aa,oa]],["Neg",[Ll]],["Not",[Dl]],["Pad",[dp]],["Pow",[su]],["QuickGelu",[ql,Nn]],["Range",[Yd]],["Reciprocal",[_o]],["ReduceMin",[dl]],["ReduceMean",[al]],["ReduceMax",[Xi]],["ReduceSum",[Qi]],["ReduceProd",[cl]],["ReduceL1",[qi]],["ReduceL2",[ll]],["ReduceLogSum",[hl]],["ReduceLogSumExp",[ul]],["ReduceSumSquare",[pl]],["Relu",[zl]],["Resize",[Us,Ws]],["RotaryEmbedding",[_c]],["ScatterND",[tc,ec]],["Sigmoid",[Bl]],["Sin",[Nl]],["Sinh",[wo]],["Slice",[Rt,Ut]],["SkipLayerNormalization",[W]],["Split",[gd,wd]],["Sqrt",[jl]],["Softmax",[ss,qt]],["Sub",[Eo]],["Tan",[Ul]],["Tanh",[Wl]],["ThresholdedRelu",[Gl,Nn]],["Tile",[$s]],["Transpose",[Na,Ni]],["Where",[En]]])}),Ea,Pa=g(()=>{Qe(),tr(),Xt(),Ea=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,s,n,i){Ve(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let h of t)d.push({binding:d.length,resource:{buffer:h.buffer}});for(let h of s)d.push({binding:d.length,resource:{buffer:h.buffer}});i&&d.push({binding:d.length,resource:i});let p=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:d,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}o.setPipeline(e.computePipeline),o.setBindGroup(0,p),o.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(),Ne(e.programInfo.name)}dispose(){}build(e,t){Ve(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{s.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let i=La(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${n.join(` `)} ${i.additionalImplementations} ${a}`,d=s.createShaderModule({code:o,label:e.name});is("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let p=s.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return Ne(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&s<=i&&n<=i)return[t,s,n];let a=t*s*n,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),xi,Ei,Ps,Ls,Vr,Pn=g(()=>{Qe(),Bt(),tr(),Bn(),wt(),Ar(),Pa(),xi=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let n=0;n{var i,a;let n=e.name;return(i=e.shaderCache)!=null&&i.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+s+`:${xi(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Ps=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Ls=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;!this.subgroupsSupported||!t.minSubgroupSize||!t.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]}},Vr=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 s=[],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:s},i=a=>t.features.has(a)&&s.push(a)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups")&&i("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new Ls(this.device),this.adapterInfo=new Ps(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ct(this),this.programManager=new Ea(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,yn(e.logLevel,!!e.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.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;Ve(),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()),s=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=B);let U=Number(B-this.queryTimeBase),Z=Number(R-this.queryTimeBase);if(!Number.isSafeInteger(U)||!Number.isSafeInteger(Z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:S.map(te=>({dims:te.dims,dataType:Tr(te.dataType)})),outputsMetadata:u.map(te=>({dims:te.dims,dataType:Tr(te.dataType)})),kernelId:o,kernelType:p,kernelName:h,programName:k,startTime:U,endTime:Z});else{let te="";S.forEach((fe,me)=>{te+=`input[${me}]: [${fe.dims}] | ${Tr(fe.dataType)}, `});let Q="";u.forEach((fe,me)=>{Q+=`output[${me}]: [${fe.dims}] | ${Tr(fe.dataType)}, `}),console.log(`[profiling] kernel "${o}|${p}|${h}|${k}" ${te}${Q}execution time: ${Z-U} ns`)}Re("GPU",`${k}::${B}::${R}`)}e.unmap(),this.pendingQueries.delete(e)}),Ne()}run(e,t,s,n,i,a){Ve(e.name);let o=[];for(let Q=0;Qfe):s;if(k.length!==d.length)throw new Error(`Output size ${k.length} must be equal to ${d.length}.`);let S=[],u=[];for(let Q=0;Q=a)throw new Error(`Invalid output index: ${k[Q]}`);if(k[Q]===-3)continue;let fe=k[Q]===-1,me=k[Q]===-2,Me=fe||me?i(d[Q].dataType,d[Q].dims):n(k[Q],d[Q].dataType,d[Q].dims);if(S.push(Me),Me.data===0)continue;let $e=this.gpuDataManager.get(Me.data);if(!$e)throw new Error(`no GPU data for output: ${Me.data}`);if(fe&&this.temporaryData.push($e),me){let Ae=this.kernelPersistentData.get(this.currentKernelId);Ae||(Ae=[],this.kernelPersistentData.set(this.currentKernelId,Ae)),Ae.push($e)}u.push($e)}if(o.length!==t.length||u.length!==S.length){if(u.length===0)return Ne(e.name),S;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let B;if(h){let Q=0,fe=[];h.forEach(Ae=>{let Ge=typeof Ae.data=="number"?[Ae.data]:Ae.data;if(Ge.length===0)return;let lt=Ae.type===10?2:4,Et,Kt;Ae.type===10?(Kt=Ge.length>4?16:Ge.length>2?8:Ge.length*lt,Et=Ge.length>4?16:lt*Ge.length):(Kt=Ge.length<=2?Ge.length*lt:16,Et=16),Q=Math.ceil(Q/Kt)*Kt,fe.push(Q);let Yt=Ae.type===10?8:4;Q+=Ge.length>4?Math.ceil(Ge.length/Yt)*Et:Ge.length*lt});let me=16;Q=Math.ceil(Q/me)*me;let Me=new ArrayBuffer(Q);h.forEach((Ae,Ge)=>{let lt=fe[Ge],Et=typeof Ae.data=="number"?[Ae.data]:Ae.data;if(Ae.type===6)new Int32Array(Me,lt,Et.length).set(Et);else if(Ae.type===12)new Uint32Array(Me,lt,Et.length).set(Et);else if(Ae.type===10)new Uint16Array(Me,lt,Et.length).set(Et);else if(Ae.type===1)new Float32Array(Me,lt,Et.length).set(Et);else throw new Error(`Unsupported uniform type: ${Tr(Ae.type)}`)});let $e=this.gpuDataManager.create(Q,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer($e.buffer,0,Me,0,Q),this.gpuDataManager.release($e.id),B={offset:0,size:Q,buffer:$e.buffer}}let R=this.programManager.normalizeDispatchGroupSize(p),U=R[1]===1&&R[2]===1,Z=Ei(e,t,U),te=this.programManager.getArtifact(Z);if(te||(te=this.programManager.build(e,R),this.programManager.setArtifact(Z,te),is("info",()=>`[artifact] key: ${Z}, programName: ${e.name}`)),h&&te.uniformVariablesInfo){if(h.length!==te.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${te.uniformVariablesInfo.length}, got ${h.length} in program "${te.programInfo.name}".`);for(let Q=0;Q`[ProgramManager] run "${e.name}" (key=${Z}) with ${R[0]}x${R[1]}x${R[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let Q={kernelId:this.currentKernelId,programName:te.programInfo.name,inputTensorViews:t,outputTensorViews:S};this.pendingKernels.push(Q),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(Q)}return this.programManager.run(te,o,u,R,B),Ne(e.name),S}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,s,n){let i=rr.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[1],s]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let i=n.kernelType,a=n.kernelName,o=n.kernelEntry,d=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),is("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),o(t,d[1]),0}catch(h){return s.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${h}`)),1}finally{p&&s.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${i}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(s,n,a);return i.set(t,[o,s]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let n=await Pe(this,e,t);return Mn(n.buffer,s)}}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(){is("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(){is("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){is("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Cn,Gn,Ca,Pi,Ci,wc,ka,ki,yc=g(()=>{tr(),Cn=1,Gn=()=>Cn++,Ca=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Pi=(e,t)=>{let s=Ca.get(e);if(!s)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,i)=>n*i)*s/8):0},Ci=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Pi(this.dataType,this.tensorShape)}destroy(){is("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every((s,n)=>s===t[n])}},wc=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Pi(e,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,!0,!0),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else is("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},ka=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Gn();return this.tensorTrackersById.set(e,new wc(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,n){is("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(t,s,n)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){is("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,n){let i=Gn(),a=new Ci({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(i,new wc(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,s,n,i){let a=this.backend.currentSessionId;for(let[p,h]of this.freeTensors.entries())if(h.sameTypeAndShape(e,t)){is("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=a,k}let o=this.backend.currentContext;is("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let d=await o.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:i});return new Ci({sessionId:a,context:o,tensor:d,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},ki=(...e)=>new ka(...e)}),Sa,$a,Si,Vp=g(()=>{Bt(),It(),Bn(),yc(),tr(),Sa=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),$a=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),n=Object.keys(t).sort();return s.length===n.length&&s.every((i,a)=>i===n[a]&&e[i]===t[i])},Si=class{constructor(e){this.tensorManager=ki(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],yn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let s=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(s=>$a(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(i=>i.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){is("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let i=Sa.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,s,n)}uploadTensor(e,t){if(!pt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");is("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return Mn(s,t)}}registerMLTensor(e,t,s){let n=Sa.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,n,s);return is("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${i}}`),i}registerMLConstant(e,t,s,n,i,a){if(!a)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let d=a.get(o);if(!d)throw new Error(`File with name ${o} not found in preloaded files.`);if(t+s>d.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=d.slice(t,t+s).buffer,h;switch(i.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return is("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),n.constant(i,h)}flush(){}}}),yp={};b(yp,{init:()=>gr});var Aa,an,gr,Af=g(()=>{Bt(),Pn(),tr(),Dt(),Vp(),Aa=class mf{constructor(t,s,n,i){this.module=t,this.dataType=s,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Se.size(t)!==Se.size(this.dims))throw new Error("Invalid new shape");return new mf(this.module,this.dataType,this.data,t)}},an=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,i=s/e.PTR_SIZE,a=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*i++,a));let o=Number(e.getValue(n*i++,a));this.outputCount=Number(e.getValue(n*i++,a)),this.customDataOffset=Number(e.getValue(n*i++,"*")),this.customDataSize=Number(e.getValue(n*i++,a));let d=[];for(let p=0;ptypeof d=="number"?this.inputs[d]:d))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(d,p,h)=>new Aa(this.module,p,this.output(d,h),h),a=(d,p)=>{let h=er(d,p);if(!h)throw new Error(`Unsupported data type: ${d}`);let k=h>0?this.backend.gpuDataManager.create(h).id:0;return new Aa(this.module,d,k,p)};return this.backend.run(e,s,n,i,a,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,i=n===4?"i32":"i64",a=this.module.stackAlloc((1+t.length)*n);this.module.setValue(a,t.length,i);for(let o=0;o{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Vr;await a.initialize(s,n),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,d,p,h=!1)=>{if(h)is("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(d)}, size=${Number(p)}`),a.memcpy(Number(o),Number(d));else{is("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(d)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(p));a.upload(Number(d),k)}},async(o,d,p)=>{is("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${d}, size=${p}`),await a.download(Number(o),()=>t.HEAPU8.subarray(Number(d)>>>0,Number(d+p)>>>0))},(o,d,p)=>a.createKernel(o,Number(d),p,t.UTF8ToString(t._JsepGetNodeName(Number(d)))),o=>a.releaseKernel(o),(o,d,p,h)=>{is("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${o}, contextDataOffset=${d}`);let k=new an(t,a,Number(d));return a.computeKernel(Number(o),k,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new Si(s);i("webnn",[a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,d,p,h)=>a.ensureTensor(o,d,p,h),(o,d)=>{a.uploadTensor(o,d)},async(o,d)=>a.downloadTensor(o,d)])}}}),Ah,Gp,Kp,Kn,Ih,Mp,Hp,qp,Xp,Qp,Yp,Jp,Oh=g(()=>{Xr(),si(),Bt(),It(),br(),On(),Ah=(e,t)=>{pt()._OrtInit(e,t)!==0&&ts("Can't initialize onnxruntime.")},Gp=async e=>{Ah(e.wasm.numThreads,Qr(e.logLevel))},Kp=async(e,t)=>{{let s=(Af(),M(yp)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await s("webgpu",pt(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",pt(),e)}}},Kn=new Map,Ih=e=>{let t=pt(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,i,i+n)!==0&&ts("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(i,a)),Number(t.getValue(i+n,a))]}finally{t.stackRestore(s)}},Mp=e=>{let t=pt(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Hp=async(e,t)=>{var S,u,B;let s,n,i=pt();Array.isArray(e)?[s,n]=e:e.buffer===i.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=Mp(e);let a=0,o=0,d=0,p=[],h=[],k=[];try{if([o,p]=In(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let Me=[];for(let $e of t.externalData){let Ae=typeof $e=="string"?$e:$e.path;Me.push(wn(typeof $e=="string"?$e:$e.data).then(Ge=>{i.mountExternalData(Ae,Ge)}))}await Promise.all(Me)}for(let Me of(t==null?void 0:t.executionProviders)??[])if((typeof Me=="string"?Me:Me.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof Me!="string"){let $e=Me,Ae=$e==null?void 0:$e.context,Ge=$e==null?void 0:$e.gpuDevice,lt=$e==null?void 0:$e.deviceType,Et=$e==null?void 0:$e.powerPreference;Ae?i.currentContext=Ae:Ge?i.currentContext=await i.jsepCreateMLContext(Ge):i.currentContext=await i.jsepCreateMLContext({deviceType:lt,powerPreference:Et})}else i.currentContext=await i.jsepCreateMLContext();break}a=await i._OrtCreateSession(s,n,o),a===0&&ts("Can't create a session."),(S=i.jsepOnCreateSession)==null||S.call(i),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[R,U]=Ih(a),Z=!!(t!=null&&t.enableGraphCapture),te=[],Q=[],fe=[];for(let Me=0;MeMe==="gpu-buffer"||Me==="ml-tensor")&&(d=i._OrtCreateBinding(a),d===0&&ts("Can't create IO binding."),me={handle:d,outputPreferredLocations:fe,outputPreferredLocationsEncoded:fe.map(Me=>gn(Me))}),Kn.set(a,[a,h,k,me,Z,!1]),[a,te,Q]}catch(R){throw h.forEach(U=>i._OrtFree(U)),k.forEach(U=>i._OrtFree(U)),d!==0&&i._OrtReleaseBinding(d)!==0&&ts("Can't release IO binding."),a!==0&&i._OrtReleaseSession(a)!==0&&ts("Can't release session."),R}finally{i._free(s),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&ts("Can't release session options."),p.forEach(R=>i._free(R)),(B=i.unmountExternalData)==null||B.call(i)}},qp=e=>{var p;let t=pt(),s=Kn.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,a,o,d]=s;o&&(d&&t._OrtClearBoundOutputs(o.handle)!==0&&ts("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&ts("Can't release IO binding.")),(p=t.jsepOnReleaseSession)==null||p.call(t,e),i.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n)!==0&&ts("Can't release session."),Kn.delete(e)},Xp=(e,t,s,n,i,a=!1)=>{if(!e){t.push(0);return}let o=pt(),d=o.PTR_SIZE,p=e[0],h=e[1],k=e[3],S,u;if(p==="string"&&(k==="gpu-buffer"||k==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&k!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(k==="gpu-buffer"){let U=e[2].gpuBuffer;u=er(Br(p),h);let Z=o.jsepRegisterBuffer;if(!Z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');S=Z(n,i,U,u)}else if(k==="ml-tensor"){let U=e[2].mlTensor;u=er(Br(p),h);let Z=o.jsepRegisterMLTensor;if(!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');S=Z(U,Br(p),h)}else{let U=e[2];if(Array.isArray(U)){u=d*U.length,S=o._malloc(u),s.push(S);for(let Z=0;Zo.setValue(R+te*d,Z,d===4?"i32":"i64"));let U=o._OrtCreateTensor(Br(p),S,u,R,h.length,gn(k));U===0&&ts(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(U)}finally{o.stackRestore(B)}},Qp=async(e,t,s,n,i,a)=>{var Kt,Yt;let o=pt(),d=o.PTR_SIZE,p=Kn.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],S=p[2],u=p[3],B=p[4],R=p[5],U=t.length,Z=n.length,te=0,Q=[],fe=[],me=[],Me=[],$e=o.stackSave(),Ae=o.stackAlloc(U*d),Ge=o.stackAlloc(U*d),lt=o.stackAlloc(Z*d),Et=o.stackAlloc(Z*d);try{(Kt=o.jsepOnRunStart)==null||Kt.call(o,h),[te,Q]=cr(a);for(let $t=0;$tAs*Ts,1);Cs=Tr(ps);let Ii=u==null?void 0:u.outputPreferredLocations[n[$t]];if(Cs==="string"){if(Ii==="gpu-buffer"||Ii==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let As=[];for(let Ts=0;Ts0){let As=o.jsepGetBuffer;if(!As)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ts=As(nt),qn=er(ps,ln);if(qn===void 0||!_n(Cs))throw new Error(`Unsupported data type: ${Cs}`);Gt=!0,Jt.push([Cs,Vs,{gpuBuffer:Ts,download:o.jsepCreateDownloader(Ts,qn,Cs),dispose:()=>{o._OrtReleaseTensor(jt)!==0&&ts("Can't release tensor.")}},"gpu-buffer"])}else if(Ii==="ml-tensor"&&ln>0){let As=o.jsepEnsureTensor;if(!As)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(er(ps,ln)===void 0||!Yr(Cs))throw new Error(`Unsupported data type: ${Cs}`);let Ts=await As(nt,ps,Vs,!1);Gt=!0,Jt.push([Cs,Vs,{mlTensor:Ts,download:o.jsepCreateMLTensorDownloader(nt,Cs),dispose:()=>{o.jsepReleaseTensorId(nt),o._OrtReleaseTensor(jt)}},"ml-tensor"])}else{let As=fn(Cs),Ts=new As(ln);new Uint8Array(Ts.buffer,Ts.byteOffset,Ts.byteLength).set(o.HEAPU8.subarray(nt,nt+Ts.byteLength)),Jt.push([Cs,Vs,Ts,"cpu"])}}finally{o.stackRestore(bs),Cs==="string"&&nt&&o._free(nt),Gt||o._OrtReleaseTensor(jt)}}return u&&!B&&(o._OrtClearBoundOutputs(u.handle)!==0&&ts("Can't clear bound outputs."),Kn.set(e,[h,k,S,u,B,!1])),Jt}finally{o.stackRestore($e),fe.forEach(kt=>o._OrtReleaseTensor(kt)),me.forEach(kt=>o._OrtReleaseTensor(kt)),Me.forEach(kt=>o._free(kt)),te!==0&&o._OrtReleaseRunOptions(te),Q.forEach(kt=>o._free(kt))}},Yp=e=>{let t=pt(),s=Kn.get(e);if(!s)throw new Error("invalid session id");let n=s[0],i=t._OrtEndProfiling(n);i===0&&ts("Can't get an profile file name."),t._OrtFree(i)},Jp=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Hn,wr,Ia,Mc,bc,bp,Zp,vp,$i,Ai,Fh,Dh,Lh,zh,Bh,Rh,Nh,jh,Uh=g(()=>{Qe(),Oh(),It(),Sr(),Hn=()=>!!T.wasm.proxy&&typeof document<"u",Ia=!1,Mc=!1,bc=!1,vp=new Map,$i=(e,t)=>{let s=vp.get(e);s?s.push(t):vp.set(e,[t])},Ai=()=>{if(Ia||!Mc||bc||!wr)throw new Error("worker not ready")},Fh=e=>{switch(e.data.type){case"init-wasm":Ia=!1,e.data.err?(bc=!0,Zp[1](e.data.err)):(Mc=!0,Zp[0]()),bp&&(URL.revokeObjectURL(bp),bp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=vp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Dh=async()=>{if(!Mc){if(Ia)throw new Error("multiple calls to 'initWasm()' detected.");if(bc)throw new Error("previous call to 'initWasm()' failed.");if(Ia=!0,Hn())return new Promise((e,t)=>{wr==null||wr.terminate(),Hr().then(([s,n])=>{try{wr=n,wr.onerror=a=>t(a),wr.onmessage=Fh,Zp=[e,t];let i={type:"init-wasm",in:T};wr.postMessage(i),bp=s}catch(i){t(i)}},t)});try{await ot(T.wasm),await Gp(T),Mc=!0}catch(e){throw bc=!0,e}finally{Ia=!1}}},Lh=async e=>{if(Hn())return Ai(),new Promise((t,s)=>{$i("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:T}};wr.postMessage(n)});await Kp(T,e)},zh=async e=>Hn()?(Ai(),new Promise((t,s)=>{$i("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};wr.postMessage(n,[e.buffer])})):Mp(e),Bh=async(e,t)=>{if(Hn()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ai(),new Promise((s,n)=>{$i("create",[s,n]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),wr.postMessage(i,a)})}else return Hp(e,t)},Rh=async e=>{if(Hn())return Ai(),new Promise((t,s)=>{$i("release",[t,s]);let n={type:"release",in:e};wr.postMessage(n)});qp(e)},Nh=async(e,t,s,n,i,a)=>{if(Hn()){if(s.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ai(),new Promise((o,d)=>{$i("run",[o,d]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:a}};wr.postMessage(h,Jp(p))})}else return Qp(e,t,s,n,i,a)},jh=async e=>{if(Hn())return Ai(),new Promise((t,s)=>{$i("end-profiling",[t,s]);let n={type:"end-profiling",in:e};wr.postMessage(n)});Yp(e)}}),eh,Wh,Vh,If=g(()=>{Qe(),Uh(),Bt(),rt(),On(),eh=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Wh=e=>{switch(e[3]){case"cpu":return new pe(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!_n(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:i}=e[2];return pe.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!Yr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:i}=e[2];return pe.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Vh=class{async fetchModelAndCopyToWasmMemory(e){return zh(await wn(e))}async loadModel(e,t){Ve();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await Bh(s,t),Ne()}async dispose(){return Rh(this.sessionId)}async run(e,t,s){Ve();let n=[],i=[];Object.entries(e).forEach(S=>{let u=S[0],B=S[1],R=this.inputNames.indexOf(u);if(R===-1)throw new Error(`invalid input '${u}'`);n.push(B),i.push(R)});let a=[],o=[];Object.entries(t).forEach(S=>{let u=S[0],B=S[1],R=this.outputNames.indexOf(u);if(R===-1)throw new Error(`invalid output '${u}'`);a.push(B),o.push(R)});let d=n.map((S,u)=>eh(S,()=>`input "${this.inputNames[i[u]]}"`)),p=a.map((S,u)=>S?eh(S,()=>`output "${this.outputNames[o[u]]}"`):null),h=await Nh(this.sessionId,i,d,o,p,s),k={};for(let S=0;Ssh,initializeFlags:()=>th,wasmBackend:()=>Kh});var th,sh,Kh,Of=g(()=>{Qe(),Uh(),If(),Sr(),th=()=>{if((typeof T.wasm.initTimeout!="number"||T.wasm.initTimeout<0)&&(T.wasm.initTimeout=0),T.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 T.wasm.proxy!="boolean"&&(T.wasm.proxy=!1),typeof T.wasm.trace!="boolean"&&(T.wasm.trace=!1),typeof T.wasm.numThreads!="number"||!Number.isInteger(T.wasm.numThreads)||T.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)T.wasm.numThreads=1;else{let e=typeof navigator>"u"?j("node:os").cpus().length:navigator.hardwareConcurrency;T.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},sh=class{async init(e){th(),await Dh(),await Lh(e)}async createInferenceSessionHandler(e,t){let s=new Vh;return await s.loadModel(e,t),Promise.resolve(s)}},Kh=new sh});Qe(),Qe(),Qe();var Ff="1.21.0-dev.20241205-d27fecd3d3",Df=Oe;{let e=(Of(),M(Gh)).wasmBackend;H("webgpu",e,5),H("webnn",e,5),H("cpu",e,10),H("wasm",e,10)}Object.defineProperty(T.versions,"web",{value:Ff,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":(Le,A,r)=>{var _;r.r(A),r.d(A,{Tensor:()=>j.Tensor,createInferenceSession:()=>oe,deviceToExecutionProviders:()=>H,isONNXProxy:()=>Y,isONNXTensor:()=>z});var I=r("./src/env.js"),N=r("?2ce3"),X=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs"),j=r("./node_modules/onnxruntime-common/dist/esm/index.js");const g=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"}}),b=[];let y,M;const v=Symbol.for("onnxruntime");if(v in globalThis)M=globalThis[v];else if(I.apis.IS_NODE_ENV){switch(M=N??(_||(_=r.t(N,2))),process.platform){case"win32":b.push("dml");break;case"linux":process.arch==="x64"&&b.push("cuda");break}b.push("cpu"),y=["cpu"]}else M=X,I.apis.IS_WEBNN_AVAILABLE&&b.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),I.apis.IS_WEBGPU_AVAILABLE&&b.push("webgpu"),b.push("wasm"),y=["wasm"];const L=M.InferenceSession;function H(D=null){if(!D)return y;switch(D){case"auto":return b;case"gpu":return b.filter($=>["webgpu","cuda","dml","webnn-gpu"].includes($))}if(b.includes(D))return[g[D]??D];throw new Error(`Unsupported device: "${D}". Should be one of: ${b.join(", ")}.`)}let re=null;async function oe(D,$,w){re&&await re;const C=L.create(D,$);re??(re=C);const T=await C;return T.config=w,T}function z(D){return D instanceof M.Tensor}const V=M==null?void 0:M.env;V!=null&&V.wasm&&(V.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${I.env.version}/dist/`,V.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(V.wasm.numThreads=1)),V!=null&&V.webgpu&&(V.webgpu.powerPreference="high-performance");function Y(){var D;return(D=V==null?void 0:V.wasm)==null?void 0:D.proxy}I.env.backends.onnx=V},"./src/base/feature_extraction_utils.js":(Le,A,r)=>{r.r(A),r.d(A,{FeatureExtractor:()=>X,validate_audio_inputs:()=>j});var _=r("./src/utils/constants.js"),I=r("./src/utils/generic.js"),N=r("./src/utils/hub.js");class X extends I.Callable{constructor(b){super(),this.config=b}static async from_pretrained(b,y){const M=await(0,N.getModelJSON)(b,_.FEATURE_EXTRACTOR_NAME,!0,y);return new this(M)}}function j(g,b){var y;if(!(g instanceof Float32Array||g instanceof Float64Array))throw new Error(`${b} expects input to be a Float32Array or a Float64Array, but got ${((y=g==null?void 0:g.constructor)==null?void 0:y.name)??typeof g} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(Le,A,r)=>{r.r(A),r.d(A,{ImageProcessor:()=>D,post_process_instance_segmentation:()=>Y,post_process_object_detection:()=>v,post_process_panoptic_segmentation:()=>V,post_process_semantic_segmentation:()=>L});var _=r("./src/utils/generic.js"),I=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");r("./src/utils/image.js");var X=r("./src/utils/core.js"),j=r("./src/utils/hub.js"),g=r("./src/utils/constants.js");function b($,w,C=0,T=null){const ee=$/w;let J=(0,N.bankers_round)(ee)*w;return T!==null&&J>T&&(J=Math.floor(ee)*w),Jw&&he.push(Be)}else{let Be=(0,N.max)(se.data)[1];if(Be===ge-1||(xe=(0,N.softmax)(se.data),xe[Be]Xe*ze[(ie+1)%2])),qe.boxes.push(et),qe.classes.push(Be),qe.scores.push(xe[Be])}}Ce.push(qe)}return Ce}function L($,w=null){const C=$.logits,T=C.dims[0];if(w!==null&&w.length!==T)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ee=[];for(let J=0;Jze[he]&&(ze[he]=se[he],qe[he]=ue)}const Ue=new Array(ce.dims[0]);for(let ue=0;ueue!==void 0);ee.push({segmentation:Te,labels:ut})}return ee}function H($,w,C,T){const ee=[],J=[],le=[];for(let ce=0;ce<$.dims[0];++ce){const ge=$[ce],Ce=w[ce],Te=(0,N.max)(ge.data)[1];if(Te===T)continue;const qe=(0,N.softmax)(ge.data)[Te];qe>C&&(ee.push(Ce),J.push(qe),le.push(Te))}return[ee,J,le]}function re($,w,C,T=.5,ee=.8){const J=[];let le=0,ce=0;const ge=w[C].data;for(let Te=0;Te<$.length;++Te)$[Te]===C&&(J.push(Te),++le),ge[Te]>=T&&++ce;let Ce=le>0&&ce>0;return Ce&&(Ce=le/ce>ee),[Ce,J]}function oe($,w,C,T,ee,J=null,le=null){const[ce,ge]=le??$[0].dims,Ce=new I.Tensor("int32",new Int32Array(ce*ge),[ce,ge]),Te=[];if(le!==null)for(let ue=0;ue<$.length;++ue)$[ue]=(0,I.interpolate)($[ue],le,"bilinear",!1);const ze=new Int32Array($[0].data.length),qe=new Float32Array($[0].data.length);for(let ue=0;ue<$.length;++ue){let se=w[ue];const he=$[ue].data;for(let xe=0;xeqe[xe]&&(ze[xe]=ue,qe[xe]=he[xe])}let Ue=0;const ut=Ce.data;for(let ue=0;ue200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max($,w)/Math.min($,w)}`);let J=Math.round($/C)*C,le=Math.round(w/C)*C;if(J*le>ee){const ce=Math.sqrt($*w/ee);J=Math.floor($/ce/C)*C,le=Math.floor(w/ce/C)*C}else if(J*leJ?Ce=Math.floor(J*ge/ee):J>ee&&(ge=Math.floor(ee*Ce/J)),await w.resize(Ce,ge,{resample:T}))}async crop_margin(w,C=200){const T=w.clone().grayscale(),ee=(0,N.min)(T.data)[0],le=(0,N.max)(T.data)[0]-ee;if(le===0)return w;const ce=C/255;let ge=T.width,Ce=T.height,Te=0,ze=0;const qe=T.data;for(let Ue=0;Uethis.preprocess(J)));return{pixel_values:(0,I.stack)(T.map(J=>J.pixel_values),0),original_sizes:T.map(J=>J.original_size),reshaped_input_sizes:T.map(J=>J.reshaped_input_size)}}static async from_pretrained(w,C){const T=await(0,j.getModelJSON)(w,g.IMAGE_PROCESSOR_NAME,!0,C);return new this(T)}}},"./src/base/processing_utils.js":(Le,A,r)=>{r.r(A),r.d(A,{Processor:()=>X});var _=r("./src/utils/constants.js"),I=r("./src/utils/generic.js"),N=r("./src/utils/hub.js");class X extends I.Callable{constructor(g,b){super(),this.config=g,this.components=b}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(g,b={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(g,{tokenize:!1,...b})}batch_decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...g)}async _call(g,...b){for(const y of[this.image_processor,this.feature_extractor,this.tokenizer])if(y)return y(g,...b);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(g,b){const[y,M]=await Promise.all([this.uses_processor_config?(0,N.getModelJSON)(g,_.PROCESSOR_NAME,!0,b):{},Promise.all(this.classes.filter(v=>v in this).map(async v=>{const L=await this[v].from_pretrained(g,b);return[v.replace(/_class$/,""),L]})).then(Object.fromEntries)]);return new this(y,M)}}_e(X,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),_e(X,"uses_processor_config",!1)},"./src/configs.js":(Le,A,r)=>{r.r(A),r.d(A,{AutoConfig:()=>b,PretrainedConfig:()=>g,getKeyValueShapes:()=>j});var _=r("./src/utils/core.js"),I=r("./src/utils/hub.js");async function N(y,M){return await(0,I.getModelJSON)(y,"config.json",!0,M)}function X(y){const M={};let v={};switch(y.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":v=X(y.text_config);break;case"moondream1":v=X(y.phi_config);break;case"musicgen":v=X(y.decoder);break;case"multi_modality":v=X(y.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":M.num_heads="num_attention_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size",M.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.dim_kv="head_dim";break;case"openelm":M.num_heads="num_kv_heads",M.num_layers="num_transformer_layers",M.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":M.num_heads="num_heads",M.num_layers="num_layers",M.hidden_size="hidden_size";break;case"bloom":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="hidden_size";break;case"mpt":M.num_heads="n_heads",M.num_layers="n_layers",M.hidden_size="d_model";break;case"exaone":M.num_heads="num_key_value_heads",M.num_layers="num_layers",M.dim_kv="head_dim",M.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":M.num_decoder_layers="num_decoder_layers",M.num_decoder_heads="num_heads",M.decoder_dim_kv="d_kv",M.num_encoder_layers="num_layers",M.num_encoder_heads="num_heads",M.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":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="d_model",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="d_model";break;case"speecht5":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="hidden_size",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="hidden_size";break;case"trocr":M.num_encoder_layers=M.num_decoder_layers="decoder_layers",M.num_encoder_heads=M.num_decoder_heads="decoder_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":M.num_encoder_layers=M.num_decoder_layers="num_hidden_layers",M.num_encoder_heads=M.num_decoder_heads="num_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const H=X(y.decoder),re="num_decoder_layers"in H,oe=(0,_.pick)(y,["model_type","is_encoder_decoder"]);return re?(oe.num_decoder_layers=H.num_decoder_layers,oe.num_decoder_heads=H.num_decoder_heads,oe.decoder_hidden_size=H.decoder_hidden_size,oe.num_encoder_layers=H.num_encoder_layers,oe.num_encoder_heads=H.num_encoder_heads,oe.encoder_hidden_size=H.encoder_hidden_size):(oe.num_layers=H.num_layers,oe.num_heads=H.num_heads,oe.hidden_size=H.hidden_size),oe}const L={...v,...(0,_.pick)(y,["model_type","multi_query","is_encoder_decoder"])};for(const H in M)L[H]=y[M[H]];return L}function j(y,{prefix:M="past_key_values",batch_size:v=1}={}){const L={},H=y.normalized_config;if(H.is_encoder_decoder&&"num_encoder_heads"in H&&"num_decoder_heads"in H){const re=H.encoder_dim_kv??H.encoder_hidden_size/H.num_encoder_heads,oe=H.decoder_dim_kv??H.decoder_hidden_size/H.num_decoder_heads,z=[v,H.num_encoder_heads,0,re],V=[v,H.num_decoder_heads,0,oe];for(let Y=0;Y{var T,ee;r.r(A),r.d(A,{apis:()=>oe,env:()=>w});var _=r("?569f"),I=r("?3f59"),N=r("?154a");const X="3.2.0",j=typeof window<"u"&&typeof window.document<"u",g=typeof self<"u"&&((T=self.constructor)==null?void 0:T.name)==="DedicatedWorkerGlobalScope",b=typeof self<"u"&&"caches"in self,y=typeof navigator<"u"&&"gpu"in navigator,M=typeof navigator<"u"&&"ml"in navigator,v=typeof process<"u",L=v&&((ee=process==null?void 0:process.release)==null?void 0:ee.name)==="node",H=!C(_),re=!C(I),oe=Object.freeze({IS_BROWSER_ENV:j,IS_WEBWORKER_ENV:g,IS_WEB_CACHE_AVAILABLE:b,IS_WEBGPU_AVAILABLE:y,IS_WEBNN_AVAILABLE:M,IS_PROCESS_AVAILABLE:v,IS_NODE_ENV:L,IS_FS_AVAILABLE:H,IS_PATH_AVAILABLE:re}),z=H&&re;let V="./";if(z){const J=Object({url:self.location.href}).url;J?V=I.dirname(I.dirname(N.fileURLToPath(J))):typeof __dirname<"u"&&(V=I.dirname(__dirname))}const Y=z?I.join(V,"/.cache/"):null,D="/models/",$=z?I.join(V,D):D,w={version:X,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(j||g),localModelPath:$,useFS:H,useBrowserCache:b,useFSCache:H,cacheDir:Y,useCustomCache:!1,customCache:null};function C(J){return Object.keys(J).length===0}},"./src/generation/configuration_utils.js":(Le,A,r)=>{r.r(A),r.d(A,{GenerationConfig:()=>I});var _=r("./src/utils/core.js");class I{constructor(X){_e(this,"max_length",20);_e(this,"max_new_tokens",null);_e(this,"min_length",0);_e(this,"min_new_tokens",null);_e(this,"early_stopping",!1);_e(this,"max_time",null);_e(this,"do_sample",!1);_e(this,"num_beams",1);_e(this,"num_beam_groups",1);_e(this,"penalty_alpha",null);_e(this,"use_cache",!0);_e(this,"temperature",1);_e(this,"top_k",50);_e(this,"top_p",1);_e(this,"typical_p",1);_e(this,"epsilon_cutoff",0);_e(this,"eta_cutoff",0);_e(this,"diversity_penalty",0);_e(this,"repetition_penalty",1);_e(this,"encoder_repetition_penalty",1);_e(this,"length_penalty",1);_e(this,"no_repeat_ngram_size",0);_e(this,"bad_words_ids",null);_e(this,"force_words_ids",null);_e(this,"renormalize_logits",!1);_e(this,"constraints",null);_e(this,"forced_bos_token_id",null);_e(this,"forced_eos_token_id",null);_e(this,"remove_invalid_values",!1);_e(this,"exponential_decay_length_penalty",null);_e(this,"suppress_tokens",null);_e(this,"streamer",null);_e(this,"begin_suppress_tokens",null);_e(this,"forced_decoder_ids",null);_e(this,"guidance_scale",null);_e(this,"num_return_sequences",1);_e(this,"output_attentions",!1);_e(this,"output_hidden_states",!1);_e(this,"output_scores",!1);_e(this,"return_dict_in_generate",!1);_e(this,"pad_token_id",null);_e(this,"bos_token_id",null);_e(this,"eos_token_id",null);_e(this,"encoder_no_repeat_ngram_size",0);_e(this,"decoder_start_token_id",null);_e(this,"generation_kwargs",{});Object.assign(this,(0,_.pick)(X,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Le,A,r)=>{r.r(A),r.d(A,{ClassifierFreeGuidanceLogitsProcessor:()=>z,ForcedBOSTokenLogitsProcessor:()=>g,ForcedEOSTokenLogitsProcessor:()=>b,LogitsProcessor:()=>N,LogitsProcessorList:()=>j,LogitsWarper:()=>X,MinLengthLogitsProcessor:()=>H,MinNewTokensLengthLogitsProcessor:()=>re,NoBadWordsLogitsProcessor:()=>oe,NoRepeatNGramLogitsProcessor:()=>v,RepetitionPenaltyLogitsProcessor:()=>L,SuppressTokensAtBeginLogitsProcessor:()=>y,TemperatureLogitsWarper:()=>V,TopKLogitsWarper:()=>D,TopPLogitsWarper:()=>Y,WhisperTimeStampLogitsProcessor:()=>M});var _=r("./src/utils/generic.js");r("./src/utils/tensor.js");var I=r("./src/utils/maths.js");class N extends _.Callable{_call(w,C){throw Error("`_call` should be implemented in a subclass")}}class X extends _.Callable{_call(w,C){throw Error("`_call` should be implemented in a subclass")}}class j extends _.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,C){let T=C;for(const ee of this.processors)T=ee(w,T);return T}[Symbol.iterator](){return this.processors.values()}}class g extends N{constructor(w){super(),this.bos_token_id=w}_call(w,C){for(let T=0;T=1&&J[J.length-1]>=this.timestamp_begin,ce=J.length<2||J[J.length-2]>=this.timestamp_begin;if(le&&(ce?ee.subarray(this.timestamp_begin).fill(-1/0):ee.subarray(0,this.eos_token_id).fill(-1/0)),w[T].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ze=this.timestamp_begin+this.max_initial_timestamp_index;ee.subarray(ze+1).fill(-1/0)}const ge=(0,I.log_softmax)(ee),Ce=Math.log(ge.subarray(this.timestamp_begin).map(Math.exp).reduce((ze,qe)=>ze+qe)),Te=(0,I.max)(ge.subarray(0,this.timestamp_begin))[0];Ce>Te&&ee.subarray(0,this.timestamp_begin).fill(-1/0)}return C}}class v extends N{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const C=w.length,T=[];for(let J=0;J1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,C){if(C.dims[0]!==2*w.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 ${C.dims[0]} for the logits and ${w.length} for the input ids.`);const T=w.length,ee=C.slice([0,T],null),J=C.slice([T,C.dims[0]],null);for(let le=0;le1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger(T)||T<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${T}`);this.top_p=w,this.filter_value=C,this.min_tokens_to_keep=T}}class D extends X{constructor(w,{filter_value:C=-1/0,min_tokens_to_keep:T=1}={}){if(super(),!Number.isInteger(w)||w<0)throw new Error(`\`top_k\` must be a positive integer, but is ${w}`);this.top_k=Math.max(w,T),this.filter_value=C}}},"./src/generation/logits_sampler.js":(Le,A,r)=>{r.r(A),r.d(A,{LogitsSampler:()=>X});var _=r("./src/utils/generic.js"),I=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class X extends _.Callable{constructor(M){super(),this.generation_config=M}async _call(M){return this.sample(M)}async sample(M){throw Error("sample should be implemented in subclasses.")}getLogits(M,v){let L=M.dims.at(-1),H=M.data;if(v===-1)H=H.slice(-L);else{let re=v*L;H=H.slice(re,re+L)}return H}randomSelect(M){let v=0;for(let H=0;H1)return new b(M);if(M.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${M.num_return_sequences}.`);return new j(M)}}class j extends X{async sample(M){const v=(0,N.max)(M.data)[1];return[[BigInt(v),0]]}}class g extends X{async sample(M){let v=M.dims.at(-1);this.generation_config.top_k>0&&(v=Math.min(this.generation_config.top_k,v));const[L,H]=await(0,I.topk)(M,v),re=(0,N.softmax)(L.data);return Array.from({length:this.generation_config.num_beams},()=>{const oe=this.randomSelect(re);return[H.data[oe],Math.log(re[oe])]})}}class b extends X{async sample(M){let v=M.dims.at(-1);this.generation_config.top_k>0&&(v=Math.min(this.generation_config.top_k,v));const[L,H]=await(0,I.topk)(M,v),re=(0,N.softmax)(L.data);return Array.from({length:this.generation_config.num_beams},(oe,z)=>[H.data[z],Math.log(re[z])])}}},"./src/generation/stopping_criteria.js":(Le,A,r)=>{r.r(A),r.d(A,{EosTokenCriteria:()=>j,InterruptableStoppingCriteria:()=>g,MaxLengthCriteria:()=>X,StoppingCriteria:()=>I,StoppingCriteriaList:()=>N});var _=r("./src/utils/generic.js");class I extends _.Callable{_call(y,M){throw Error("StoppingCriteria needs to be subclassed")}}class N extends _.Callable{constructor(){super(),this.criteria=[]}push(y){this.criteria.push(y)}extend(y){y instanceof N?y=y.criteria:y instanceof I&&(y=[y]),this.criteria.push(...y)}_call(y,M){const v=new Array(y.length).fill(!1);for(const L of this.criteria){const H=L(y,M);for(let re=0;reM.length>=this.max_length)}}class j extends I{constructor(y){super(),Array.isArray(y)||(y=[y]),this.eos_token_id=y}_call(y,M){return y.map(v=>{const L=v.at(-1);return this.eos_token_id.some(H=>L==H)})}}class g extends I{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(y,M){return new Array(y.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Le,A,r)=>{r.r(A),r.d(A,{BaseStreamer:()=>X,TextStreamer:()=>g,WhisperTextStreamer:()=>b});var _=r("./src/utils/core.js"),I=r("./src/tokenizers.js"),N=r("./src/env.js");class X{put(M){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const j=N.apis.IS_PROCESS_AVAILABLE?y=>process.stdout.write(y):y=>console.log(y);class g extends X{constructor(M,{skip_prompt:v=!1,callback_function:L=null,token_callback_function:H=null,decode_kwargs:re={},...oe}={}){super(),this.tokenizer=M,this.skip_prompt=v,this.callback_function=L??j,this.token_callback_function=H,this.decode_kwargs={...re,...oe},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(M){var re;if(M.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 v=M[0];(re=this.token_callback_function)==null||re.call(this,v),this.token_cache=(0,_.mergeArrays)(this.token_cache,v);const L=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let H;L.endsWith(` `)?(H=L.slice(this.print_len),this.token_cache=[],this.print_len=0):L.length>0&&(0,I.is_chinese_char)(L.charCodeAt(L.length-1))?(H=L.slice(this.print_len),this.print_len+=H.length):(H=L.slice(this.print_len,L.lastIndexOf(" ")+1),this.print_len+=H.length),this.on_finalized_text(H,!1)}end(){let M;this.token_cache.length>0?(M=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):M="",this.next_tokens_are_prompt=!0,this.on_finalized_text(M,!0)}on_finalized_text(M,v){var L,H;M.length>0&&((L=this.callback_function)==null||L.call(this,M)),v&&this.callback_function===j&&N.apis.IS_PROCESS_AVAILABLE&&((H=this.callback_function)==null||H.call(this,` `))}}class b extends g{constructor(M,{skip_prompt:v=!1,callback_function:L=null,token_callback_function:H=null,on_chunk_start:re=null,on_chunk_end:oe=null,on_finalize:z=null,time_precision:V=.02,skip_special_tokens:Y=!0,decode_kwargs:D={}}={}){super(M,{skip_prompt:v,callback_function:L,token_callback_function:H,decode_kwargs:{skip_special_tokens:Y,...D}}),this.timestamp_begin=M.timestamp_begin,this.on_chunk_start=re,this.on_chunk_end=oe,this.on_finalize=z,this.time_precision=V,this.waiting_for_timestamp=!1}put(M){var L,H;if(M.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const v=M[0];if(v.length===1){const re=Number(v[0])-this.timestamp_begin;if(re>=0){const oe=re*this.time_precision;this.waiting_for_timestamp?(L=this.on_chunk_end)==null||L.call(this,oe):(H=this.on_chunk_start)==null||H.call(this,oe),this.waiting_for_timestamp=!this.waiting_for_timestamp,M=[[]]}}return super.put(M)}end(){var M;super.end(),(M=this.on_finalize)==null||M.call(this)}}},"./src/models.js":(Le,A,r)=>{r.r(A),r.d(A,{ASTForAudioClassification:()=>zi,ASTModel:()=>za,ASTPreTrainedModel:()=>Xt,AlbertForMaskedLM:()=>is,AlbertForQuestionAnswering:()=>zn,AlbertForSequenceClassification:()=>yn,AlbertModel:()=>Ln,AlbertPreTrainedModel:()=>Rr,AutoModel:()=>Vd,AutoModelForAudioClassification:()=>oc,AutoModelForAudioFrameClassification:()=>lc,AutoModelForCTC:()=>ic,AutoModelForCausalLM:()=>Qd,AutoModelForDepthEstimation:()=>pc,AutoModelForDocumentQuestionAnswering:()=>uc,AutoModelForImageClassification:()=>Zd,AutoModelForImageFeatureExtraction:()=>mc,AutoModelForImageMatting:()=>dc,AutoModelForImageSegmentation:()=>ec,AutoModelForImageToImage:()=>cc,AutoModelForMaskGeneration:()=>nc,AutoModelForMaskedLM:()=>Yd,AutoModelForNormalEstimation:()=>xa,AutoModelForObjectDetection:()=>sc,AutoModelForPoseEstimation:()=>hc,AutoModelForQuestionAnswering:()=>mp,AutoModelForSemanticSegmentation:()=>tc,AutoModelForSeq2SeqLM:()=>Hd,AutoModelForSequenceClassification:()=>Gd,AutoModelForSpeechSeq2Seq:()=>qd,AutoModelForTextToSpectrogram:()=>hp,AutoModelForTextToWaveform:()=>Xd,AutoModelForTokenClassification:()=>Kd,AutoModelForUniversalSegmentation:()=>fp,AutoModelForVision2Seq:()=>Jd,AutoModelForXVector:()=>ac,AutoModelForZeroShotObjectDetection:()=>rc,BartForConditionalGeneration:()=>He,BartForSequenceClassification:()=>ct,BartModel:()=>Pe,BartPretrainedModel:()=>ye,BaseModelOutput:()=>Fe,BeitForImageClassification:()=>au,BeitModel:()=>ou,BeitPreTrainedModel:()=>Co,BertForMaskedLM:()=>Re,BertForQuestionAnswering:()=>Ne,BertForSequenceClassification:()=>je,BertForTokenClassification:()=>Ve,BertModel:()=>ve,BertPreTrainedModel:()=>pe,BlenderbotForConditionalGeneration:()=>ys,BlenderbotModel:()=>Se,BlenderbotPreTrainedModel:()=>ns,BlenderbotSmallForConditionalGeneration:()=>Js,BlenderbotSmallModel:()=>Xs,BlenderbotSmallPreTrainedModel:()=>Fs,BloomForCausalLM:()=>Fl,BloomModel:()=>Ol,BloomPreTrainedModel:()=>mo,CLIPModel:()=>Xa,CLIPPreTrainedModel:()=>en,CLIPSegForImageSegmentation:()=>sl,CLIPSegModel:()=>tl,CLIPSegPreTrainedModel:()=>Vi,CLIPTextModel:()=>Ic,CLIPTextModelWithProjection:()=>Qa,CLIPVisionModel:()=>Oc,CLIPVisionModelWithProjection:()=>Ya,CamembertForMaskedLM:()=>ir,CamembertForQuestionAnswering:()=>mn,CamembertForSequenceClassification:()=>Kr,CamembertForTokenClassification:()=>Or,CamembertModel:()=>qs,CamembertPreTrainedModel:()=>ks,CausalLMOutput:()=>on,CausalLMOutputWithPast:()=>gp,ChineseCLIPModel:()=>pr,ChineseCLIPPreTrainedModel:()=>Fc,ClapAudioModelWithProjection:()=>nd,ClapModel:()=>rn,ClapPreTrainedModel:()=>fr,ClapTextModelWithProjection:()=>nn,CodeGenForCausalLM:()=>ml,CodeGenModel:()=>Yi,CodeGenPreTrainedModel:()=>ai,CohereForCausalLM:()=>zc,CohereModel:()=>bl,CoherePreTrainedModel:()=>oo,ConvBertForMaskedLM:()=>Qe,ConvBertForQuestionAnswering:()=>Ot,ConvBertForSequenceClassification:()=>rt,ConvBertForTokenClassification:()=>mt,ConvBertModel:()=>Oe,ConvBertPreTrainedModel:()=>de,ConvNextForImageClassification:()=>Wc,ConvNextModel:()=>Ko,ConvNextPreTrainedModel:()=>Go,ConvNextV2ForImageClassification:()=>Tu,ConvNextV2Model:()=>Vc,ConvNextV2PreTrainedModel:()=>Ho,DPTForDepthEstimation:()=>jn,DPTModel:()=>No,DPTPreTrainedModel:()=>Ro,DebertaForMaskedLM:()=>kr,DebertaForQuestionAnswering:()=>Dr,DebertaForSequenceClassification:()=>Fr,DebertaForTokenClassification:()=>Sr,DebertaModel:()=>Hr,DebertaPreTrainedModel:()=>zt,DebertaV2ForMaskedLM:()=>$r,DebertaV2ForQuestionAnswering:()=>ot,DebertaV2ForSequenceClassification:()=>qr,DebertaV2ForTokenClassification:()=>or,DebertaV2Model:()=>dr,DebertaV2PreTrainedModel:()=>Zs,DecisionTransformerModel:()=>bd,DecisionTransformerPreTrainedModel:()=>da,DeiTForImageClassification:()=>Io,DeiTModel:()=>Ao,DeiTPreTrainedModel:()=>vn,DepthAnythingForDepthEstimation:()=>jo,DepthAnythingPreTrainedModel:()=>fu,DepthProForDepthEstimation:()=>yu,DepthProPreTrainedModel:()=>wu,DetrForObjectDetection:()=>uu,DetrForSegmentation:()=>du,DetrModel:()=>lu,DetrObjectDetectionOutput:()=>jr,DetrPreTrainedModel:()=>ci,DetrSegmentationOutput:()=>tn,Dinov2ForImageClassification:()=>Xo,Dinov2Model:()=>xu,Dinov2PreTrainedModel:()=>qo,DistilBertForMaskedLM:()=>br,DistilBertForQuestionAnswering:()=>ts,DistilBertForSequenceClassification:()=>us,DistilBertForTokenClassification:()=>Mr,DistilBertModel:()=>It,DistilBertPreTrainedModel:()=>pt,DonutSwinModel:()=>vu,DonutSwinPreTrainedModel:()=>Vo,EfficientNetForImageClassification:()=>cd,EfficientNetModel:()=>Qs,EfficientNetPreTrainedModel:()=>dd,ElectraForMaskedLM:()=>At,ElectraForQuestionAnswering:()=>Os,ElectraForSequenceClassification:()=>rs,ElectraForTokenClassification:()=>ws,ElectraModel:()=>Ft,ElectraPreTrainedModel:()=>xt,EsmForMaskedLM:()=>Lr,EsmForSequenceClassification:()=>vr,EsmForTokenClassification:()=>An,EsmModel:()=>Xr,EsmPreTrainedModel:()=>cr,ExaoneForCausalLM:()=>fl,ExaoneModel:()=>li,ExaonePreTrainedModel:()=>eo,FalconForCausalLM:()=>Pr,FalconModel:()=>ep,FalconPreTrainedModel:()=>ra,FastViTForImageClassification:()=>Bc,FastViTModel:()=>Ql,FastViTPreTrainedModel:()=>To,Florence2ForConditionalGeneration:()=>Va,Florence2PreTrainedModel:()=>Wa,GLPNForDepthEstimation:()=>Wo,GLPNModel:()=>_i,GLPNPreTrainedModel:()=>Uo,GPT2LMHeadModel:()=>nl,GPT2Model:()=>rl,GPT2PreTrainedModel:()=>Gi,GPTBigCodeForCausalLM:()=>hl,GPTBigCodeModel:()=>pl,GPTBigCodePreTrainedModel:()=>Qi,GPTJForCausalLM:()=>cl,GPTJModel:()=>dl,GPTJPreTrainedModel:()=>Xi,GPTNeoForCausalLM:()=>al,GPTNeoModel:()=>mr,GPTNeoPreTrainedModel:()=>Hi,GPTNeoXForCausalLM:()=>ul,GPTNeoXModel:()=>ll,GPTNeoXPreTrainedModel:()=>qi,Gemma2ForCausalLM:()=>xl,Gemma2Model:()=>Tl,Gemma2PreTrainedModel:()=>lo,GemmaForCausalLM:()=>vl,GemmaModel:()=>ds,GemmaPreTrainedModel:()=>ao,GraniteForCausalLM:()=>Ml,GraniteModel:()=>Lc,GranitePreTrainedModel:()=>io,GroupViTModel:()=>Xl,GroupViTPreTrainedModel:()=>vo,HieraForImageClassification:()=>Fo,HieraModel:()=>pu,HieraPreTrainedModel:()=>Oo,HubertForCTC:()=>Ku,HubertForSequenceClassification:()=>Hu,HubertModel:()=>Gu,HubertPreTrainedModel:()=>Up,IJepaForImageClassification:()=>Ul,IJepaModel:()=>jl,IJepaPreTrainedModel:()=>wo,Idefics3ForConditionalGeneration:()=>ji,Idefics3PreTrainedModel:()=>Ha,ImageMattingOutput:()=>_c,JAISLMHeadModel:()=>ol,JAISModel:()=>il,JAISPreTrainedModel:()=>Ki,JinaCLIPModel:()=>oi,JinaCLIPPreTrainedModel:()=>ii,JinaCLIPTextModel:()=>Wi,JinaCLIPVisionModel:()=>hr,LlamaForCausalLM:()=>Dc,LlamaModel:()=>Zi,LlamaPreTrainedModel:()=>Ji,LlavaForConditionalGeneration:()=>ni,LlavaOnevisionForConditionalGeneration:()=>ja,LlavaPreTrainedModel:()=>Nr,LongT5ForConditionalGeneration:()=>Ee,LongT5Model:()=>bn,LongT5PreTrainedModel:()=>Jr,M2M100ForConditionalGeneration:()=>Au,M2M100Model:()=>$u,M2M100PreTrainedModel:()=>Zo,MBartForCausalLM:()=>ms,MBartForConditionalGeneration:()=>it,MBartForSequenceClassification:()=>Ct,MBartModel:()=>_t,MBartPreTrainedModel:()=>wt,MPNetForMaskedLM:()=>Qr,MPNetForQuestionAnswering:()=>gn,MPNetForSequenceClassification:()=>_n,MPNetForTokenClassification:()=>Yr,MPNetModel:()=>fn,MPNetPreTrainedModel:()=>er,MT5ForConditionalGeneration:()=>ae,MT5Model:()=>q,MT5PreTrainedModel:()=>E,MarianMTModel:()=>Kc,MarianModel:()=>Su,MarianPreTrainedModel:()=>Jo,MaskFormerForInstanceSegmentation:()=>fi,MaskFormerModel:()=>bu,MaskFormerPreTrainedModel:()=>Mu,MaskedLMOutput:()=>Ws,MgpstrForSceneTextRecognition:()=>xd,MgpstrModelOutput:()=>vd,MgpstrPreTrainedModel:()=>Td,MistralForCausalLM:()=>Zc,MistralModel:()=>td,MistralPreTrainedModel:()=>ta,MobileBertForMaskedLM:()=>si,MobileBertForQuestionAnswering:()=>Tr,MobileBertForSequenceClassification:()=>Br,MobileBertModel:()=>In,MobileBertPreTrainedModel:()=>zr,MobileLLMForCausalLM:()=>Rn,MobileLLMModel:()=>_l,MobileLLMPreTrainedModel:()=>to,MobileNetV1ForImageClassification:()=>md,MobileNetV1Model:()=>hd,MobileNetV1PreTrainedModel:()=>aa,MobileNetV2ForImageClassification:()=>_d,MobileNetV2Model:()=>fd,MobileNetV2PreTrainedModel:()=>la,MobileNetV3ForImageClassification:()=>wd,MobileNetV3Model:()=>gd,MobileNetV3PreTrainedModel:()=>Ti,MobileNetV4ForImageClassification:()=>Md,MobileNetV4Model:()=>yd,MobileNetV4PreTrainedModel:()=>ua,MobileViTForImageClassification:()=>eu,MobileViTModel:()=>Zl,MobileViTPreTrainedModel:()=>ur,MobileViTV2ForImageClassification:()=>su,MobileViTV2Model:()=>tu,MobileViTV2PreTrainedModel:()=>xo,ModelOutput:()=>Je,Moondream1ForConditionalGeneration:()=>Ua,MoonshineForConditionalGeneration:()=>Na,MoonshineModel:()=>ar,MoonshinePreTrainedModel:()=>Ri,MptForCausalLM:()=>Ll,MptModel:()=>Dl,MptPreTrainedModel:()=>fo,MultiModalityCausalLM:()=>ca,MultiModalityPreTrainedModel:()=>rp,MusicgenForCausalLM:()=>sp,MusicgenForConditionalGeneration:()=>xn,MusicgenModel:()=>pd,MusicgenPreTrainedModel:()=>oa,NomicBertModel:()=>at,NomicBertPreTrainedModel:()=>Ze,OPTForCausalLM:()=>Bl,OPTModel:()=>zl,OPTPreTrainedModel:()=>_o,Olmo2ForCausalLM:()=>yl,Olmo2Model:()=>wl,Olmo2PreTrainedModel:()=>no,OlmoForCausalLM:()=>ro,OlmoModel:()=>gl,OlmoPreTrainedModel:()=>so,OpenELMForCausalLM:()=>Pl,OpenELMModel:()=>El,OpenELMPreTrainedModel:()=>uo,OwlViTForObjectDetection:()=>nu,OwlViTModel:()=>ru,OwlViTPreTrainedModel:()=>Eo,Owlv2ForObjectDetection:()=>Rc,Owlv2Model:()=>iu,Owlv2PreTrainedModel:()=>Po,PaliGemmaForConditionalGeneration:()=>Ka,PaliGemmaPreTrainedModel:()=>Ga,PatchTSMixerForPrediction:()=>kd,PatchTSMixerModel:()=>np,PatchTSMixerPreTrainedModel:()=>pa,PatchTSTForPrediction:()=>Cd,PatchTSTModel:()=>Pd,PatchTSTPreTrainedModel:()=>Ed,Phi3ForCausalLM:()=>Il,Phi3Model:()=>ui,Phi3PreTrainedModel:()=>ho,Phi3VForCausalLM:()=>lr,Phi3VPreTrainedModel:()=>qa,PhiForCausalLM:()=>Nn,PhiModel:()=>Al,PhiPreTrainedModel:()=>po,PreTrainedModel:()=>ie,PretrainedMixin:()=>gs,PvtForImageClassification:()=>Vl,PvtModel:()=>Mo,PvtPreTrainedModel:()=>di,PyAnnoteForAudioFrameClassification:()=>Fu,PyAnnoteModel:()=>Ou,PyAnnotePreTrainedModel:()=>wi,QuestionAnsweringModelOutput:()=>Ys,Qwen2ForCausalLM:()=>kl,Qwen2Model:()=>Cl,Qwen2PreTrainedModel:()=>co,Qwen2VLForConditionalGeneration:()=>$l,Qwen2VLPreTrainedModel:()=>Sl,RTDetrForObjectDetection:()=>sn,RTDetrModel:()=>ko,RTDetrObjectDetectionOutput:()=>Ks,RTDetrPreTrainedModel:()=>Ur,ResNetForImageClassification:()=>Do,ResNetModel:()=>hu,ResNetPreTrainedModel:()=>pi,RoFormerForMaskedLM:()=>gt,RoFormerForQuestionAnswering:()=>K,RoFormerForSequenceClassification:()=>F,RoFormerForTokenClassification:()=>ne,RoFormerModel:()=>dt,RoFormerPreTrainedModel:()=>ht,RobertaForMaskedLM:()=>xr,RobertaForQuestionAnswering:()=>Tt,RobertaForSequenceClassification:()=>es,RobertaForTokenClassification:()=>_s,RobertaModel:()=>Ns,RobertaPreTrainedModel:()=>Dt,SamImageSegmentationOutput:()=>ku,SamModel:()=>Gc,SamPreTrainedModel:()=>Cu,SapiensForDepthEstimation:()=>gu,SapiensForNormalEstimation:()=>Uc,SapiensForSemanticSegmentation:()=>_u,SapiensPreTrainedModel:()=>mi,SegformerForImageClassification:()=>od,SegformerForSemanticSegmentation:()=>ad,SegformerModel:()=>tp,SegformerPreTrainedModel:()=>vi,Seq2SeqLMOutput:()=>_p,SequenceClassifierOutput:()=>Qt,SiglipModel:()=>Ja,SiglipPreTrainedModel:()=>Ui,SiglipTextModel:()=>Za,SiglipVisionModel:()=>el,SpeechT5ForSpeechToText:()=>Yu,SpeechT5ForTextToSpeech:()=>Ju,SpeechT5HifiGan:()=>Jc,SpeechT5Model:()=>Yc,SpeechT5PreTrainedModel:()=>bi,SqueezeBertForMaskedLM:()=>On,SqueezeBertForQuestionAnswering:()=>Dn,SqueezeBertForSequenceClassification:()=>Fn,SqueezeBertModel:()=>wn,SqueezeBertPreTrainedModel:()=>Bt,StableLmForCausalLM:()=>ud,StableLmModel:()=>ld,StableLmPreTrainedModel:()=>ia,Starcoder2ForCausalLM:()=>rd,Starcoder2Model:()=>sd,Starcoder2PreTrainedModel:()=>sa,Swin2SRForImageSuperResolution:()=>jc,Swin2SRModel:()=>mu,Swin2SRPreTrainedModel:()=>Bo,SwinForImageClassification:()=>zo,SwinModel:()=>hi,SwinPreTrainedModel:()=>Lo,T5ForConditionalGeneration:()=>Bn,T5Model:()=>Mn,T5PreTrainedModel:()=>tr,TableTransformerForObjectDetection:()=>cu,TableTransformerModel:()=>$o,TableTransformerObjectDetectionOutput:()=>Nc,TableTransformerPreTrainedModel:()=>So,TokenClassifierOutput:()=>Us,TrOCRForCausalLM:()=>ed,TrOCRPreTrainedModel:()=>Zu,UniSpeechForCTC:()=>Bu,UniSpeechForSequenceClassification:()=>Ru,UniSpeechModel:()=>zu,UniSpeechPreTrainedModel:()=>Wn,UniSpeechSatForAudioFrameClassification:()=>Uu,UniSpeechSatForCTC:()=>ea,UniSpeechSatForSequenceClassification:()=>ju,UniSpeechSatModel:()=>Nu,UniSpeechSatPreTrainedModel:()=>yi,ViTForImageClassification:()=>Nl,ViTMAEModel:()=>Kl,ViTMAEPreTrainedModel:()=>Gl,ViTMSNForImageClassification:()=>ql,ViTMSNModel:()=>Hl,ViTMSNPreTrainedModel:()=>bo,ViTModel:()=>Rl,ViTPreTrainedModel:()=>go,VisionEncoderDecoderModel:()=>Ni,VitMatteForImageMatting:()=>Jl,VitMattePreTrainedModel:()=>Yl,VitPoseForPoseEstimation:()=>Wl,VitPosePreTrainedModel:()=>yo,VitsModel:()=>na,VitsModelOutput:()=>wp,VitsPreTrainedModel:()=>id,Wav2Vec2BertForCTC:()=>Wu,Wav2Vec2BertForSequenceClassification:()=>Vu,Wav2Vec2BertModel:()=>qc,Wav2Vec2BertPreTrainedModel:()=>Mi,Wav2Vec2ForAudioFrameClassification:()=>Un,Wav2Vec2ForCTC:()=>Hc,Wav2Vec2ForSequenceClassification:()=>gi,Wav2Vec2Model:()=>Iu,Wav2Vec2PreTrainedModel:()=>Wr,WavLMForAudioFrameClassification:()=>Qc,WavLMForCTC:()=>qu,WavLMForSequenceClassification:()=>Xu,WavLMForXVector:()=>Qu,WavLMModel:()=>Xc,WavLMPreTrainedModel:()=>Tn,WeSpeakerResNetModel:()=>Lu,WeSpeakerResNetPreTrainedModel:()=>Du,WhisperForConditionalGeneration:()=>Ra,WhisperModel:()=>Ba,WhisperPreTrainedModel:()=>Bi,XLMForQuestionAnswering:()=>Ss,XLMForSequenceClassification:()=>Gs,XLMForTokenClassification:()=>Mt,XLMModel:()=>Er,XLMPreTrainedModel:()=>os,XLMRobertaForMaskedLM:()=>sr,XLMRobertaForQuestionAnswering:()=>La,XLMRobertaForSequenceClassification:()=>Zr,XLMRobertaForTokenClassification:()=>ri,XLMRobertaModel:()=>yt,XLMRobertaPreTrainedModel:()=>De,XLMWithLMHeadModel:()=>Ds,XVectorOutput:()=>fc,YolosForObjectDetection:()=>Yo,YolosModel:()=>Eu,YolosObjectDetectionOutput:()=>Pu,YolosPreTrainedModel:()=>Qo});var _=r("./src/configs.js"),I=r("./src/backends/onnx.js"),N=r("./src/utils/dtypes.js"),X=r("./src/utils/generic.js"),j=r("./src/utils/core.js"),g=r("./src/utils/hub.js"),b=r("./src/utils/constants.js"),y=r("./src/generation/logits_process.js"),M=r("./src/generation/configuration_utils.js"),v=r("./src/utils/tensor.js"),L=r("./src/utils/image.js"),H=r("./src/utils/maths.js"),re=r("./src/generation/stopping_criteria.js"),oe=r("./src/generation/logits_sampler.js"),z=r("./src/env.js"),V=r("./src/models/whisper/generation_whisper.js"),Y=r("./src/models/whisper/common_whisper.js");const D={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},$=new Map,w=new Map,C=new Map;async function T(f,P,W){var vs;const be=((vs=W.config)==null?void 0:vs["transformers.js_config"])??{};let Ie=W.device??be.device;Ie&&typeof Ie!="string"&&(Ie.hasOwnProperty(P)?Ie=Ie[P]:(console.warn(`device not specified for "${P}". Using the default device.`),Ie=null));const ke=Ie??(z.apis.IS_NODE_ENV?"cpu":"wasm"),Ye=(0,I.deviceToExecutionProviders)(ke);let tt=W.dtype??be.dtype;if(typeof tt!="string"&&(tt&&tt.hasOwnProperty(P)?tt=tt[P]:(tt=N.DEFAULT_DEVICE_DTYPE_MAPPING[ke]??N.DATA_TYPES.fp32,console.warn(`dtype not specified for "${P}". Using the default dtype (${tt}) for this device (${ke}).`))),tt===N.DATA_TYPES.auto){let cs=be.dtype;typeof cs!="string"&&(cs=cs[P]),cs&&cs!==N.DATA_TYPES.auto&&N.DATA_TYPES.hasOwnProperty(cs)?tt=cs:tt=N.DEFAULT_DEVICE_DTYPE_MAPPING[ke]??N.DATA_TYPES.fp32}const ft=tt;if(N.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(ft)){if(ft===N.DATA_TYPES.fp16&&ke==="webgpu"&&!await(0,N.isWebGpuFp16Supported)())throw new Error(`The device (${ke}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${ft}. Should be one of: ${Object.keys(N.DATA_TYPES).join(", ")}`);const vt=be.kv_cache_dtype?typeof be.kv_cache_dtype=="string"?be.kv_cache_dtype:be.kv_cache_dtype[ft]??"float32":void 0;if(vt&&!["float32","float16"].includes(vt))throw new Error(`Invalid kv_cache_dtype: ${vt}. Should be one of: float32, float16`);const Rt={dtype:ft,kv_cache_dtype:vt},Ut=N.DEFAULT_DTYPE_SUFFIX_MAPPING[ft],Lt=`${W.subfolder??""}/${P}${Ut}.onnx`,Vt={...W.session_options};Vt.executionProviders??(Vt.executionProviders=Ye);const Zt=be.free_dimension_overrides;Zt?Vt.freeDimensionOverrides??(Vt.freeDimensionOverrides=Zt):ke.startsWith("webnn")&&!Vt.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 ss=(0,g.getModelFile)(f,Lt,!0,W),qt=W.use_external_data_format??be.use_external_data_format;let as=[];if(qt&&(qt===!0||typeof qt=="object"&&qt.hasOwnProperty(P)&&qt[P]===!0)){if(z.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const cs=`${P}${Ut}.onnx_data`,Es=`${W.subfolder??""}/${cs}`;as.push(new Promise(async($s,Hs)=>{const js=await(0,g.getModelFile)(f,Es,!0,W);$s({path:cs,data:js})}))}else Vt.externalData!==void 0&&(as=Vt.externalData.map(async cs=>{if(typeof cs.data=="string"){const Es=await(0,g.getModelFile)(f,cs.data,!0,W);return{...cs,data:Es}}return cs}));if(as.length>0&&(Vt.externalData=await Promise.all(as)),ke==="webgpu"){const cs=(0,_.getKeyValueShapes)(W.config,{prefix:"present"});if(Object.keys(cs).length>0&&!(0,I.isONNXProxy)()){const Es={};for(const $s in cs)Es[$s]="gpu-buffer";Vt.preferredOutputLocation=Es}}return{buffer:await ss,session_options:Vt,session_config:Rt}}async function ee(f,P,W){return Object.fromEntries(await Promise.all(Object.keys(P).map(async be=>{const{buffer:Ie,session_options:ke,session_config:Ye}=await T(f,P[be],W),tt=await(0,I.createInferenceSession)(Ie,ke,Ye);return[be,tt]})))}async function J(f,P,W){return Object.fromEntries(await Promise.all(Object.keys(P).map(async be=>{const Ie=await(0,g.getModelJSON)(f,P[be],!1,W);return[be,Ie]})))}function le(f,P){const W=Object.create(null),be=[];for(const Ye of f.inputNames){const tt=P[Ye];if(!(tt instanceof v.Tensor)){be.push(Ye);continue}W[Ye]=(0,I.isONNXProxy)()?tt.clone():tt}if(be.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${be.join(", ")}.`);const Ie=Object.keys(P).length,ke=f.inputNames.length;if(Ie>ke){let Ye=Object.keys(P).filter(tt=>!f.inputNames.includes(tt));console.warn(`WARNING: Too many inputs were provided (${Ie} > ${ke}). The following inputs will be ignored: "${Ye.join(", ")}".`)}return W}async function ce(f,P){const W=le(f,P);try{const be=Object.fromEntries(Object.entries(W).map(([ke,Ye])=>[ke,Ye.ort_tensor]));let Ie=await f.run(be);return Ie=ge(Ie),Ie}catch(be){const Ie=Object.fromEntries(Object.entries(W).map(([ke,{type:Ye,dims:tt,data:ft}])=>[ke,{type:Ye,dims:tt,data:ft}]));throw console.error(`An error occurred during model execution: "${be}".`),console.error("Inputs given to model:",Ie),be}}function ge(f){for(let P in f)(0,I.isONNXTensor)(f[P])?f[P]=new v.Tensor(f[P]):typeof f[P]=="object"&&ge(f[P]);return f}function Ce(f){if(f instanceof v.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(P=>P.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 v.Tensor("int64",BigInt64Array.from(f.flat().map(P=>BigInt(P))),[f.length,f[0].length])}else return new v.Tensor("int64",BigInt64Array.from(f.map(P=>BigInt(P))),[1,f.length])}function Te(f){return new v.Tensor("bool",[f],[1])}async function ze(f,P){let{encoder_outputs:W,input_ids:be,decoder_input_ids:Ie,...ke}=P;if(!W){const tt=(0,j.pick)(P,f.sessions.model.inputNames);W=(await qe(f,tt)).last_hidden_state}return ke.input_ids=Ie,ke.encoder_hidden_states=W,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(ke.encoder_attention_mask=P.attention_mask),await Ue(f,ke,!0)}async function qe(f,P){const W=f.sessions.model,be=(0,j.pick)(P,W.inputNames);if(W.inputNames.includes("inputs_embeds")&&!be.inputs_embeds){if(!P.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");be.inputs_embeds=await f.encode_text({input_ids:P.input_ids})}return W.inputNames.includes("token_type_ids")&&!be.token_type_ids&&(be.token_type_ids=new v.Tensor("int64",new BigInt64Array(be.input_ids.data.length),be.input_ids.dims)),await ce(W,be)}async function Ue(f,P,W=!1){const be=f.sessions[W?"decoder_model_merged":"model"],{past_key_values:Ie,...ke}=P;if(be.inputNames.includes("use_cache_branch")&&(ke.use_cache_branch=Te(!!Ie)),be.inputNames.includes("position_ids")&&ke.attention_mask&&!ke.position_ids){const tt=f.config.model_type==="paligemma"?1:0;ke.position_ids=he(ke,Ie,tt)}f.addPastKeyValues(ke,Ie);const Ye=(0,j.pick)(ke,be.inputNames);return await ce(be,Ye)}function ut({image_token_id:f,inputs_embeds:P,image_features:W,input_ids:be,attention_mask:Ie}){const ke=be.tolist().map(vt=>vt.reduce((Rt,Ut,Lt)=>(Ut==f&&Rt.push(Lt),Rt),[])),Ye=ke.reduce((vt,Rt)=>vt+Rt.length,0),tt=W.dims[0];if(Ye!==tt)throw new Error(`Image features and image tokens do not match: tokens: ${Ye}, features ${tt}`);let ft=0;for(let vt=0;vtke.dims[1])){if(Iett==f.config.image_token_index)){const tt=f.config.num_image_tokens;if(!tt)throw new Error("`num_image_tokens` is missing in the model configuration.");const ft=ke.dims[1]-(Ie-tt);W.input_ids=ke.slice(null,[-ft,null]),W.attention_mask=(0,v.ones)([1,Ie+ft])}}}return W}function Be(f,P,W,be){return W.past_key_values&&(P=P.map(Ie=>[Ie.at(-1)])),{...W,decoder_input_ids:Ce(P)}}function et(f,...P){return f.config.is_encoder_decoder?Be(f,...P):xe(f,...P)}function Xe(f,P,W,be){const Ie=!!W.past_key_values;return be.guidance_scale!==null&&be.guidance_scale>1&&(Ie?W.input_ids=(0,v.cat)([W.input_ids,W.input_ids],0):(W.input_ids=(0,v.cat)([W.input_ids,(0,v.full_like)(W.input_ids,BigInt(be.pad_token_id))],0),W.attention_mask=(0,v.cat)([W.attention_mask,(0,v.full_like)(W.attention_mask,0n)],0))),(Ie||!W.pixel_values)&&(W.pixel_values=(0,v.full)([0,0,3,384,384],1)),Ie&&(W.images_seq_mask=new v.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),W.images_emb_mask=new v.Tensor("bool",new Array(0).fill(!1),[1,1,0])),W}class ie extends X.Callable{constructor(W,be,Ie){super();_e(this,"main_input_name","input_ids");_e(this,"forward_params",["input_ids","attention_mask"]);this.config=W,this.sessions=be,this.configs=Ie;const ke=C.get(this.constructor),Ye=$.get(ke);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ye){case D.DecoderOnly:this.can_generate=!0,this._forward=Ue,this._prepare_inputs_for_generation=xe;break;case D.Seq2Seq:case D.Vision2Seq:case D.Musicgen:this.can_generate=!0,this._forward=ze,this._prepare_inputs_for_generation=Be;break;case D.EncoderDecoder:this._forward=ze;break;case D.ImageTextToText:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=et;break;case D.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=et;break;case D.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Xe;break;default:this._forward=qe;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var be;const W=[];for(const Ie of Object.values(this.sessions))(be=Ie==null?void 0:Ie.handler)!=null&&be.dispose&&W.push(Ie.handler.dispose());return await Promise.all(W)}static async from_pretrained(W,{progress_callback:be=null,config:Ie=null,cache_dir:ke=null,local_files_only:Ye=!1,revision:tt="main",model_file_name:ft=null,subfolder:vt="onnx",device:Rt=null,dtype:Ut=null,use_external_data_format:Lt=null,session_options:Vt={}}={}){let Zt={progress_callback:be,config:Ie,cache_dir:ke,local_files_only:Ye,revision:tt,model_file_name:ft,subfolder:vt,device:Rt,dtype:Ut,use_external_data_format:Lt,session_options:Vt};const ss=C.get(this),qt=$.get(ss);Ie=Zt.config=await _.AutoConfig.from_pretrained(W,Zt);let as;if(qt===D.DecoderOnly)as=await Promise.all([ee(W,{model:Zt.model_file_name??"model"},Zt),J(W,{generation_config:"generation_config.json"},Zt)]);else if(qt===D.Seq2Seq||qt===D.Vision2Seq)as=await Promise.all([ee(W,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Zt),J(W,{generation_config:"generation_config.json"},Zt)]);else if(qt===D.MaskGeneration)as=await Promise.all([ee(W,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Zt)]);else if(qt===D.EncoderDecoder)as=await Promise.all([ee(W,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Zt)]);else if(qt===D.ImageTextToText){const xs={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ie.is_encoder_decoder&&(xs.model="encoder_model"),as=await Promise.all([ee(W,xs,Zt),J(W,{generation_config:"generation_config.json"},Zt)])}else if(qt===D.Musicgen)as=await Promise.all([ee(W,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Zt),J(W,{generation_config:"generation_config.json"},Zt)]);else if(qt===D.MultiModality)as=await Promise.all([ee(W,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},Zt),J(W,{generation_config:"generation_config.json"},Zt)]);else if(qt===D.Phi3V)as=await Promise.all([ee(W,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},Zt),J(W,{generation_config:"generation_config.json"},Zt)]);else{if(qt!==D.EncoderOnly){const xs=ss??(Ie==null?void 0:Ie.model_type);xs!=="custom"&&console.warn(`Model type for '${xs}' not found, assuming encoder-only architecture. Please report this at ${b.GITHUB_ISSUE_URL}.`)}as=await Promise.all([ee(W,{model:Zt.model_file_name??"model"},Zt)])}return new this(Ie,...as)}async _call(W){return await this.forward(W)}async forward(W){return await this._forward(this,W)}get generation_config(){var W;return((W=this.configs)==null?void 0:W.generation_config)??null}_get_logits_warper(W){const be=new y.LogitsProcessorList;return W.temperature!==null&&W.temperature!==1&&be.push(new y.TemperatureLogitsWarper(W.temperature)),W.top_k!==null&&W.top_k!==0&&be.push(new y.TopKLogitsWarper(W.top_k)),W.top_p!==null&&W.top_p<1&&be.push(new y.TopPLogitsWarper(W.top_p)),be}_get_logits_processor(W,be,Ie=null){const ke=new y.LogitsProcessorList;if(W.repetition_penalty!==null&&W.repetition_penalty!==1&&ke.push(new y.RepetitionPenaltyLogitsProcessor(W.repetition_penalty)),W.no_repeat_ngram_size!==null&&W.no_repeat_ngram_size>0&&ke.push(new y.NoRepeatNGramLogitsProcessor(W.no_repeat_ngram_size)),W.bad_words_ids!==null&&ke.push(new y.NoBadWordsLogitsProcessor(W.bad_words_ids,W.eos_token_id)),W.min_length!==null&&W.eos_token_id!==null&&W.min_length>0&&ke.push(new y.MinLengthLogitsProcessor(W.min_length,W.eos_token_id)),W.min_new_tokens!==null&&W.eos_token_id!==null&&W.min_new_tokens>0&&ke.push(new y.MinNewTokensLengthLogitsProcessor(be,W.min_new_tokens,W.eos_token_id)),W.forced_bos_token_id!==null&&ke.push(new y.ForcedBOSTokenLogitsProcessor(W.forced_bos_token_id)),W.forced_eos_token_id!==null&&ke.push(new y.ForcedEOSTokenLogitsProcessor(W.max_length,W.forced_eos_token_id)),W.begin_suppress_tokens!==null){const Ye=be>1||W.forced_bos_token_id===null?be:be+1;ke.push(new y.SuppressTokensAtBeginLogitsProcessor(W.begin_suppress_tokens,Ye))}return W.guidance_scale!==null&&W.guidance_scale>1&&ke.push(new y.ClassifierFreeGuidanceLogitsProcessor(W.guidance_scale)),Ie!==null&&ke.extend(Ie),ke}_prepare_generation_config(W,be,Ie=M.GenerationConfig){const ke={...this.config};for(const tt of["decoder","generator","text_config"])tt in ke&&Object.assign(ke,ke[tt]);const Ye=new Ie(ke);return Object.assign(Ye,this.generation_config??{}),W&&Object.assign(Ye,W),be&&Object.assign(Ye,(0,j.pick)(be,Object.getOwnPropertyNames(Ye))),Ye}_get_stopping_criteria(W,be=null){const Ie=new re.StoppingCriteriaList;return W.max_length!==null&&Ie.push(new re.MaxLengthCriteria(W.max_length,this.config.max_position_embeddings??null)),W.eos_token_id!==null&&Ie.push(new re.EosTokenCriteria(W.eos_token_id)),be&&Ie.extend(be),Ie}_validate_model_class(){if(!this.can_generate){const W=[fa,_a,ma,ha],be=C.get(this.constructor),Ie=new Set,ke=this.config.model_type;for(const tt of W){const ft=tt.get(ke);ft&&Ie.add(ft[0])}let Ye=`The current model class (${be}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ie.size>0&&(Ye+=` Please use the following class instead: ${[...Ie].join(", ")}`),Error(Ye)}}prepare_inputs_for_generation(...W){return this._prepare_inputs_for_generation(this,...W)}_update_model_kwargs_for_generation({generated_input_ids:W,outputs:be,model_inputs:Ie,is_encoder_decoder:ke}){return Ie.past_key_values=this.getPastKeyValues(be,Ie.past_key_values),Ie.input_ids=new v.Tensor("int64",W.flat(),[W.length,1]),ke||(Ie.attention_mask=(0,v.cat)([Ie.attention_mask,(0,v.ones)([Ie.attention_mask.dims[0],1])],1)),Ie.position_ids=null,Ie}_prepare_model_inputs({inputs:W,bos_token_id:be,model_kwargs:Ie}){const ke=(0,j.pick)(Ie,this.forward_params),Ye=this.main_input_name;if(Ye in ke){if(W)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else ke[Ye]=W;return{inputs_tensor:ke[Ye],model_inputs:ke,model_input_name:Ye}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:W,model_inputs:be,model_input_name:Ie,generation_config:ke}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!be.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:tt,pixel_values:ft,attention_mask:vt,...Rt}=be,Ut=await this._prepare_inputs_embeds(be);be={...Rt,...(0,j.pick)(Ut,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ye}=await qe(this,be);if(ke.guidance_scale!==null&&ke.guidance_scale>1)Ye=(0,v.cat)([Ye,(0,v.full_like)(Ye,0)],0),"attention_mask"in be&&(be.attention_mask=(0,v.cat)([be.attention_mask,(0,v.zeros_like)(be.attention_mask)],0));else if(be.decoder_input_ids){const tt=Ce(be.decoder_input_ids).dims[0];if(tt!==Ye.dims[0]){if(Ye.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ye.dims[0]}) than the decoder inputs (${tt}).`);Ye=(0,v.cat)(Array.from({length:tt},()=>Ye),0)}}return be.encoder_outputs=Ye,be}_prepare_decoder_input_ids_for_generation({batch_size:W,model_input_name:be,model_kwargs:Ie,decoder_start_token_id:ke,bos_token_id:Ye,generation_config:tt}){let{decoder_input_ids:ft,...vt}=Ie;if(!(ft instanceof v.Tensor)){if(ft)Array.isArray(ft[0])||(ft=Array.from({length:W},()=>ft));else if(ke??(ke=Ye),this.config.model_type==="musicgen")ft=Array.from({length:W*this.config.decoder.num_codebooks},()=>[ke]);else if(Array.isArray(ke)){if(ke.length!==W)throw new Error(`\`decoder_start_token_id\` expcted to have length ${W} but got ${ke.length}`);ft=ke}else ft=Array.from({length:W},()=>[ke]);ft=Ce(ft)}return Ie.decoder_attention_mask=(0,v.ones_like)(ft),{input_ids:ft,model_inputs:vt}}async generate({inputs:W=null,generation_config:be=null,logits_processor:Ie=null,stopping_criteria:ke=null,streamer:Ye=null,...tt}){this._validate_model_class(),be=this._prepare_generation_config(be,tt);let{inputs_tensor:ft,model_inputs:vt,model_input_name:Rt}=this._prepare_model_inputs({inputs:W,model_kwargs:tt});const Ut=this.config.is_encoder_decoder;Ut&&("encoder_outputs"in vt||(vt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ft,model_inputs:vt,model_input_name:Rt,generation_config:be})));let Lt;Ut?{input_ids:Lt,model_inputs:vt}=this._prepare_decoder_input_ids_for_generation({batch_size:vt[Rt].dims.at(0),model_input_name:Rt,model_kwargs:vt,decoder_start_token_id:be.decoder_start_token_id,bos_token_id:be.bos_token_id,generation_config:be}):Lt=vt[Rt];let Vt=Lt.dims.at(-1);be.max_new_tokens!==null&&(be.max_length=Vt+be.max_new_tokens);const Zt=this._get_logits_processor(be,Vt,Ie),ss=this._get_stopping_criteria(be,ke),qt=vt[Rt].dims.at(0),as=oe.LogitsSampler.getSampler(be),xs=new Array(qt).fill(0),vs=Lt.tolist();Ye&&Ye.put(vs);let cs,Es={};for(;;){if(vt=this.prepare_inputs_for_generation(vs,vt,be),cs=await this.forward(vt),be.output_attentions&&be.return_dict_in_generate){const rr=this.getAttentions(cs);for(const Ar in rr)Ar in Es||(Es[Ar]=[]),Es[Ar].push(rr[Ar])}const js=cs.logits.slice(null,-1,null),_r=Zt(vs,js),En=[];for(let rr=0;rr<_r.dims.at(0);++rr){const Ar=_r[rr],Ea=await as(Ar);for(const[Pa,xi]of Ea){const Ei=BigInt(Pa);xs[rr]+=xi,vs[rr].push(Ei),En.push([Ei]);break}}if(Ye&&Ye.put(En),ss(vs).every(rr=>rr))break;vt=this._update_model_kwargs_for_generation({generated_input_ids:En,outputs:cs,model_inputs:vt,is_encoder_decoder:Ut})}Ye&&Ye.end();const $s=this.getPastKeyValues(cs,vt.past_key_values,!0),Hs=new v.Tensor("int64",vs.flat(),[vs.length,vs[0].length]);if(be.return_dict_in_generate)return{sequences:Hs,past_key_values:$s,...Es};for(const js of Object.values(cs))js.location==="gpu-buffer"&&js.dispose();return Hs}getPastKeyValues(W,be,Ie=!1){const ke=Object.create(null);for(const Ye in W)if(Ye.startsWith("present")){const tt=Ye.replace("present","past_key_values"),ft=Ye.includes("encoder");if(ft&&be?ke[tt]=be[tt]:ke[tt]=W[Ye],be&&(!ft||Ie)){const vt=be[tt];vt.location==="gpu-buffer"&&vt.dispose()}}return ke}getAttentions(W){const be={};for(const Ie of["cross_attentions","encoder_attentions","decoder_attentions"])for(const ke in W)ke.startsWith(Ie)&&(Ie in be||(be[Ie]=[]),be[Ie].push(W[ke]));return be}addPastKeyValues(W,be){var Ie,ke,Ye;if(be)Object.assign(W,be);else{const tt=this.sessions.decoder_model_merged??this.sessions.model,ft=((Ie=tt==null?void 0:tt.config)==null?void 0:Ie.kv_cache_dtype)??"float32",vt=ft==="float16"?new Uint16Array:[],Rt=((Ye=(ke=W[this.main_input_name]??W.attention_mask)==null?void 0:ke.dims)==null?void 0:Ye[0])??1,Ut=(0,_.getKeyValueShapes)(this.config,{batch_size:Rt});for(const Lt in Ut)W[Lt]=new v.Tensor(ft,vt,Ut[Lt])}}async encode_image({pixel_values:W}){const be=(await ce(this.sessions.vision_encoder,{pixel_values:W})).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 (${be.dims[1]}).`),this.config.num_image_tokens=be.dims[1]),be}async encode_text({input_ids:W}){return(await ce(this.sessions.embed_tokens,{input_ids:W})).inputs_embeds}}class Je{}class Fe extends Je{constructor({last_hidden_state:P,hidden_states:W=null,attentions:be=null}){super(),this.last_hidden_state=P,this.hidden_states=W,this.attentions=be}}class pe extends ie{}class ve extends pe{}class Re extends pe{async _call(P){return new Ws(await super._call(P))}}class je extends pe{async _call(P){return new Qt(await super._call(P))}}class Ve extends pe{async _call(P){return new Us(await super._call(P))}}class Ne extends pe{async _call(P){return new Ys(await super._call(P))}}class Ze extends ie{}class at extends Ze{}class ht extends ie{}class dt extends ht{}class gt extends ht{async _call(P){return new Ws(await super._call(P))}}class F extends ht{async _call(P){return new Qt(await super._call(P))}}class ne extends ht{async _call(P){return new Us(await super._call(P))}}class K extends ht{async _call(P){return new Ys(await super._call(P))}}class de extends ie{}class Oe extends de{}class Qe extends de{async _call(P){return new Ws(await super._call(P))}}class rt extends de{async _call(P){return new Qt(await super._call(P))}}class mt extends de{async _call(P){return new Us(await super._call(P))}}class Ot extends de{async _call(P){return new Ys(await super._call(P))}}class xt extends ie{}class Ft extends xt{}class At extends xt{async _call(P){return new Ws(await super._call(P))}}class rs extends xt{async _call(P){return new Qt(await super._call(P))}}class ws extends xt{async _call(P){return new Us(await super._call(P))}}class Os extends xt{async _call(P){return new Ys(await super._call(P))}}class ks extends ie{}class qs extends ks{}class ir extends ks{async _call(P){return new Ws(await super._call(P))}}class Kr extends ks{async _call(P){return new Qt(await super._call(P))}}class Or extends ks{async _call(P){return new Us(await super._call(P))}}class mn extends ks{async _call(P){return new Ys(await super._call(P))}}class zt extends ie{}class Hr extends zt{}class kr extends zt{async _call(P){return new Ws(await super._call(P))}}class Fr extends zt{async _call(P){return new Qt(await super._call(P))}}class Sr extends zt{async _call(P){return new Us(await super._call(P))}}class Dr extends zt{async _call(P){return new Ys(await super._call(P))}}class Zs extends ie{}class dr extends Zs{}class $r extends Zs{async _call(P){return new Ws(await super._call(P))}}class qr extends Zs{async _call(P){return new Qt(await super._call(P))}}class or extends Zs{async _call(P){return new Us(await super._call(P))}}class ot extends Zs{async _call(P){return new Ys(await super._call(P))}}class pt extends ie{}class It extends pt{}class us extends pt{async _call(P){return new Qt(await super._call(P))}}class Mr extends pt{async _call(P){return new Us(await super._call(P))}}class ts extends pt{async _call(P){return new Ys(await super._call(P))}}class br extends pt{async _call(P){return new Ws(await super._call(P))}}class cr extends ie{}class Xr extends cr{}class Lr extends cr{async _call(P){return new Ws(await super._call(P))}}class vr extends cr{async _call(P){return new Qt(await super._call(P))}}class An extends cr{async _call(P){return new Us(await super._call(P))}}class zr extends ie{}class In extends zr{}class si extends zr{async _call(P){return new Ws(await super._call(P))}}class Br extends zr{async _call(P){return new Qt(await super._call(P))}}class Tr extends zr{async _call(P){return new Ys(await super._call(P))}}class er extends ie{}class fn extends er{}class Qr extends er{async _call(P){return new Ws(await super._call(P))}}class _n extends er{async _call(P){return new Qt(await super._call(P))}}class Yr extends er{async _call(P){return new Us(await super._call(P))}}class gn extends er{async _call(P){return new Ys(await super._call(P))}}class Bt extends ie{}class wn extends Bt{}class On extends Bt{async _call(P){return new Ws(await super._call(P))}}class Fn extends Bt{async _call(P){return new Qt(await super._call(P))}}class Dn extends Bt{async _call(P){return new Ys(await super._call(P))}}class Rr extends ie{}class Ln extends Rr{}class yn extends Rr{async _call(P){return new Qt(await super._call(P))}}class zn extends Rr{async _call(P){return new Ys(await super._call(P))}}class is extends Rr{async _call(P){return new Ws(await super._call(P))}}class tr extends ie{constructor(){super(...arguments);_e(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Mn extends tr{}class Bn extends tr{}class Jr extends ie{}class bn extends Jr{}class Ee extends Jr{}class E extends ie{}class q extends E{}class ae extends E{}class ye extends ie{}class Pe extends ye{}class He extends ye{}class ct extends ye{async _call(P){return new Qt(await super._call(P))}}class wt extends ie{}class _t extends wt{}class it extends wt{}class Ct extends wt{async _call(P){return new Qt(await super._call(P))}}class ms extends wt{}class ns extends ie{}class Se extends ns{}class ys extends ns{}class Fs extends ie{}class Xs extends Fs{}class Js extends Fs{}class Dt extends ie{}class Ns extends Dt{}class xr extends Dt{async _call(P){return new Ws(await super._call(P))}}class es extends Dt{async _call(P){return new Qt(await super._call(P))}}class _s extends Dt{async _call(P){return new Us(await super._call(P))}}class Tt extends Dt{async _call(P){return new Ys(await super._call(P))}}class os extends ie{}class Er extends os{}class Ds extends os{async _call(P){return new Ws(await super._call(P))}}class Gs extends os{async _call(P){return new Qt(await super._call(P))}}class Mt extends os{async _call(P){return new Us(await super._call(P))}}class Ss extends os{async _call(P){return new Ys(await super._call(P))}}class De extends ie{}class yt extends De{}class sr extends De{async _call(P){return new Ws(await super._call(P))}}class Zr extends De{async _call(P){return new Qt(await super._call(P))}}class ri extends De{async _call(P){return new Us(await super._call(P))}}class La extends De{async _call(P){return new Ys(await super._call(P))}}class Xt extends ie{}class za extends Xt{}class zi extends Xt{}class Bi extends ie{constructor(){super(...arguments);_e(this,"requires_attention_mask",!1);_e(this,"main_input_name","input_features");_e(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ba extends Bi{}class Ra extends Bi{_prepare_generation_config(P,W){return super._prepare_generation_config(P,W,V.WhisperGenerationConfig)}_retrieve_init_tokens(P){const W=[P.decoder_start_token_id];let be=P.language;const Ie=P.task;if(P.is_multilingual){be||(console.warn("No language specified - defaulting to English (en)."),be="en");const Ye=`<|${(0,Y.whisper_language_to_code)(be)}|>`;W.push(P.lang_to_id[Ye]),W.push(P.task_to_id[Ie??"transcribe"])}else if(be||Ie)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!P.return_timestamps&&P.no_timestamps_token_id&&W.at(-1)!==P.no_timestamps_token_id?W.push(P.no_timestamps_token_id):P.return_timestamps&&W.at(-1)===P.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),W.pop()),W.filter(ke=>ke!=null)}async generate({inputs:P=null,generation_config:W=null,logits_processor:be=null,stopping_criteria:Ie=null,...ke}){W=this._prepare_generation_config(W,ke);const Ye=ke.decoder_input_ids??this._retrieve_init_tokens(W);if(W.return_timestamps&&(be??(be=new y.LogitsProcessorList),be.push(new y.WhisperTimeStampLogitsProcessor(W,Ye))),W.begin_suppress_tokens&&(be??(be=new y.LogitsProcessorList),be.push(new y.SuppressTokensAtBeginLogitsProcessor(W.begin_suppress_tokens,Ye.length))),W.return_token_timestamps){if(!W.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.");W.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),W.output_attentions=!0,W.return_dict_in_generate=!0}const tt=await super.generate({inputs:P,generation_config:W,logits_processor:be,decoder_input_ids:Ye,...ke});return W.return_token_timestamps&&(tt.token_timestamps=this._extract_token_timestamps(tt,W.alignment_heads,W.num_frames)),tt}_extract_token_timestamps(P,W,be=null,Ie=.02){if(!P.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`.");be==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 ke=this.config.median_filter_width;ke===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),ke=7);const Ye=P.cross_attentions,tt=Array.from({length:this.config.decoder_layers},(ss,qt)=>(0,v.cat)(Ye.map(as=>as[qt]),2)),ft=(0,v.stack)(W.map(([ss,qt])=>{if(ss>=tt.length)throw new Error(`Layer index ${ss} is out of bounds for cross attentions (length ${tt.length}).`);return be?tt[ss].slice(null,qt,null,[0,be]):tt[ss].slice(null,qt)})).transpose(1,0,2,3),[vt,Rt]=(0,v.std_mean)(ft,-2,0,!0),Ut=ft.clone();for(let ss=0;ssas[Hs+1]-as[Hs]),cs=(0,j.mergeArrays)([1],vs).map($s=>!!$s),Es=[];for(let $s=0;$sLt.findIndex(Vt=>Vt==ke)),ft=tt.every(Lt=>Lt===-1),vt=tt.every(Lt=>Lt!==-1);if(!ft&&!vt)throw new Error("Every input should contain either 0 or 1 image token.");if(ft)return{inputs_embeds:P,attention_mask:Ie};const Rt=[],Ut=[];for(let Lt=0;LtArray.from({length:P.dims[0]},vs=>Array.from({length:P.dims[1]},cs=>1))),Zt=W?W.tolist():[],ss=be?be.tolist():[];let qt=0,as=0;for(let xs=0;xsLt[xs][Ls]==1),Es=vs.reduce((Ps,Ls,Vr)=>(Ls==ft&&Ps.push(Vr),Ps),[]).map(Ps=>vs[Ps+1]),$s=Es.filter(Ps=>Ps==Ye).length,Hs=Es.filter(Ps=>Ps==tt).length;let js=[],_r=0,En=$s,gc=Hs;for(let Ps=0;Psgr>_r&&an==Ye),Vr=vs.findIndex((an,gr)=>gr>_r&&an==tt),Pn=En>0&&Ls!==-1?Ls:vs.length+1,Cn=gc>0&&Vr!==-1?Vr:vs.length+1;let Gn,Ca,Pi,Ci;Pn0?(0,H.max)(js.at(-1))[0]+1:0;js.push(Array.from({length:3*yc},(an,gr)=>Sa+gr%yc));const $a=yc+Sa,Si=wc*ka*ki,Vp=Array.from({length:Si},(an,gr)=>$a+Math.floor(gr/(ka*ki))),yp=Array.from({length:Si},(an,gr)=>$a+Math.floor(gr/ki)%ka),Aa=Array.from({length:Si},(an,gr)=>$a+gr%ki);js.push([Vp,yp,Aa].flat()),_r=Gn+Si}if(_r0?(0,H.max)(js.at(-1))[0]+1:0,Ls=vs.length-_r;js.push(Array.from({length:3*Ls},(Vr,Pn)=>Ps+Pn%Ls))}const rr=js.reduce((Ps,Ls)=>Ps+Ls.length,0),Ar=new Array(rr);let Ea=0;for(let Ps=0;Ps<3;++Ps)for(let Ls=0;LsUt[qt%Ut.length]),Zt=Array.from({length:Lt[0]},(ss,qt)=>(0,H.max)(Ut.subarray(Lt[1]*qt,Lt[1]*(qt+1)))[0]+1+Lt[1]);return[new v.Tensor("int64",Vt,[3,...Lt]),new v.Tensor("int64",Zt,[Zt.length,1])]}else{const[Ut,Lt]=P.dims,Vt=BigInt64Array.from({length:3*Ut*Lt},(Zt,ss)=>BigInt(Math.floor(ss%Lt/Ut)));return[new v.Tensor("int64",Vt,[3,...P.dims]),(0,v.zeros)([Ut,1])]}}async encode_image({pixel_values:P,image_grid_thw:W}){return(await ce(this.sessions.vision_encoder,{pixel_values:P,grid_thw:W})).image_features}_merge_input_ids_with_image_features(P){return ut({image_token_id:this.config.image_token_id,...P})}prepare_inputs_for_generation(P,W,be){if(W.attention_mask&&!W.position_ids)if(!W.past_key_values)[W.position_ids,W.rope_deltas]=this.get_rope_index(W.input_ids,W.image_grid_thw,W.video_grid_thw,W.attention_mask);else{W.pixel_values=null;const Ie=BigInt(Object.values(W.past_key_values)[0].dims.at(-2)),ke=W.rope_deltas.map(Ye=>Ie+Ye);W.position_ids=(0,v.stack)([ke,ke,ke],0)}return W}}class po extends ie{}class Al extends po{}class Nn extends po{}class ho extends ie{}class ui extends ho{}class Il extends ho{}class mo extends ie{}class Ol extends mo{}class Fl extends mo{}class fo extends ie{}class Dl extends fo{}class Ll extends fo{}class _o extends ie{}class zl extends _o{}class Bl extends _o{}class go extends ie{}class Rl extends go{}class Nl extends go{async _call(P){return new Qt(await super._call(P))}}class wo extends ie{}class jl extends wo{}class Ul extends wo{async _call(P){return new Qt(await super._call(P))}}class yo extends ie{}class Wl extends yo{}class di extends ie{}class Mo extends di{}class Vl extends di{async _call(P){return new Qt(await super._call(P))}}class Gl extends ie{}class Kl extends Gl{}class bo extends ie{}class Hl extends bo{}class ql extends bo{async _call(P){return new Qt(await super._call(P))}}class vo extends ie{}class Xl extends vo{}class To extends ie{}class Ql extends To{}class Bc extends To{async _call(P){return new Qt(await super._call(P))}}class Yl extends ie{}class Jl extends Yl{async _call(P){return new _c(await super._call(P))}}class ur extends ie{}class Zl extends ur{}class eu extends ur{async _call(P){return new Qt(await super._call(P))}}class xo extends ie{}class tu extends xo{}class su extends xo{async _call(P){return new Qt(await super._call(P))}}class Eo extends ie{}class ru extends Eo{}class nu extends Eo{}class Po extends ie{}class iu extends Po{}class Rc extends Po{}class Co extends ie{}class ou extends Co{}class au extends Co{async _call(P){return new Qt(await super._call(P))}}class ci extends ie{}class lu extends ci{}class uu extends ci{async _call(P){return new jr(await super._call(P))}}class du extends ci{async _call(P){return new tn(await super._call(P))}}class jr extends Je{constructor({logits:P,pred_boxes:W}){super(),this.logits=P,this.pred_boxes=W}}class tn extends Je{constructor({logits:P,pred_boxes:W,pred_masks:be}){super(),this.logits=P,this.pred_boxes=W,this.pred_masks=be}}class Ur extends ie{}class ko extends Ur{}class sn extends Ur{async _call(P){return new Ks(await super._call(P))}}class Ks extends Je{constructor({logits:P,pred_boxes:W}){super(),this.logits=P,this.pred_boxes=W}}class So extends ie{}class $o extends So{}class cu extends So{async _call(P){return new Nc(await super._call(P))}}class Nc extends jr{}class vn extends ie{}class Ao extends vn{}class Io extends vn{async _call(P){return new Qt(await super._call(P))}}class Oo extends ie{}class pu extends Oo{}class Fo extends Oo{async _call(P){return new Qt(await super._call(P))}}class pi extends ie{}class hu extends pi{}class Do extends pi{async _call(P){return new Qt(await super._call(P))}}class Lo extends ie{}class hi extends Lo{}class zo extends Lo{async _call(P){return new Qt(await super._call(P))}}class Bo extends ie{}class mu extends Bo{}class jc extends Bo{}class Ro extends ie{}class No extends Ro{}class jn extends Ro{}class fu extends ie{}class jo extends fu{}class mi extends ie{}class _u extends mi{}class gu extends mi{}class Uc extends mi{}class wu extends ie{}class yu extends wu{}class Mu extends ie{}class bu extends Mu{}class fi extends Mu{}class Uo extends ie{}class _i extends Uo{}class Wo extends Uo{}class Vo extends ie{}class vu extends Vo{}class Go extends ie{}class Ko extends Go{}class Wc extends Go{async _call(P){return new Qt(await super._call(P))}}class Ho extends ie{}class Vc extends Ho{}class Tu extends Ho{async _call(P){return new Qt(await super._call(P))}}class qo extends ie{}class xu extends qo{}class Xo extends qo{async _call(P){return new Qt(await super._call(P))}}class Qo extends ie{}class Eu extends Qo{}class Yo extends Qo{async _call(P){return new Pu(await super._call(P))}}class Pu extends Je{constructor({logits:P,pred_boxes:W}){super(),this.logits=P,this.pred_boxes=W}}class Cu extends ie{}class Gc extends Cu{async get_image_embeddings({pixel_values:P}){return await qe(this,{pixel_values:P})}async forward(P){if((!P.image_embeddings||!P.image_positional_embeddings)&&(P={...P,...await this.get_image_embeddings(P)}),!P.input_labels&&P.input_points){const be=P.input_points.dims.slice(0,-1),Ie=be.reduce((ke,Ye)=>ke*Ye,1);P.input_labels=new v.Tensor("int64",new BigInt64Array(Ie).fill(1n),be)}const W={image_embeddings:P.image_embeddings,image_positional_embeddings:P.image_positional_embeddings};return P.input_points&&(W.input_points=P.input_points),P.input_labels&&(W.input_labels=P.input_labels),P.input_boxes&&(W.input_boxes=P.input_boxes),await ce(this.sessions.prompt_encoder_mask_decoder,W)}async _call(P){return new ku(await super._call(P))}}class ku extends Je{constructor({iou_scores:P,pred_masks:W}){super(),this.iou_scores=P,this.pred_masks=W}}class Jo extends ie{}class Su extends Jo{}class Kc extends Jo{}class Zo extends ie{}class $u extends Zo{}class Au extends Zo{}class Wr extends ie{}class Iu extends Wr{}class Hc extends Wr{async _call(P){return new on(await super._call(P))}}class gi extends Wr{async _call(P){return new Qt(await super._call(P))}}class Un extends Wr{async _call(P){return new Us(await super._call(P))}}class wi extends ie{}class Ou extends wi{}class Fu extends wi{async _call(P){return new Us(await super._call(P))}}class Du extends ie{}class Lu extends Du{}class Wn extends ie{}class zu extends Wn{}class Bu extends Wn{async _call(P){return new on(await super._call(P))}}class Ru extends Wn{async _call(P){return new Qt(await super._call(P))}}class yi extends ie{}class Nu extends yi{}class ea extends yi{async _call(P){return new on(await super._call(P))}}class ju extends yi{async _call(P){return new Qt(await super._call(P))}}class Uu extends yi{async _call(P){return new Us(await super._call(P))}}class Mi extends ie{}class qc extends Mi{}class Wu extends Mi{async _call(P){return new on(await super._call(P))}}class Vu extends Mi{async _call(P){return new Qt(await super._call(P))}}class Up extends ie{}class Gu extends Wr{}class Ku extends Wr{async _call(P){return new on(await super._call(P))}}class Hu extends Wr{async _call(P){return new Qt(await super._call(P))}}class Tn extends ie{}class Xc extends Tn{}class qu extends Tn{async _call(P){return new on(await super._call(P))}}class Xu extends Tn{async _call(P){return new Qt(await super._call(P))}}class Qu extends Tn{async _call(P){return new fc(await super._call(P))}}class Qc extends Tn{async _call(P){return new Us(await super._call(P))}}class bi extends ie{}class Yc extends bi{}class Yu extends bi{}class Ju extends bi{async generate_speech(P,W,{threshold:be=.5,minlenratio:Ie=0,maxlenratio:ke=20,vocoder:Ye=null}={}){const tt={input_ids:P},{encoder_outputs:ft,encoder_attention_mask:vt}=await qe(this,tt),Rt=ft.dims[1]/this.config.reduction_factor,Ut=Math.floor(Rt*ke),Lt=Math.floor(Rt*Ie),Vt=this.config.num_mel_bins;let Zt=[],ss=null,qt=null,as=0;for(;;){++as;const cs=Te(!!qt);let Es;qt?Es=qt.output_sequence_out:Es=new v.Tensor("float32",new Float32Array(Vt),[1,1,Vt]);let $s={use_cache_branch:cs,output_sequence:Es,encoder_attention_mask:vt,speaker_embeddings:W,encoder_hidden_states:ft};this.addPastKeyValues($s,ss),qt=await ce(this.sessions.decoder_model_merged,$s),ss=this.getPastKeyValues(qt,ss);const{prob:Hs,spectrum:js}=qt;if(Zt.push(js),as>=Lt&&(Array.from(Hs.data).filter(_r=>_r>=be).length>0||as>=Ut))break}const xs=(0,v.cat)(Zt),{waveform:vs}=await ce(Ye.sessions.model,{spectrogram:xs});return{spectrogram:xs,waveform:vs}}}class Jc extends ie{constructor(){super(...arguments);_e(this,"main_input_name","spectrogram")}}class Zu extends ie{}class ed extends Zu{}class ta extends ie{}class td extends ta{}class Zc extends ta{}class sa extends ie{}class sd extends sa{}class rd extends sa{}class ra extends ie{}class ep extends ra{}class Pr extends ra{}class fr extends ie{}class rn extends fr{}class nn extends fr{static async from_pretrained(P,W={}){return super.from_pretrained(P,{model_file_name:"text_model",...W})}}class nd extends fr{static async from_pretrained(P,W={}){return super.from_pretrained(P,{model_file_name:"audio_model",...W})}}class id extends ie{}class na extends id{async _call(P){return new wp(await super._call(P))}}class vi extends ie{}class tp extends vi{}class od extends vi{}class ad extends vi{}class ia extends ie{}class ld extends ia{}class ud extends ia{}class dd extends ie{}class Qs extends dd{}class cd extends dd{async _call(P){return new Qt(await super._call(P))}}class oa extends ie{}class pd extends oa{}class sp extends oa{}class xn extends ie{constructor(){super(...arguments);_e(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(W){const[be,Ie]=W.dims,ke=this.config.decoder.num_codebooks,Ye=Ie-ke;let tt=0;for(let Rt=0;Rt0&&Vt<=Ye&&(W.data[tt++]=W.data[Rt])}const ft=Math.floor(be/ke),vt=tt/(ft*ke);return new v.Tensor(W.type,W.data.slice(0,tt),[ft,ke,vt])}prepare_inputs_for_generation(W,be,Ie){let ke=structuredClone(W);for(let tt=0;tt=ft&&(ke[tt][ft]=BigInt(this.config.decoder.pad_token_id));return Ie.guidance_scale!==null&&Ie.guidance_scale>1&&(ke=ke.concat(ke)),super.prepare_inputs_for_generation(ke,be,Ie)}async generate(W){const be=await super.generate(W),Ie=this._apply_and_filter_by_delay_pattern_mask(be).unsqueeze_(0),{audio_values:ke}=await ce(this.sessions.encodec_decode,{audio_codes:Ie});return ke}}class aa extends ie{}class hd extends aa{}class md extends aa{async _call(P){return new Qt(await super._call(P))}}class la extends ie{}class fd extends la{}class _d extends la{async _call(P){return new Qt(await super._call(P))}}class Ti extends ie{}class gd extends Ti{}class wd extends Ti{async _call(P){return new Qt(await super._call(P))}}class ua extends ie{}class yd extends ua{}class Md extends ua{async _call(P){return new Qt(await super._call(P))}}class da extends ie{}class bd extends da{}class rp extends ie{}class ca extends rp{constructor(...W){super(...W);_e(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(W){const be=this._generation_mode??"text";let Ie;if(be==="text"||!W.past_key_values){const vt=this.sessions.prepare_inputs_embeds,Rt=(0,j.pick)(W,vt.inputNames);Ie=await ce(vt,Rt)}else{const vt=this.sessions.gen_img_embeds,Rt=(0,j.pick)({image_ids:W.input_ids},vt.inputNames);Ie=await ce(vt,Rt)}const ke={...W,...Ie},Ye=await Ue(this,ke),tt=this.sessions[be==="text"?"lm_head":"gen_head"];if(!tt)throw new Error(`Unable to find "${tt}" generation head`);const ft=await ce(tt,(0,j.pick)(Ye,tt.inputNames));return{...Ie,...Ye,...ft}}async generate(W){return this._generation_mode="text",super.generate(W)}async generate_images(W){this._generation_mode="image";const be=(W.inputs??W[this.main_input_name]).dims[1],ke=(await super.generate(W)).slice(null,[be,null]),Ye=this.sessions.image_decode,{decoded_image:tt}=await ce(Ye,{generated_tokens:ke}),ft=tt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),vt=[];for(const Rt of ft){const Ut=L.RawImage.fromTensor(Rt);vt.push(Ut)}return vt}}class vd extends Je{constructor({char_logits:P,bpe_logits:W,wp_logits:be}){super(),this.char_logits=P,this.bpe_logits=W,this.wp_logits=be}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Td extends ie{}class xd extends Td{async _call(P){return new vd(await super._call(P))}}class Ed extends ie{}class Pd extends Ed{}class Cd extends Ed{}class pa extends ie{}class np extends pa{}class kd extends pa{}class gs{static async from_pretrained(P,{progress_callback:W=null,config:be=null,cache_dir:Ie=null,local_files_only:ke=!1,revision:Ye="main",model_file_name:tt=null,subfolder:ft="onnx",device:vt=null,dtype:Rt=null,use_external_data_format:Ut=null,session_options:Lt={}}={}){const Vt={progress_callback:W,config:be,cache_dir:Ie,local_files_only:ke,revision:Ye,model_file_name:tt,subfolder:ft,device:vt,dtype:Rt,use_external_data_format:Ut,session_options:Lt};if(Vt.config=await _.AutoConfig.from_pretrained(P,Vt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const Zt of this.MODEL_CLASS_MAPPINGS){const ss=Zt.get(Vt.config.model_type);if(ss)return await ss[1].from_pretrained(P,Vt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Vt.config.model_type}", attempting to construct from base class.`),await ie.from_pretrained(P,Vt);throw Error(`Unsupported model type: ${Vt.config.model_type}`)}}_e(gs,"MODEL_CLASS_MAPPINGS",null),_e(gs,"BASE_IF_FAIL",!1);const Wp=new Map([["bert",["BertModel",ve]],["nomic_bert",["NomicBertModel",at]],["roformer",["RoFormerModel",dt]],["electra",["ElectraModel",Ft]],["esm",["EsmModel",Xr]],["convbert",["ConvBertModel",Oe]],["camembert",["CamembertModel",qs]],["deberta",["DebertaModel",Hr]],["deberta-v2",["DebertaV2Model",dr]],["mpnet",["MPNetModel",fn]],["albert",["AlbertModel",Ln]],["distilbert",["DistilBertModel",It]],["roberta",["RobertaModel",Ns]],["xlm",["XLMModel",Er]],["xlm-roberta",["XLMRobertaModel",yt]],["clap",["ClapModel",rn]],["clip",["CLIPModel",Xa]],["clipseg",["CLIPSegModel",tl]],["chinese_clip",["ChineseCLIPModel",pr]],["siglip",["SiglipModel",Ja]],["jina_clip",["JinaCLIPModel",oi]],["mobilebert",["MobileBertModel",In]],["squeezebert",["SqueezeBertModel",wn]],["wav2vec2",["Wav2Vec2Model",Iu]],["wav2vec2-bert",["Wav2Vec2BertModel",qc]],["unispeech",["UniSpeechModel",zu]],["unispeech-sat",["UniSpeechSatModel",Nu]],["hubert",["HubertModel",Gu]],["wavlm",["WavLMModel",Xc]],["audio-spectrogram-transformer",["ASTModel",za]],["vits",["VitsModel",na]],["pyannote",["PyAnnoteModel",Ou]],["wespeaker-resnet",["WeSpeakerResNetModel",Lu]],["detr",["DetrModel",lu]],["rt_detr",["RTDetrModel",ko]],["table-transformer",["TableTransformerModel",$o]],["vit",["ViTModel",Rl]],["ijepa",["IJepaModel",jl]],["pvt",["PvtModel",Mo]],["vit_msn",["ViTMSNModel",Hl]],["vit_mae",["ViTMAEModel",Kl]],["groupvit",["GroupViTModel",Xl]],["fastvit",["FastViTModel",Ql]],["mobilevit",["MobileViTModel",Zl]],["mobilevitv2",["MobileViTV2Model",tu]],["owlvit",["OwlViTModel",ru]],["owlv2",["Owlv2Model",iu]],["beit",["BeitModel",ou]],["deit",["DeiTModel",Ao]],["hiera",["HieraModel",pu]],["convnext",["ConvNextModel",Ko]],["convnextv2",["ConvNextV2Model",Vc]],["dinov2",["Dinov2Model",xu]],["resnet",["ResNetModel",hu]],["swin",["SwinModel",hi]],["swin2sr",["Swin2SRModel",mu]],["donut-swin",["DonutSwinModel",vu]],["yolos",["YolosModel",Eu]],["dpt",["DPTModel",No]],["glpn",["GLPNModel",_i]],["hifigan",["SpeechT5HifiGan",Jc]],["efficientnet",["EfficientNetModel",Qs]],["decision_transformer",["DecisionTransformerModel",bd]],["patchtst",["PatchTSTForPrediction",Pd]],["patchtsmixer",["PatchTSMixerForPrediction",np]],["mobilenet_v1",["MobileNetV1Model",hd]],["mobilenet_v2",["MobileNetV2Model",fd]],["mobilenet_v3",["MobileNetV3Model",gd]],["mobilenet_v4",["MobileNetV4Model",yd]],["maskformer",["MaskFormerModel",bu]],["mgp-str",["MgpstrForSceneTextRecognition",xd]]]),ip=new Map([["t5",["T5Model",Mn]],["longt5",["LongT5Model",bn]],["mt5",["MT5Model",q]],["bart",["BartModel",Pe]],["mbart",["MBartModel",_t]],["marian",["MarianModel",Su]],["whisper",["WhisperModel",Ba]],["m2m_100",["M2M100Model",$u]],["blenderbot",["BlenderbotModel",Se]],["blenderbot-small",["BlenderbotSmallModel",Xs]]]),op=new Map([["bloom",["BloomModel",Ol]],["jais",["JAISModel",il]],["gpt2",["GPT2Model",rl]],["gptj",["GPTJModel",dl]],["gpt_bigcode",["GPTBigCodeModel",pl]],["gpt_neo",["GPTNeoModel",mr]],["gpt_neox",["GPTNeoXModel",ll]],["codegen",["CodeGenModel",Yi]],["llama",["LlamaModel",Zi]],["exaone",["ExaoneModel",li]],["olmo",["OlmoModel",gl]],["olmo2",["Olmo2Model",wl]],["mobilellm",["MobileLLMModel",_l]],["granite",["GraniteModel",Lc]],["cohere",["CohereModel",bl]],["gemma",["GemmaModel",ds]],["gemma2",["Gemma2Model",Tl]],["openelm",["OpenELMModel",El]],["qwen2",["Qwen2Model",Cl]],["phi",["PhiModel",Al]],["phi3",["Phi3Model",ui]],["mpt",["MptModel",Dl]],["opt",["OPTModel",zl]],["mistral",["MistralModel",td]],["starcoder2",["Starcoder2Model",sd]],["falcon",["FalconModel",ep]],["stablelm",["StableLmModel",ld]]]),ha=new Map([["speecht5",["SpeechT5ForSpeechToText",Yu]],["whisper",["WhisperForConditionalGeneration",Ra]],["moonshine",["MoonshineForConditionalGeneration",Na]]]),Sd=new Map([["speecht5",["SpeechT5ForTextToSpeech",Ju]]]),$d=new Map([["vits",["VitsModel",na]],["musicgen",["MusicgenForConditionalGeneration",xn]]]),ap=new Map([["bert",["BertForSequenceClassification",je]],["roformer",["RoFormerForSequenceClassification",F]],["electra",["ElectraForSequenceClassification",rs]],["esm",["EsmForSequenceClassification",vr]],["convbert",["ConvBertForSequenceClassification",rt]],["camembert",["CamembertForSequenceClassification",Kr]],["deberta",["DebertaForSequenceClassification",Fr]],["deberta-v2",["DebertaV2ForSequenceClassification",qr]],["mpnet",["MPNetForSequenceClassification",_n]],["albert",["AlbertForSequenceClassification",yn]],["distilbert",["DistilBertForSequenceClassification",us]],["roberta",["RobertaForSequenceClassification",es]],["xlm",["XLMForSequenceClassification",Gs]],["xlm-roberta",["XLMRobertaForSequenceClassification",Zr]],["bart",["BartForSequenceClassification",ct]],["mbart",["MBartForSequenceClassification",Ct]],["mobilebert",["MobileBertForSequenceClassification",Br]],["squeezebert",["SqueezeBertForSequenceClassification",Fn]]]),Ad=new Map([["bert",["BertForTokenClassification",Ve]],["roformer",["RoFormerForTokenClassification",ne]],["electra",["ElectraForTokenClassification",ws]],["esm",["EsmForTokenClassification",An]],["convbert",["ConvBertForTokenClassification",mt]],["camembert",["CamembertForTokenClassification",Or]],["deberta",["DebertaForTokenClassification",Sr]],["deberta-v2",["DebertaV2ForTokenClassification",or]],["mpnet",["MPNetForTokenClassification",Yr]],["distilbert",["DistilBertForTokenClassification",Mr]],["roberta",["RobertaForTokenClassification",_s]],["xlm",["XLMForTokenClassification",Mt]],["xlm-roberta",["XLMRobertaForTokenClassification",ri]]]),ma=new Map([["t5",["T5ForConditionalGeneration",Bn]],["longt5",["LongT5ForConditionalGeneration",Ee]],["mt5",["MT5ForConditionalGeneration",ae]],["bart",["BartForConditionalGeneration",He]],["mbart",["MBartForConditionalGeneration",it]],["marian",["MarianMTModel",Kc]],["m2m_100",["M2M100ForConditionalGeneration",Au]],["blenderbot",["BlenderbotForConditionalGeneration",ys]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Js]]]),fa=new Map([["bloom",["BloomForCausalLM",Fl]],["gpt2",["GPT2LMHeadModel",nl]],["jais",["JAISLMHeadModel",ol]],["gptj",["GPTJForCausalLM",cl]],["gpt_bigcode",["GPTBigCodeForCausalLM",hl]],["gpt_neo",["GPTNeoForCausalLM",al]],["gpt_neox",["GPTNeoXForCausalLM",ul]],["codegen",["CodeGenForCausalLM",ml]],["llama",["LlamaForCausalLM",Dc]],["exaone",["ExaoneForCausalLM",fl]],["olmo",["OlmoForCausalLM",ro]],["olmo2",["Olmo2ForCausalLM",yl]],["mobilellm",["MobileLLMForCausalLM",Rn]],["granite",["GraniteForCausalLM",Ml]],["cohere",["CohereForCausalLM",zc]],["gemma",["GemmaForCausalLM",vl]],["gemma2",["Gemma2ForCausalLM",xl]],["openelm",["OpenELMForCausalLM",Pl]],["qwen2",["Qwen2ForCausalLM",kl]],["phi",["PhiForCausalLM",Nn]],["phi3",["Phi3ForCausalLM",Il]],["mpt",["MptForCausalLM",Ll]],["opt",["OPTForCausalLM",Bl]],["mbart",["MBartForCausalLM",ms]],["mistral",["MistralForCausalLM",Zc]],["starcoder2",["Starcoder2ForCausalLM",rd]],["falcon",["FalconForCausalLM",Pr]],["trocr",["TrOCRForCausalLM",ed]],["stablelm",["StableLmForCausalLM",ud]],["phi3_v",["Phi3VForCausalLM",lr]]]),lp=new Map([["multi_modality",["MultiModalityCausalLM",ca]]]),Id=new Map([["bert",["BertForMaskedLM",Re]],["roformer",["RoFormerForMaskedLM",gt]],["electra",["ElectraForMaskedLM",At]],["esm",["EsmForMaskedLM",Lr]],["convbert",["ConvBertForMaskedLM",Qe]],["camembert",["CamembertForMaskedLM",ir]],["deberta",["DebertaForMaskedLM",kr]],["deberta-v2",["DebertaV2ForMaskedLM",$r]],["mpnet",["MPNetForMaskedLM",Qr]],["albert",["AlbertForMaskedLM",is]],["distilbert",["DistilBertForMaskedLM",br]],["roberta",["RobertaForMaskedLM",xr]],["xlm",["XLMWithLMHeadModel",Ds]],["xlm-roberta",["XLMRobertaForMaskedLM",sr]],["mobilebert",["MobileBertForMaskedLM",si]],["squeezebert",["SqueezeBertForMaskedLM",On]]]),Od=new Map([["bert",["BertForQuestionAnswering",Ne]],["roformer",["RoFormerForQuestionAnswering",K]],["electra",["ElectraForQuestionAnswering",Os]],["convbert",["ConvBertForQuestionAnswering",Ot]],["camembert",["CamembertForQuestionAnswering",mn]],["deberta",["DebertaForQuestionAnswering",Dr]],["deberta-v2",["DebertaV2ForQuestionAnswering",ot]],["mpnet",["MPNetForQuestionAnswering",gn]],["albert",["AlbertForQuestionAnswering",zn]],["distilbert",["DistilBertForQuestionAnswering",ts]],["roberta",["RobertaForQuestionAnswering",Tt]],["xlm",["XLMForQuestionAnswering",Ss]],["xlm-roberta",["XLMRobertaForQuestionAnswering",La]],["mobilebert",["MobileBertForQuestionAnswering",Tr]],["squeezebert",["SqueezeBertForQuestionAnswering",Dn]]]),_a=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ni]],["idefics3",["Idefics3ForConditionalGeneration",ji]]]),up=new Map([["llava",["LlavaForConditionalGeneration",ni]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",ja]],["moondream1",["Moondream1ForConditionalGeneration",Ua]],["florence2",["Florence2ForConditionalGeneration",Va]],["qwen2-vl",["Qwen2VLForConditionalGeneration",$l]],["idefics3",["Idefics3ForConditionalGeneration",ji]],["paligemma",["PaliGemmaForConditionalGeneration",Ka]]]),dp=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ni]]]),cp=new Map([["vit",["ViTForImageClassification",Nl]],["ijepa",["IJepaForImageClassification",Ul]],["pvt",["PvtForImageClassification",Vl]],["vit_msn",["ViTMSNForImageClassification",ql]],["fastvit",["FastViTForImageClassification",Bc]],["mobilevit",["MobileViTForImageClassification",eu]],["mobilevitv2",["MobileViTV2ForImageClassification",su]],["beit",["BeitForImageClassification",au]],["deit",["DeiTForImageClassification",Io]],["hiera",["HieraForImageClassification",Fo]],["convnext",["ConvNextForImageClassification",Wc]],["convnextv2",["ConvNextV2ForImageClassification",Tu]],["dinov2",["Dinov2ForImageClassification",Xo]],["resnet",["ResNetForImageClassification",Do]],["swin",["SwinForImageClassification",zo]],["segformer",["SegformerForImageClassification",od]],["efficientnet",["EfficientNetForImageClassification",cd]],["mobilenet_v1",["MobileNetV1ForImageClassification",md]],["mobilenet_v2",["MobileNetV2ForImageClassification",_d]],["mobilenet_v3",["MobileNetV3ForImageClassification",wd]],["mobilenet_v4",["MobileNetV4ForImageClassification",Md]]]),Vn=new Map([["detr",["DetrForObjectDetection",uu]],["rt_detr",["RTDetrForObjectDetection",sn]],["table-transformer",["TableTransformerForObjectDetection",cu]],["yolos",["YolosForObjectDetection",Yo]]]),ga=new Map([["owlvit",["OwlViTForObjectDetection",nu]],["owlv2",["Owlv2ForObjectDetection",Rc]]]),wa=new Map([["detr",["DetrForSegmentation",du]],["clipseg",["CLIPSegForImageSegmentation",sl]]]),ya=new Map([["segformer",["SegformerForSemanticSegmentation",ad]],["sapiens",["SapiensForSemanticSegmentation",_u]]]),Ma=new Map([["detr",["DetrForSegmentation",du]],["maskformer",["MaskFormerForInstanceSegmentation",fi]]]),Fd=new Map([["sam",["SamModel",Gc]]]),Dd=new Map([["wav2vec2",["Wav2Vec2ForCTC",Hc]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Wu]],["unispeech",["UniSpeechForCTC",Bu]],["unispeech-sat",["UniSpeechSatForCTC",ea]],["wavlm",["WavLMForCTC",qu]],["hubert",["HubertForCTC",Ku]]]),ba=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",gi]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Vu]],["unispeech",["UniSpeechForSequenceClassification",Ru]],["unispeech-sat",["UniSpeechSatForSequenceClassification",ju]],["wavlm",["WavLMForSequenceClassification",Xu]],["hubert",["HubertForSequenceClassification",Hu]],["audio-spectrogram-transformer",["ASTForAudioClassification",zi]]]),va=new Map([["wavlm",["WavLMForXVector",Qu]]]),Ld=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Uu]],["wavlm",["WavLMForAudioFrameClassification",Qc]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Un]],["pyannote",["PyAnnoteForAudioFrameClassification",Fu]]]),zd=new Map([["vitmatte",["VitMatteForImageMatting",Jl]]]),Bd=new Map([["patchtst",["PatchTSTForPrediction",Cd]],["patchtsmixer",["PatchTSMixerForPrediction",kd]]]),Rd=new Map([["swin2sr",["Swin2SRForImageSuperResolution",jc]]]),Nd=new Map([["dpt",["DPTForDepthEstimation",jn]],["depth_anything",["DepthAnythingForDepthEstimation",jo]],["glpn",["GLPNForDepthEstimation",Wo]],["sapiens",["SapiensForDepthEstimation",gu]],["depth_pro",["DepthProForDepthEstimation",yu]]]),Ta=new Map([["sapiens",["SapiensForNormalEstimation",Uc]]]),jd=new Map([["vitpose",["VitPoseForPoseEstimation",Wl]]]),Ud=new Map([["clip",["CLIPVisionModelWithProjection",Ya]],["siglip",["SiglipVisionModel",el]],["jina_clip",["JinaCLIPVisionModel",hr]]]),Wd=[[Wp,D.EncoderOnly],[ip,D.EncoderDecoder],[op,D.DecoderOnly],[ap,D.EncoderOnly],[Ad,D.EncoderOnly],[ma,D.Seq2Seq],[ha,D.Seq2Seq],[fa,D.DecoderOnly],[lp,D.MultiModality],[Id,D.EncoderOnly],[Od,D.EncoderOnly],[_a,D.Vision2Seq],[up,D.ImageTextToText],[cp,D.EncoderOnly],[wa,D.EncoderOnly],[Ma,D.EncoderOnly],[ya,D.EncoderOnly],[zd,D.EncoderOnly],[Bd,D.EncoderOnly],[Rd,D.EncoderOnly],[Nd,D.EncoderOnly],[Ta,D.EncoderOnly],[jd,D.EncoderOnly],[Vn,D.EncoderOnly],[ga,D.EncoderOnly],[Fd,D.MaskGeneration],[Dd,D.EncoderOnly],[ba,D.EncoderOnly],[Sd,D.Seq2Seq],[$d,D.EncoderOnly],[va,D.EncoderOnly],[Ld,D.EncoderOnly],[Ud,D.EncoderOnly]];for(const[f,P]of Wd)for(const[W,be]of f.values())$.set(W,P),C.set(be,W),w.set(W,be);const pp=[["MusicgenForConditionalGeneration",xn,D.Musicgen],["Phi3VForCausalLM",lr,D.Phi3V],["CLIPTextModelWithProjection",Qa,D.EncoderOnly],["SiglipTextModel",Za,D.EncoderOnly],["JinaCLIPTextModel",Wi,D.EncoderOnly],["ClapTextModelWithProjection",nn,D.EncoderOnly],["ClapAudioModelWithProjection",nd,D.EncoderOnly]];for(const[f,P,W]of pp)$.set(f,W),C.set(P,f),w.set(f,P);class Vd extends gs{}_e(Vd,"MODEL_CLASS_MAPPINGS",Wd.map(P=>P[0])),_e(Vd,"BASE_IF_FAIL",!0);class Gd extends gs{}_e(Gd,"MODEL_CLASS_MAPPINGS",[ap]);class Kd extends gs{}_e(Kd,"MODEL_CLASS_MAPPINGS",[Ad]);class Hd extends gs{}_e(Hd,"MODEL_CLASS_MAPPINGS",[ma]);class qd extends gs{}_e(qd,"MODEL_CLASS_MAPPINGS",[ha]);class hp extends gs{}_e(hp,"MODEL_CLASS_MAPPINGS",[Sd]);class Xd extends gs{}_e(Xd,"MODEL_CLASS_MAPPINGS",[$d]);class Qd extends gs{}_e(Qd,"MODEL_CLASS_MAPPINGS",[fa]);class Yd extends gs{}_e(Yd,"MODEL_CLASS_MAPPINGS",[Id]);class mp extends gs{}_e(mp,"MODEL_CLASS_MAPPINGS",[Od]);class Jd extends gs{}_e(Jd,"MODEL_CLASS_MAPPINGS",[_a]);class Zd extends gs{}_e(Zd,"MODEL_CLASS_MAPPINGS",[cp]);class ec extends gs{}_e(ec,"MODEL_CLASS_MAPPINGS",[wa]);class tc extends gs{}_e(tc,"MODEL_CLASS_MAPPINGS",[ya]);class fp extends gs{}_e(fp,"MODEL_CLASS_MAPPINGS",[Ma]);class sc extends gs{}_e(sc,"MODEL_CLASS_MAPPINGS",[Vn]);class rc extends gs{}_e(rc,"MODEL_CLASS_MAPPINGS",[ga]);class nc extends gs{}_e(nc,"MODEL_CLASS_MAPPINGS",[Fd]);class ic extends gs{}_e(ic,"MODEL_CLASS_MAPPINGS",[Dd]);class oc extends gs{}_e(oc,"MODEL_CLASS_MAPPINGS",[ba]);class ac extends gs{}_e(ac,"MODEL_CLASS_MAPPINGS",[va]);class lc extends gs{}_e(lc,"MODEL_CLASS_MAPPINGS",[Ld]);class uc extends gs{}_e(uc,"MODEL_CLASS_MAPPINGS",[dp]);class dc extends gs{}_e(dc,"MODEL_CLASS_MAPPINGS",[zd]);class cc extends gs{}_e(cc,"MODEL_CLASS_MAPPINGS",[Rd]);class pc extends gs{}_e(pc,"MODEL_CLASS_MAPPINGS",[Nd]);class xa extends gs{}_e(xa,"MODEL_CLASS_MAPPINGS",[Ta]);class hc extends gs{}_e(hc,"MODEL_CLASS_MAPPINGS",[jd]);class mc extends gs{}_e(mc,"MODEL_CLASS_MAPPINGS",[Ud]);class _p extends Je{constructor({logits:P,past_key_values:W,encoder_outputs:be,decoder_attentions:Ie=null,cross_attentions:ke=null}){super(),this.logits=P,this.past_key_values=W,this.encoder_outputs=be,this.decoder_attentions=Ie,this.cross_attentions=ke}}class Qt extends Je{constructor({logits:P}){super(),this.logits=P}}class fc extends Je{constructor({logits:P,embeddings:W}){super(),this.logits=P,this.embeddings=W}}class Us extends Je{constructor({logits:P}){super(),this.logits=P}}class Ws extends Je{constructor({logits:P}){super(),this.logits=P}}class Ys extends Je{constructor({start_logits:P,end_logits:W}){super(),this.start_logits=P,this.end_logits=W}}class on extends Je{constructor({logits:P}){super(),this.logits=P}}class gp extends Je{constructor({logits:P,past_key_values:W}){super(),this.logits=P,this.past_key_values=W}}class _c extends Je{constructor({alphas:P}){super(),this.alphas=P}}class wp extends Je{constructor({waveform:P,spectrogram:W}){super(),this.waveform=P,this.spectrogram=W}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(Le,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>N});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var I=r("./src/utils/audio.js");class N extends _.FeatureExtractor{constructor(j){super(j);const g=this.config.sampling_rate,b=(0,I.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let y=0;y{r.r(A),r.d(A,{AutoFeatureExtractor:()=>X});var _=r("./src/utils/constants.js"),I=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var N=r("./src/models/feature_extractors.js");class X{static async from_pretrained(g,b={}){const y=await(0,I.getModelJSON)(g,_.FEATURE_EXTRACTOR_NAME,!0,b),M=y.feature_extractor_type,v=N[M];if(!v)throw new Error(`Unknown feature_extractor_type: '${M}'. Please report this at ${_.GITHUB_ISSUE_URL}.`);return new v(y)}}},"./src/models/auto/image_processing_auto.js":(Le,A,r)=>{r.r(A),r.d(A,{AutoImageProcessor:()=>j});var _=r("./src/utils/constants.js"),I=r("./src/utils/hub.js"),N=r("./src/base/image_processors_utils.js"),X=r("./src/models/image_processors.js");class j{static async from_pretrained(b,y={}){const M=await(0,I.getModelJSON)(b,_.IMAGE_PROCESSOR_NAME,!0,y),v=M.image_processor_type??M.feature_extractor_type;let L=X[v];return L||(v!==void 0&&console.warn(`Image processor type '${v}' not found, assuming base ImageProcessor. Please report this at ${_.GITHUB_ISSUE_URL}.`),L=N.ImageProcessor),new L(M)}}},"./src/models/auto/processing_auto.js":(Le,A,r)=>{r.r(A),r.d(A,{AutoProcessor:()=>b});var _=r("./src/utils/constants.js"),I=r("./src/utils/hub.js"),N=r("./src/base/processing_utils.js"),X=r("./src/models/processors.js"),j=r("./src/models/image_processors.js"),g=r("./src/models/feature_extractors.js");class b{static async from_pretrained(M,v={}){const L=await(0,I.getModelJSON)(M,_.IMAGE_PROCESSOR_NAME,!0,v),{image_processor_type:H,feature_extractor_type:re,processor_class:oe}=L;if(oe&&X[oe])return X[oe].from_pretrained(M,v);if(!H&&!re)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const z={};if(H){const Y=j[H];if(!Y)throw new Error(`Unknown image_processor_type: '${H}'.`);z.image_processor=new Y(L)}if(re){const Y=j[re];if(Y)z.image_processor=new Y(L);else{const D=g[re];if(!D)throw new Error(`Unknown feature_extractor_type: '${re}'.`);z.feature_extractor=new D(L)}}const V={};return new N.Processor(V,z)}}},"./src/models/beit/image_processing_beit.js":(Le,A,r)=>{r.r(A),r.d(A,{BeitFeatureExtractor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(Le,A,r)=>{r.r(A),r.d(A,{BitImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(Le,A,r)=>{r.r(A),r.d(A,{ChineseCLIPFeatureExtractor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(Le,A,r)=>{r.r(A),r.d(A,{ClapFeatureExtractor:()=>N});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var I=r("./src/utils/audio.js");class N extends _.FeatureExtractor{constructor(j){super(j),this.mel_filters=(0,I.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,I.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,I.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(j,g,b,y){let M;const v=j.length-g;if(v>0)if(b==="rand_trunc"){const L=Math.floor(Math.random()*(v+1));j=j.subarray(L,L+g),M=await this._extract_fbank_features(j,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${b}" not implemented`);else{if(v<0){let L=new Float64Array(g);if(L.set(j),y==="repeat")for(let H=j.length;H{r.r(A),r.d(A,{CLIPFeatureExtractor:()=>N,CLIPImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/convnext/image_processing_convnext.js":(Le,A,r)=>{r.r(A),r.d(A,{ConvNextFeatureExtractor:()=>N,ConvNextImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{constructor(j){super(j),this.crop_pct=this.config.crop_pct??.875}async resize(j){var b;const g=(b=this.size)==null?void 0:b.shortest_edge;if(g===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(g<384){const y=Math.floor(g/this.crop_pct),[M,v]=this.get_resize_output_image_size(j,{shortest_edge:y});j=await j.resize(M,v,{resample:this.resample}),j=await j.center_crop(g,g)}else j=await j.resize(g,g,{resample:this.resample});return j}}class N extends I{}},"./src/models/deit/image_processing_deit.js":(Le,A,r)=>{r.r(A),r.d(A,{DeiTFeatureExtractor:()=>N,DeiTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/detr/image_processing_detr.js":(Le,A,r)=>{r.r(A),r.d(A,{DetrFeatureExtractor:()=>X,DetrImageProcessor:()=>N});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class N extends _.ImageProcessor{async _call(g){const b=await super._call(g),y=[b.pixel_values.dims[0],64,64],M=(0,I.full)(y,1n);return{...b,pixel_mask:M}}post_process_object_detection(...g){return(0,_.post_process_object_detection)(...g)}post_process_panoptic_segmentation(...g){return(0,_.post_process_panoptic_segmentation)(...g)}post_process_instance_segmentation(...g){return(0,_.post_process_instance_segmentation)(...g)}}class X extends N{}},"./src/models/donut/image_processing_donut.js":(Le,A,r)=>{r.r(A),r.d(A,{DonutFeatureExtractor:()=>N,DonutImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{pad_image(j,g,b,y={}){const[M,v,L]=g;let H=this.image_mean;Array.isArray(this.image_mean)||(H=new Array(L).fill(H));let re=this.image_std;Array.isArray(re)||(re=new Array(L).fill(H));const oe=H.map((z,V)=>-z/re[V]);return super.pad_image(j,g,b,{center:!0,constant_values:oe,...y})}}class N extends I{}},"./src/models/dpt/image_processing_dpt.js":(Le,A,r)=>{r.r(A),r.d(A,{DPTFeatureExtractor:()=>N,DPTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/efficientnet/image_processing_efficientnet.js":(Le,A,r)=>{r.r(A),r.d(A,{EfficientNetImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{constructor(X){super(X),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(j=>j*j))}}},"./src/models/feature_extractors.js":(Le,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>_.ASTFeatureExtractor,ClapFeatureExtractor:()=>I.ClapFeatureExtractor,ImageFeatureExtractor:()=>v.ImageProcessor,MoonshineFeatureExtractor:()=>N.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>X.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>j.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>g.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>b.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor});var _=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),I=r("./src/models/clap/feature_extraction_clap.js"),N=r("./src/models/moonshine/feature_extraction_moonshine.js"),X=r("./src/models/pyannote/feature_extraction_pyannote.js"),j=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),g=r("./src/models/speecht5/feature_extraction_speecht5.js"),b=r("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),y=r("./src/models/wespeaker/feature_extraction_wespeaker.js"),M=r("./src/models/whisper/feature_extraction_whisper.js"),v=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(Le,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>X});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class X extends _.Processor{constructor(g,b){super(g,b);const{tasks_answer_post_processing_type:y,task_prompts_without_inputs:M,task_prompts_with_input:v}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(y??{})),this.task_prompts_without_inputs=new Map(Object.entries(M??{})),this.task_prompts_with_input=new Map(Object.entries(v??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(g){typeof g=="string"&&(g=[g]);const b=[];for(const y of g)if(this.task_prompts_without_inputs.has(y))b.push(this.task_prompts_without_inputs.get(y));else{for(const[M,v]of this.task_prompts_with_input)if(y.includes(M)){b.push(v.replaceAll("{input}",y).replaceAll(M,""));break}b.length!==g.length&&b.push(y)}return b}post_process_generation(g,b,y){const M=this.tasks_answer_post_processing_type.get(b)??"pure_text";g=g.replaceAll("","").replaceAll("","");let v;switch(M){case"pure_text":v=g;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const L=M==="ocr"?"quad_boxes":"bboxes",H=g.matchAll(this.regexes[L]),re=[],oe=[];for(const[z,V,...Y]of H)re.push(V?V.trim():re.at(-1)??""),oe.push(Y.map((D,$)=>(Number(D)+.5)/this.size_per_bin*y[$%2]));v={labels:re,[L]:oe};break;default:throw new Error(`Task "${b}" (of type "${M}") not yet implemented.`)}return{[b]:v}}async _call(g,b=null,y={}){if(!g&&!b)throw new Error("Either text or images must be provided");const M=await this.image_processor(g,y),v=b?this.tokenizer(b,y):{};return{...M,...v}}}_e(X,"tokenizer_class",N.AutoTokenizer),_e(X,"image_processor_class",I.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(Le,A,r)=>{r.r(A),r.d(A,{GLPNFeatureExtractor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":(Le,A,r)=>{r.r(A),r.d(A,{Idefics3ImageProcessor:()=>N});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class N extends _.ImageProcessor{constructor(j){super(j),this.do_image_splitting=j.do_image_splitting??!0,this.max_image_size=j.max_image_size}get_resize_for_vision_encoder(j,g){let[b,y]=j.dims.slice(-2);const M=y/b;return y>=b?(y=Math.ceil(y/g)*g,b=Math.floor(y/M),b=Math.ceil(b/g)*g):(b=Math.ceil(b/g)*g,y=Math.floor(b*M),y=Math.ceil(y/g)*g),{height:b,width:y}}async _call(j,{do_image_splitting:g=null,return_row_col_info:b=!1}={}){let y;if(!Array.isArray(j))y=[[j]];else{if(j.length===0||!j[0])throw new Error("No images provided.");Array.isArray(j[0])?y=j:y=[j]}let M=[],v=[],L=[];const H=[],re=[];for(const C of y){let T=await Promise.all(C.map(le=>this.preprocess(le)));H.push(...T.map(le=>le.original_size)),re.push(...T.map(le=>le.reshaped_input_size)),T.forEach(le=>le.pixel_values.unsqueeze_(0));const{longest_edge:ee}=this.max_image_size;let J;if(g??this.do_image_splitting){let le=new Array(T.length),ce=new Array(T.length);J=await Promise.all(T.map(async(ge,Ce)=>{const Te=this.get_resize_for_vision_encoder(ge.pixel_values,ee),ze=await(0,I.interpolate_4d)(ge.pixel_values,{size:[Te.height,Te.width]}),{frames:qe,num_splits_h:Ue,num_splits_w:ut}=await this.split_image(ze,this.max_image_size);return le[Ce]=Ue,ce[Ce]=ut,(0,I.cat)(qe,0)})),v.push(le),L.push(ce)}else{const le=[ee,ee];J=await Promise.all(T.map(ce=>(0,I.interpolate_4d)(ce.pixel_values,{size:le}))),v.push(new Array(T.length).fill(0)),L.push(new Array(T.length).fill(0))}M.push((0,I.cat)(J,0))}const oe=M.length,[z,V,Y,D]=M[0].dims;let $,w;if(oe===1)$=M[0].unsqueeze_(0),w=(0,I.full)([oe,z,Y,D],!0);else{const C=Math.max(...M.map(J=>J.dims.at(0)));w=(0,I.full)([oe,C,Y,D],!0);const T=w.data,ee=C*Y*D;for(let J=0;Jb||L>y){H=Math.ceil(v/b),re=Math.ceil(L/y);const oe=Math.ceil(v/H),z=Math.ceil(L/re);for(let D=0;D{r.r(A),r.d(A,{Idefics3Processor:()=>y});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");var X=r("./src/utils/core.js");function j(M,v,L,H,re,oe){let z="";for(let V=0;V`+re.repeat(M);z+=` `}return z+=` ${H}${oe}`+re.repeat(M)+`${H}`,z}function g(M,v,L,H){return`${v}${H}`+L.repeat(M)+`${v}`}function b(M,v,L,H,re,oe){return M===0&&v===0?g(L,H,re,oe):j(L,M,v,H,re,oe)}class y extends _.Processor{constructor(){super(...arguments);_e(this,"fake_image_token","");_e(this,"image_token","");_e(this,"global_img_token","")}async _call(L,H=null,re={}){re.return_row_col_info??(re.return_row_col_info=!0);let oe;H&&(oe=await this.image_processor(H,re)),Array.isArray(L)||(L=[L]);const z=oe.rows??[new Array(L.length).fill(0)],V=oe.cols??[new Array(L.length).fill(0)],Y=this.config.image_seq_len,D=[],$=[];for(let C=0;Cb(Ce,J[Te],Y,this.fake_image_token,this.image_token,this.global_img_token)),ce=T.split(this.image_token);if(ce.length===0)throw new Error("The image token should be present in the text.");let ge=ce[0];for(let Ce=0;Ce{r.r(A),r.d(A,{BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BitImageProcessor:()=>I.BitImageProcessor,CLIPFeatureExtractor:()=>X.CLIPFeatureExtractor,CLIPImageProcessor:()=>X.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>N.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>j.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>j.ConvNextImageProcessor,DPTFeatureExtractor:()=>M.DPTFeatureExtractor,DPTImageProcessor:()=>M.DPTImageProcessor,DeiTFeatureExtractor:()=>g.DeiTFeatureExtractor,DeiTImageProcessor:()=>g.DeiTImageProcessor,DetrFeatureExtractor:()=>b.DetrFeatureExtractor,DetrImageProcessor:()=>b.DetrImageProcessor,DonutFeatureExtractor:()=>y.DonutFeatureExtractor,DonutImageProcessor:()=>y.DonutImageProcessor,EfficientNetImageProcessor:()=>v.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>L.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>H.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>oe.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>z.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>V.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>Y.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>Y.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>D.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>D.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>$.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>$.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>w.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>w.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>T.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>T.MobileViTImageProcessor,NougatImageProcessor:()=>ee.NougatImageProcessor,OwlViTFeatureExtractor:()=>le.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>le.OwlViTImageProcessor,Owlv2ImageProcessor:()=>J.Owlv2ImageProcessor,Phi3VImageProcessor:()=>ce.Phi3VImageProcessor,PvtImageProcessor:()=>ge.PvtImageProcessor,Qwen2VLImageProcessor:()=>Ce.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Te.RTDetrImageProcessor,SamImageProcessor:()=>ze.SamImageProcessor,SegformerFeatureExtractor:()=>qe.SegformerFeatureExtractor,SegformerImageProcessor:()=>qe.SegformerImageProcessor,SiglipImageProcessor:()=>Ue.SiglipImageProcessor,Swin2SRImageProcessor:()=>ut.Swin2SRImageProcessor,VLMImageProcessor:()=>re.VLMImageProcessor,ViTFeatureExtractor:()=>ue.ViTFeatureExtractor,ViTImageProcessor:()=>ue.ViTImageProcessor,VitMatteImageProcessor:()=>se.VitMatteImageProcessor,VitPoseImageProcessor:()=>he.VitPoseImageProcessor,YolosFeatureExtractor:()=>xe.YolosFeatureExtractor,YolosImageProcessor:()=>xe.YolosImageProcessor});var _=r("./src/models/beit/image_processing_beit.js"),I=r("./src/models/bit/image_processing_bit.js"),N=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),X=r("./src/models/clip/image_processing_clip.js"),j=r("./src/models/convnext/image_processing_convnext.js"),g=r("./src/models/deit/image_processing_deit.js"),b=r("./src/models/detr/image_processing_detr.js"),y=r("./src/models/donut/image_processing_donut.js"),M=r("./src/models/dpt/image_processing_dpt.js"),v=r("./src/models/efficientnet/image_processing_efficientnet.js"),L=r("./src/models/glpn/image_processing_glpn.js"),H=r("./src/models/idefics3/image_processing_idefics3.js"),re=r("./src/models/janus/image_processing_janus.js"),oe=r("./src/models/jina_clip/image_processing_jina_clip.js"),z=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),V=r("./src/models/mask2former/image_processing_mask2former.js"),Y=r("./src/models/maskformer/image_processing_maskformer.js"),D=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),$=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),w=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),T=r("./src/models/mobilevit/image_processing_mobilevit.js"),ee=r("./src/models/nougat/image_processing_nougat.js"),J=r("./src/models/owlv2/image_processing_owlv2.js"),le=r("./src/models/owlvit/image_processing_owlvit.js"),ce=r("./src/models/phi3_v/image_processing_phi3_v.js"),ge=r("./src/models/pvt/image_processing_pvt.js"),Ce=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Te=r("./src/models/rt_detr/image_processing_rt_detr.js"),ze=r("./src/models/sam/image_processing_sam.js"),qe=r("./src/models/segformer/image_processing_segformer.js"),Ue=r("./src/models/siglip/image_processing_siglip.js"),ut=r("./src/models/swin2sr/image_processing_swin2sr.js"),ue=r("./src/models/vit/image_processing_vit.js"),se=r("./src/models/vitmatte/image_processing_vitmatte.js"),he=r("./src/models/vitpose/image_processing_vitpose.js"),xe=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(Le,A,r)=>{r.r(A),r.d(A,{VLMImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{constructor(X){super({do_pad:!0,pad_size:{width:X.image_size,height:X.image_size},...X}),this.constant_values=this.config.background_color.map(j=>j*this.rescale_factor)}pad_image(X,j,g,b){return super.pad_image(X,j,g,{constant_values:this.constant_values,center:!0,...b})}}},"./src/models/janus/processing_janus.js":(Le,A,r)=>{r.r(A),r.d(A,{VLChatProcessor:()=>b});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),X=r("./src/utils/core.js"),j=r("./src/utils/tensor.js"),g=r("./src/utils/image.js");class b extends _.Processor{constructor(M,v){super(M,v),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(M,{images:v=null,chat_template:L="default"}={}){v?Array.isArray(v)||(v=[v]):v=await Promise.all(M.filter(J=>J.images).flatMap(J=>J.images).map(J=>g.RawImage.read(J)));const H=this.tokenizer,re=H.apply_chat_template(M,{tokenize:!1,add_generation_prompt:!0,chat_template:L}),oe=J=>H.encode(J,{add_special_tokens:!1}),z=re.split(this.image_tag),V=z.length-1;if(v.length!==V)throw new Error(`Number of images provided (${v.length}) does not match number of "${this.image_tag}" image tags (${V})`);const[Y,D,$]=H.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=oe(z[0]),C=new Array(w.length).fill(!1);for(let J=1;J0){const J=await this.image_processor(v);return J.pixel_values.unsqueeze_(0),{...ee,...J}}return ee}}_e(b,"image_processor_class",I.AutoImageProcessor),_e(b,"tokenizer_class",N.AutoTokenizer),_e(b,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(Le,A,r)=>{r.r(A),r.d(A,{JinaCLIPImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{constructor(X){const{resize_mode:j,fill_color:g,interpolation:b,size:y,...M}=X,v=j==="squash"?{width:y,height:y}:j==="shortest"?{shortest_edge:y}:{longest_edge:y},L=b==="bicubic"?3:2;super({...M,size:v,resample:L,do_center_crop:!0,crop_size:y,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(Le,A,r)=>{r.r(A),r.d(A,{JinaCLIPProcessor:()=>X});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class X extends _.Processor{async _call(g=null,b=null,y={}){if(!g&&!b)throw new Error("Either text or images must be provided");const M=g?this.tokenizer(g,y):{},v=b?await this.image_processor(b,y):{};return{...M,...v}}}_e(X,"tokenizer_class",N.AutoTokenizer),_e(X,"image_processor_class",I.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(Le,A,r)=>{r.r(A),r.d(A,{LlavaOnevisionImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(Le,A,r)=>{r.r(A),r.d(A,{Mask2FormerImageProcessor:()=>I});var _=r("./src/models/maskformer/image_processing_maskformer.js");class I extends _.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(Le,A,r)=>{r.r(A),r.d(A,{MaskFormerFeatureExtractor:()=>N,MaskFormerImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_panoptic_segmentation(...j){return(0,_.post_process_panoptic_segmentation)(...j)}post_process_instance_segmentation(...j){return(0,_.post_process_instance_segmentation)(...j)}}class N extends I{}},"./src/models/mgp_str/processing_mgp_str.js":(Le,A,r)=>{r.r(A),r.d(A,{MgpstrProcessor:()=>g});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),X=r("./src/utils/maths.js");const j={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class g extends _.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(y,M){if(!j.hasOwnProperty(M))throw new Error(`Format ${M} is not supported.`);const[v,L]=j[M],H=this[v].bind(this),[re,oe]=y.dims,z=[],V=[],Y=y.tolist();for(let $=0;$0?T.reduce((J,le)=>J*le,1):0;V.push(C),z.push(ee)}return[H(V),z]}char_decode(y){return this.char_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}bpe_decode(y){return this.bpe_tokenizer.batch_decode(y)}wp_decode(y){return this.wp_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}batch_decode([y,M,v]){const[L,H]=this._decode_helper(y,"char"),[re,oe]=this._decode_helper(M,"bpe"),[z,V]=this._decode_helper(v,"wp"),Y=[],D=[];for(let $=0;${r.r(A),r.d(A,{MobileNetV1FeatureExtractor:()=>N,MobileNetV1ImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(Le,A,r)=>{r.r(A),r.d(A,{MobileNetV2FeatureExtractor:()=>N,MobileNetV2ImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(Le,A,r)=>{r.r(A),r.d(A,{MobileNetV3FeatureExtractor:()=>N,MobileNetV3ImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(Le,A,r)=>{r.r(A),r.d(A,{MobileNetV4FeatureExtractor:()=>N,MobileNetV4ImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/mobilevit/image_processing_mobilevit.js":(Le,A,r)=>{r.r(A),r.d(A,{MobileViTFeatureExtractor:()=>N,MobileViTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/moonshine/feature_extraction_moonshine.js":(Le,A,r)=>{r.r(A),r.d(A,{MoonshineFeatureExtractor:()=>N});var _=r("./src/base/feature_extraction_utils.js"),I=r("./src/utils/tensor.js");class N extends _.FeatureExtractor{async _call(j){(0,_.validate_audio_inputs)(j,"MoonshineFeatureExtractor"),j instanceof Float64Array&&(j=new Float32Array(j));const g=[1,j.length];return{input_values:new I.Tensor("float32",j,g)}}}},"./src/models/moonshine/processing_moonshine.js":(Le,A,r)=>{r.r(A),r.d(A,{MoonshineProcessor:()=>X});var _=r("./src/models/auto/feature_extraction_auto.js"),I=r("./src/tokenizers.js"),N=r("./src/base/processing_utils.js");class X extends N.Processor{async _call(g){return await this.feature_extractor(g)}}_e(X,"tokenizer_class",I.AutoTokenizer),_e(X,"feature_extractor_class",_.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(Le,A,r)=>{r.r(A),r.d(A,{NougatImageProcessor:()=>I});var _=r("./src/models/donut/image_processing_donut.js");class I extends _.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(Le,A,r)=>{r.r(A),r.d(A,{Owlv2ImageProcessor:()=>I});var _=r("./src/models/owlvit/image_processing_owlvit.js");class I extends _.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(Le,A,r)=>{r.r(A),r.d(A,{OwlViTFeatureExtractor:()=>N,OwlViTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_object_detection(...j){return(0,_.post_process_object_detection)(...j)}}class N extends I{}},"./src/models/owlvit/processing_owlvit.js":(Le,A,r)=>{r.r(A),r.d(A,{OwlViTProcessor:()=>X});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class X extends _.Processor{}_e(X,"tokenizer_class",N.AutoTokenizer),_e(X,"image_processor_class",I.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(Le,A,r)=>{r.r(A),r.d(A,{PaliGemmaProcessor:()=>g});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");const X="";function j(b,y,M,v,L){return`${v.repeat(M*L)}${y}${b} `}class g extends _.Processor{async _call(y,M=null,v={}){M||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),M=""),Array.isArray(y)||(y=[y]),Array.isArray(M)||(M=[M]);const L=this.tokenizer.bos_token,H=this.image_processor.config.image_seq_length;let re;M.some(V=>V.includes(X))?re=M.map(V=>{const Y=V.replaceAll(X,X.repeat(H)),D=Y.lastIndexOf(X),$=D===-1?0:D+X.length;return Y.slice(0,$)+L+Y.slice($)+` `}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),re=M.map(V=>j(V,L,H,X,y.length)));const oe=this.tokenizer(re,v);return{...await this.image_processor(y,v),...oe}}}_e(g,"tokenizer_class",N.AutoTokenizer),_e(g,"image_processor_class",I.AutoImageProcessor),_e(g,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(Le,A,r)=>{r.r(A),r.d(A,{Phi3VImageProcessor:()=>y});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");const N=336,X=[2,3],{ceil:j,floor:g,sqrt:b}=Math;class y extends _.ImageProcessor{constructor(v){super({...v,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=v.num_crops}calc_num_image_tokens_from_image_size(v,L){const{num_img_tokens:H}=this.config;return g((g(L/N)*g(v/N)+1)*H+1+(g(L/N)+1)*b(H))}get_resize_output_image_size(v,L){const H=this._num_crops,[re,oe]=v.size;let z=re/oe,V=1;for(;V*Math.ceil(V/z)<=H;)V+=1;V-=1;const Y=Math.floor(V*336),D=Math.floor(Y/z);return[Y,D]}pad_image(v,L,H,re={}){const[oe,z]=L,V=N*j(oe/N),Y=N*j(z/N),D=[1,1,1].map(($,w)=>($-this.image_mean[w])/this.image_std[w]);return super.pad_image(v,L,{width:Y,height:V},{center:!0,constant_values:D,...re})}async _call(v,{num_crops:L=null}={}){if(this._num_crops=L??(L=this.config.num_crops),L<4||b(L)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(v)||(v=[v]);const H=v.length,re=await Promise.all(v.map(C=>this.preprocess(C))),oe=re.map(C=>C.original_size),z=re.map(C=>C.reshaped_input_size),V=[];for(const{pixel_values:C}of re){C.unsqueeze_(0);const[T,ee]=C.dims.slice(-2),J=await(0,I.interpolate_4d)(C,{size:[N,N],mode:"bicubic"});if(L>0){const le=[],ce=b(L),ge=g(ee/ce),Ce=g(T/ce);for(let ze=0;zeC.map(T=>N*j(T/N))),$=new I.Tensor("int64",D.flat(),[H,2]),w=D.map(([C,T])=>this.calc_num_image_tokens_from_image_size(T,C));return{pixel_values:Y,original_sizes:oe,reshaped_input_sizes:z,image_sizes:$,num_img_tokens:w}}}},"./src/models/phi3_v/processing_phi3_v.js":(Le,A,r)=>{r.r(A),r.d(A,{Phi3VProcessor:()=>g});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");const X="<|image|>",j=/<\|image_\d+\|>/g;class g extends _.Processor{async _call(y,M=null,{padding:v=!0,truncation:L=!0,num_crops:H=null}={}){Array.isArray(y)||(y=[y]);let re,oe;if(M){oe=await this.image_processor(M,{num_crops:H});const{num_img_tokens:z}=oe,V=y.map((D,$)=>D.split(j).join(X.repeat(z[$])));re=this.tokenizer(V,{padding:v,truncation:L});const Y=this.tokenizer.model.convert_tokens_to_ids([X])[0];re.input_ids.map_(D=>D==Y?-D:D)}else re=this.tokenizer(y);return{...re,...oe}}}_e(g,"image_processor_class",I.AutoImageProcessor),_e(g,"tokenizer_class",N.AutoTokenizer)},"./src/models/processors.js":(Le,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>_.Florence2Processor,Idefics3Processor:()=>X.Idefics3Processor,JinaCLIPProcessor:()=>g.JinaCLIPProcessor,MgpstrProcessor:()=>I.MgpstrProcessor,MoonshineProcessor:()=>N.MoonshineProcessor,OwlViTProcessor:()=>b.OwlViTProcessor,PaliGemmaProcessor:()=>M.PaliGemmaProcessor,Phi3VProcessor:()=>y.Phi3VProcessor,PyAnnoteProcessor:()=>v.PyAnnoteProcessor,Qwen2VLProcessor:()=>L.Qwen2VLProcessor,SamProcessor:()=>H.SamProcessor,SpeechT5Processor:()=>re.SpeechT5Processor,VLChatProcessor:()=>j.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>oe.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>z.WhisperProcessor});var _=r("./src/models/florence2/processing_florence2.js"),I=r("./src/models/mgp_str/processing_mgp_str.js"),N=r("./src/models/moonshine/processing_moonshine.js"),X=r("./src/models/idefics3/processing_idefics3.js"),j=r("./src/models/janus/processing_janus.js"),g=r("./src/models/jina_clip/processing_jina_clip.js"),b=r("./src/models/owlvit/processing_owlvit.js"),y=r("./src/models/phi3_v/processing_phi3_v.js"),M=r("./src/models/paligemma/processing_paligemma.js"),v=r("./src/models/pyannote/processing_pyannote.js"),L=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),H=r("./src/models/sam/processing_sam.js"),re=r("./src/models/speecht5/processing_speecht5.js"),oe=r("./src/models/wav2vec2/processing_wav2vec2.js"),z=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(Le,A,r)=>{r.r(A),r.d(A,{PvtImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(Le,A,r)=>{r.r(A),r.d(A,{PyAnnoteFeatureExtractor:()=>X});var _=r("./src/base/feature_extraction_utils.js"),I=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");class X extends _.FeatureExtractor{async _call(g){(0,_.validate_audio_inputs)(g,"PyAnnoteFeatureExtractor"),g instanceof Float64Array&&(g=new Float32Array(g));const b=[1,1,g.length];return{input_values:new I.Tensor("float32",g,b)}}samples_to_frames(g){return(g-this.config.offset)/this.config.step}post_process_speaker_diarization(g,b){const y=b/this.samples_to_frames(b)/this.config.sampling_rate,M=[];for(const v of g.tolist()){const L=[];let H=-1;for(let re=0;re({id:re,start:oe*y,end:z*y,confidence:V/(z-oe)})))}return M}}},"./src/models/pyannote/processing_pyannote.js":(Le,A,r)=>{r.r(A),r.d(A,{PyAnnoteProcessor:()=>N});var _=r("./src/base/processing_utils.js"),I=r("./src/models/pyannote/feature_extraction_pyannote.js");class N extends _.Processor{async _call(j){return await this.feature_extractor(j)}post_process_speaker_diarization(...j){return this.feature_extractor.post_process_speaker_diarization(...j)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}_e(N,"feature_extractor_class",I.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(Le,A,r)=>{r.r(A),r.d(A,{Qwen2VLImageProcessor:()=>N});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class N extends _.ImageProcessor{async _call(j,...g){const{pixel_values:b,original_sizes:y,reshaped_input_sizes:M}=await super._call(j,...g);let v=b;const{temporal_patch_size:L,merge_size:H,patch_size:re}=this.config;v.dims[0]===1&&(v=(0,I.cat)(Array.from({length:L},()=>v),0));const oe=v.dims[0]/L,z=v.dims[1],V=Math.floor(v.dims[2]/re),Y=Math.floor(v.dims[3]/re),D=v.view(oe,L,z,Math.floor(V/H),H,re,Math.floor(Y/H),H,re).permute(0,3,6,4,7,2,1,5,8).view(oe*V*Y,z*L*re*re),$=new I.Tensor("int64",[oe,V,Y],[1,3]);return{pixel_values:D,image_grid_thw:$,original_sizes:y,reshaped_input_sizes:M}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(Le,A,r)=>{r.r(A),r.d(A,{Qwen2VLProcessor:()=>X});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");class X extends _.Processor{async _call(g,b=null,...y){Array.isArray(g)||(g=[g]);let M,v;if(b&&(M=await this.image_processor(b),v=M.image_grid_thw),v){let H=this.image_processor.config.merge_size**2,re=0;const oe=v.tolist();g=g.map(z=>{for(;z.includes("<|image_pad|>");){const V=Number(oe[re++].reduce((Y,D)=>Y*D,1n));z=z.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(V/H)))}return z.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(g),...M}}}_e(X,"image_processor_class",I.AutoImageProcessor),_e(X,"tokenizer_class",N.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(Le,A,r)=>{r.r(A),r.d(A,{RTDetrImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_object_detection(...X){return(0,_.post_process_object_detection)(...X)}}},"./src/models/sam/image_processing_sam.js":(Le,A,r)=>{r.r(A),r.d(A,{SamImageProcessor:()=>X});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/core.js"),N=r("./src/utils/tensor.js");class X extends _.ImageProcessor{reshape_input_points(g,b,y,M=!1){g=structuredClone(g);let v=(0,I.calculateDimensions)(g);if(v.length===3)M||(v=[1,...v]),g=[g];else if(v.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 L=0;LM!==b.dims[v]))throw Error(`The first ${y.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N.Tensor("int64",g.flat(1/0).map(BigInt),y)}async _call(g,{input_points:b=null,input_labels:y=null,input_boxes:M=null}={}){const v=await super._call(g);if(b&&(v.input_points=this.reshape_input_points(b,v.original_sizes,v.reshaped_input_sizes)),y){if(!v.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");v.input_labels=this.add_input_labels(y,v.input_points)}return M&&(v.input_boxes=this.reshape_input_points(M,v.original_sizes,v.reshaped_input_sizes,!0)),v}async post_process_masks(g,b,y,{mask_threshold:M=0,binarize:v=!0,pad_size:L=null}={}){const H=[];L=L??this.pad_size;const re=[L.height,L.width];for(let oe=0;oeM&&($[w]=1);Y=new N.Tensor("bool",$,Y.dims)}H.push(Y)}return H}generate_crop_boxes(g,b,{crop_n_layers:y=0,overlap_ratio:M=.3413333333333333,points_per_crop:v=32,crop_n_points_downscale_factor:L=1}={}){}}},"./src/models/sam/processing_sam.js":(Le,A,r)=>{r.r(A),r.d(A,{SamProcessor:()=>N});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js");class N extends _.Processor{async _call(...j){return await this.image_processor(...j)}post_process_masks(...j){return this.image_processor.post_process_masks(...j)}reshape_input_points(...j){return this.image_processor.reshape_input_points(...j)}}_e(N,"image_processor_class",I.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(Le,A,r)=>{r.r(A),r.d(A,{SeamlessM4TFeatureExtractor:()=>X});var _=r("./src/base/feature_extraction_utils.js"),I=r("./src/utils/tensor.js"),N=r("./src/utils/audio.js");class X extends _.FeatureExtractor{constructor(g){super(g);const b=this.config.sampling_rate,y=(0,N.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(b/2),b,null,"kaldi",!0);for(let M=0;My*32768),(0,N.spectrogram)(g,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:b,transpose:!0})}async _call(g,{padding:b=!0,pad_to_multiple_of:y=2,do_normalize_per_mel_bins:M=!0,return_attention_mask:v=!0}={}){(0,_.validate_audio_inputs)(g,"SeamlessM4TFeatureExtractor");let L=await this._extract_fbank_features(g,this.config.max_length);if(M){const[$,w]=L.dims,C=L.data;for(let T=0;T0){const ee=new Float32Array(w*($+T));ee.set(C),ee.fill(this.config.padding_value,C.length);const J=$+T;L=new I.Tensor(L.type,ee,[J,w]),v&&(H=new I.Tensor("int64",new BigInt64Array(J),[1,J]),H.data.fill(1n,0,$))}}const[re,oe]=L.dims,z=this.config.stride;if(re%z!==0)throw new Error(`The number of frames (${re}) must be a multiple of the stride (${z}).`);const Y=L.view(1,Math.floor(re/z),oe*z),D={input_features:Y};if(v){const $=Y.dims[1],w=new BigInt64Array($);if(H){const C=H.data;for(let T=1,ee=0;T{r.r(A),r.d(A,{SegformerFeatureExtractor:()=>N,SegformerImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_semantic_segmentation(...j){return(0,_.post_process_semantic_segmentation)(...j)}}class N extends I{}},"./src/models/siglip/image_processing_siglip.js":(Le,A,r)=>{r.r(A),r.d(A,{SiglipImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(Le,A,r)=>{r.r(A),r.d(A,{SpeechT5FeatureExtractor:()=>I});var _=r("./src/base/feature_extraction_utils.js");class I extends _.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(Le,A,r)=>{r.r(A),r.d(A,{SpeechT5Processor:()=>X});var _=r("./src/base/processing_utils.js"),I=r("./src/tokenizers.js"),N=r("./src/models/auto/feature_extraction_auto.js");class X extends _.Processor{async _call(g){return await this.feature_extractor(g)}}_e(X,"tokenizer_class",I.AutoTokenizer),_e(X,"feature_extractor_class",N.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(Le,A,r)=>{r.r(A),r.d(A,{Swin2SRImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{pad_image(X,j,g,b={}){const[y,M,v]=j;return super.pad_image(X,j,{width:M+(g-M%g)%g,height:y+(g-y%g)%g},{mode:"symmetric",center:!1,constant_values:-1,...b})}}},"./src/models/vit/image_processing_vit.js":(Le,A,r)=>{r.r(A),r.d(A,{ViTFeatureExtractor:()=>N,ViTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class N extends I{}},"./src/models/vitmatte/image_processing_vitmatte.js":(Le,A,r)=>{r.r(A),r.d(A,{VitMatteImageProcessor:()=>N});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class N extends _.ImageProcessor{async _call(j,g){Array.isArray(j)||(j=[j]),Array.isArray(g)||(g=[g]);const b=await Promise.all(j.map(v=>this.preprocess(v))),y=await Promise.all(g.map(v=>this.preprocess(v,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,I.stack)(b.map((v,L)=>(0,I.cat)([v.pixel_values,y[L].pixel_values],0)),0),original_sizes:b.map(v=>v.original_size),reshaped_input_sizes:b.map(v=>v.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(Le,A,r)=>{r.r(A),r.d(A,{VitPoseImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_pose_estimation(X,j,{threshold:g=null}={}){const b=X.tolist(),[y,M,v,L]=X.dims,H=[];for(let re=0;re{r.r(A),r.d(A,{Wav2Vec2FeatureExtractor:()=>N});var _=r("./src/base/feature_extraction_utils.js"),I=r("./src/utils/tensor.js");class N extends _.FeatureExtractor{_zero_mean_unit_var_norm(j){const b=j.reduce((M,v)=>M+v,0)/j.length,y=j.reduce((M,v)=>M+(v-b)**2,0)/j.length;return j.map(M=>(M-b)/Math.sqrt(y+1e-7))}async _call(j){(0,_.validate_audio_inputs)(j,"Wav2Vec2FeatureExtractor"),j instanceof Float64Array&&(j=new Float32Array(j));let g=j;this.config.do_normalize&&(g=this._zero_mean_unit_var_norm(g));const b=[1,g.length];return{input_values:new I.Tensor("float32",g,b),attention_mask:new I.Tensor("int64",new BigInt64Array(g.length).fill(1n),b)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(Le,A,r)=>{r.r(A),r.d(A,{Wav2Vec2ProcessorWithLM:()=>N});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/feature_extraction_auto.js");class N extends _.Processor{async _call(j){return await this.feature_extractor(j)}}_e(N,"feature_extractor_class",I.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(Le,A,r)=>{r.r(A),r.d(A,{WeSpeakerFeatureExtractor:()=>N});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var I=r("./src/utils/audio.js");class N extends _.FeatureExtractor{constructor(j){super(j);const g=this.config.sampling_rate,b=(0,I.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let y=0;yg*32768),(0,I.spectrogram)(j,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(j){(0,_.validate_audio_inputs)(j,"WeSpeakerFeatureExtractor");const g=(await this._extract_fbank_features(j)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const b=g.mean(1).data,y=g.data,[M,v,L]=g.dims;for(let H=0;H{r.r(A),r.d(A,{WHISPER_LANGUAGE_MAPPING:()=>I,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>N,whisper_language_to_code:()=>X});const _=[["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"]],I=new Map(_),N=new Map([..._.map(([j,g])=>[g,j]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function X(j){j=j.toLowerCase();let g=N.get(j);if(g===void 0)if(I.has(j))g=j;else{const y=j.length===2?I.keys():I.values();throw new Error(`Language "${j}" is not supported. Must be one of: ${JSON.stringify(y)}`)}return g}},"./src/models/whisper/feature_extraction_whisper.js":(Le,A,r)=>{r.r(A),r.d(A,{WhisperFeatureExtractor:()=>X});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var I=r("./src/utils/audio.js"),N=r("./src/utils/maths.js");class X extends _.FeatureExtractor{constructor(g){var b;super(g),(b=this.config).mel_filters??(b.mel_filters=(0,I.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,I.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(g){const b=await(0,I.spectrogram)(g,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),y=b.data,M=(0,N.max)(y)[0];for(let v=0;vthis.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`."),b=g.slice(0,this.config.n_samples)):(b=new Float32Array(this.config.n_samples),b.set(g)),{input_features:(await this._extract_fbank_features(b)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(Le,A,r)=>{r.r(A),r.d(A,{WhisperGenerationConfig:()=>I});var _=r("./src/generation/configuration_utils.js");class I extends _.GenerationConfig{constructor(){super(...arguments);_e(this,"return_timestamps",null);_e(this,"return_token_timestamps",null);_e(this,"num_frames",null);_e(this,"alignment_heads",null);_e(this,"task",null);_e(this,"language",null);_e(this,"no_timestamps_token_id",null);_e(this,"prompt_ids",null);_e(this,"is_multilingual",null);_e(this,"lang_to_id",null);_e(this,"task_to_id",null);_e(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(Le,A,r)=>{r.r(A),r.d(A,{WhisperProcessor:()=>X});var _=r("./src/models/auto/feature_extraction_auto.js"),I=r("./src/tokenizers.js"),N=r("./src/base/processing_utils.js");class X extends N.Processor{async _call(g){return await this.feature_extractor(g)}}_e(X,"tokenizer_class",I.AutoTokenizer),_e(X,"feature_extractor_class",_.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(Le,A,r)=>{r.r(A),r.d(A,{YolosFeatureExtractor:()=>N,YolosImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_object_detection(...j){return(0,_.post_process_object_detection)(...j)}}class N extends I{}},"./src/ops/registry.js":(Le,A,r)=>{r.r(A),r.d(A,{TensorOpRegistry:()=>X});var _=r("./src/backends/onnx.js"),I=r("./src/utils/tensor.js");const N=async(j,g,b)=>{const y=await(0,_.createInferenceSession)(new Uint8Array(j),g);return async M=>{const v=Object.fromEntries(Object.entries(M).map(([H,re])=>[H,re.ort_tensor])),L=await y.run(v);return Array.isArray(b)?b.map(H=>new I.Tensor(L[H])):new I.Tensor(L[b])}};class X{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=N([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=N([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=N([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=N([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=N([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=N([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}static get slice(){return this._slice||(this._slice=N([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}_e(X,"session_options",{})},"./src/pipelines.js":(Le,A,r)=>{r.r(A),r.d(A,{AudioClassificationPipeline:()=>ce,AutomaticSpeechRecognitionPipeline:()=>Ce,DepthEstimationPipeline:()=>Be,DocumentQuestionAnsweringPipeline:()=>se,FeatureExtractionPipeline:()=>J,FillMaskPipeline:()=>Y,ImageClassificationPipeline:()=>ze,ImageFeatureExtractionPipeline:()=>le,ImageSegmentationPipeline:()=>qe,ImageToImagePipeline:()=>xe,ImageToTextPipeline:()=>Te,ObjectDetectionPipeline:()=>ut,Pipeline:()=>re,QuestionAnsweringPipeline:()=>V,SummarizationPipeline:()=>$,Text2TextGenerationPipeline:()=>D,TextClassificationPipeline:()=>oe,TextGenerationPipeline:()=>T,TextToAudioPipeline:()=>he,TokenClassificationPipeline:()=>z,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>ge,ZeroShotClassificationPipeline:()=>ee,ZeroShotImageClassificationPipeline:()=>Ue,ZeroShotObjectDetectionPipeline:()=>ue,pipeline:()=>ie});var _=r("./src/tokenizers.js"),I=r("./src/models.js"),N=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var X=r("./src/utils/generic.js"),j=r("./src/utils/core.js"),g=r("./src/utils/maths.js"),b=r("./src/utils/audio.js"),y=r("./src/utils/tensor.js"),M=r("./src/utils/image.js");async function v(Fe){return Array.isArray(Fe)||(Fe=[Fe]),await Promise.all(Fe.map(pe=>M.RawImage.read(pe)))}async function L(Fe,pe){return Array.isArray(Fe)||(Fe=[Fe]),await Promise.all(Fe.map(ve=>typeof ve=="string"||ve instanceof URL?(0,b.read_audio)(ve,pe):ve instanceof Float64Array?new Float32Array(ve):ve))}function H(Fe,pe){pe&&(Fe=Fe.map(Ne=>Ne|0));const[ve,Re,je,Ve]=Fe;return{xmin:ve,ymin:Re,xmax:je,ymax:Ve}}class re extends X.Callable{constructor({task:pe,model:ve,tokenizer:Re=null,processor:je=null}){super(),this.task=pe,this.model=ve,this.tokenizer=Re,this.processor=je}async dispose(){await this.model.dispose()}}class oe extends re{constructor(pe){super(pe)}async _call(pe,{top_k:ve=1}={}){const Re=this.tokenizer(pe,{padding:!0,truncation:!0}),je=await this.model(Re),Ve=this.model.config.problem_type==="multi_label_classification"?at=>at.sigmoid():at=>new y.Tensor("float32",(0,g.softmax)(at.data),at.dims),Ne=this.model.config.id2label,Ze=[];for(const at of je.logits){const ht=Ve(at),dt=await(0,y.topk)(ht,ve),gt=dt[0].tolist(),ne=dt[1].tolist().map((K,de)=>({label:Ne?Ne[K]:`LABEL_${K}`,score:gt[de]}));ve===1?Ze.push(...ne):Ze.push(ne)}return Array.isArray(pe)||ve===1?Ze:Ze[0]}}class z extends re{constructor(pe){super(pe)}async _call(pe,{ignore_labels:ve=["O"]}={}){const Re=Array.isArray(pe),je=this.tokenizer(Re?pe:[pe],{padding:!0,truncation:!0}),Ne=(await this.model(je)).logits,Ze=this.model.config.id2label,at=[];for(let ht=0;htmt==this.tokenizer.sep_token_id);at[gt].map((mt,Ot)=>mt==1&&(Ot===0||Ot>ne&&ht.findIndex(xt=>xt==F[Ot])===-1));const K=Ve[gt].tolist(),de=Ne[gt].tolist();for(let mt=1;mtOt==F[mt])!==-1)&&(K[mt]=-1/0,de[mt]=-1/0);const Oe=(0,g.softmax)(K).map((mt,Ot)=>[mt,Ot]),Qe=(0,g.softmax)(de).map((mt,Ot)=>[mt,Ot]);Oe[0][0]=0,Qe[0][0]=0;const rt=(0,j.product)(Oe,Qe).filter(mt=>mt[0][1]<=mt[1][1]).map(mt=>[mt[0][1],mt[1][1],mt[0][0]*mt[1][0]]).sort((mt,Ot)=>Ot[2]-mt[2]);for(let mt=0;mtK==this.tokenizer.mask_token_id);if(ht===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const dt=je[Ze][ht],gt=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),ve),F=gt[0].tolist(),ne=gt[1].tolist();Ve.push(ne.map((K,de)=>{const Oe=at.slice();return Oe[ht]=K,{score:F[de],token:Number(K),token_str:this.tokenizer.model.vocab[K],sequence:this.tokenizer.decode(Oe,{skip_special_tokens:!0})}}))}return Array.isArray(pe)?Ve:Ve[0]}}class D extends re{constructor(ve){super(ve);_e(this,"_key","generated_text")}async _call(ve,Re={}){Array.isArray(ve)||(ve=[ve]),this.model.config.prefix&&(ve=ve.map(ht=>this.model.config.prefix+ht));const je=this.model.config.task_specific_params;je&&je[this.task]&&je[this.task].prefix&&(ve=ve.map(ht=>je[this.task].prefix+ht));const Ve=this.tokenizer,Ne={padding:!0,truncation:!0};let Ze;this instanceof w&&"_build_translation_inputs"in Ve?Ze=Ve._build_translation_inputs(ve,Ne,Re):Ze=Ve(ve,Ne);const at=await this.model.generate({...Ze,...Re});return Ve.batch_decode(at,{skip_special_tokens:!0}).map(ht=>({[this._key]:ht}))}}class $ extends D{constructor(ve){super(ve);_e(this,"_key","summary_text")}}class w extends D{constructor(ve){super(ve);_e(this,"_key","translation_text")}}function C(Fe){return Array.isArray(Fe)&&Fe.every(pe=>"role"in pe&&"content"in pe)}class T extends re{constructor(pe){super(pe)}async _call(pe,ve={}){let Re=!1,je=!1,Ve;if(typeof pe=="string")Ve=pe=[pe];else if(Array.isArray(pe)&&pe.every(ne=>typeof ne=="string"))Re=!0,Ve=pe;else{if(C(pe))pe=[pe];else if(Array.isArray(pe)&&pe.every(C))Re=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");je=!0,Ve=pe.map(ne=>this.tokenizer.apply_chat_template(ne,{tokenize:!1,add_generation_prompt:!0}))}const Ne=ve.add_special_tokens??!1,Ze=je?!1:ve.return_full_text??!0;this.tokenizer.padding_side="left";const at=this.tokenizer(Ve,{add_special_tokens:Ne,padding:!0,truncation:!0}),ht=await this.model.generate({...at,...ve}),dt=this.tokenizer.batch_decode(ht,{skip_special_tokens:!0});let gt;!Ze&&at.input_ids.dims.at(-1)>0&&(gt=this.tokenizer.batch_decode(at.input_ids,{skip_special_tokens:!0}).map(ne=>ne.length));const F=Array.from({length:pe.length},ne=>[]);for(let ne=0;ne[ve.toLowerCase(),Re])),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(pe,ve,{hypothesis_template:Re="This example is {}.",multi_label:je=!1}={}){const Ve=Array.isArray(pe);Ve||(pe=[pe]),Array.isArray(ve)||(ve=[ve]);const Ne=ve.map(ht=>Re.replace("{}",ht)),Ze=je||ve.length===1,at=[];for(const ht of pe){const dt=[];for(const ne of Ne){const K=this.tokenizer(ht,{text_pair:ne,padding:!0,truncation:!0}),de=await this.model(K);Ze?dt.push([de.logits.data[this.contradiction_id],de.logits.data[this.entailment_id]]):dt.push(de.logits.data[this.entailment_id])}const F=(Ze?dt.map(ne=>(0,g.softmax)(ne)[1]):(0,g.softmax)(dt)).map((ne,K)=>[ne,K]).sort((ne,K)=>K[0]-ne[0]);at.push({sequence:ht,labels:F.map(ne=>ve[ne[1]]),scores:F.map(ne=>ne[0])})}return Ve?at:at[0]}}class J extends re{constructor(pe){super(pe)}async _call(pe,{pooling:ve="none",normalize:Re=!1,quantize:je=!1,precision:Ve="binary"}={}){const Ne=this.tokenizer(pe,{padding:!0,truncation:!0}),Ze=await this.model(Ne);let at=Ze.last_hidden_state??Ze.logits??Ze.token_embeddings;if(ve!=="none")if(ve==="mean")at=(0,y.mean_pooling)(at,Ne.attention_mask);else if(ve==="cls")at=at.slice(null,0);else throw Error(`Pooling method '${ve}' not supported.`);return Re&&(at=at.normalize(2,-1)),je&&(at=(0,y.quantize_embeddings)(at,Ve)),at}}class le extends re{constructor(pe){super(pe)}async _call(pe,{pool:ve=null}={}){const Re=await v(pe),{pixel_values:je}=await this.processor(Re),Ve=await this.model({pixel_values:je});let Ne;if(ve){if(!("pooler_output"in Ve))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ne=Ve.pooler_output}else Ne=Ve.last_hidden_state??Ve.logits??Ve.image_embeds;return Ne}}class ce extends re{constructor(pe){super(pe)}async _call(pe,{top_k:ve=5}={}){const Re=this.processor.feature_extractor.config.sampling_rate,je=await L(pe,Re),Ve=this.model.config.id2label,Ne=[];for(const Ze of je){const at=await this.processor(Ze),dt=(await this.model(at)).logits[0],gt=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),ve),F=gt[0].tolist(),K=gt[1].tolist().map((de,Oe)=>({label:Ve?Ve[de]:`LABEL_${de}`,score:F[Oe]}));Ne.push(K)}return Array.isArray(pe)?Ne:Ne[0]}}class ge extends re{constructor(pe){super(pe)}async _call(pe,ve,{hypothesis_template:Re="This is a sound of {}."}={}){const je=!Array.isArray(pe);je&&(pe=[pe]);const Ve=ve.map(dt=>Re.replace("{}",dt)),Ne=this.tokenizer(Ve,{padding:!0,truncation:!0}),Ze=this.processor.feature_extractor.config.sampling_rate,at=await L(pe,Ze),ht=[];for(const dt of at){const gt=await this.processor(dt),F=await this.model({...Ne,...gt}),ne=(0,g.softmax)(F.logits_per_audio.data);ht.push([...ne].map((K,de)=>({score:K,label:ve[de]})))}return je?ht[0]:ht}}class Ce extends re{constructor(pe){super(pe)}async _call(pe,ve={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(pe,ve);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(pe,ve);case"moonshine":return this._call_moonshine(pe,ve);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(pe,ve){ve.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ve.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Re=!Array.isArray(pe);Re&&(pe=[pe]);const je=this.processor.feature_extractor.config.sampling_rate,Ve=await L(pe,je),Ne=[];for(const Ze of Ve){const at=await this.processor(Ze),dt=(await this.model(at)).logits[0],gt=[];for(const ne of dt)gt.push((0,g.max)(ne.data)[1]);const F=this.tokenizer.decode(gt);Ne.push({text:F})}return Re?Ne[0]:Ne}async _call_whisper(pe,ve){const Re=ve.return_timestamps??!1,je=ve.chunk_length_s??0,Ve=ve.force_full_sequences??!1;let Ne=ve.stride_length_s??null;const Ze={...ve};Re==="word"&&(Ze.return_token_timestamps=!0,Ze.return_timestamps=!1);const at=!Array.isArray(pe);at&&(pe=[pe]);const ht=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,dt=this.processor.feature_extractor.config.hop_length,gt=this.processor.feature_extractor.config.sampling_rate,F=await L(pe,gt),ne=[];for(const K of F){let de=[];if(je>0){if(Ne===null)Ne=je/6;else if(je<=Ne)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const rt=gt*je,mt=gt*Ne,Ot=rt-2*mt;let xt=0;for(;;){const Ft=xt+rt,At=K.subarray(xt,Ft),rs=await this.processor(At),ws=xt===0,Os=Ft>=K.length;if(de.push({stride:[At.length,ws?0:mt,Os?0:mt],input_features:rs.input_features,is_last:Os}),Os)break;xt+=Ot}}else de=[{stride:[K.length,0,0],input_features:(await this.processor(K)).input_features,is_last:!0}];for(const rt of de){Ze.num_frames=Math.floor(rt.stride[0]/dt);const mt=await this.model.generate({inputs:rt.input_features,...Ze});Re==="word"?(rt.tokens=mt.sequences.tolist()[0],rt.token_timestamps=mt.token_timestamps.tolist()[0].map(Ot=>(0,g.round)(Ot,2))):rt.tokens=mt[0].tolist(),rt.stride=rt.stride.map(Ot=>Ot/gt)}const[Oe,Qe]=this.tokenizer._decode_asr(de,{time_precision:ht,return_timestamps:Re,force_full_sequences:Ve});ne.push({text:Oe,...Qe})}return at?ne[0]:ne}async _call_moonshine(pe,ve){const Re=!Array.isArray(pe);Re&&(pe=[pe]);const je=this.processor.feature_extractor.config.sampling_rate,Ve=await L(pe,je),Ne=[];for(const Ze of Ve){const at=await this.processor(Ze),ht=Math.floor(Ze.length/je)*6,dt=await this.model.generate({max_new_tokens:ht,...ve,...at}),gt=this.processor.batch_decode(dt,{skip_special_tokens:!0})[0];Ne.push({text:gt})}return Re?Ne[0]:Ne}}class Te extends re{constructor(pe){super(pe)}async _call(pe,ve={}){const Re=Array.isArray(pe),je=await v(pe),{pixel_values:Ve}=await this.processor(je),Ne=[];for(const Ze of Ve){Ze.dims=[1,...Ze.dims];const at=await this.model.generate({inputs:Ze,...ve}),ht=this.tokenizer.batch_decode(at,{skip_special_tokens:!0}).map(dt=>({generated_text:dt.trim()}));Ne.push(ht)}return Re?Ne:Ne[0]}}class ze extends re{constructor(pe){super(pe)}async _call(pe,{top_k:ve=5}={}){const Re=await v(pe),{pixel_values:je}=await this.processor(Re),Ve=await this.model({pixel_values:je}),Ne=this.model.config.id2label,Ze=[];for(const at of Ve.logits){const ht=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(at.data),at.dims),ve),dt=ht[0].tolist(),F=ht[1].tolist().map((ne,K)=>({label:Ne?Ne[ne]:`LABEL_${ne}`,score:dt[K]}));Ze.push(F)}return Array.isArray(pe)?Ze:Ze[0]}}class qe extends re{constructor(pe){super(pe),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(pe,{threshold:ve=.5,mask_threshold:Re=.5,overlap_mask_area_threshold:je=.8,label_ids_to_fuse:Ve=null,target_sizes:Ne=null,subtask:Ze=null}={}){if(Array.isArray(pe)&&pe.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ht=await v(pe),dt=ht.map(Qe=>[Qe.height,Qe.width]),{pixel_values:gt,pixel_mask:F}=await this.processor(ht),ne=await this.model({pixel_values:gt,pixel_mask:F});let K=null;if(Ze!==null)K=this.subtasks_mapping[Ze];else for(let[Qe,rt]of Object.entries(this.subtasks_mapping))if(rt in this.processor.image_processor){K=this.processor.image_processor[rt].bind(this.processor.image_processor),Ze=Qe;break}const de=this.model.config.id2label,Oe=[];if(Ze==="panoptic"||Ze==="instance"){const Qe=K(ne,ve,Re,je,Ve,Ne??dt)[0],rt=Qe.segmentation;for(const mt of Qe.segments_info){const Ot=new Uint8ClampedArray(rt.data.length);for(let Ft=0;FtRe.replace("{}",F)),Ze=this.tokenizer(Ne,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:at}=await this.processor(Ve),ht=await this.model({...Ze,pixel_values:at}),dt=this.model.config.model_type==="siglip"?F=>F.sigmoid().data:F=>(0,g.softmax)(F.data),gt=[];for(const F of ht.logits_per_image){const K=[...dt(F)].map((de,Oe)=>({score:de,label:ve[Oe]}));K.sort((de,Oe)=>Oe.score-de.score),gt.push(K)}return je?gt:gt[0]}}class ut extends re{constructor(pe){super(pe)}async _call(pe,{threshold:ve=.9,percentage:Re=!1}={}){const je=Array.isArray(pe);if(je&&pe.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ve=await v(pe),Ne=Re?null:Ve.map(ne=>[ne.height,ne.width]),{pixel_values:Ze,pixel_mask:at}=await this.processor(Ve),ht=await this.model({pixel_values:Ze,pixel_mask:at}),dt=this.processor.image_processor.post_process_object_detection(ht,ve,Ne),gt=this.model.config.id2label,F=dt.map(ne=>ne.boxes.map((K,de)=>({score:ne.scores[de],label:gt[ne.classes[de]],box:H(K,!Re)})));return je?F:F[0]}}class ue extends re{constructor(pe){super(pe)}async _call(pe,ve,{threshold:Re=.1,top_k:je=null,percentage:Ve=!1}={}){const Ne=Array.isArray(pe),Ze=await v(pe),at=this.tokenizer(ve,{padding:!0,truncation:!0}),ht=await this.processor(Ze),dt=[];for(let gt=0;gt({score:Oe.scores[mt],label:ve[Oe.classes[mt]],box:H(rt,!Ve)})).sort((rt,mt)=>mt.score-rt.score);je!==null&&(Qe=Qe.slice(0,je)),dt.push(Qe)}return Ne?dt:dt[0]}}class se extends re{constructor(pe){super(pe)}async _call(pe,ve,Re={}){const je=(await v(pe))[0],{pixel_values:Ve}=await this.processor(je),Ne=`${ve}`,Ze=this.tokenizer(Ne,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,at=await this.model.generate({inputs:Ve,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ze,...Re}),dt=this.tokenizer.batch_decode(at)[0].match(/(.*?)<\/s_answer>/);let gt=null;return dt&&dt.length>=2&&(gt=dt[1].trim()),[{answer:gt}]}}class he extends re{constructor(ve){super(ve);_e(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ve.vocoder??null}async _call(ve,{speaker_embeddings:Re=null}={}){return this.processor?this._call_text_to_spectrogram(ve,{speaker_embeddings:Re}):this._call_text_to_waveform(ve)}async _call_text_to_waveform(ve){const Re=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:je}=await this.model(Re),Ve=this.model.config.sampling_rate;return{audio:je.data,sampling_rate:Ve}}async _call_text_to_spectrogram(ve,{speaker_embeddings:Re}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await I.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Re=="string"||Re instanceof URL)&&(Re=new Float32Array(await(await fetch(Re)).arrayBuffer())),Re instanceof Float32Array)Re=new y.Tensor("float32",Re,[1,Re.length]);else if(!(Re instanceof y.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:je}=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:Ve}=await this.model.generate_speech(je,Re,{vocoder:this.vocoder}),Ne=this.processor.feature_extractor.config.sampling_rate;return{audio:Ve.data,sampling_rate:Ne}}}class xe extends re{constructor(pe){super(pe)}async _call(pe){const ve=await v(pe),Re=await this.processor(ve),je=await this.model(Re),Ve=[];for(const Ne of je.reconstruction){const Ze=Ne.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ve.push(M.RawImage.fromTensor(Ze))}return Ve.length>1?Ve:Ve[0]}}class Be extends re{constructor(pe){super(pe)}async _call(pe){const ve=await v(pe),Re=await this.processor(ve),{predicted_depth:je}=await this.model(Re),Ve=[];for(let Ne=0;Ne1?Ve:Ve[0]}}const et=Object.freeze({"text-classification":{tokenizer:_.AutoTokenizer,pipeline:oe,model:I.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:_.AutoTokenizer,pipeline:z,model:I.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:_.AutoTokenizer,pipeline:V,model:I.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:_.AutoTokenizer,pipeline:Y,model:I.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:_.AutoTokenizer,pipeline:$,model:I.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:_.AutoTokenizer,pipeline:w,model:I.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:_.AutoTokenizer,pipeline:D,model:I.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:_.AutoTokenizer,pipeline:T,model:I.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:_.AutoTokenizer,pipeline:ee,model:I.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ce,model:I.AutoModelForAudioClassification,processor:N.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:_.AutoTokenizer,pipeline:ge,model:I.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:_.AutoTokenizer,pipeline:Ce,model:[I.AutoModelForSpeechSeq2Seq,I.AutoModelForCTC],processor:N.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:_.AutoTokenizer,pipeline:he,model:[I.AutoModelForTextToWaveform,I.AutoModelForTextToSpectrogram],processor:[N.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:_.AutoTokenizer,pipeline:Te,model:I.AutoModelForVision2Seq,processor:N.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ze,model:I.AutoModelForImageClassification,processor:N.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:qe,model:[I.AutoModelForImageSegmentation,I.AutoModelForSemanticSegmentation,I.AutoModelForUniversalSegmentation],processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:_.AutoTokenizer,pipeline:Ue,model:I.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ut,model:I.AutoModelForObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:_.AutoTokenizer,pipeline:ue,model:I.AutoModelForZeroShotObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:_.AutoTokenizer,pipeline:se,model:I.AutoModelForDocumentQuestionAnswering,processor:N.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:xe,model:I.AutoModelForImageToImage,processor:N.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Be,model:I.AutoModelForDepthEstimation,processor:N.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:_.AutoTokenizer,pipeline:J,model:I.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:N.AutoProcessor,pipeline:le,model:[I.AutoModelForImageFeatureExtraction,I.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Xe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ie(Fe,pe=null,{progress_callback:ve=null,config:Re=null,cache_dir:je=null,local_files_only:Ve=!1,revision:Ne="main",device:Ze=null,dtype:at=null,model_file_name:ht=null,session_options:dt={}}={}){Fe=Xe[Fe]??Fe;const gt=et[Fe.split("_",1)[0]];if(!gt)throw Error(`Unsupported pipeline: ${Fe}. Must be one of [${Object.keys(et)}]`);pe||(pe=gt.default.model,console.log(`No model specified. Using default model: "${pe}".`));const F={progress_callback:ve,config:Re,cache_dir:je,local_files_only:Ve,revision:Ne,device:Ze,dtype:at,model_file_name:ht,session_options:dt},ne=new Map([["tokenizer",gt.tokenizer],["model",gt.model],["processor",gt.processor]]),K=await Je(ne,pe,F);K.task=Fe,(0,j.dispatchCallback)(ve,{status:"ready",task:Fe,model:pe});const de=gt.pipeline;return new de(K)}async function Je(Fe,pe,ve){const Re=Object.create(null),je=[];for(const[Ve,Ne]of Fe.entries()){if(!Ne)continue;let Ze;Array.isArray(Ne)?Ze=new Promise(async(at,ht)=>{var gt,F;let dt;for(const ne of Ne){if(ne===null){at(null);return}try{at(await ne.from_pretrained(pe,ve));return}catch(K){if((gt=K.message)!=null&>.includes("Unsupported model type"))dt=K;else if((F=K.message)!=null&&F.includes("Could not locate file"))dt=K;else{ht(K);return}}}ht(dt)}):Ze=Ne.from_pretrained(pe,ve),Re[Ve]=Ze,je.push(Ze)}await Promise.all(je);for(const[Ve,Ne]of Object.entries(Re))Re[Ve]=await Ne;return Re}},"./src/tokenizers.js":(Le,A,r)=>{r.r(A),r.d(A,{AlbertTokenizer:()=>kr,AutoTokenizer:()=>bn,BartTokenizer:()=>ts,BertTokenizer:()=>Hr,BlenderbotSmallTokenizer:()=>zn,BlenderbotTokenizer:()=>yn,BloomTokenizer:()=>Lr,CLIPTokenizer:()=>Fn,CamembertTokenizer:()=>ot,CodeGenTokenizer:()=>On,CodeLlamaTokenizer:()=>zr,CohereTokenizer:()=>Bn,ConvBertTokenizer:()=>$r,DebertaTokenizer:()=>Dr,DebertaV2Tokenizer:()=>Zs,DistilBertTokenizer:()=>or,ElectraTokenizer:()=>It,EsmTokenizer:()=>er,FalconTokenizer:()=>Br,GPT2Tokenizer:()=>Mr,GPTNeoXTokenizer:()=>Tr,GemmaTokenizer:()=>Qr,Grok1Tokenizer:()=>_n,HerbertTokenizer:()=>dr,LlamaTokenizer:()=>An,M2M100Tokenizer:()=>Bt,MBart50Tokenizer:()=>cr,MBartTokenizer:()=>br,MPNetTokenizer:()=>si,MarianTokenizer:()=>Rr,MgpstrTokenizer:()=>Jr,MobileBertTokenizer:()=>Fr,NllbTokenizer:()=>gn,NougatTokenizer:()=>tr,PreTrainedTokenizer:()=>zt,Qwen2Tokenizer:()=>fn,RoFormerTokenizer:()=>qr,RobertaTokenizer:()=>Xr,SiglipTokenizer:()=>Dn,SpeechT5Tokenizer:()=>is,SqueezeBertTokenizer:()=>Sr,T5Tokenizer:()=>us,TokenizerModel:()=>le,VitsTokenizer:()=>Mn,Wav2Vec2CTCTokenizer:()=>Ln,WhisperTokenizer:()=>wn,XLMRobertaTokenizer:()=>In,XLMTokenizer:()=>pt,is_chinese_char:()=>Y});var _=r("./src/utils/generic.js"),I=r("./src/utils/core.js"),N=r("./src/utils/hub.js"),X=r("./src/utils/maths.js"),j=r("./src/utils/tensor.js"),g=r("./src/utils/data-structures.js"),b=r("./node_modules/@huggingface/jinja/dist/index.js"),y=r("./src/models/whisper/common_whisper.js");r("./src/utils/constants.js");async function M(Ee,E){const q=await Promise.all([(0,N.getModelJSON)(Ee,"tokenizer.json",!0,E),(0,N.getModelJSON)(Ee,"tokenizer_config.json",!0,E)]);return E.legacy!==null&&(q[1].legacy=E.legacy),q}function v(Ee,E){const q=[];let ae=0;for(const ye of Ee.matchAll(E)){const Pe=ye[0];ae0&&q.push(Pe),ae=ye.index+Pe.length}return ae=19968&&Ee<=40959||Ee>=13312&&Ee<=19903||Ee>=131072&&Ee<=173791||Ee>=173824&&Ee<=177983||Ee>=177984&&Ee<=178207||Ee>=178208&&Ee<=183983||Ee>=63744&&Ee<=64255||Ee>=194560&&Ee<=195103}function D(Ee,E,q){const ae=[];let ye=0;for(;yethis.tokens_to_ids.get(q)??this.unk_token_id)}convert_ids_to_tokens(E){return E.map(q=>this.vocab[q]??this.unk_token)}}class ce extends le{constructor(E){super(E),this.tokens_to_ids=H(E.vocab),this.unk_token_id=this.tokens_to_ids.get(E.unk_token),this.unk_token=E.unk_token,this.max_input_chars_per_word=E.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[q,ae]of this.tokens_to_ids)this.vocab[ae]=q}encode(E){const q=[];for(const ae of E){const ye=[...ae];if(ye.length>this.max_input_chars_per_word){q.push(this.unk_token);continue}let Pe=!1,He=0;const ct=[];for(;He0&&(it=this.config.continuing_subword_prefix+it),this.tokens_to_ids.has(it)){_t=it;break}--wt}if(_t===null){Pe=!0;break}ct.push(_t),He=wt}Pe?q.push(this.unk_token):q.push(...ct)}return q}}class ge extends le{constructor(E,q){super(E);const ae=E.vocab.length;this.vocab=new Array(ae),this.scores=new Array(ae);for(let ye=0;ye[ye,Pe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=q.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,X.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new g.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(E){const q=E.chars,ae=1;let ye=0;for(;ye{const Ee=[...Array.from({length:94},(ye,Pe)=>Pe+33),...Array.from({length:12},(ye,Pe)=>Pe+161),...Array.from({length:82},(ye,Pe)=>Pe+174)],E=Ee.slice();let q=0;for(let ye=0;ye<256;++ye)Ee.includes(ye)||(Ee.push(ye),E.push(256+q),q+=1);const ae=E.map(ye=>String.fromCharCode(ye));return Object.fromEntries(Ee.map((ye,Pe)=>[ye,ae[Pe]]))})(),Te=(0,I.reverseDictionary)(Ce);class ze extends le{constructor(E){super(E),this.tokens_to_ids=H(E.vocab),this.unk_token_id=this.tokens_to_ids.get(E.unk_token),this.unk_token=E.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ae,ye]of this.tokens_to_ids)this.vocab[ye]=ae;const q=Array.isArray(E.merges[0]);this.merges=q?E.merges:E.merges.map(ae=>ae.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ae,ye)=>[JSON.stringify(ae),ye])),this.end_of_word_suffix=E.end_of_word_suffix,this.continuing_subword_suffix=E.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(E){if(E.length===0)return[];const q=this.cache.get(E);if(q!==void 0)return q;const ae=Array.from(E);this.end_of_word_suffix&&(ae[ae.length-1]+=this.end_of_word_suffix);let ye=[];if(ae.length>1){const Pe=new g.PriorityQueue((wt,_t)=>wt.score<_t.score);let He={token:ae[0],bias:0,prev:null,next:null},ct=He;for(let wt=1;wt`<0x${ct.toString(16).toUpperCase().padStart(2,"0")}>`);He.every(ct=>this.tokens_to_ids.has(ct))?q.push(...He):q.push(this.unk_token)}else q.push(this.unk_token)}return q}}class qe extends le{constructor(E,q){super(E),this.tokens_to_ids=H(q.target_lang?E.vocab[q.target_lang]:E.vocab),this.bos_token=q.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=q.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=q.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[ae,ye]of this.tokens_to_ids)this.vocab[ye]=ae}encode(E){return E}}class Ue extends _.Callable{constructor(E){super(),this.config=E}static fromConfig(E){if(E===null)return null;switch(E.type){case"BertNormalizer":return new Je(E);case"Precompiled":return new ws(E);case"Sequence":return new ie(E);case"Replace":return new ut(E);case"NFC":return new ue(E);case"NFKC":return new se(E);case"NFKD":return new he(E);case"Strip":return new xe(E);case"StripAccents":return new Be(E);case"Lowercase":return new et(E);case"Prepend":return new Xe(E);default:throw new Error(`Unknown Normalizer type: ${E.type}`)}}normalize(E){throw Error("normalize should be implemented in subclass.")}_call(E){return this.normalize(E)}}class ut extends Ue{normalize(E){const q=L(this.config.pattern);return q===null?E:E.replaceAll(q,this.config.content)}}class ue extends Ue{normalize(E){return E=E.normalize("NFC"),E}}class se extends Ue{normalize(E){return E=E.normalize("NFKC"),E}}class he extends Ue{normalize(E){return E=E.normalize("NFKD"),E}}class xe extends Ue{normalize(E){return this.config.strip_left&&this.config.strip_right?E=E.trim():(this.config.strip_left&&(E=E.trimStart()),this.config.strip_right&&(E=E.trimEnd())),E}}class Be extends Ue{normalize(E){return E=z(E),E}}class et extends Ue{normalize(E){return E=E.toLowerCase(),E}}class Xe extends Ue{normalize(E){return E=this.config.prepend+E,E}}class ie extends Ue{constructor(E){super(E),this.normalizers=E.normalizers.map(q=>Ue.fromConfig(q))}normalize(E){return this.normalizers.reduce((q,ae)=>ae.normalize(q),E)}}class Je extends Ue{_tokenize_chinese_chars(E){const q=[];for(let ae=0;aethis.pre_tokenize_text(ae,q)):this.pre_tokenize_text(E,q)).flat()}_call(E,q){return this.pre_tokenize(E,q)}}class pe extends Fe{constructor(E){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(E,q){return E.trim().match(this.pattern)||[]}}class ve extends Fe{constructor(E){super(),this.config=E,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=Ce,this.text_encoder=new TextEncoder}pre_tokenize_text(E,q){return this.add_prefix_space&&!E.startsWith(" ")&&(E=" "+E),(this.use_regex?E.match(this.pattern)||[]:[E]).map(ye=>Array.from(this.text_encoder.encode(ye),Pe=>this.byte_encoder[Pe]).join(""))}}class Re extends Fe{constructor(E){super(),this.config=E,this.pattern=L(this.config.pattern,this.config.invert)}pre_tokenize_text(E,q){var ae;return this.pattern===null?[]:this.config.invert?E.match(this.pattern)||[]:((ae=this.config.behavior)==null?void 0:ae.toLowerCase())==="removed"?E.split(this.pattern).filter(ye=>ye):v(E,this.pattern)}}class je extends Fe{constructor(E){super(),this.config=E,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(E,q){return E.match(this.pattern)||[]}}class Ve extends Fe{constructor(E){super(),this.config=E;const q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(q,"gu")}pre_tokenize_text(E,q){return E.match(this.pattern)||[]}}class Ne extends _.Callable{constructor(E){super(),this.config=E}static fromConfig(E){if(E===null)return null;switch(E.type){case"TemplateProcessing":return new ht(E);case"ByteLevel":return new dt(E);case"RobertaProcessing":return new at(E);case"BertProcessing":return new Ze(E);case"Sequence":return new gt(E);default:throw new Error(`Unknown PostProcessor type: ${E.type}`)}}post_process(E,...q){throw Error("post_process should be implemented in subclass.")}_call(E,...q){return this.post_process(E,...q)}}class Ze extends Ne{constructor(E){super(E),this.cls=E.cls[0],this.sep=E.sep[0]}post_process(E,q=null,{add_special_tokens:ae=!0}={}){ae&&(E=(0,I.mergeArrays)([this.cls],E,[this.sep]));let ye=new Array(E.length).fill(0);if(q!==null){const Pe=ae&&this instanceof at?[this.sep]:[],He=ae?[this.sep]:[];E=(0,I.mergeArrays)(E,Pe,q,He),ye=(0,I.mergeArrays)(ye,new Array(q.length+Pe.length+He.length).fill(1))}return{tokens:E,token_type_ids:ye}}}class at extends Ze{}class ht extends Ne{constructor(E){super(E),this.single=E.single,this.pair=E.pair}post_process(E,q=null,{add_special_tokens:ae=!0}={}){const ye=q===null?this.single:this.pair;let Pe=[],He=[];for(const ct of ye)"SpecialToken"in ct?ae&&(Pe.push(ct.SpecialToken.id),He.push(ct.SpecialToken.type_id)):"Sequence"in ct&&(ct.Sequence.id==="A"?(Pe=(0,I.mergeArrays)(Pe,E),He=(0,I.mergeArrays)(He,new Array(E.length).fill(ct.Sequence.type_id))):ct.Sequence.id==="B"&&(Pe=(0,I.mergeArrays)(Pe,q),He=(0,I.mergeArrays)(He,new Array(q.length).fill(ct.Sequence.type_id))));return{tokens:Pe,token_type_ids:He}}}class dt extends Ne{post_process(E,q=null){return q&&(E=(0,I.mergeArrays)(E,q)),{tokens:E}}}class gt extends Ne{constructor(E){super(E),this.processors=E.processors.map(q=>Ne.fromConfig(q))}post_process(E,q=null,ae={}){let ye;for(const Pe of this.processors)if(Pe instanceof dt)E=Pe.post_process(E).tokens,q&&(q=Pe.post_process(q).tokens);else{const He=Pe.post_process(E,q,ae);E=He.tokens,ye=He.token_type_ids}return{tokens:E,token_type_ids:ye}}}class F extends _.Callable{constructor(E){super(),this.config=E,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=E.trim_offsets}static fromConfig(E){if(E===null)return null;switch(E.type){case"WordPiece":return new Qe(E);case"Metaspace":return new rs(E);case"ByteLevel":return new rt(E);case"Replace":return new ne(E);case"ByteFallback":return new K(E);case"Fuse":return new de(E);case"Strip":return new Oe(E);case"Sequence":return new Ot(E);case"CTC":return new mt(E);case"BPEDecoder":return new xt(E);default:throw new Error(`Unknown Decoder type: ${E.type}`)}}_call(E){return this.decode(E)}decode(E){return this.decode_chain(E).join("")}decode_chain(E){throw Error("`decode_chain` should be implemented in subclass.")}}class ne extends F{decode_chain(E){const q=L(this.config.pattern);return q===null?E:E.map(ae=>ae.replaceAll(q,this.config.content))}}class K extends F{constructor(E){super(E),this.text_decoder=new TextDecoder}decode_chain(E){const q=[];let ae=[];for(const ye of E){let Pe=null;if(ye.length===6&&ye.startsWith("<0x")&&ye.endsWith(">")){const He=parseInt(ye.slice(3,5),16);isNaN(He)||(Pe=He)}if(Pe!==null)ae.push(Pe);else{if(ae.length>0){const He=this.text_decoder.decode(Uint8Array.from(ae));q.push(He),ae=[]}q.push(ye)}}if(ae.length>0){const ye=this.text_decoder.decode(Uint8Array.from(ae));q.push(ye),ae=[]}return q}}class de extends F{decode_chain(E){return[E.join("")]}}class Oe extends F{constructor(E){super(E),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(E){return E.map(q=>{let ae=0;for(let Pe=0;Pe(ae!==0&&(q.startsWith(this.config.prefix)?q=q.replace(this.config.prefix,""):q=" "+q),this.cleanup&&(q=oe(q)),q))}}class rt extends F{constructor(E){super(E),this.byte_decoder=Te,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(E){const q=E.join(""),ae=new Uint8Array([...q].map(Pe=>this.byte_decoder[Pe]));return this.text_decoder.decode(ae)}decode_chain(E){const q=[];let ae=[];for(const ye of E)this.added_tokens.find(Pe=>Pe.content===ye)!==void 0?(ae.length>0&&(q.push(this.convert_tokens_to_string(ae)),ae=[]),q.push(ye)):ae.push(ye);return ae.length>0&&q.push(this.convert_tokens_to_string(ae)),q}}class mt extends F{constructor(E){super(E),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(E){if(E.length===0)return"";const q=[E[0]];for(let Pe=1;PePe!==this.pad_token).join("");return this.cleanup&&(ye=oe(ye).replaceAll(this.word_delimiter_token," ").trim()),ye}decode_chain(E){return[this.convert_tokens_to_string(E)]}}class Ot extends F{constructor(E){super(E),this.decoders=E.decoders.map(q=>F.fromConfig(q))}decode_chain(E){return this.decoders.reduce((q,ae)=>ae.decode_chain(q),E)}}class xt extends F{constructor(E){super(E),this.suffix=this.config.suffix}decode_chain(E){return E.map((q,ae)=>q.replaceAll(this.suffix,ae===E.length-1?"":" "))}}class Ft extends F{decode_chain(E){let q="";for(let ae=1;aeae.normalize("NFKC")).join("~"):E=E.normalize("NFKC"),E}}class Os extends Fe{constructor(E){super(),this.tokenizers=E.pretokenizers.map(q=>Fe.fromConfig(q))}pre_tokenize_text(E,q){return this.tokenizers.reduce((ae,ye)=>ye.pre_tokenize(ae,q),[E])}}class ks extends Fe{constructor(E){super()}pre_tokenize_text(E,q){return E.match(/\w+|[^\w\s]+/g)||[]}}class qs extends Fe{constructor(E){super()}pre_tokenize_text(E,q){return $(E)}}class ir extends Fe{constructor(E){super(),this.config=E,this.pattern=L(this.config.pattern),this.content=this.config.content}pre_tokenize_text(E,q){return this.pattern===null?[E]:[E.replaceAll(this.pattern,this.config.content)]}}const Kr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Or(Ee,E,q,ae){for(const ye of Object.keys(Ee)){const Pe=E-Ee[ye].length,He=q(ye),ct=new Array(Pe).fill(He);Ee[ye]=ae==="right"?(0,I.mergeArrays)(Ee[ye],ct):(0,I.mergeArrays)(ct,Ee[ye])}}function mn(Ee,E){for(const q of Object.keys(Ee))Ee[q].length=E}class zt extends _.Callable{constructor(q,ae){super();_e(this,"return_token_type_ids",!1);_e(this,"padding_side","right");this._tokenizer_config=ae,this.normalizer=Ue.fromConfig(q.normalizer),this.pre_tokenizer=Fe.fromConfig(q.pre_tokenizer),this.model=le.fromConfig(q.model,ae),this.post_processor=Ne.fromConfig(q.post_processor),this.decoder=F.fromConfig(q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ye of q.added_tokens){const Pe=new J(ye);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=ae.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((ye,Pe)=>Pe.content.length-ye.content.length).map(ye=>`${ye.lstrip?"\\s*":""}(${(0,I.escapeRegExp)(ye.content)})${ye.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.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=ae.model_max_length,this.remove_space=ae.remove_space,this.clean_up_tokenization_spaces=ae.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ae.do_lowercase_and_remove_accent??!1,ae.padding_side&&(this.padding_side=ae.padding_side),this.legacy=!1,this.chat_template=ae.chat_template??null,Array.isArray(this.chat_template)){const ye=Object.create(null);for(const{name:Pe,template:He}of this.chat_template){if(typeof Pe!="string"||typeof He!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ye[Pe]=He}this.chat_template=ye}this._compiled_template_cache=new Map}getToken(...q){for(const ae of q){const ye=this._tokenizer_config[ae];if(ye)if(typeof ye=="object"){if(ye.__type==="AddedToken")return ye.content;throw Error(`Unknown token: ${ye}`)}else return ye}return null}static async from_pretrained(q,{progress_callback:ae=null,config:ye=null,cache_dir:Pe=null,local_files_only:He=!1,revision:ct="main",legacy:wt=null}={}){const _t=await M(q,{progress_callback:ae,config:ye,cache_dir:Pe,local_files_only:He,revision:ct,legacy:wt});return new this(..._t)}_call(q,{text_pair:ae=null,add_special_tokens:ye=!0,padding:Pe=!1,truncation:He=null,max_length:ct=null,return_tensor:wt=!0,return_token_type_ids:_t=null}={}){const it=Array.isArray(q);let Ct;if(it){if(q.length===0)throw Error("text array must be non-empty");if(ae!==null){if(Array.isArray(ae)){if(q.length!==ae.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Ct=q.map((ns,Se)=>this._encode_plus(ns,{text_pair:ae[Se],add_special_tokens:ye,return_token_type_ids:_t}))}else Ct=q.map(ns=>this._encode_plus(ns,{add_special_tokens:ye,return_token_type_ids:_t}))}else{if(q==null)throw Error("text may not be null or undefined");if(Array.isArray(ae))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Ct=[this._encode_plus(q,{text_pair:ae,add_special_tokens:ye,return_token_type_ids:_t})]}if(ct===null?Pe==="max_length"?ct=this.model_max_length:ct=(0,X.max)(Ct.map(ns=>ns.input_ids.length))[0]:He||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."),ct=Math.min(ct,this.model_max_length??1/0),Pe||He)for(let ns=0;nsct?He&&mn(Ct[ns],ct):Pe&&Or(Ct[ns],ct,Se=>Se==="input_ids"?this.pad_token_id:0,this.padding_side));const ms={};if(wt){if(!(Pe&&He)&&Ct.some(Se=>{var ys;for(const Fs of Object.keys(Se))if(Se[Fs].length!==((ys=Ct[0][Fs])==null?void 0:ys.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 ns=[Ct.length,Ct[0].input_ids.length];for(const Se of Object.keys(Ct[0]))ms[Se]=new j.Tensor("int64",BigInt64Array.from(Ct.flatMap(ys=>ys[Se]).map(BigInt)),ns)}else{for(const ns of Object.keys(Ct[0]))ms[ns]=Ct.map(Se=>Se[ns]);if(!it)for(const ns of Object.keys(ms))ms[ns]=ms[ns][0]}return ms}_encode_text(q){return q===null?null:(this.added_tokens_regex?q.split(this.added_tokens_regex).filter(Pe=>Pe):[q]).map((Pe,He)=>{if(this.added_tokens.find(wt=>wt.content===Pe)!==void 0)return Pe;{if(this.remove_space===!0&&(Pe=Pe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Pe=V(Pe)),this.normalizer!==null&&(Pe=this.normalizer(Pe)),Pe.length===0)return[];const wt=this.pre_tokenizer!==null?this.pre_tokenizer(Pe,{section_index:He}):[Pe];return this.model(wt)}}).flat()}_encode_plus(q,{text_pair:ae=null,add_special_tokens:ye=!0,return_token_type_ids:Pe=null}={}){const{tokens:He,token_type_ids:ct}=this._tokenize_helper(q,{pair:ae,add_special_tokens:ye}),wt=this.model.convert_tokens_to_ids(He),_t={input_ids:wt,attention_mask:new Array(wt.length).fill(1)};return(Pe??this.return_token_type_ids)&&ct&&(_t.token_type_ids=ct),_t}_tokenize_helper(q,{pair:ae=null,add_special_tokens:ye=!1}={}){const Pe=this._encode_text(q),He=this._encode_text(ae);return this.post_processor?this.post_processor(Pe,He,{add_special_tokens:ye}):{tokens:(0,I.mergeArrays)(Pe??[],He??[])}}tokenize(q,{pair:ae=null,add_special_tokens:ye=!1}={}){return this._tokenize_helper(q,{pair:ae,add_special_tokens:ye}).tokens}encode(q,{text_pair:ae=null,add_special_tokens:ye=!0,return_token_type_ids:Pe=null}={}){return this._encode_plus(q,{text_pair:ae,add_special_tokens:ye,return_token_type_ids:Pe}).input_ids}batch_decode(q,ae={}){return q instanceof j.Tensor&&(q=q.tolist()),q.map(ye=>this.decode(ye,ae))}decode(q,ae={}){if(q instanceof j.Tensor&&(q=re(q)),!Array.isArray(q)||q.length===0||!(0,I.isIntegralNumber)(q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(q,ae)}decode_single(q,{skip_special_tokens:ae=!1,clean_up_tokenization_spaces:ye=null}){let Pe=this.model.convert_ids_to_tokens(q);ae&&(Pe=Pe.filter(ct=>!this.special_tokens.includes(ct)));let He=this.decoder?this.decoder(Pe):Pe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(He=He.replaceAll(this.decoder.end_of_word_suffix," "),ae&&(He=He.trim())),(ye??this.clean_up_tokenization_spaces)&&(He=oe(He)),He}get_chat_template({chat_template:q=null,tools:ae=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ye=this.chat_template;if(q!==null&&Object.hasOwn(ye,q))q=ye[q];else if(q===null)if(ae!==null&&"tool_use"in ye)q=ye.tool_use;else if("default"in ye)q=ye.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(ye).sort()}.`)}else if(q===null)if(this.chat_template)q=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 q}apply_chat_template(q,{tools:ae=null,documents:ye=null,chat_template:Pe=null,add_generation_prompt:He=!1,tokenize:ct=!0,padding:wt=!1,truncation:_t=!1,max_length:it=null,return_tensor:Ct=!0,return_dict:ms=!1,tokenizer_kwargs:ns={},...Se}={}){if(Pe=this.get_chat_template({chat_template:Pe,tools:ae}),typeof Pe!="string")throw Error(`chat_template must be a string, but got ${typeof Pe}`);let ys=this._compiled_template_cache.get(Pe);ys===void 0&&(ys=new b.Template(Pe),this._compiled_template_cache.set(Pe,ys));const Fs=Object.create(null);for(const Js of Kr){const Dt=this.getToken(Js);Dt&&(Fs[Js]=Dt)}const Xs=ys.render({messages:q,add_generation_prompt:He,tools:ae,documents:ye,...Fs,...Se});if(ct){const Js=this._call(Xs,{add_special_tokens:!1,padding:wt,truncation:_t,max_length:it,return_tensor:Ct,...ns});return ms?Js:Js.input_ids}return Xs}}class Hr extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class kr extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Fr extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Sr extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Dr extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Zs extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class dr extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class $r extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class qr extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class or extends zt{}class ot extends zt{}class pt extends zt{constructor(q,ae){super(q,ae);_e(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 It extends zt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class us extends zt{}class Mr extends zt{}class ts extends zt{}class br extends zt{constructor(E,q){super(E,q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)),this.lang_to_token=ae=>ae}_build_translation_inputs(E,q,ae){return Yr(this,E,q,ae)}}class cr extends br{}class Xr extends zt{}class Lr extends zt{}const vr="▁";class An extends zt{constructor(q,ae){super(q,ae);_e(this,"padding_side","left");this.legacy=ae.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new At({replacement:vr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(q){if(q===null)return null;if(this.legacy||q.length===0)return super._encode_text(q);let ae=super._encode_text(vr+q.replaceAll(vr," "));return ae.length>1&&ae[0]===vr&&this.special_tokens.includes(ae[1])&&(ae=ae.slice(1)),ae}}class zr extends zt{}class In extends zt{}class si extends zt{}class Br extends zt{}class Tr extends zt{}class er extends zt{}class fn extends zt{}class Qr extends zt{}class _n extends zt{}function Yr(Ee,E,q,ae){if(!("language_codes"in Ee)||!Array.isArray(Ee.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Ee)||!(Ee.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Ee)||typeof Ee.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ye=ae.src_lang,Pe=ae.tgt_lang;if(!Ee.language_codes.includes(Pe))throw new Error(`Target language code "${Pe}" is not valid. Must be one of: {${Ee.language_codes.join(", ")}}`);if(ye!==void 0){if(!Ee.language_codes.includes(ye))throw new Error(`Source language code "${ye}" is not valid. Must be one of: {${Ee.language_codes.join(", ")}}`);for(const He of Ee.post_processor.config.single)if("SpecialToken"in He&&Ee.languageRegex.test(He.SpecialToken.id)){He.SpecialToken.id=Ee.lang_to_token(ye);break}}return ae.forced_bos_token_id=Ee.model.convert_tokens_to_ids([Ee.lang_to_token(Pe)])[0],Ee._call(E,q)}class gn extends zt{constructor(E,q){super(E,q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)),this.lang_to_token=ae=>ae}_build_translation_inputs(E,q,ae){return Yr(this,E,q,ae)}}class Bt extends zt{constructor(E,q){super(E,q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)).map(ae=>ae.slice(2,-2)),this.lang_to_token=ae=>`__${ae}__`}_build_translation_inputs(E,q,ae){return Yr(this,E,q,ae)}}class wn extends zt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(E,{return_timestamps:q=!1,return_language:ae=!1,time_precision:ye=null,force_full_sequences:Pe=!0}={}){if(ye===null)throw Error("Must specify time_precision");let He=null;const ct=q==="word";function wt(){return{language:He,timestamp:[null,null],text:""}}const _t=[];let it=wt(),Ct=0;const ms=this.timestamp_begin,Se=ms+1500;let ys=[],Fs=[],Xs=!1,Js=null;const Dt=new Set(this.all_special_ids);for(const es of E){const _s=es.tokens,Tt=ct?es.token_timestamps:null;let os=null,Er=ms;if("stride"in es){const[Mt,Ss,De]=es.stride;if(Ct-=Ss,Js=Mt-De,Ss&&(Er=Ss/ye+ms),De)for(let yt=_s.length-1;yt>=0;--yt){const sr=Number(_s[yt]);if(sr>=ms){if(os!==null&&(sr-ms)*ye=ms&&Ss<=Se){const De=(Ss-ms)*ye+Ct,yt=(0,X.round)(De,2);if(os!==null&&Ss>=os)Xs=!0;else if(Xs||ys.length>0&&Ss0?(ys.push(Ds),ct&&Fs.push(Gs)):ys.every(Mt=>Mt.length===0)&&(it=wt(),ys=[],Ds=[],Fs=[],Gs=[])}if(ys.length>0){if(Pe&&q)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[es,_s]=this.findLongestCommonSequence(ys,Fs),Tt=this.decode(es);it.text=Tt,ct&&(it.words=this.collateWordTimestamps(es,_s,He)),_t.push(it)}let Ns=Object.create(null);const xr=_t.map(es=>es.text).join("");if(q||ae){for(let es=0;es<_t.length;++es){const _s=_t[es];q||delete _s.timestamp,ae||delete _s.language}if(ct){const es=[];for(const _s of _t)for(const Tt of _s.words)es.push(Tt);Ns={chunks:es}}else Ns={chunks:_t}}return[xr,Ns]}findLongestCommonSequence(E,q=null){let ae=E[0],ye=ae.length,Pe=[];const He=Array.isArray(q)&&q.length>0;let ct=He?[]:null,wt=He?q[0]:null;for(let _t=1;_tSs===Er[De]&&wt[xr+De]<=q[_t][Tt+De]).length:Ds=_s.filter((Ss,De)=>Ss===Er[De]).length;const Gs=Ns/1e4,Mt=Ds/Ns+Gs;Ds>1&&Mt>Ct&&(Ct=Mt,ms=[xr,es,Tt,os])}const[Se,ys,Fs,Xs]=ms,Js=Math.floor((ys+Se)/2),Dt=Math.floor((Xs+Fs)/2);Pe.push(...ae.slice(0,Js)),ae=it.slice(Dt),ye=ae.length,He&&(ct.push(...wt.slice(0,Js)),wt=q[_t].slice(Dt))}return Pe.push(...ae),He?(ct.push(...wt),[Pe,ct]):[Pe,[]]}collateWordTimestamps(E,q,ae){const[ye,Pe,He]=this.combineTokensIntoWords(E,ae),ct=[];for(let wt=0;wt=ye){const ct=((He-ye)*ae).toFixed(2);Pe.push(`<|${ct}|>`),Pe.push([])}else Pe[Pe.length-1].push(He);return Pe=Pe.map(He=>typeof He=="string"?He:super.decode(He,q)),Pe.join("")}splitTokensOnUnicode(E){const q=this.decode(E,{decode_with_timestamps:!0}),ae="�",ye=[],Pe=[],He=[];let ct=[],wt=[],_t=0;for(let it=0;it=this.model.tokens_to_ids.get("<|endoftext|>"),Se=it.startsWith(" "),ys=it.trim(),Fs=wt.test(ys);if(ns||Se||Fs||Pe.length===0)Pe.push(it),He.push(Ct),ct.push(ms);else{const Xs=Pe.length-1;Pe[Xs]+=it,He[Xs].push(...Ct),ct[Xs].push(...ms)}}return[Pe,He,ct]}mergePunctuations(E,q,ae,ye,Pe){const He=structuredClone(E),ct=structuredClone(q),wt=structuredClone(ae);let _t=He.length-2,it=He.length-1;for(;_t>=0;)He[_t].startsWith(" ")&&ye.includes(He[_t].trim())?(He[it]=He[_t]+He[it],ct[it]=(0,I.mergeArrays)(ct[_t],ct[it]),wt[it]=(0,I.mergeArrays)(wt[_t],wt[it]),He[_t]="",ct[_t]=[],wt[_t]=[]):it=_t,--_t;for(_t=0,it=1;itCt),ct.filter(Ct=>Ct.length>0),wt.filter(Ct=>Ct.length>0)]}}class On extends zt{}class Fn extends zt{}class Dn extends zt{}class Rr extends zt{constructor(E,q){super(E,q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ae=>this.languageRegex.test(ae)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(E){if(E===null)return null;const[q,...ae]=E.trim().split(this.languageRegex);if(ae.length===0)return super._encode_text(q);if(ae.length===2){const[ye,Pe]=ae;return this.supported_language_codes.includes(ye)||console.warn(`Unsupported language code "${ye}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,I.mergeArrays)([ye],super._encode_text(Pe))}}}class Ln extends zt{}class yn extends zt{}class zn extends zt{}class is extends zt{}class tr extends zt{}class Mn extends zt{constructor(E,q){super(E,q),this.decoder=new Ft({})}}class Bn extends zt{}class Jr extends zt{}class bn{static async from_pretrained(E,{progress_callback:q=null,config:ae=null,cache_dir:ye=null,local_files_only:Pe=!1,revision:He="main",legacy:ct=null}={}){var ms;const[wt,_t]=await M(E,{progress_callback:q,config:ae,cache_dir:ye,local_files_only:Pe,revision:He,legacy:ct}),it=((ms=_t.tokenizer_class)==null?void 0:ms.replace(/Fast$/,""))??"PreTrainedTokenizer";let Ct=this.TOKENIZER_CLASS_MAPPING[it];return Ct||(console.warn(`Unknown tokenizer class "${it}", attempting to construct from base class.`),Ct=zt),new Ct(wt,_t)}}_e(bn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:us,DistilBertTokenizer:or,CamembertTokenizer:ot,DebertaTokenizer:Dr,DebertaV2Tokenizer:Zs,BertTokenizer:Hr,HerbertTokenizer:dr,ConvBertTokenizer:$r,RoFormerTokenizer:qr,XLMTokenizer:pt,ElectraTokenizer:It,MobileBertTokenizer:Fr,SqueezeBertTokenizer:Sr,AlbertTokenizer:kr,GPT2Tokenizer:Mr,BartTokenizer:ts,MBartTokenizer:br,MBart50Tokenizer:cr,RobertaTokenizer:Xr,WhisperTokenizer:wn,CodeGenTokenizer:On,CLIPTokenizer:Fn,SiglipTokenizer:Dn,MarianTokenizer:Rr,BloomTokenizer:Lr,NllbTokenizer:gn,M2M100Tokenizer:Bt,LlamaTokenizer:An,CodeLlamaTokenizer:zr,XLMRobertaTokenizer:In,MPNetTokenizer:si,FalconTokenizer:Br,GPTNeoXTokenizer:Tr,EsmTokenizer:er,Wav2Vec2CTCTokenizer:Ln,BlenderbotTokenizer:yn,BlenderbotSmallTokenizer:zn,SpeechT5Tokenizer:is,NougatTokenizer:tr,VitsTokenizer:Mn,Qwen2Tokenizer:fn,GemmaTokenizer:Qr,Grok1Tokenizer:_n,CohereTokenizer:Bn,MgpstrTokenizer:Jr,PreTrainedTokenizer:zt})},"./src/utils/audio.js":(Le,A,r)=>{r.r(A),r.d(A,{hamming:()=>y,hanning:()=>b,mel_filter_bank:()=>z,read_audio:()=>j,spectrogram:()=>w,window_function:()=>C});var _=r("./src/utils/hub.js"),I=r("./src/utils/maths.js"),N=r("./src/utils/core.js"),X=r("./src/utils/tensor.js");async function j(T,ee){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 J=await(await(0,_.getFile)(T)).arrayBuffer(),le=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${le.sampleRate}Hz.`);const ce=await le.decodeAudioData(J);let ge;if(ce.numberOfChannels===2){const Ce=Math.sqrt(2),Te=ce.getChannelData(0),ze=ce.getChannelData(1);ge=new Float32Array(Te.length);for(let qe=0;qe2595*Math.log10(1+T/700),kaldi:T=>1127*Math.log(1+T/700),slaney:(T,ee=1e3,J=15,le=27/Math.log(6.4))=>T>=ee?J+Math.log(T/ee)*le:3*T/200};function v(T,ee="htk"){const J=M[ee];if(!J)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof T=="number"?J(T):T.map(le=>J(le))}const L={htk:T=>700*(10**(T/2595)-1),kaldi:T=>700*(Math.exp(T/1127)-1),slaney:(T,ee=1e3,J=15,le=Math.log(6.4)/27)=>T>=J?ee*Math.exp(le*(T-J)):200*T/3};function H(T,ee="htk"){const J=L[ee];if(!J)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof T=="number"?J(T):T.map(le=>J(le))}function re(T,ee){const J=Float64Array.from({length:ee.length-1},(Ce,Te)=>ee[Te+1]-ee[Te]),le=Array.from({length:T.length},()=>new Array(ee.length));for(let Ce=0;Cenew Array(T.length));for(let Ce=0;CeT+le*ge)}function z(T,ee,J,le,ce,ge=null,Ce="htk",Te=!1){if(ge!==null&&ge!=="slaney")throw new Error('norm must be one of null or "slaney"');const ze=v(J,Ce),qe=v(le,Ce),Ue=oe(ze,qe,ee+2);let ut=H(Ue,Ce),ue;if(Te){const he=ce/(T*2);ue=v(Float64Array.from({length:T},(xe,Be)=>Be*he),Ce),ut=Ue}else ue=oe(0,Math.floor(ce/2),T);const se=re(ue,ut);if(ge!==null&&ge==="slaney")for(let he=0;hece)throw Error(`frame_length (${J}) may not be larger than fft_length (${ce})`);if(Fe!==J)throw new Error(`Length of the window (${Fe}) must equal frame_length (${J})`);if(le<=0)throw new Error("hop_length must be greater than zero");if(ge===null&&Ue!==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(Ce){if(Te!=="reflect")throw new Error(`pad_mode="${Te}" not implemented yet.`);const F=Math.floor((ce-1)/2)+1;T=V(T,F,F)}let pe=Math.floor(1+Math.floor((T.length-J)/le));et!==null&&pepe?ie&&(je=Xe):je=Re=Xe);const Ve=new I.FFT(ce),Ne=new Float64Array(ce),Ze=new Float64Array(Ve.outputBufferSize),at=new Float32Array(ve*je);for(let F=0;F=1;--de)Ne[de]-=qe*Ne[de-1];Ne[0]*=1-qe}for(let de=0;deMath.pow(Te,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(J&&(Ce=Ce.subarray(0,T)),le===null)return Ce;if(T>le)throw new Error(`Length of the window (${T}) may not be larger than frame_length (${le})`);return Ce}},"./src/utils/constants.js":(Le,A,r)=>{r.r(A),r.d(A,{CHAT_TEMPLATE_NAME:()=>g,CONFIG_NAME:()=>I,FEATURE_EXTRACTOR_NAME:()=>N,GENERATION_CONFIG_NAME:()=>b,GITHUB_ISSUE_URL:()=>_,IMAGE_PROCESSOR_NAME:()=>X,PROCESSOR_NAME:()=>j});const _="https://github.com/huggingface/transformers.js/issues/new/choose",I="config.json",N="preprocessor_config.json",X=N,j="processor_config.json",g="chat_template.json",b="generation_config.json"},"./src/utils/core.js":(Le,A,r)=>{r.r(A),r.d(A,{calculateDimensions:()=>b,calculateReflectOffset:()=>L,count:()=>oe,dispatchCallback:()=>_,escapeRegExp:()=>N,isIntegralNumber:()=>j,isNullishDimension:()=>g,isTypedArray:()=>X,len:()=>re,mergeArrays:()=>M,pick:()=>H,pop:()=>y,product:()=>v,reverseDictionary:()=>I});function _(z,V){z&&z(V)}function I(z){return Object.fromEntries(Object.entries(z).map(([V,Y])=>[Y,V]))}function N(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X(z){var V,Y,D;return((D=(Y=(V=z==null?void 0:z.prototype)==null?void 0:V.__proto__)==null?void 0:Y.constructor)==null?void 0:D.name)==="TypedArray"}function j(z){return Number.isInteger(z)||typeof z=="bigint"}function g(z){return z==null||z===-1}function b(z){const V=[];let Y=z;for(;Array.isArray(Y);)V.push(Y.length),Y=Y[0];return V}function y(z,V,Y=void 0){const D=z[V];if(D!==void 0)return delete z[V],D;if(Y===void 0)throw Error(`Key ${V} does not exist in object.`);return Y}function M(...z){return Array.prototype.concat.apply([],z)}function v(...z){return z.reduce((V,Y)=>V.flatMap(D=>Y.map($=>[D,$])))}function L(z,V){return Math.abs((z+V)%(2*V)-V)}function H(z,V){return Object.assign({},...V.map(Y=>{if(z[Y]!==void 0)return{[Y]:z[Y]}}))}function re(z){let V=0;for(const Y of z)++V;return V}function oe(z,V){let Y=0;for(const D of z)D===V&&++Y;return Y}},"./src/utils/data-structures.js":(Le,A,r)=>{r.r(A),r.d(A,{CharTrie:()=>I,PriorityQueue:()=>_,TokenLattice:()=>X});class _{constructor(b=(M,v)=>M>v,y=1/0){this._heap=[],this._comparator=b,this._maxSize=y}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...b){return this.extend(b)}extend(b){for(const y of b)if(this.size0&&this._swap(0,y),this._heap.pop(),this._siftDown(),b}replace(b){const y=this.peek();return this._heap[0]=b,this._siftDown(),y}_parent(b){return(b+1>>>1)-1}_left(b){return(b<<1)+1}_right(b){return b+1<<1}_greater(b,y){return this._comparator(this._heap[b],this._heap[y])}_swap(b,y){const M=this._heap[b];this._heap[b]=this._heap[y],this._heap[y]=M}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(b){for(;b>0&&this._greater(b,this._parent(b));)this._swap(b,this._parent(b)),b=this._parent(b)}_siftDown(){let b=0;for(;this._left(b)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const v=new j(this.bosTokenId,0,0,0,0),L=new j(this.eosTokenId,1,this.len,0,0);this.nodes.push(v.clone()),this.nodes.push(L.clone()),this.beginNodes[this.len].push(L),this.endNodes[0].push(v)}insert(b,y,M,v){const L=this.nodes.length,H=new j(v,L,b,y,M);this.beginNodes[b].push(H),this.endNodes[b+y].push(H),this.nodes.push(H)}viterbi(){const b=this.len;let y=0;for(;y<=b;){if(this.beginNodes[y].length==0)return[];for(let re of this.beginNodes[y]){re.prev=null;let oe=0,z=null;for(let V of this.endNodes[y]){const Y=V.backtraceScore+re.score;(z===null||Y>oe)&&(z=V.clone(),oe=Y)}if(z!==null)re.prev=z,re.backtraceScore=oe;else return[]}++y}const M=[],L=this.beginNodes[b][0].prev;if(L===null)return[];let H=L.clone();for(;H.prev!==null;)M.push(H.clone()),H=H.clone().prev.clone();return M.reverse(),M}piece(b){return this.chars.slice(b.pos,b.pos+b.length).join("")}tokens(){return this.viterbi().map(y=>this.piece(y))}tokenIds(){return this.viterbi().map(y=>y.tokenId)}}class j{constructor(b,y,M,v,L){this.tokenId=b,this.nodeId=y,this.pos=M,this.length=v,this.score=L,this.prev=null,this.backtraceScore=0}clone(){const b=new j(this.tokenId,this.nodeId,this.pos,this.length,this.score);return b.prev=this.prev,b.backtraceScore=this.backtraceScore,b}}},"./src/utils/devices.js":(Le,A,r)=>{r.r(A),r.d(A,{DEVICE_TYPES:()=>_});const _=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":(Le,A,r)=>{r.r(A),r.d(A,{DATA_TYPES:()=>X,DEFAULT_DEVICE_DTYPE_MAPPING:()=>j,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>g,isWebGpuFp16Supported:()=>N});var _=r("./src/env.js"),I=r("./src/utils/devices.js");const N=function(){let b;return async function(){if(b===void 0)if(!_.apis.IS_WEBGPU_AVAILABLE)b=!1;else try{b=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{b=!1}return b}}(),X=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),j=Object.freeze({[I.DEVICE_TYPES.wasm]:X.q8}),g=Object.freeze({[X.fp32]:"",[X.fp16]:"_fp16",[X.int8]:"_int8",[X.uint8]:"_uint8",[X.q8]:"_quantized",[X.q4]:"_q4",[X.q4f16]:"_q4f16",[X.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Le,A,r)=>{r.r(A),r.d(A,{Callable:()=>_});const _=class{constructor(){let I=function(...N){return I._call(...N)};return Object.setPrototypeOf(I,new.target.prototype)}_call(...I){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Le,A,r)=>{r.r(A),r.d(A,{getFile:()=>y,getModelFile:()=>re,getModelJSON:()=>oe});var _=r("?7a2c"),I=r("?a42a"),N=r("./src/env.js"),X=r("./src/utils/core.js");const j={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 g{constructor(D){if(this.filePath=D,this.headers=new Headers,this.exists=_.existsSync(D),this.exists){this.status=200,this.statusText="OK";let $=_.statSync(D);this.headers.set("content-length",$.size.toString()),this.updateContentType();let w=this;this.body=new ReadableStream({start(C){w.arrayBuffer().then(T=>{C.enqueue(new Uint8Array(T)),C.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const D=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",j[D]??"application/octet-stream")}clone(){let D=new g(this.filePath);return D.exists=this.exists,D.status=this.status,D.statusText=this.statusText,D.headers=new Headers(this.headers),D}async arrayBuffer(){return(await _.promises.readFile(this.filePath)).buffer}async blob(){const D=await _.promises.readFile(this.filePath);return new Blob([D],{type:this.headers.get("content-type")})}async text(){return await _.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function b(Y,D=null,$=null){let w;try{w=new URL(Y)}catch{return!1}return!(D&&!D.includes(w.protocol)||$&&!$.includes(w.hostname))}async function y(Y){var D;if(N.env.useFS&&!b(Y,["http:","https:","blob:"]))return new g(Y);if(typeof process<"u"&&((D=process==null?void 0:process.release)==null?void 0:D.name)==="node"){const $=!!(nr!=null&&nr.TESTING_REMOTELY),w=N.env.version,C=new Headers;if(C.set("User-Agent",`transformers.js/${w}; is_ci/${$};`),b(Y,["http:","https:"],["huggingface.co","hf.co"])){const ee=(nr==null?void 0:nr.HF_TOKEN)??(nr==null?void 0:nr.HF_ACCESS_TOKEN);ee&&C.set("Authorization",`Bearer ${ee}`)}return fetch(Y,{headers:C})}else return fetch(Y)}const M={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 v(Y,D,$){if(!$)return null;const w=M[Y]??`Error (${Y}) occurred while trying to load file`;throw Error(`${w}: "${D}".`)}class L{constructor(D){this.path=D}async match(D){let $=I.join(this.path,D),w=new g($);if(w.exists)return w}async put(D,$){const w=Buffer.from(await $.arrayBuffer());let C=I.join(this.path,D);try{await _.promises.mkdir(I.dirname(C),{recursive:!0}),await _.promises.writeFile(C,w)}catch(T){console.warn("An error occurred while writing the file to cache:",T)}}}async function H(Y,...D){for(let $ of D)try{let w=await Y.match($);if(w)return w}catch{continue}}async function re(Y,D,$=!0,w={}){if(!N.env.allowLocalModels){if(w.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(!N.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,X.dispatchCallback)(w.progress_callback,{status:"initiate",name:Y,file:D});let C;if(!C&&N.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{C=await caches.open("transformers-cache")}catch(ut){console.warn("An error occurred while opening the browser cache:",ut)}}if(!C&&N.env.useFSCache&&(C=new L(w.cache_dir??N.env.cacheDir)),!C&&N.env.useCustomCache){if(!N.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!N.env.customCache.match||!N.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");C=N.env.customCache}const T=w.revision??"main";let ee=V(Y,D),J=V(N.env.localModelPath,ee),le=V(N.env.remoteHost,N.env.remotePathTemplate.replaceAll("{model}",Y).replaceAll("{revision}",encodeURIComponent(T)),D),ce=T==="main"?ee:V(Y,T,D),ge,Ce=C instanceof L?ce:le,Te=!1,ze;C&&(ze=await H(C,J,Ce));const qe=ze!==void 0;if(ze===void 0){if(N.env.allowLocalModels)if(b(ee,["http:","https:"])){if(w.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ee}.`);if(!N.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ee}.`)}else try{ze=await y(J),ge=J}catch(ue){console.warn(`Unable to load from local path "${J}": "${ue}"`)}if(ze===void 0||ze.status===404){if(w.local_files_only||!N.env.allowRemoteModels){if($)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${J}".`);return null}if(ze=await y(le),ze.status!==200)return v(ze.status,le,$);ge=Ce}Te=C&&typeof Response<"u"&&ze instanceof Response&&ze.status===200}(0,X.dispatchCallback)(w.progress_callback,{status:"download",name:Y,file:D});let Ue;return w.progress_callback?qe&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ue=new Uint8Array(await ze.arrayBuffer()),(0,X.dispatchCallback)(w.progress_callback,{status:"progress",name:Y,file:D,progress:100,loaded:Ue.length,total:Ue.length})):Ue=await z(ze,ut=>{(0,X.dispatchCallback)(w.progress_callback,{status:"progress",name:Y,file:D,...ut})}):Ue=new Uint8Array(await ze.arrayBuffer()),Te&&ge&&await C.match(ge)===void 0&&await C.put(ge,new Response(Ue,{headers:ze.headers})).catch(ut=>{console.warn(`Unable to add response to browser cache: ${ut}.`)}),(0,X.dispatchCallback)(w.progress_callback,{status:"done",name:Y,file:D}),Ue}async function oe(Y,D,$=!0,w={}){let C=await re(Y,D,$,w);if(C===null)return{};let ee=new TextDecoder("utf-8").decode(C);return JSON.parse(ee)}async function z(Y,D){const $=Y.headers.get("Content-Length");$===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let w=parseInt($??"0"),C=new Uint8Array(w),T=0;const ee=Y.body.getReader();async function J(){const{done:le,value:ce}=await ee.read();if(le)return;let ge=T+ce.length;if(ge>w){w=ge;let Te=new Uint8Array(w);Te.set(C),C=Te}C.set(ce,T),T=ge;const Ce=T/w*100;return D({progress:Ce,loaded:T,total:w}),J()}return await J(),C}function V(...Y){return Y=Y.map((D,$)=>($&&(D=D.replace(new RegExp("^/"),"")),$!==Y.length-1&&(D=D.replace(new RegExp("/$"),"")),D)),Y.join("/")}},"./src/utils/image.js":(Le,A,r)=>{r.r(A),r.d(A,{RawImage:()=>H,load_image:()=>re});var _=r("./src/utils/core.js"),I=r("./src/utils/hub.js"),N=r("./src/env.js"),X=r("./src/utils/tensor.js"),j=r("?2b25");let g,b,y;const M=N.apis.IS_BROWSER_ENV||N.apis.IS_WEBWORKER_ENV;if(M)g=(oe,z)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(oe,z)},y=self.createImageBitmap,b=self.ImageData;else if(j)y=async oe=>{const V=(await oe.metadata()).channels,{data:Y,info:D}=await oe.rotate().raw().toBuffer({resolveWithObject:!0}),$=new H(new Uint8ClampedArray(Y),D.width,D.height,D.channels);return V!==void 0&&V!==D.channels&&$.convert(V),$};else throw new Error("Unable to load image processing library.");const v={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},L=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class H{constructor(z,V,Y,D){this.data=z,this.width=V,this.height=Y,this.channels=D}get size(){return[this.width,this.height]}static async read(z){if(z instanceof H)return z;if(typeof z=="string"||z instanceof URL)return await this.fromURL(z);throw new Error(`Unsupported input type: ${typeof z}`)}static fromCanvas(z){if(!M)throw new Error("fromCanvas() is only supported in browser environments.");const Y=z.getContext("2d").getImageData(0,0,z.width,z.height).data;return new H(Y,z.width,z.height,4)}static async fromURL(z){const V=await(0,I.getFile)(z);if(V.status!==200)throw new Error(`Unable to read image from "${z}" (${V.status} ${V.statusText})`);const Y=await V.blob();return this.fromBlob(Y)}static async fromBlob(z){if(M){const V=await y(z),Y=g(V.width,V.height).getContext("2d");return Y.drawImage(V,0,0),new this(Y.getImageData(0,0,V.width,V.height).data,V.width,V.height,4)}else{const V=j(await z.arrayBuffer());return await y(V)}}static fromTensor(z,V="CHW"){if(z.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${z.dims.length} dimensions.`);if(V==="CHW")z=z.transpose(1,2,0);else if(V!=="HWC")throw new Error(`Unsupported channel format: ${V}`);if(!(z.data instanceof Uint8ClampedArray||z.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${z.type}`);switch(z.dims[2]){case 1:case 2:case 3:case 4:return new H(z.data,z.dims[1],z.dims[0],z.dims[2]);default:throw new Error(`Unsupported number of channels: ${z.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const z=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let V=0,Y=0;V=0?T=Y:J=-Y,D>=0?ee=D:le=-D,C.drawImage(w,T,ee,z,V,J,le,z,V),new H(C.getImageData(0,0,z,V).data,z,V,4).convert($)}else{let $=this.toSharp();if(Y>=0&&D>=0)$=$.extract({left:Math.floor(Y),top:Math.floor(D),width:z,height:V});else if(Y<=0&&D<=0){const w=Math.floor(-D),C=Math.floor(-Y);$=$.extend({top:w,left:C,right:z-this.width-C,bottom:V-this.height-w})}else{let w=[0,0],C=0;D<0?(w[0]=Math.floor(-D),w[1]=V-this.height-w[0]):C=Math.floor(D);let T=[0,0],ee=0;Y<0?(T[0]=Math.floor(-Y),T[1]=z-this.width-T[0]):ee=Math.floor(Y),$=$.extend({top:w[0],bottom:w[1],left:T[0],right:T[1]}).extract({left:ee,top:C,width:z,height:V})}return await y($)}}async toBlob(z="image/png",V=1){if(!M)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:z,quality:V})}toTensor(z="CHW"){let V=new X.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(z!=="HWC")if(z==="CHW")V=V.permute(2,0,1);else throw new Error(`Unsupported channel format: ${z}`);return V}toCanvas(){if(!M)throw new Error("toCanvas() is only supported in browser environments.");const z=this.clone().rgba(),V=g(z.width,z.height),Y=new b(z.data,z.width,z.height);return V.getContext("2d").putImageData(Y,0,0),V}split(){const{data:z,width:V,height:Y,channels:D}=this,$=z.constructor,w=z.length/D,C=Array.from({length:D},()=>new $(w));for(let T=0;Tnew H(T,V,Y,1))}_update(z,V,Y,D=null){return this.data=z,this.width=V,this.height=Y,D!==null&&(this.channels=D),this}clone(){return new H(this.data.slice(),this.width,this.height,this.channels)}convert(z){if(this.channels===z)return this;switch(z){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(z){if(M){if(N.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const V=z.split(".").pop().toLowerCase(),Y=L.get(V)??"image/png",D=await this.toBlob(Y),$=URL.createObjectURL(D),w=document.createElement("a");w.href=$,w.download=z,w.click(),w.remove()}else{if(N.env.useFS)return await this.toSharp().toFile(z);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(M)throw new Error("toSharp() is only supported in server-side environments.");return j(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const re=H.read.bind(H)},"./src/utils/maths.js":(Le,A,r)=>{r.r(A),r.d(A,{FFT:()=>re,bankers_round:()=>V,cos_sim:()=>g,dot:()=>j,dynamic_time_warping:()=>Y,interpolate_data:()=>_,log_softmax:()=>X,magnitude:()=>b,max:()=>M,medianFilter:()=>oe,min:()=>y,permute_data:()=>I,round:()=>z,softmax:()=>N});function _(D,[$,w,C],[T,ee],J="bilinear",le=!1){const ce=ee/C,ge=T/w,Ce=new D.constructor(T*ee*$),Te=w*C,ze=T*ee;for(let qe=0;qe=0;--le)T[le]=ce,C[le]=$[w[le]],ce*=C[le];const ee=w.map((le,ce)=>T[w.indexOf(ce)]),J=new D.constructor(D.length);for(let le=0;le=0;--ge)ce+=Ce%$[ge]*ee[ge],Ce=Math.floor(Ce/$[ge]);J[ce]=D[le]}return[J,C]}function N(D){const $=M(D)[0],w=D.map(ee=>Math.exp(ee-$)),C=w.reduce((ee,J)=>ee+J,0);return w.map(ee=>ee/C)}function X(D){const $=M(D)[0];let w=0;for(let ee=0;eeee-$-C)}function j(D,$){let w=0;for(let C=0;C$+w*w,0))}function y(D){if(D.length===0)throw Error("Array must not be empty");let $=D[0],w=0;for(let C=1;C$&&($=D[C],w=C);return[Number($),w]}function v(D){return D>0&&(D&D-1)===0}class L{constructor($){if(this.size=$|0,this.size<=1||!v(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=$<<1,this.table=new Float64Array(this.size*2);for(let C=0;CC;C<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>T&3)<>>1);for(let T=0;T<$.length;T+=2)C[T>>>1]=$[T];return C}toComplexArray($,w){const C=w||this.createComplexArray();for(let T=0;T>>1],C[T+1]=0;return C}transform($,w){if($===w)throw new Error("Input and output buffers must be different");this._transform4($,w,1)}realTransform($,w){if($===w)throw new Error("Input and output buffers must be different");this._realTransform4($,w,1)}inverseTransform($,w){if($===w)throw new Error("Input and output buffers must be different");this._transform4($,w,-1);for(let C=0;C<$.length;++C)$[C]/=this.size}_transform4($,w,C){const T=this._csize;let J=1<>=2;J>=2;J>>=2){le=T/J<<1;const ze=le>>>2;for(ce=0;ce>>1,J>>>1)}else for(ce=0,ge=0;ce>>1,J>>>1,C)}const Te=this.table;for(J>>=2;J>=2;J>>=2){le=T/J<<1;const qe=le>>>1,Ue=qe>>>1,ut=Ue>>>1;for(ce=0;ce>>1;for(let qe=2;qe>1;++Ce){const Te=(Ce+1-$)**2/2,ze=Math.sqrt(ce**2+ge**2)**Te,qe=Te*Math.atan2(ge,ce),Ue=2*Ce;ee[Ue]=ze*Math.cos(qe),ee[Ue+1]=ze*Math.sin(qe),J[Ue]=ee[Ue],J[Ue+1]=-ee[Ue+1]}this._slicedChirpBuffer=ee.subarray(w,C),this._f=new L(T>>1),this._f.transform(this._chirpBuffer,J)}_transform($,w,C){const T=this._buffer1,ee=this._buffer2,J=this._outBuffer1,le=this._outBuffer2,ce=this._chirpBuffer,ge=this._slicedChirpBuffer,Ce=this._a;if(C)for(let Te=0;Te>1,Ue=w[qe];T[Te]=Ue*ge[Te],T[ze]=Ue*ge[ze]}else for(let Te=0;Te=D.length&&(ce=2*(D.length-1)-ce),C[J++]=D[ce]}C.sort(),w[ee]=C[T]}return w}function z(D,$){const w=Math.pow(10,$);return Math.round(D*w)/w}function V(D){const $=Math.round(D);return Math.abs(D)%1===.5?$%2===0?$:$-1:$}function Y(D){const $=D.length,w=D[0].length,C=[$+1,w+1],T=Array.from({length:C[0]},()=>Array(C[1]).fill(1/0));T[0][0]=0;const ee=Array.from({length:C[0]},()=>Array(C[1]).fill(-1));for(let Ce=1;Ce0||le>0;)switch(ce.push(J-1),ge.push(le-1),ee[J][le]){case 0:--J,--le;break;case 1:--J;break;case 2:--le;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${J}, ${le}]. Please file a bug report.`)}return ce.reverse(),ge.reverse(),[ce,ge]}},"./src/utils/tensor.js":(Le,A,r)=>{r.r(A),r.d(A,{Tensor:()=>j,cat:()=>w,full:()=>ce,full_like:()=>ge,interpolate:()=>y,interpolate_4d:()=>M,layer_norm:()=>V,matmul:()=>v,mean:()=>ee,mean_pooling:()=>z,ones:()=>Ce,ones_like:()=>Te,permute:()=>b,quantize_embeddings:()=>ut,rand:()=>Ue,rfft:()=>L,slice:()=>oe,stack:()=>C,std_mean:()=>T,topk:()=>H,zeros:()=>ze,zeros_like:()=>qe});var _=r("./src/utils/maths.js"),I=r("./src/backends/onnx.js"),N=r("./src/ops/registry.js");const X=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,uint4:Uint8Array,int4:Int8Array});class j{constructor(...se){_e(this,"ort_tensor");return(0,I.isONNXTensor)(se[0])?this.ort_tensor=se[0]:this.ort_tensor=new I.Tensor(se[0],se[1],se[2]),new Proxy(this,{get:(he,xe)=>{if(typeof xe=="string"){let Be=Number(xe);if(Number.isInteger(Be))return he._getitem(Be)}return he[xe]},set:(he,xe,Be)=>he[xe]=Be})}get dims(){return this.ort_tensor.dims}set dims(se){this.ort_tensor.dims=se}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[se,...he]=this.dims;if(he.length>0){const xe=he.reduce((Be,et)=>Be*et);for(let Be=0;Be0){const Be=xe.reduce((et,Xe)=>et*Xe);return this._subarray(se,Be,xe)}else return new j(this.type,[this.data[se]],xe)}indexOf(se){const he=this.data;for(let xe=0;xeRe)throw new Error(`Invalid slice: ${pe}`);const je=[Math.max(ve,0),Math.min(Re,this.dims[Fe])];xe.push(je),he.push(je[1]-je[0])}else throw new Error(`Invalid slice: ${pe}`)}const Be=xe.map(([Fe,pe])=>pe-Fe),et=Be.reduce((Fe,pe)=>Fe*pe),Xe=this.data,ie=new Xe.constructor(et),Je=this.stride();for(let Fe=0;Fe=0;--ve){const je=Be[ve];pe+=(Re%je+xe[ve][0])*Je[ve],Re=Math.floor(Re/je)}ie[Fe]=Xe[pe]}return new j(this.type,ie,he)}permute(...se){return b(this,se)}transpose(...se){return this.permute(...se)}sum(se=null,he=!1){return this.norm(1,se,he)}norm(se="fro",he=null,xe=!1){if(se==="fro")se=2;else if(typeof se=="string")throw Error(`Unsupported norm: ${se}`);const Be=this.data;if(he===null){let ie=Be.reduce((Je,Fe)=>Je+Fe**se,0)**(1/se);return new j(this.type,[ie],[])}he=$(he,this.dims.length);const et=this.dims.slice();et[he]=1;const Xe=new Be.constructor(Be.length/this.dims[he]);for(let ie=0;ie=0;--Fe){const Re=this.dims[Fe];if(Fe!==he){const je=pe%Re;Je+=je*ve,ve*=et[Fe]}pe=Math.floor(pe/Re)}Xe[Je]+=Be[ie]**se}if(se!==1)for(let ie=0;ie=0;--Je){const ve=this.dims[Je];if(Je!==he){const Re=Fe%ve;ie+=Re*pe,pe*=this.dims[Je]}Fe=Math.floor(Fe/ve)}Be[Xe]/=et[ie]}return this}normalize(se=2,he=1){return this.clone().normalize_(se,he)}stride(){return J(this.dims)}squeeze(se=null){return new j(this.type,this.data,Y(this.dims,se))}squeeze_(se=null){return this.dims=Y(this.dims,se),this}unsqueeze(se=null){return new j(this.type,this.data,D(this.dims,se))}unsqueeze_(se=null){return this.dims=D(this.dims,se),this}flatten_(se=0,he=-1){he=(he+this.dims.length)%this.dims.length;let xe=this.dims.slice(0,se),Be=this.dims.slice(se,he+1),et=this.dims.slice(he+1);return this.dims=[...xe,Be.reduce((Xe,ie)=>Xe*ie,1),...et],this}flatten(se=0,he=-1){return this.clone().flatten_(se,he)}view(...se){let he=-1;for(let Be=0;Beie!==he?et*Xe:et,1);se[he]=xe.length/Be}return new j(this.type,xe,se)}neg_(){const se=this.data;for(let he=0;heet*Xe);if(he!==xe)throw Error(`cannot reshape array of size ${he} into shape (${se})`);let Be=ue;for(let et=se.length-1;et>=0;et--)Be=Be.reduce((Xe,ie)=>{let Je=Xe[Xe.length-1];return Je.lengthnew j("int64",ue,[ue.length]);async function oe(ue,se,he,xe,Be){return await(await N.TensorOpRegistry.slice)({x:ue,s:re(se),e:re(he),a:re(xe),t:re(Be??new Array(xe.length).fill(1))})}function z(ue,se){const he=ue.data,xe=se.data,Be=[ue.dims[0],ue.dims[2]],et=new he.constructor(Be[0]*Be[1]),[Xe,ie,Je]=ue.dims;let Fe=0;for(let pe=0;pehe!==1):typeof se=="number"?ue[se]===1&&ue.splice(se,1):Array.isArray(se)&&(ue=ue.filter((he,xe)=>he!==1||!se.includes(xe))),ue}function D(ue,se){return se=$(se,ue.length+1),ue=ue.slice(),ue.splice(se,0,1),ue}function $(ue,se,he=null,xe=!0){if(xe&&(ue<-se||ue>=se))throw new Error(`IndexError: index ${ue} is out of bounds for dimension${he===null?"":" "+he} with size ${se}`);return ue<0&&(ue=(ue%se+se)%se),ue}function w(ue,se=0){se=$(se,ue[0].dims.length);const he=ue[0].dims.slice();he[se]=ue.reduce((Xe,ie)=>Xe+ie.dims[se],0);const xe=he.reduce((Xe,ie)=>Xe*ie,1),Be=new ue[0].data.constructor(xe),et=ue[0].type;if(se===0){let Xe=0;for(const ie of ue){const Je=ie.data;Be.set(Je,Xe),Xe+=Je.length}}else{let Xe=0;for(let ie=0;ie=0;--Re){const Ne=Fe[Re];let Ze=je%Ne;Re===se&&(Ze+=Xe),ve+=Ze*Ve,Ve*=he[Re],je=Math.floor(je/Ne)}Be[ve]=Je[pe]}Xe+=Fe[se]}}return new j(et,Be,he)}function C(ue,se=0){return w(ue.map(he=>he.unsqueeze(se)),se)}function T(ue,se=null,he=1,xe=!1){const Be=ue.data,et=ue.dims;if(se===null){const Re=Be.reduce((Ze,at)=>Ze+at,0)/Be.length,je=Math.sqrt(Be.reduce((Ze,at)=>Ze+(at-Re)**2,0)/(Be.length-he)),Ve=new j(ue.type,[Re],[]);return[new j(ue.type,[je],[]),Ve]}se=$(se,et.length);const Xe=ee(ue,se,xe),ie=Xe.data,Je=et.slice();Je[se]=1;const Fe=new Be.constructor(Be.length/et[se]);for(let ve=0;ve=0;--je){const Ze=et[je];if(je!==se){const at=Ve%Ze;Re+=at*Ne,Ne*=Je[je]}Ve=Math.floor(Ve/Ze)}Fe[Re]+=(Be[ve]-ie[Re])**2}for(let ve=0;veJe+Fe,0);return new j(ue.type,[ie/xe.length],[])}const Be=ue.dims;se=$(se,Be.length);const et=Be.slice();et[se]=1;const Xe=new xe.constructor(xe.length/Be[se]);for(let ie=0;ie=0;--Fe){const Re=Be[Fe];if(Fe!==se){const je=pe%Re;Je+=je*ve,ve*=et[Fe]}pe=Math.floor(pe/Re)}Xe[Je]+=xe[ie]}if(Be[se]!==1)for(let ie=0;ie=0;--he)se[he]=xe,xe*=ue[he];return se}function le(ue,se,he,xe){const Be=ue.reduce((et,Xe)=>et*Xe,1);return new j(he,new xe(Be).fill(se),ue)}function ce(ue,se){let he,xe;if(typeof se=="number")he="float32",xe=Float32Array;else if(typeof se=="bigint")he="int64",xe=BigInt64Array;else if(typeof se=="boolean")he="bool",xe=Uint8Array;else throw new Error(`Unsupported data type: ${typeof se}`);return le(ue,se,he,xe)}function ge(ue,se){return ce(ue.dims,se)}function Ce(ue){return le(ue,1n,"int64",BigInt64Array)}function Te(ue){return Ce(ue.dims)}function ze(ue){return le(ue,0n,"int64",BigInt64Array)}function qe(ue){return ze(ue.dims)}function Ue(ue){const se=ue.reduce((he,xe)=>he*xe,1);return new j("float32",Float32Array.from({length:se},()=>Math.random()),ue)}function ut(ue,se){if(ue.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ue.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(se))throw new Error("The precision must be either 'binary' or 'ubinary'");const he=se==="binary",xe=he?"int8":"uint8",Be=he?Int8Array:Uint8Array,et=ue.data,Xe=new Be(et.length/8);for(let ie=0;ie0?1:0,Fe=Math.floor(ie/8),pe=ie%8;Xe[Fe]|=Je<<7-pe,he&&pe===0&&(Xe[Fe]-=128)}return new j(xe,Xe,[ue.dims[0],ue.dims[1]/8])}}},ei={};function fs(Le){var A=ei[Le];if(A!==void 0)return A.exports;var r=ei[Le]={exports:{}};return Gr[Le](r,r.exports,fs),r.exports}fs.m=Gr,(()=>{var Le=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,A;fs.t=function(r,_){if(_&1&&(r=this(r)),_&8||typeof r=="object"&&r&&(_&4&&r.__esModule||_&16&&typeof r.then=="function"))return r;var I=Object.create(null);fs.r(I);var N={};A=A||[null,Le({}),Le([]),Le(Le)];for(var X=_&2&&r;typeof X=="object"&&!~A.indexOf(X);X=Le(X))Object.getOwnPropertyNames(X).forEach(j=>N[j]=()=>r[j]);return N.default=()=>r,fs.d(I,N),I}})(),fs.d=(Le,A)=>{for(var r in A)fs.o(A,r)&&!fs.o(Le,r)&&Object.defineProperty(Le,r,{enumerable:!0,get:A[r]})},fs.o=(Le,A)=>Object.prototype.hasOwnProperty.call(Le,A),fs.r=Le=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Le,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Le,"__esModule",{value:!0})},(()=>{var Le;if(typeof self.location.href=="string"&&(Le=self.location.href),!Le)throw new Error("Automatic publicPath is not supported in this browser");Le=Le.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),fs.p=Le})(),fs.b=new URL("./",self.location.href);var c={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/fs.r(c),fs.d(c,{ASTFeatureExtractor:()=>y.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>_.AlbertTokenizer,AudioClassificationPipeline:()=>A.AudioClassificationPipeline,AutoConfig:()=>I.AutoConfig,AutoFeatureExtractor:()=>M.AutoFeatureExtractor,AutoImageProcessor:()=>H.AutoImageProcessor,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>r.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>r.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>r.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>z.AutoProcessor,AutoTokenizer:()=>_.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>A.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>_.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>V.BaseStreamer,BeitFeatureExtractor:()=>L.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>_.BertTokenizer,BitImageProcessor:()=>L.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>_.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>_.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>_.BloomTokenizer,CLIPFeatureExtractor:()=>L.CLIPFeatureExtractor,CLIPImageProcessor:()=>L.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModel:()=>r.CLIPTextModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>_.CLIPTokenizer,CLIPVisionModel:()=>r.CLIPVisionModel,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>_.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>L.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>y.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>D.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>_.CodeGenTokenizer,CodeLlamaTokenizer:()=>_.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>_.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>_.ConvBertTokenizer,ConvNextFeatureExtractor:()=>L.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>L.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>L.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>L.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>_.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>_.DebertaV2Tokenizer,DecisionTransformerModel:()=>r.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>r.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>L.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>L.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>A.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>L.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>L.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>_.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>A.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>L.DonutFeatureExtractor,DonutImageProcessor:()=>L.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>L.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>_.ElectraTokenizer,EosTokenCriteria:()=>Y.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>_.EsmTokenizer,ExaoneForCausalLM:()=>r.ExaoneForCausalLM,ExaoneModel:()=>r.ExaoneModel,ExaonePreTrainedModel:()=>r.ExaonePreTrainedModel,FFT:()=>g.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>_.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>A.FeatureExtractionPipeline,FeatureExtractor:()=>b.FeatureExtractor,FillMaskPipeline:()=>A.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>oe.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>D.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>D.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>L.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>_.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>_.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>_.GemmaTokenizer,GraniteForCausalLM:()=>r.GraniteForCausalLM,GraniteModel:()=>r.GraniteModel,GranitePreTrainedModel:()=>r.GranitePreTrainedModel,Grok1Tokenizer:()=>_.Grok1Tokenizer,GroupViTModel:()=>r.GroupViTModel,GroupViTPreTrainedModel:()=>r.GroupViTPreTrainedModel,HerbertTokenizer:()=>_.HerbertTokenizer,HieraForImageClassification:()=>r.HieraForImageClassification,HieraModel:()=>r.HieraModel,HieraPreTrainedModel:()=>r.HieraPreTrainedModel,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,IJepaForImageClassification:()=>r.IJepaForImageClassification,IJepaModel:()=>r.IJepaModel,IJepaPreTrainedModel:()=>r.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>r.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>L.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>oe.Idefics3Processor,ImageClassificationPipeline:()=>A.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>A.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>y.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>v.ImageProcessor,ImageSegmentationPipeline:()=>A.ImageSegmentationPipeline,ImageToImagePipeline:()=>A.ImageToImagePipeline,ImageToTextPipeline:()=>A.ImageToTextPipeline,InterruptableStoppingCriteria:()=>Y.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>L.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>oe.JinaCLIPProcessor,JinaCLIPTextModel:()=>r.JinaCLIPTextModel,JinaCLIPVisionModel:()=>r.JinaCLIPVisionModel,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>_.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>r.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>L.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>D.LogitsProcessor,LogitsProcessorList:()=>D.LogitsProcessorList,LogitsWarper:()=>D.LogitsWarper,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>_.M2M100Tokenizer,MBart50Tokenizer:()=>_.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>_.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>_.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>_.MarianTokenizer,Mask2FormerImageProcessor:()=>L.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>L.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>L.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>Y.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>oe.MgpstrProcessor,MgpstrTokenizer:()=>_.MgpstrTokenizer,MinLengthLogitsProcessor:()=>D.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>D.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>_.MobileBertTokenizer,MobileLLMForCausalLM:()=>r.MobileLLMForCausalLM,MobileLLMModel:()=>r.MobileLLMModel,MobileLLMPreTrainedModel:()=>r.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>L.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>L.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>L.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>L.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>L.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>L.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>L.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>L.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>L.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>L.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>y.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>oe.MoonshineProcessor,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MultiModalityCausalLM:()=>r.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>r.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>_.NllbTokenizer,NoBadWordsLogitsProcessor:()=>D.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>D.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>L.NougatImageProcessor,NougatTokenizer:()=>_.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>A.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>r.Olmo2ForCausalLM,Olmo2Model:()=>r.Olmo2Model,Olmo2PreTrainedModel:()=>r.Olmo2PreTrainedModel,OlmoForCausalLM:()=>r.OlmoForCausalLM,OlmoModel:()=>r.OlmoModel,OlmoPreTrainedModel:()=>r.OlmoPreTrainedModel,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>L.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>L.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>oe.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>L.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>oe.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>r.PatchTSMixerForPrediction,PatchTSMixerModel:()=>r.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>r.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>r.PatchTSTForPrediction,PatchTSTModel:()=>r.PatchTSTModel,PatchTSTPreTrainedModel:()=>r.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,Phi3VForCausalLM:()=>r.Phi3VForCausalLM,Phi3VImageProcessor:()=>L.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>oe.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>A.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>_.PreTrainedTokenizer,PretrainedConfig:()=>I.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>re.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>L.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>y.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>oe.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>A.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>_.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>L.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>oe.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>L.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawImage:()=>X.RawImage,RepetitionPenaltyLogitsProcessor:()=>D.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>_.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>_.RobertaTokenizer,SamImageProcessor:()=>L.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>oe.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>y.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>L.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>L.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>L.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>_.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>y.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>oe.SpeechT5Processor,SpeechT5Tokenizer:()=>_.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>_.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>Y.StoppingCriteria,StoppingCriteriaList:()=>Y.StoppingCriteriaList,SummarizationPipeline:()=>A.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>D.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>L.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>_.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>D.TemperatureLogitsWarper,Tensor:()=>j.Tensor,Text2TextGenerationPipeline:()=>A.Text2TextGenerationPipeline,TextClassificationPipeline:()=>A.TextClassificationPipeline,TextGenerationPipeline:()=>A.TextGenerationPipeline,TextStreamer:()=>V.TextStreamer,TextToAudioPipeline:()=>A.TextToAudioPipeline,TokenClassificationPipeline:()=>A.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>_.TokenizerModel,TopKLogitsWarper:()=>D.TopKLogitsWarper,TopPLogitsWarper:()=>D.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>A.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>oe.VLChatProcessor,VLMImageProcessor:()=>L.VLMImageProcessor,ViTFeatureExtractor:()=>L.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>L.ViTImageProcessor,ViTMAEModel:()=>r.ViTMAEModel,ViTMAEPreTrainedModel:()=>r.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>r.ViTMSNForImageClassification,ViTMSNModel:()=>r.ViTMSNModel,ViTMSNPreTrainedModel:()=>r.ViTMSNPreTrainedModel,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>L.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>L.VitPoseImageProcessor,VitPosePreTrainedModel:()=>r.VitPosePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>_.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>_.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>y.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>oe.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>y.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>oe.WhisperProcessor,WhisperTextStreamer:()=>V.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>D.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>_.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>_.XLMRobertaTokenizer,XLMTokenizer:()=>_.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>L.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>L.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>A.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>A.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>A.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>A.ZeroShotObjectDetectionPipeline,bankers_round:()=>g.bankers_round,cat:()=>j.cat,cos_sim:()=>g.cos_sim,dot:()=>g.dot,dynamic_time_warping:()=>g.dynamic_time_warping,env:()=>Le.env,full:()=>j.full,full_like:()=>j.full_like,getKeyValueShapes:()=>I.getKeyValueShapes,hamming:()=>N.hamming,hanning:()=>N.hanning,interpolate:()=>j.interpolate,interpolate_4d:()=>j.interpolate_4d,interpolate_data:()=>g.interpolate_data,is_chinese_char:()=>_.is_chinese_char,layer_norm:()=>j.layer_norm,load_image:()=>X.load_image,log_softmax:()=>g.log_softmax,magnitude:()=>g.magnitude,matmul:()=>j.matmul,max:()=>g.max,mean:()=>j.mean,mean_pooling:()=>j.mean_pooling,medianFilter:()=>g.medianFilter,mel_filter_bank:()=>N.mel_filter_bank,min:()=>g.min,ones:()=>j.ones,ones_like:()=>j.ones_like,permute:()=>j.permute,permute_data:()=>g.permute_data,pipeline:()=>A.pipeline,quantize_embeddings:()=>j.quantize_embeddings,rand:()=>j.rand,read_audio:()=>N.read_audio,rfft:()=>j.rfft,round:()=>g.round,slice:()=>j.slice,softmax:()=>g.softmax,spectrogram:()=>N.spectrogram,stack:()=>j.stack,std_mean:()=>j.std_mean,topk:()=>j.topk,window_function:()=>N.window_function,zeros:()=>j.zeros,zeros_like:()=>j.zeros_like});var Le=fs("./src/env.js"),A=fs("./src/pipelines.js"),r=fs("./src/models.js"),_=fs("./src/tokenizers.js"),I=fs("./src/configs.js"),N=fs("./src/utils/audio.js"),X=fs("./src/utils/image.js"),j=fs("./src/utils/tensor.js"),g=fs("./src/utils/maths.js"),b=fs("./src/base/feature_extraction_utils.js"),y=fs("./src/models/feature_extractors.js"),M=fs("./src/models/auto/feature_extraction_auto.js"),v=fs("./src/base/image_processors_utils.js"),L=fs("./src/models/image_processors.js"),H=fs("./src/models/auto/image_processing_auto.js"),re=fs("./src/base/processing_utils.js"),oe=fs("./src/models/processors.js"),z=fs("./src/models/auto/processing_auto.js"),V=fs("./src/generation/streamers.js"),Y=fs("./src/generation/stopping_criteria.js"),D=fs("./src/generation/logits_process.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.AutoFeatureExtractor,c.AutoImageProcessor;var ff=c.AutoModel;c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC;var _f=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.AutoModelForPoseEstimation,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation,c.AutoModelForVision2Seq,c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection;var gf=c.AutoProcessor,Ph=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.ClassifierFreeGuidanceLogitsProcessor,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.DeiTImageProcessor,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DepthProForDepthEstimation,c.DepthProPreTrainedModel,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrImageProcessor,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.DonutImageProcessor,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.ExaoneForCausalLM,c.ExaoneModel,c.ExaonePreTrainedModel,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.ForcedBOSTokenLogitsProcessor,c.ForcedEOSTokenLogitsProcessor,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.GraniteForCausalLM,c.GraniteModel,c.GranitePreTrainedModel,c.Grok1Tokenizer,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.IJepaForImageClassification,c.IJepaModel,c.IJepaPreTrainedModel,c.Idefics3ForConditionalGeneration,c.Idefics3ImageProcessor,c.Idefics3PreTrainedModel,c.Idefics3Processor,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageProcessor,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline;var wf=c.InterruptableStoppingCriteria;c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.JinaCLIPImageProcessor,c.JinaCLIPModel,c.JinaCLIPPreTrainedModel,c.JinaCLIPProcessor,c.JinaCLIPTextModel,c.JinaCLIPVisionModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaOnevisionForConditionalGeneration,c.LlavaOnevisionImageProcessor,c.LlavaPreTrainedModel,c.LogitsProcessor,c.LogitsProcessorList,c.LogitsWarper,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.Mask2FormerImageProcessor,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerImageProcessor,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MgpstrForSceneTextRecognition,c.MgpstrModelOutput,c.MgpstrPreTrainedModel,c.MgpstrProcessor,c.MgpstrTokenizer,c.MinLengthLogitsProcessor,c.MinNewTokensLengthLogitsProcessor,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileLLMForCausalLM,c.MobileLLMModel,c.MobileLLMPreTrainedModel,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1ImageProcessor,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2ImageProcessor,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3ImageProcessor,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4ImageProcessor,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.MoonshineFeatureExtractor,c.MoonshineForConditionalGeneration,c.MoonshineModel,c.MoonshinePreTrainedModel,c.MoonshineProcessor,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MultiModalityCausalLM,c.MultiModalityPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NoBadWordsLogitsProcessor,c.NoRepeatNGramLogitsProcessor,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.Olmo2ForCausalLM,c.Olmo2Model,c.Olmo2PreTrainedModel,c.OlmoForCausalLM,c.OlmoModel,c.OlmoPreTrainedModel,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTImageProcessor,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.PaliGemmaForConditionalGeneration,c.PaliGemmaPreTrainedModel,c.PaliGemmaProcessor,c.PatchTSMixerForPrediction,c.PatchTSMixerModel,c.PatchTSMixerPreTrainedModel,c.PatchTSTForPrediction,c.PatchTSTModel,c.PatchTSTPreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.Phi3VForCausalLM,c.Phi3VImageProcessor,c.Phi3VPreTrainedModel,c.Phi3VProcessor,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.Qwen2VLForConditionalGeneration,c.Qwen2VLImageProcessor,c.Qwen2VLPreTrainedModel,c.Qwen2VLProcessor,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel,c.RawImage,c.RepetitionPenaltyLogitsProcessor,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.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerImageProcessor,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.SuppressTokensAtBeginLogitsProcessor,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.TemperatureLogitsWarper;var zp=c.Tensor;c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline;var Ch=c.TextStreamer;c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TopKLogitsWarper,c.TopPLogitsWarper,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.VLChatProcessor,c.VLMImageProcessor,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.VitPoseForPoseEstimation,c.VitPoseImageProcessor,c.VitPosePreTrainedModel,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;var yf=c.WhisperForConditionalGeneration;c.WhisperModel,c.WhisperPreTrainedModel,c.WhisperProcessor,c.WhisperTextStreamer,c.WhisperTimeStampLogitsProcessor,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.YolosImageProcessor,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;var Bp=c.env,Mf=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.load_image,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.rand,c.read_audio,c.rfft,c.round,c.slice,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;const kh=16e3,bf=.3,vf=.1,Tf=3e4,Cc=500,Li=Tf/Cc,xf=1e3/Cc,Ef=2e3/Cc,Pf=1e3/Cc;Bp.allowRemoteModels=!0,Bp.allowLocalModels=!1,Bp.backends.onnx.wasm.proxy=!1;const kc="onnx-community/whisper-base",Sh="schmuell/Llama-3.2-1B-Instruct",Cf="onnx-community/silero-vad",Sc=new wf;let ti=!1;var Rp=new Array(Li),$c=0,$n=0,hn=0,$h=0;class kf{constructor(){_e(this,"loaded",!1);_e(this,"past_key_values_cache",null);_e(this,"model",null)}async init(A=null){return this.loaded||(this.tokenizer??(this.tokenizer=Ph.from_pretrained(Sh,{progress_callback:A})),this.model??(this.model=_f.from_pretrained(Sh,{dtype:"q4f16",device:"webgpu",use_external_data_format:!0,progress_callback:A})),this.loaded=!0),Promise.all([this.tokenizer,this.model])}async generate(A){const[r,_]=await Ac.init(),I=r.apply_chat_template(A,{add_generation_prompt:!0,return_dict:!0});let N,X=0,j;const g=()=>{N??(N=performance.now()),X++>0&&(j=X/(performance.now()-N)*1e3)},b=H=>{self.postMessage({status:"update",output:H,tps:j,numTokens:X})},y=new Ch(r,{skip_prompt:!0,skip_special_tokens:!0,callback_function:b,token_callback_function:g});self.postMessage({status:"start"});const{past_key_values:M,sequences:v}=await _.generate({...I,do_sample:!0,top_k:3,temperature:.2,max_new_tokens:1024,streamer:y,stopping_criteria:Sc,return_dict_in_generate:!0});this.past_key_values_cache=M;const L=r.batch_decode(v,{skip_special_tokens:!0});self.postMessage({status:"complete",output:L})}async load(){const[A,r]=await this.init(I=>{self.postMessage(I)}),_=A("a");await r.generate({..._,max_new_tokens:1})}reset(){this.past_key_values_cache=null}}class Sf{constructor(){_e(this,"loaded",!1);_e(this,"model",null);_e(this,"lastIsSpeech",!1)}async init(A=null){return this.loaded||(this.model=await ff.from_pretrained(Cf,{config:{model_type:"custom"},dtype:"fp32"}).catch(r=>{throw self.postMessage({error:r}),r}),this.loaded=!0),this.sr=new zp("int64",[kh],[]),this.state=new zp("float32",new Float32Array(2*1*128),[2,1,128]),Promise.all([this.model])}async load(){await this.init(A=>{self.postMessage(A)})}reset(){}async run(A){let r=0,_=0;for(;rbf;b!==this.lastIsSpeech&&(this.lastIsSpeech=b),b&&_++,r+=512}return _>0}}class $f{constructor(){_e(this,"loaded",!1);_e(this,"model",null)}async init(A=null){return this.loaded||(this.tokenizer??(this.tokenizer=Ph.from_pretrained(kc,{progress_callback:A})),this.processor??(this.processor=gf.from_pretrained(kc,{progress_callback:A})),this.model=yf.from_pretrained(kc,{dtype:{encoder_model:"fp32",decoder_model_merged:"q4"},device:"webgpu",progress_callback:A}),this.loaded=!0),Promise.all([this.tokenizer,this.processor,this.model])}async load(){const[A,r,_]=await this.init(I=>{self.postMessage(I)});await _.generate({input_features:Mf([1,80,3e3],0),max_new_tokens:1})}reset(){}async generate(A,r,_){const[I,N,X]=await this.init(),j=new Ch(I,{skip_prompt:!0,skip_special_tokens:!0,callback_function:_});let g;if(kc.startsWith("moon")){const y=await N(A);g=await X.generate({...y,max_new_tokens:64,language:r,streamer:j})}else{const y=await N(A);g=await X.generate({...y,max_new_tokens:64,language:r,streamer:j})}return I.batch_decode(g,{skip_special_tokens:!0})[0]}}const Ac=new kf,Np=new Sf,jp=new $f;self.addEventListener("message",async Le=>{const{type:A,data:r}=Le.data;switch(A){case"load":{const _=r.split(",");for(let I=0;I<_.length;I++){const N=_[I];switch(self.postMessage({status:"loading",data:"Loading "+N+" ..."}),N){case"llm":await Ac.load();break;case"vad":await Np.load();break;case"whisper":await jp.load();break}console.log(`${N} ready.`)}self.postMessage({status:"ready"})}break;case"generate":Sc.reset(),ti||(ti=!0,await Ac.generate(r),ti=!1);break;case"interrupt":Sc.interrupt();break;case"reset":Ac.reset(),Np.reset(),jp.reset(),Sc.reset();break;case"audio":if(ti)$h++;else{ti=!0,Rp[$c]=r,await Np.run(r)?($n++,hn=0):hn++;const I=$n>=Pf&&hn>=xf||$n>=Li;if(console.log(`Spoken: ${$n}, Silence: ${hn}, toWhisper: ${I}, Dropped: ${$h}`),hn>Ef&&($n=0,hn=0),$c=($c+1)%Li,I){console.log(`Flushing ${$n} spoken and ${hn} silence chunks`);const N=$n+hn;let X=($c+Li-N)%Li;const j=new Float32Array(N*kh);let g=0;for(let y=0;y{self.postMessage({status:"whisper-update",output:y,cont:!0})});ti=!1,self.postMessage({status:"whisper-update",output:b,cont:!1})}ti=!1}break}})})();