diff --git "a/assets/worker-CBJT5Xf9.js" "b/assets/worker-CBJT5Xf9.js" new file mode 100644--- /dev/null +++ "b/assets/worker-CBJT5Xf9.js" @@ -0,0 +1,2787 @@ +var U_=Object.defineProperty;var V_=(Ee,$,r)=>$ in Ee?U_(Ee,$,{enumerable:!0,configurable:!0,writable:!0,value:r}):Ee[$]=r;var fe=(Ee,$,r)=>V_(Ee,typeof $!="symbol"?$+"":$,r);var kn={},_f={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Ee,$,r)=>{Ee.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb":(Ee,$,r)=>{Ee.exports=r.p+"ort.bundle.min.mjs"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Ee,$,r)=>{r.r($),r.d($,{Environment:()=>st,Interpreter:()=>dt,Template:()=>ht,parse:()=>ye,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}),R=class{constructor(L,oe){this.value=L,this.type=oe}};function Y(L){return/\w/.test(L)}function N(L){return/[0-9]/.test(L)}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(L,oe={}){return L.endsWith(` +`)&&(L=L.slice(0,-1)),L=L.replace(/{#.*?#}/gs,"{##}"),oe.lstrip_blocks&&(L=L.replace(/^[ \t]*({[#%])/gm,"$1")),oe.trim_blocks&&(L=L.replace(/([#%]})\n/g,"$1")),L.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function M(L,oe={}){var Je,ut,mt;const H=[],me=y(L,oe);let Ae=0;const We=vt=>{let kt="";for(;vt(me[Ae]);){if(me[Ae]==="\\"){if(++Ae,Ae>=me.length)throw new SyntaxError("Unexpected end of input");const At=me[Ae++],is=b.get(At);if(is===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);kt+=is;continue}if(kt+=me[Ae++],Ae>=me.length)throw new SyntaxError("Unexpected end of input")}return kt};e:for(;Ae0){H.push(new R(At,_.Text));continue}}We(At=>/\s/.test(At));const kt=me[Ae];if(kt==="-"||kt==="+"){const At=(ut=H.at(-1))==null?void 0:ut.type;if(At===_.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${kt}`);switch(At){case _.Identifier:case _.NumericLiteral:case _.BooleanLiteral:case _.NullLiteral:case _.StringLiteral:case _.CloseParen:case _.CloseSquareBracket:break;default:{++Ae;const is=We(N);H.push(new R(`${kt}${is}`,is.length>0?_.NumericLiteral:_.UnaryOperator));continue}}}for(const[At,is]of g)if(me.slice(Ae,Ae+At.length)===At){H.push(new R(At,is)),Ae+=At.length;continue e}if(kt==="'"||kt==='"'){++Ae;const At=We(is=>is!==kt);H.push(new R(At,_.StringLiteral)),++Ae;continue}if(N(kt)){const At=We(N);H.push(new R(At,_.NumericLiteral));continue}if(Y(kt)){const At=We(Y),is=Object.hasOwn(I,At)?I[At]:_.Identifier;is===_.In&&((mt=H.at(-1))==null?void 0:mt.type)===_.Not?(H.pop(),H.push(new R("not in",_.NotIn))):H.push(new R(At,is));continue}throw new SyntaxError(`Unexpected character: ${kt}`)}return H}var v=class{constructor(){fe(this,"type","Statement")}},O=class extends v{constructor(oe){super();fe(this,"type","Program");this.body=oe}},K=class extends v{constructor(oe,H,me){super();fe(this,"type","If");this.test=oe,this.body=H,this.alternate=me}},te=class extends v{constructor(oe,H,me,Ae){super();fe(this,"type","For");this.loopvar=oe,this.iterable=H,this.body=me,this.defaultBlock=Ae}},ne=class extends v{constructor(oe,H){super();fe(this,"type","Set");this.assignee=oe,this.value=H}},W=class extends v{constructor(oe,H,me){super();fe(this,"type","Macro");this.name=oe,this.args=H,this.body=me}},U=class extends v{constructor(){super(...arguments);fe(this,"type","Expression")}},X=class extends U{constructor(oe,H,me){super();fe(this,"type","MemberExpression");this.object=oe,this.property=H,this.computed=me}},A=class extends U{constructor(oe,H){super();fe(this,"type","CallExpression");this.callee=oe,this.args=H}},S=class extends U{constructor(oe){super();fe(this,"type","Identifier");this.value=oe}},w=class extends U{constructor(oe){super();fe(this,"type","Literal");this.value=oe}},x=class extends w{constructor(){super(...arguments);fe(this,"type","NumericLiteral")}},F=class extends w{constructor(){super(...arguments);fe(this,"type","StringLiteral")}},ae=class extends w{constructor(){super(...arguments);fe(this,"type","BooleanLiteral")}},ie=class extends w{constructor(){super(...arguments);fe(this,"type","NullLiteral")}},ve=class extends w{constructor(){super(...arguments);fe(this,"type","ArrayLiteral")}},we=class extends w{constructor(){super(...arguments);fe(this,"type","TupleLiteral")}},re=class extends w{constructor(){super(...arguments);fe(this,"type","ObjectLiteral")}},xe=class extends U{constructor(oe,H,me){super();fe(this,"type","BinaryExpression");this.operator=oe,this.left=H,this.right=me}},ce=class extends U{constructor(oe,H){super();fe(this,"type","FilterExpression");this.operand=oe,this.filter=H}},Se=class extends U{constructor(oe,H){super();fe(this,"type","SelectExpression");this.iterable=oe,this.test=H}},Ie=class extends U{constructor(oe,H,me){super();fe(this,"type","TestExpression");this.operand=oe,this.negate=H,this.test=me}},Ce=class extends U{constructor(oe,H){super();fe(this,"type","UnaryExpression");this.operator=oe,this.argument=H}},tt=class extends U{constructor(oe=void 0,H=void 0,me=void 0){super();fe(this,"type","SliceExpression");this.start=oe,this.stop=H,this.step=me}},Ge=class extends U{constructor(oe,H){super();fe(this,"type","KeywordArgumentExpression");this.key=oe,this.value=H}};function ye(L){const oe=new O([]);let H=0;function me(it,Tt){const Dt=L[H++];if(!Dt||Dt.type!==it)throw new Error(`Parser Error: ${Tt}. ${Dt.type} !== ${it}.`);return Dt}function Ae(){switch(L[H].type){case _.Text:return ut();case _.OpenStatement:return mt();case _.OpenExpression:return vt();default:throw new SyntaxError(`Unexpected token type: ${L[H].type}`)}}function We(...it){return H+it.length<=L.length&&it.some((Tt,Dt)=>Tt!==L[H+Dt].type)}function Je(...it){return H+it.length<=L.length&&it.every((Tt,Dt)=>Tt===L[H+Dt].type)}function ut(){return new F(me(_.Text,"Expected text token").value)}function mt(){me(_.OpenStatement,"Expected opening statement token");let it;switch(L[H].type){case _.Set:++H,it=kt(),me(_.CloseStatement,"Expected closing statement token");break;case _.If:++H,it=At(),me(_.OpenStatement,"Expected {% token"),me(_.EndIf,"Expected endif token"),me(_.CloseStatement,"Expected %} token");break;case _.Macro:++H,it=is(),me(_.OpenStatement,"Expected {% token"),me(_.EndMacro,"Expected endmacro token"),me(_.CloseStatement,"Expected %} token");break;case _.For:++H,it=ks(),me(_.OpenStatement,"Expected {% token"),me(_.EndFor,"Expected endfor token"),me(_.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${L[H].type}`)}return it}function vt(){me(_.OpenExpression,"Expected opening expression token");const it=Ds();return me(_.CloseExpression,"Expected closing expression token"),it}function kt(){const it=Ds();if(Je(_.Equals)){++H;const Tt=kt();return new ne(it,Tt)}return it}function At(){var Vs,Nr,Ir,Ms,ar,Is,Tr,ts;const it=Ds();me(_.CloseStatement,"Expected closing statement token");const Tt=[],Dt=[];for(;!(((Vs=L[H])==null?void 0:Vs.type)===_.OpenStatement&&(((Nr=L[H+1])==null?void 0:Nr.type)===_.ElseIf||((Ir=L[H+1])==null?void 0:Ir.type)===_.Else||((Ms=L[H+1])==null?void 0:Ms.type)===_.EndIf));)Tt.push(Ae());if(((ar=L[H])==null?void 0:ar.type)===_.OpenStatement&&((Is=L[H+1])==null?void 0:Is.type)!==_.EndIf)if(++H,Je(_.ElseIf))me(_.ElseIf,"Expected elseif token"),Dt.push(At());else for(me(_.Else,"Expected else token"),me(_.CloseStatement,"Expected closing statement token");!(((Tr=L[H])==null?void 0:Tr.type)===_.OpenStatement&&((ts=L[H+1])==null?void 0:ts.type)===_.EndIf);)Dt.push(Ae());return new K(it,Tt,Dt)}function is(){const it=or();if(it.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Tt=$r();me(_.CloseStatement,"Expected closing statement token");const Dt=[];for(;We(_.OpenStatement,_.EndMacro);)Dt.push(Ae());return new W(it,Tt,Dt)}function ws(it=!1){const Tt=it?or:Ds,Dt=[Tt()],Vs=Je(_.Comma);for(;Vs&&(++H,Dt.push(Tt()),!!Je(_.Comma)););return Vs?new we(Dt):Dt[0]}function ks(){const it=ws(!0);if(!(it instanceof S||it instanceof we))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${it.type} instead`);me(_.In,"Expected `in` keyword following loop variable");const Tt=Ds();me(_.CloseStatement,"Expected closing statement token");const Dt=[];for(;We(_.OpenStatement,_.EndFor)&&We(_.OpenStatement,_.Else);)Dt.push(Ae());const Vs=[];if(Je(_.OpenStatement,_.Else))for(++H,++H,me(_.CloseStatement,"Expected closing statement token");We(_.OpenStatement,_.EndFor);)Vs.push(Ae());return new te(it,Tt,Dt,Vs)}function Ds(){return sr()}function sr(){const it=kr();if(Je(_.If)){++H;const Tt=kr();if(Je(_.Else)){++H;const Dt=kr();return new K(Tt,[it],[Dt])}else return new Se(it,Tt)}return it}function kr(){let it=Qr();for(;Je(_.Or);){const Tt=L[H];++H;const Dt=Qr();it=new xe(Tt,it,Dt)}return it}function Qr(){let it=Us();for(;Je(_.And);){const Tt=L[H];++H;const Dt=Us();it=new xe(Tt,it,Dt)}return it}function Us(){let it;for(;Je(_.Not);){const Tt=L[H];++H;const Dt=Us();it=new Ce(Tt,Dt)}return it??xr()}function xr(){let it=Nt();for(;Je(_.ComparisonBinaryOperator)||Je(_.In)||Je(_.NotIn);){const Tt=L[H];++H;const Dt=Nt();it=new xe(Tt,it,Dt)}return it}function Nt(){let it=Ar();for(;Je(_.AdditiveBinaryOperator);){const Tt=L[H];++H;const Dt=Ar();it=new xe(Tt,it,Dt)}return it}function Xr(){const it=Jr();return Je(_.OpenParen)?Sr(it):it}function Sr(it){let Tt=new A(it,$r());return Je(_.OpenParen)&&(Tt=Sr(Tt)),Tt}function $r(){me(_.OpenParen,"Expected opening parenthesis for arguments list");const it=Yr();return me(_.CloseParen,"Expected closing parenthesis for arguments list"),it}function Yr(){const it=[];for(;!Je(_.CloseParen);){let Tt=Ds();if(Je(_.Equals)){if(++H,!(Tt instanceof S))throw new SyntaxError("Expected identifier for keyword argument");const Dt=Ds();Tt=new Ge(Tt,Dt)}it.push(Tt),Je(_.Comma)&&++H}return it}function cr(){const it=[];let Tt=!1;for(;!Je(_.CloseSquareBracket);)Je(_.Colon)?(it.push(void 0),++H,Tt=!0):(it.push(Ds()),Je(_.Colon)&&(++H,Tt=!0));if(it.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Tt){if(it.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new tt(...it)}return it[0]}function Jr(){let it=or();for(;Je(_.Dot)||Je(_.OpenSquareBracket);){const Tt=L[H];++H;let Dt;const Vs=Tt.type!==_.Dot;if(Vs)Dt=cr(),me(_.CloseSquareBracket,"Expected closing square bracket");else if(Dt=or(),Dt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");it=new X(it,Dt,Vs)}return it}function Ar(){let it=Br();for(;Je(_.MultiplicativeBinaryOperator);){const Tt=L[H];++H;const Dt=Br();it=new xe(Tt,it,Dt)}return it}function Br(){let it=Rr();for(;Je(_.Is);){++H;const Tt=Je(_.Not);Tt&&++H;let Dt=or();if(Dt instanceof ae?Dt=new S(Dt.value.toString()):Dt instanceof ie&&(Dt=new S("none")),!(Dt instanceof S))throw new SyntaxError("Expected identifier for the test");it=new Ie(it,Tt,Dt)}return it}function Rr(){let it=Xr();for(;Je(_.Pipe);){++H;let Tt=or();if(!(Tt instanceof S))throw new SyntaxError("Expected identifier for the filter");Je(_.OpenParen)&&(Tt=Sr(Tt)),it=new ce(it,Tt)}return it}function or(){const it=L[H];switch(it.type){case _.NumericLiteral:return++H,new x(Number(it.value));case _.StringLiteral:return++H,new F(it.value);case _.BooleanLiteral:return++H,new ae(it.value.toLowerCase()==="true");case _.NullLiteral:return++H,new ie(null);case _.Identifier:return++H,new S(it.value);case _.OpenParen:{++H;const Tt=ws();if(L[H].type!==_.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${L[H].type} instead`);return++H,Tt}case _.OpenSquareBracket:{++H;const Tt=[];for(;!Je(_.CloseSquareBracket);)Tt.push(Ds()),Je(_.Comma)&&++H;return++H,new ve(Tt)}case _.OpenCurlyBracket:{++H;const Tt=new Map;for(;!Je(_.CloseCurlyBracket);){const Dt=Ds();me(_.Colon,"Expected colon between key and value in object literal");const Vs=Ds();Tt.set(Dt,Vs),Je(_.Comma)&&++H}return++H,new re(Tt)}default:throw new SyntaxError(`Unexpected token: ${it.type}`)}}for(;H=0?(oe=(oe??(oe=0))<0?Math.max(L.length+oe,0):Math.min(oe,L.length),H=(H??(H=L.length))<0?Math.max(L.length+H,0):Math.min(H,L.length)):(oe=(oe??(oe=L.length-1))<0?Math.max(L.length+oe,-1):Math.min(oe,L.length-1),H=(H??(H=-1))<-1?Math.max(L.length+H,-1):Math.min(H,L.length-1));const We=[];for(let Je=oe;Ae*Jeoe.toUpperCase())}var Be=class{constructor(L=void 0){fe(this,"type","RuntimeValue");fe(this,"value");fe(this,"builtins",new Map);this.value=L}__bool__(){return new Ke(!!this.value)}},Ze=class extends Be{constructor(){super(...arguments);fe(this,"type","NumericValue")}},se=class extends Be{constructor(){super(...arguments);fe(this,"type","StringValue");fe(this,"builtins",new Map([["upper",new Ve(()=>new se(this.value.toUpperCase()))],["lower",new Ve(()=>new se(this.value.toLowerCase()))],["strip",new Ve(()=>new se(this.value.trim()))],["title",new Ve(()=>new se(ke(this.value)))],["length",new Ze(this.value.length)],["rstrip",new Ve(()=>new se(this.value.trimEnd()))],["lstrip",new Ve(()=>new se(this.value.trimStart()))]]))}},Ke=class extends Be{constructor(){super(...arguments);fe(this,"type","BooleanValue")}},je=class extends Be{constructor(){super(...arguments);fe(this,"type","ObjectValue");fe(this,"builtins",new Map([["get",new Ve(([oe,H])=>{if(!(oe instanceof se))throw new Error(`Object key must be a string: got ${oe.type}`);return this.value.get(oe.value)??H??new Ne})],["items",new Ve(()=>new Te(Array.from(this.value.entries()).map(([oe,H])=>new Te([new se(oe),H]))))]]))}__bool__(){return new Ke(this.value.size>0)}},le=class extends je{constructor(){super(...arguments);fe(this,"type","KeywordArgumentsValue")}},Te=class extends Be{constructor(){super(...arguments);fe(this,"type","ArrayValue");fe(this,"builtins",new Map([["length",new Ze(this.value.length)]]))}__bool__(){return new Ke(this.value.length>0)}},Ue=class extends Te{constructor(){super(...arguments);fe(this,"type","TupleValue")}},Ve=class extends Be{constructor(){super(...arguments);fe(this,"type","FunctionValue")}},Ne=class extends Be{constructor(){super(...arguments);fe(this,"type","NullValue")}},Re=class extends Be{constructor(){super(...arguments);fe(this,"type","UndefinedValue")}},st=class{constructor(L){fe(this,"variables",new Map([["namespace",new Ve(L=>{if(L.length===0)return new je(new Map);if(L.length!==1||!(L[0]instanceof je))throw new Error("`namespace` expects either zero arguments or a single object argument");return L[0]})]]));fe(this,"tests",new Map([["boolean",L=>L.type==="BooleanValue"],["callable",L=>L instanceof Ve],["odd",L=>{if(L.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${L.type}`);return L.value%2!==0}],["even",L=>{if(L.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${L.type}`);return L.value%2===0}],["false",L=>L.type==="BooleanValue"&&!L.value],["true",L=>L.type==="BooleanValue"&&L.value],["none",L=>L.type==="NullValue"],["string",L=>L.type==="StringValue"],["number",L=>L.type==="NumericValue"],["integer",L=>L.type==="NumericValue"&&Number.isInteger(L.value)],["iterable",L=>L.type==="ArrayValue"||L.type==="StringValue"],["mapping",L=>L.type==="ObjectValue"],["lower",L=>{const oe=L.value;return L.type==="StringValue"&&oe===oe.toLowerCase()}],["upper",L=>{const oe=L.value;return L.type==="StringValue"&&oe===oe.toUpperCase()}],["none",L=>L.type==="NullValue"],["defined",L=>L.type!=="UndefinedValue"],["undefined",L=>L.type==="UndefinedValue"],["equalto",(L,oe)=>L.value===oe.value],["eq",(L,oe)=>L.value===oe.value]]));this.parent=L}set(L,oe){return this.declareVariable(L,ct(oe))}declareVariable(L,oe){if(this.variables.has(L))throw new SyntaxError(`Variable already declared: ${L}`);return this.variables.set(L,oe),oe}setVariable(L,oe){return this.variables.set(L,oe),oe}resolve(L){if(this.variables.has(L))return this;if(this.parent)return this.parent.resolve(L);throw new Error(`Unknown variable: ${L}`)}lookupVariable(L){try{return this.resolve(L).variables.get(L)??new Re}catch{return new Re}}},dt=class{constructor(L){fe(this,"global");this.global=L??new st}run(L){return this.evaluate(L,this.global)}evaluateBinaryExpression(L,oe){const H=this.evaluate(L.left,oe);switch(L.operator.value){case"and":return H.__bool__().value?this.evaluate(L.right,oe):H;case"or":return H.__bool__().value?H:this.evaluate(L.right,oe)}const me=this.evaluate(L.right,oe);switch(L.operator.value){case"==":return new Ke(H.value==me.value);case"!=":return new Ke(H.value!=me.value)}if(H instanceof Re||me instanceof Re)throw new Error("Cannot perform operation on undefined values");if(H instanceof Ne||me instanceof Ne)throw new Error("Cannot perform operation on null values");if(H instanceof Ze&&me instanceof Ze)switch(L.operator.value){case"+":return new Ze(H.value+me.value);case"-":return new Ze(H.value-me.value);case"*":return new Ze(H.value*me.value);case"/":return new Ze(H.value/me.value);case"%":return new Ze(H.value%me.value);case"<":return new Ke(H.value":return new Ke(H.value>me.value);case">=":return new Ke(H.value>=me.value);case"<=":return new Ke(H.value<=me.value)}else if(H instanceof Te&&me instanceof Te)switch(L.operator.value){case"+":return new Te(H.value.concat(me.value))}else if(me instanceof Te){const Ae=me.value.find(We=>We.value===H.value)!==void 0;switch(L.operator.value){case"in":return new Ke(Ae);case"not in":return new Ke(!Ae)}}if(H instanceof se||me instanceof se)switch(L.operator.value){case"+":return new se(H.value.toString()+me.value.toString())}if(H instanceof se&&me instanceof se)switch(L.operator.value){case"in":return new Ke(me.value.includes(H.value));case"not in":return new Ke(!me.value.includes(H.value))}if(H instanceof se&&me instanceof je)switch(L.operator.value){case"in":return new Ke(me.value.has(H.value));case"not in":return new Ke(!me.value.has(H.value))}throw new SyntaxError(`Unknown operator "${L.operator.value}" between ${H.type} and ${me.type}`)}evaluateArguments(L,oe){const H=[],me=new Map;for(const Ae of L)if(Ae.type==="KeywordArgumentExpression"){const We=Ae;me.set(We.key.value,this.evaluate(We.value,oe))}else{if(me.size>0)throw new Error("Positional arguments must come before keyword arguments");H.push(this.evaluate(Ae,oe))}return[H,me]}evaluateFilterExpression(L,oe){const H=this.evaluate(L.operand,oe);if(L.filter.type==="Identifier"){const me=L.filter;if(me.value==="tojson")return new se(lt(H));if(H instanceof Te)switch(me.value){case"list":return H;case"first":return H.value[0];case"last":return H.value[H.value.length-1];case"length":return new Ze(H.value.length);case"reverse":return new Te(H.value.reverse());case"sort":return new Te(H.value.sort((Ae,We)=>{if(Ae.type!==We.type)throw new Error(`Cannot compare different types: ${Ae.type} and ${We.type}`);switch(Ae.type){case"NumericValue":return Ae.value-We.value;case"StringValue":return Ae.value.localeCompare(We.value);default:throw new Error(`Cannot compare type: ${Ae.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${me.value}`)}else if(H instanceof se)switch(me.value){case"length":return new Ze(H.value.length);case"upper":return new se(H.value.toUpperCase());case"lower":return new se(H.value.toLowerCase());case"title":return new se(ke(H.value));case"capitalize":return new se(H.value.charAt(0).toUpperCase()+H.value.slice(1));case"trim":return new se(H.value.trim());case"indent":return new se(H.value.split(` +`).map((Ae,We)=>We===0||Ae.length===0?Ae:" "+Ae).join(` +`));case"string":return H;default:throw new Error(`Unknown StringValue filter: ${me.value}`)}else if(H instanceof Ze)switch(me.value){case"abs":return new Ze(Math.abs(H.value));default:throw new Error(`Unknown NumericValue filter: ${me.value}`)}else if(H instanceof je)switch(me.value){case"items":return new Te(Array.from(H.value.entries()).map(([Ae,We])=>new Te([new se(Ae),We])));case"length":return new Ze(H.value.size);default:throw new Error(`Unknown ObjectValue filter: ${me.value}`)}throw new Error(`Cannot apply filter "${me.value}" to type: ${H.type}`)}else if(L.filter.type==="CallExpression"){const me=L.filter;if(me.callee.type!=="Identifier")throw new Error(`Unknown filter: ${me.callee.type}`);const Ae=me.callee.value;if(Ae==="tojson"){const[,We]=this.evaluateArguments(me.args,oe),Je=We.get("indent")??new Ne;if(!(Je instanceof Ze||Je instanceof Ne))throw new Error("If set, indent must be a number");return new se(lt(H,Je.value))}if(H instanceof Te){switch(Ae){case"selectattr":case"rejectattr":{const We=Ae==="selectattr";if(H.value.some(At=>!(At instanceof je)))throw new Error(`\`${Ae}\` can only be applied to array of objects`);if(me.args.some(At=>At.type!=="StringLiteral"))throw new Error(`arguments of \`${Ae}\` must be strings`);const[Je,ut,mt]=me.args.map(At=>this.evaluate(At,oe));let vt;if(ut){const At=oe.tests.get(ut.value);if(!At)throw new Error(`Unknown test: ${ut.value}`);vt=At}else vt=(...At)=>At[0].__bool__().value;const kt=H.value.filter(At=>{const is=At.value.get(Je.value),ws=is?vt(is,mt):!1;return We?ws:!ws});return new Te(kt)}case"map":{const[,We]=this.evaluateArguments(me.args,oe);if(We.has("attribute")){const Je=We.get("attribute");if(!(Je instanceof se))throw new Error("attribute must be a string");const ut=We.get("default"),mt=H.value.map(vt=>{if(!(vt instanceof je))throw new Error("items in map must be an object");return vt.value.get(Je.value)??ut??new Re});return new Te(mt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Ae}`)}else if(H instanceof se){switch(Ae){case"indent":{const[We,Je]=this.evaluateArguments(me.args,oe),ut=We.at(0)??Je.get("width")??new Ze(4);if(!(ut instanceof Ze))throw new Error("width must be a number");const mt=We.at(1)??Je.get("first")??new Ke(!1),vt=We.at(2)??Je.get("blank")??new Ke(!1),kt=H.value.split(` +`),At=" ".repeat(ut.value),is=kt.map((ws,ks)=>!mt.value&&ks===0||!vt.value&&ws.length===0?ws:At+ws);return new se(is.join(` +`))}}throw new Error(`Unknown StringValue filter: ${Ae}`)}else throw new Error(`Cannot apply filter "${Ae}" to type: ${H.type}`)}throw new Error(`Unknown filter: ${L.filter.type}`)}evaluateTestExpression(L,oe){const H=this.evaluate(L.operand,oe),me=oe.tests.get(L.test.value);if(!me)throw new Error(`Unknown test: ${L.test.value}`);const Ae=me(H);return new Ke(L.negate?!Ae:Ae)}evaluateUnaryExpression(L,oe){const H=this.evaluate(L.argument,oe);switch(L.operator.value){case"not":return new Ke(!H.value);default:throw new SyntaxError(`Unknown operator: ${L.operator.value}`)}}evalProgram(L,oe){return this.evaluateBlock(L.body,oe)}evaluateBlock(L,oe){let H="";for(const me of L){const Ae=this.evaluate(me,oe);Ae.type!=="NullValue"&&Ae.type!=="UndefinedValue"&&(H+=Ae.value)}return new se(H)}evaluateIdentifier(L,oe){return oe.lookupVariable(L.value)}evaluateCallExpression(L,oe){const[H,me]=this.evaluateArguments(L.args,oe);me.size>0&&H.push(new le(me));const Ae=this.evaluate(L.callee,oe);if(Ae.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Ae.type}`);return Ae.value(H,oe)}evaluateSliceExpression(L,oe,H){if(!(L instanceof Te||L instanceof se))throw new Error("Slice object must be an array or string");const me=this.evaluate(oe.start,H),Ae=this.evaluate(oe.stop,H),We=this.evaluate(oe.step,H);if(!(me instanceof Ze||me instanceof Re))throw new Error("Slice start must be numeric or undefined");if(!(Ae instanceof Ze||Ae instanceof Re))throw new Error("Slice stop must be numeric or undefined");if(!(We instanceof Ze||We instanceof Re))throw new Error("Slice step must be numeric or undefined");return L instanceof Te?new Te(de(L.value,me.value,Ae.value,We.value)):new se(de(Array.from(L.value),me.value,Ae.value,We.value).join(""))}evaluateMemberExpression(L,oe){const H=this.evaluate(L.object,oe);let me;if(L.computed){if(L.property.type==="SliceExpression")return this.evaluateSliceExpression(H,L.property,oe);me=this.evaluate(L.property,oe)}else me=new se(L.property.value);let Ae;if(H instanceof je){if(!(me instanceof se))throw new Error(`Cannot access property with non-string: got ${me.type}`);Ae=H.value.get(me.value)??H.builtins.get(me.value)}else if(H instanceof Te||H instanceof se)if(me instanceof Ze)Ae=H.value.at(me.value),H instanceof se&&(Ae=new se(H.value.at(me.value)));else if(me instanceof se)Ae=H.builtins.get(me.value);else throw new Error(`Cannot access property with non-string/non-number: got ${me.type}`);else{if(!(me instanceof se))throw new Error(`Cannot access property with non-string: got ${me.type}`);Ae=H.builtins.get(me.value)}return Ae instanceof Be?Ae:new Re}evaluateSet(L,oe){const H=this.evaluate(L.value,oe);if(L.assignee.type==="Identifier"){const me=L.assignee.value;oe.setVariable(me,H)}else if(L.assignee.type==="MemberExpression"){const me=L.assignee,Ae=this.evaluate(me.object,oe);if(!(Ae instanceof je))throw new Error("Cannot assign to member of non-object");if(me.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Ae.value.set(me.property.value,H)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(L.assignee)}`);return new Ne}evaluateIf(L,oe){const H=this.evaluate(L.test,oe);return this.evaluateBlock(H.__bool__().value?L.body:L.alternate,oe)}evaluateFor(L,oe){const H=new st(oe);let me,Ae;if(L.iterable.type==="SelectExpression"){const vt=L.iterable;Ae=this.evaluate(vt.iterable,H),me=vt.test}else Ae=this.evaluate(L.iterable,H);if(!(Ae instanceof Te))throw new Error(`Expected iterable type in for loop: got ${Ae.type}`);const We=[],Je=[];for(let vt=0;vtws.setVariable(L.loopvar.value,At);else if(L.loopvar.type==="TupleLiteral"){const ws=L.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const ks=At;if(ws.value.length!==ks.value.length)throw new Error(`Too ${ws.value.length>ks.value.length?"few":"many"} items to unpack`);is=Ds=>{for(let sr=0;sr0?We[vt-1]:new Re],["nextitem",vt{var Je;const Ae=new st(me);H=H.slice();let We;((Je=H.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(We=H.pop());for(let ut=0;utthis.evaluate(H,oe)));case"TupleLiteral":return new Ue(L.value.map(H=>this.evaluate(H,oe)));case"ObjectLiteral":{const H=new Map;for(const[me,Ae]of L.value){const We=this.evaluate(me,oe);if(!(We instanceof se))throw new Error(`Object keys must be strings: got ${We.type}`);H.set(We.value,this.evaluate(Ae,oe))}return new je(H)}case"Identifier":return this.evaluateIdentifier(L,oe);case"CallExpression":return this.evaluateCallExpression(L,oe);case"MemberExpression":return this.evaluateMemberExpression(L,oe);case"UnaryExpression":return this.evaluateUnaryExpression(L,oe);case"BinaryExpression":return this.evaluateBinaryExpression(L,oe);case"FilterExpression":return this.evaluateFilterExpression(L,oe);case"TestExpression":return this.evaluateTestExpression(L,oe);default:throw new SyntaxError(`Unknown node type: ${L.type}`)}}};function ct(L){switch(typeof L){case"number":return new Ze(L);case"string":return new se(L);case"boolean":return new Ke(L);case"undefined":return new Re;case"object":return L===null?new Ne:Array.isArray(L)?new Te(L.map(ct)):new je(new Map(Object.entries(L).map(([oe,H])=>[oe,ct(H)])));case"function":return new Ve((oe,H)=>{const me=L(...oe.map(Ae=>Ae.value))??null;return ct(me)});default:throw new Error(`Cannot convert to runtime value: ${L}`)}}function lt(L,oe,H){const me=H??0;switch(L.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(L.value);case"ArrayValue":case"ObjectValue":{const Ae=oe?" ".repeat(oe):"",We=` +`+Ae.repeat(me),Je=We+Ae;if(L.type==="ArrayValue"){const ut=L.value.map(mt=>lt(mt,oe,me+1));return oe?`[${Je}${ut.join(`,${Je}`)}${We}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(L.value.entries()).map(([mt,vt])=>{const kt=`"${mt}": ${lt(vt,oe,me+1)}`;return oe?`${Je}${kt}`:kt});return oe?`{${ut.join(",")}${We}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${L.type}`)}}var ht=class{constructor(L){fe(this,"parsed");const oe=M(L,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ye(oe)}render(L){const oe=new st;oe.set("false",!1),oe.set("true",!0),oe.set("raise_exception",Ae=>{throw new Error(Ae)}),oe.set("range",J);for(const[Ae,We]of Object.entries(L))oe.set(Ae,We);return new dt(oe).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Ee,$,r)=>{r.r($),r.d($,{registerBackend:()=>R,resolveBackendAndExecutionProviders:()=>N});const _=new Map,I=[],R=(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 O=0;O{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}}},N=async g=>{const b=g.executionProviders||[],y=b.map(ne=>typeof ne=="string"?ne:ne.name),M=y.length===0?I:y;let v;const O=[],K=new Set;for(const ne of M){const W=await Y(ne);typeof W=="string"?O.push({name:ne,err:W}):(v||(v=W),v===W&&K.add(ne))}if(!v)throw new Error(`no available backend found. ERR: ${O.map(ne=>`[${ne.name}] ${ne.err}`).join(", ")}`);for(const{name:ne,err:W}of O)y.includes(ne)&&console.warn(`removing requested execution provider "${ne}" from session options because it is not available: ${W}`);const te=b.filter(ne=>K.has(typeof ne=="string"?ne:ne.name));return[v,new Proxy(g,{get:(ne,W)=>W==="executionProviders"?te:Reflect.get(ne,W)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Ee,$,r)=>{r.r($),r.d($,{registerBackend:()=>_.registerBackend});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Ee,$,r)=>{r.r($),r.d($,{env:()=>R});var _=r("./node_modules/onnxruntime-common/dist/esm/version.js");let I="warning";const R={wasm:{},webgl:{},webgpu:{},versions:{common:_.version},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);I=Y}},get logLevel(){return I}};Object.defineProperty(R,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Ee,$,r)=>{r.r($),r.d($,{env:()=>I});var _=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const I=_.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Ee,$,r)=>{r.r($),r.d($,{InferenceSession:()=>R.InferenceSession,TRACE:()=>N.TRACE,TRACE_FUNC_BEGIN:()=>N.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>N.TRACE_FUNC_END,Tensor:()=>Y.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"),R=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Y=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 N=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":(Ee,$,r)=>{r.r($),r.d($,{InferenceSession:()=>Y});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),I=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),R=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class Y{constructor(g){this.handler=g}async run(g,b,y){(0,R.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 O=!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.");O=!1;for(const ne of b){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);M[ne]=null}if(typeof y=="object"&&y!==null)v=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const W=Object.getOwnPropertyNames(b);for(const U of this.outputNames)if(W.indexOf(U)!==-1){const X=b[U];(X===null||X instanceof I.Tensor)&&(ne=!0,O=!1,M[U]=X)}if(ne){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 ne of this.inputNames)if(typeof g[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(O)for(const ne of this.outputNames)M[ne]=null;const K=await this.handler.run(g,M,v),te={};for(const ne in K)if(Object.hasOwnProperty.call(K,ne)){const W=K[ne];W instanceof I.Tensor?te[ne]=W:te[ne]=new I.Tensor(W.type,W.data,W.dims)}return(0,R.TRACE_FUNC_END)(),te}async release(){return this.handler.dispose()}static async create(g,b,y,M){(0,R.TRACE_FUNC_BEGIN)();let v,O={};if(typeof g=="string"){if(v=g,typeof b=="object"&&b!==null)O=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)O=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 W=g;let U=0,X=g.byteLength;if(typeof b=="object"&&b!==null)O=b;else if(typeof b=="number"){if(U=b,!Number.isSafeInteger(U))throw new RangeError("'byteOffset' must be an integer.");if(U<0||U>=W.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${W.byteLength}).`);if(X=g.byteLength-U,typeof y=="number"){if(X=y,!Number.isSafeInteger(X))throw new RangeError("'byteLength' must be an integer.");if(X<=0||U+X>W.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${W.byteLength-U}].`);if(typeof M=="object"&&M!==null)O=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(W,U,X)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[K,te]=await(0,_.resolveBackendAndExecutionProviders)(O),ne=await K.createInferenceSessionHandler(v,te);return(0,R.TRACE_FUNC_END)(),new Y(ne)}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":(Ee,$,r)=>{r.r($),r.d($,{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":(Ee,$,r)=>{r.r($)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Ee,$,r)=>{r.r($)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Ee,$,r)=>{r.r($),r.d($,{tensorToDataURL:()=>_,tensorToImageData:()=>I});const _=(R,Y)=>{const N=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);N.width=R.dims[3],N.height=R.dims[2];const g=N.getContext("2d");if(g!=null){let b,y;(Y==null?void 0:Y.tensorLayout)!==void 0&&Y.tensorLayout==="NHWC"?(b=R.dims[2],y=R.dims[3]):(b=R.dims[3],y=R.dims[2]);const M=(Y==null?void 0:Y.format)!==void 0?Y.format:"RGB",v=Y==null?void 0:Y.norm;let O,K;v===void 0||v.mean===void 0?O=[255,255,255,255]:typeof v.mean=="number"?O=[v.mean,v.mean,v.mean,v.mean]:(O=[v.mean[0],v.mean[1],v.mean[2],0],v.mean[3]!==void 0&&(O[3]=v.mean[3])),v===void 0||v.bias===void 0?K=[0,0,0,0]:typeof v.bias=="number"?K=[v.bias,v.bias,v.bias,v.bias]:(K=[v.bias[0],v.bias[1],v.bias[2],0],v.bias[3]!==void 0&&(K[3]=v.bias[3]));const te=y*b;let ne=0,W=te,U=te*2,X=-1;M==="RGBA"?(ne=0,W=te,U=te*2,X=te*3):M==="RGB"?(ne=0,W=te,U=te*2):M==="RBG"&&(ne=0,U=te,W=te*2);for(let A=0;A{const N=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let g;if(N!=null){let b,y,M;(Y==null?void 0:Y.tensorLayout)!==void 0&&Y.tensorLayout==="NHWC"?(b=R.dims[2],y=R.dims[1],M=R.dims[3]):(b=R.dims[3],y=R.dims[2],M=R.dims[1]);const v=Y!==void 0&&Y.format!==void 0?Y.format:"RGB",O=Y==null?void 0:Y.norm;let K,te;O===void 0||O.mean===void 0?K=[255,255,255,255]:typeof O.mean=="number"?K=[O.mean,O.mean,O.mean,O.mean]:(K=[O.mean[0],O.mean[1],O.mean[2],255],O.mean[3]!==void 0&&(K[3]=O.mean[3])),O===void 0||O.bias===void 0?te=[0,0,0,0]:typeof O.bias=="number"?te=[O.bias,O.bias,O.bias,O.bias]:(te=[O.bias[0],O.bias[1],O.bias[2],0],O.bias[3]!==void 0&&(te[3]=O.bias[3]));const ne=y*b;if(Y!==void 0&&(Y.format!==void 0&&M===4&&Y.format!=="RGBA"||M===3&&Y.format!=="RGB"&&Y.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const W=4;let U=0,X=1,A=2,S=3,w=0,x=ne,F=ne*2,ae=-1;v==="RGBA"?(w=0,x=ne,F=ne*2,ae=ne*3):v==="RGB"?(w=0,x=ne,F=ne*2):v==="RBG"&&(w=0,F=ne,x=ne*2),g=N.createImageData(b,y);for(let ie=0;ie{r.r($)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Ee,$,r)=>{r.r($),r.d($,{bufferToTensor:()=>I,tensorFromGpuBuffer:()=>N,tensorFromImage:()=>R,tensorFromMLTensor:()=>g,tensorFromPinnedBuffer:()=>b,tensorFromTexture:()=>Y});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:O}=M,K=M.norm??{mean:255,bias:0};let te,ne;typeof K.mean=="number"?te=[K.mean,K.mean,K.mean,K.mean]:te=[K.mean[0],K.mean[1],K.mean[2],K.mean[3]??255],typeof K.bias=="number"?ne=[K.bias,K.bias,K.bias,K.bias]:ne=[K.bias[0],K.bias[1],K.bias[2],K.bias[3]??0];const W=M.format!==void 0?M.format:"RGBA",U=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",X=v*O,A=U==="RGBA"?new Float32Array(X*4):new Float32Array(X*3);let S=4,w=0,x=1,F=2,ae=3,ie=0,ve=X,we=X*2,re=-1;W==="RGB"&&(S=3,w=0,x=1,F=2,ae=-1),U==="RGBA"?re=X*3:U==="RBG"?(ie=0,we=X,ve=X*2):U==="BGR"&&(we=0,ve=X,ie=X*2);for(let ce=0;ce{const v=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,O=typeof ImageData<"u"&&y instanceof ImageData,K=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,te=typeof y=="string";let ne,W=M??{};const U=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},X=A=>typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||A instanceof OffscreenCanvas?A.getContext("2d"):null;if(v){const A=U();A.width=y.width,A.height=y.height;const S=X(A);if(S!=null){let w=y.height,x=y.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(w=M.resizedHeight,x=M.resizedWidth),M!==void 0){if(W=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");W.tensorFormat="RGBA",W.height=w,W.width=x}else W.tensorFormat="RGBA",W.height=w,W.width=x;S.drawImage(y,0,0),ne=S.getImageData(0,0,x,w).data}else throw new Error("Can not access image data")}else if(O){let A,S;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?(A=M.resizedHeight,S=M.resizedWidth):(A=y.height,S=y.width),M!==void 0&&(W=M),W.format="RGBA",W.height=A,W.width=S,M!==void 0){const w=U();w.width=S,w.height=A;const x=X(w);if(x!=null)x.putImageData(y,0,0),ne=x.getImageData(0,0,S,A).data;else throw new Error("Can not access image data")}else ne=y.data}else if(K){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const A=U();A.width=y.width,A.height=y.height;const S=X(A);if(S!=null){const w=y.height,x=y.width;return S.drawImage(y,0,0,x,w),ne=S.getImageData(0,0,x,w).data,W.height=w,W.width=x,I(ne,W)}else throw new Error("Can not access image data")}else{if(te)return new Promise((A,S)=>{const w=U(),x=X(w);if(!y||!x)return S();const F=new Image;F.crossOrigin="Anonymous",F.src=y,F.onload=()=>{w.width=F.width,w.height=F.height,x.drawImage(F,0,0,w.width,w.height);const ae=x.getImageData(0,0,w.width,w.height);W.height=w.height,W.width=w.width,A(I(ae.data,W))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ne!==void 0)return I(ne,W);throw new Error("Input data provided is not supported - aborted tensor creation")},Y=(y,M)=>{const{width:v,height:O,download:K,dispose:te}=M,ne=[1,O,v,4];return new _.Tensor({location:"texture",type:"float32",texture:y,dims:ne,download:K,dispose:te})},N=(y,M)=>{const{dataType:v,dims:O,download:K,dispose:te}=M;return new _.Tensor({location:"gpu-buffer",type:v??"float32",gpuBuffer:y,dims:O,download:K,dispose:te})},g=(y,M)=>{const{dataType:v,dims:O,download:K,dispose:te}=M;return new _.Tensor({location:"ml-tensor",type:v??"float32",mlTensor:y,dims:O,download:K,dispose:te})},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":(Ee,$,r)=>{r.r($)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Ee,$,r)=>{r.r($),r.d($,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>I,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>_,checkTypedArray:()=>Y});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 R=!1;const Y=()=>{if(!R){R=!0;const N=typeof BigInt64Array<"u"&&BigInt64Array.from,g=typeof BigUint64Array<"u"&&BigUint64Array.from,b=typeof Float16Array<"u"&&Float16Array.from;N&&(_.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":(Ee,$,r)=>{r.r($),r.d($,{Tensor:()=>N});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),I=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),R=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Y=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class N{constructor(b,y,M){(0,R.checkTypedArray)();let v,O;if(typeof b=="object"&&"location"in b)switch(this.dataLocation=b.location,v=b.type,O=b.dims,b.location){case"cpu-pinned":{const te=R.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(!te)throw new TypeError(`unsupported type "${v}" to create tensor from pinned buffer`);if(!(b.data instanceof te))throw new TypeError(`buffer should be of type ${te.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 te,ne;if(typeof b=="string")if(v=b,ne=M,b==="string"){if(!Array.isArray(y))throw new TypeError("A string tensor's data must be a string array.");te=y}else{const W=R.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(W===void 0)throw new TypeError(`Unsupported tensor type: ${b}.`);if(Array.isArray(y)){if(b==="float16"&&W===Uint16Array||b==="uint4"||b==="int4")throw new TypeError(`Creating a ${b} tensor from number array is not supported. Please use ${W.name} as data.`);b==="uint64"||b==="int64"?te=W.from(y,BigInt):te=W.from(y)}else if(y instanceof W)te=y;else if(y instanceof Uint8ClampedArray)if(b==="uint8")te=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 ${W}`)}else if(ne=y,Array.isArray(b)){if(b.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const W=typeof b[0];if(W==="string")v="string",te=b;else if(W==="boolean")v="bool",te=Uint8Array.from(b);else throw new TypeError(`Invalid element type of data array: ${W}.`)}else if(b instanceof Uint8ClampedArray)v="uint8",te=Uint8Array.from(b);else{const W=R.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(b.constructor);if(W===void 0)throw new TypeError(`Unsupported type for tensor data: ${b.constructor}.`);v=W,te=b}if(ne===void 0)ne=[te.length];else if(!Array.isArray(ne))throw new TypeError("A tensor's dims must be a number array");O=ne,this.cpuData=te,this.dataLocation="cpu"}const K=(0,Y.calculateSize)(O);if(this.cpuData&&K!==this.cpuData.length&&!((v==="uint4"||v==="int4")&&Math.ceil(K/2)===this.cpuData.length))throw new Error(`Tensor's size(${K}) does not match data length(${this.cpuData.length}).`);this.type=v,this.dims=O,this.size=K}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,Y.tensorReshape)(this,b)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Ee,$,r)=>{r.r($),r.d($,{calculateSize:()=>I,tensorReshape:()=>R});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const I=Y=>{let N=1;for(let g=0;g{switch(Y.location){case"cpu":return new _.Tensor(Y.type,Y.data,N);case"cpu-pinned":return new _.Tensor({location:"cpu-pinned",data:Y.data,type:Y.type,dims:N});case"texture":return new _.Tensor({location:"texture",texture:Y.texture,type:Y.type,dims:N});case"gpu-buffer":return new _.Tensor({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:N});case"ml-tensor":return new _.Tensor({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:N});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Ee,$,r)=>{r.r($),r.d($,{Tensor:()=>I});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const I=_.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Ee,$,r)=>{r.r($),r.d($,{TRACE:()=>I,TRACE_FUNC_BEGIN:()=>Y,TRACE_FUNC_END:()=>N});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}`)},R=(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 O=0;O{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||R("BEGIN",g)},N=g=>{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||R("END",g)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Ee,$,r)=>{r.r($),r.d($,{TrainingSession:()=>Y});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),I=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const R="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Y{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||{},[O,K]=await(0,_.resolveBackendAndExecutionProviders)(v);if(O.createTrainingSessionHandler){const te=await O.createTrainingSessionHandler(g.checkpointState,g.trainModel,y,M,K);return new Y(te,!!g.optimizerModel,!!g.evalModel)}else throw new Error(R)}typeNarrowingForRunStep(g,b,y,M,v){const O={};let K={};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 te=!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.");te=!1;for(const ne of M){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(b.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);O[ne]=null}if(typeof v=="object"&&v!==null)K=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const W=Object.getOwnPropertyNames(M);for(const U of b)if(W.indexOf(U)!==-1){const X=M[U];(X===null||X instanceof I.Tensor)&&(ne=!0,te=!1,O[U]=X)}if(ne){if(typeof v=="object"&&v!==null)K=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else K=M}}else if(typeof M<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of g)if(typeof y[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(te)for(const ne of b)O[ne]=null;return[O,K]}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),O=await this.handler.runTrainStep(g,M,v);return this.convertHandlerReturnTypeToMapOfTensors(O)}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),O=await this.handler.runEvalStep(g,M,v);return this.convertHandlerReturnTypeToMapOfTensors(O)}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":(Ee,$,r)=>{r.r($),r.d($,{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":(Ee,$,r)=>{r.r($),r.d($,{version:()=>_});const _="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96":(Ee,$,r)=>{r.r($),r.d($,{InferenceSession:()=>lt,TRACE:()=>Ue,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>Re,Tensor:()=>le,default:()=>xf,env:()=>F,registerBackend:()=>K});/*! + * ONNX Runtime Web v1.21.0-dev.20250114-228dd16893 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var _=Object.defineProperty,I=Object.getOwnPropertyDescriptor,R=Object.getOwnPropertyNames,Y=Object.prototype.hasOwnProperty,N=(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 R(t))!Y.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,O,K,te,ne,W=g(()=>{v=new Map,O=[],K=(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=O.indexOf(e);i!==-1&&O.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}}},ne=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?O:s,i,a=[],o=new Set;for(let p of n){let h=await te(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 u=t.filter(p=>o.has(typeof p=="string"?p:p.name));return[i,new Proxy(e,{get:(p,h)=>h==="executionProviders"?u:Reflect.get(p,h)})]}}),U=g(()=>{W()}),X,A=g(()=>{X="1.21.0-dev.20241212-1f88284f96"}),S,w,x=g(()=>{A(),S="warning",w={wasm:{},webgl:{},webgpu:{},versions:{common:X},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);S=e}},get logLevel(){return S}},Object.defineProperty(w,"logLevel",{enumerable:!0})}),F,ae=g(()=>{x(),F=w}),ie,ve,we=g(()=>{ie=(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",u=t==null?void 0:t.norm,p,h;u===void 0||u.mean===void 0?p=[255,255,255,255]:typeof u.mean=="number"?p=[u.mean,u.mean,u.mean,u.mean]:(p=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(p[3]=u.mean[3])),u===void 0||u.bias===void 0?h=[0,0,0,0]:typeof u.bias=="number"?h=[u.bias,u.bias,u.bias,u.bias]:(h=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(h[3]=u.bias[3]));let k=a*i,P=0,d=k,z=k*2,B=-1;o==="RGBA"?(P=0,d=k,z=k*2,B=k*3):o==="RGB"?(P=0,d=k,z=k*2):o==="RBG"&&(P=0,z=k,d=k*2);for(let V=0;V{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 u=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 P=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 d=4,z=0,B=1,V=2,Z=3,ee=0,Q=P,he=P*2,pe=-1;u==="RGBA"?(ee=0,Q=P,he=P*2,pe=P*3):u==="RGB"?(ee=0,Q=P,he=P*2):u==="RBG"&&(ee=0,he=P,Q=P*2),n=s.createImageData(i,a);for(let Me=0;Me{je(),re=(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 u=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),P=4,d=0,z=1,B=2,V=3,Z=0,ee=h,Q=h*2,he=-1;u==="RGB"&&(P=3,d=0,z=1,B=2,V=-1),p==="RGBA"?he=h*3:p==="RBG"?(Z=0,Q=h,ee=h*2):p==="BGR"&&(Q=0,ee=h,Z=h*2);for(let pe=0;pe{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,u=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 P=h(k);if(P!=null){let d=e.height,z=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,z=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=d,u.width=z}else u.tensorFormat="RGBA",u.height=d,u.width=z;P.drawImage(e,0,0),o=P.getImageData(0,0,z,d).data}else throw new Error("Can not access image data")}else if(n){let k,P;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,P=t.resizedWidth):(k=e.height,P=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=k,u.width=P,t!==void 0){let d=p();d.width=P,d.height=k;let z=h(d);if(z!=null)z.putImageData(e,0,0),o=z.getImageData(0,0,P,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 P=h(k);if(P!=null){let d=e.height,z=e.width;return P.drawImage(e,0,0,z,d),o=P.getImageData(0,0,z,d).data,u.height=d,u.width=z,re(o,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((k,P)=>{let d=p(),z=h(d);if(!e||!z)return P();let B=new Image;B.crossOrigin="Anonymous",B.src=e,B.onload=()=>{d.width=B.width,d.height=B.height,z.drawImage(B,0,0,d.width,d.height);let V=z.getImageData(0,0,d.width,d.height);u.height=d.height,u.width=d.width,k(re(V.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return re(o,u);throw new Error("Input data provided is not supported - aborted tensor creation")},ce=(e,t)=>{let{width:s,height:n,download:i,dispose:a}=t,o=[1,n,s,4];return new Ke({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:a})},Se=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:a}=t;return new Ke({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:i,dispose:a})},Ie=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:a}=t;return new Ke({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:i,dispose:a})},Ce=(e,t,s)=>new Ke({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Ge,ye,J,de,ke=g(()=>{Ge=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ye=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),J=!1,de=()=>{if(!J){J=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(Ge.set("int64",BigInt64Array),ye.set(BigInt64Array,"int64")),t&&(Ge.set("uint64",BigUint64Array),ye.set(BigUint64Array,"uint64")),s?(Ge.set("float16",Float16Array),ye.set(Float16Array,"float16")):Ge.set("float16",Uint16Array)}}}),Be,Ze,se=g(()=>{je(),Be=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Ke(e.type,e.data,t);case"cpu-pinned":return new Ke({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ke({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ke({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ke({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ke,je=g(()=>{we(),tt(),ke(),se(),Ke=class{constructor(e,t,s){de();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=Ge.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,u;if(typeof e=="string")if(n=e,u=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=Ge.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(u=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=ye.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,o=e}if(u===void 0)u=[o.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");i=u,this.cpuData=o,this.dataLocation="cpu"}let a=Be(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 xe(e,t)}static fromTexture(e,t){return ce(e,t)}static fromGpuBuffer(e,t){return Se(e,t)}static fromMLTensor(e,t){return Ie(e,t)}static fromPinnedBuffer(e,t,s){return Ce(e,t,s)}toDataURL(e){return ie(this,e)}toImageData(e){return ve(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 Ze(this,e)}}}),le,Te=g(()=>{je(),le=Ke}),Ue,Ve,Ne,Re,st=g(()=>{x(),Ue=(e,t)=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ve=(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)||Ve("BEGIN",e)},Re=e=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Ve("END",e)}}),dt,ct=g(()=>{W(),Te(),st(),dt=class gf{constructor(t){this.handler=t}async run(t,s,n){Ne();let i={},a={};if(typeof t!="object"||t===null||t instanceof le||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 le)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 P of this.outputNames)if(k.indexOf(P)!==-1){let d=s[P];(d===null||d instanceof le)&&(h=!0,o=!1,i[P]=d)}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 u=await this.handler.run(t,i,a),p={};for(let h in u)if(Object.hasOwnProperty.call(u,h)){let k=u[h];k instanceof le?p[h]=k:p[h]=new le(k.type,k.data,k.dims)}return Re(),p}async release(){return this.handler.dispose()}static async create(t,s,n,i){Ne();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,P=0,d=t.byteLength;if(typeof s=="object"&&s!==null)o=s;else if(typeof s=="number"){if(P=s,!Number.isSafeInteger(P))throw new RangeError("'byteOffset' must be an integer.");if(P<0||P>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(d=t.byteLength-P,typeof n=="number"){if(d=n,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||P+d>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-P}].`);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,P,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,p]=await ne(o),h=await u.createInferenceSessionHandler(a,p);return Re(),new gf(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),lt,ht=g(()=>{ct(),lt=dt}),L=g(()=>{}),oe=g(()=>{}),H=g(()=>{}),me=g(()=>{}),Ae={};b(Ae,{InferenceSession:()=>lt,TRACE:()=>Ue,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>Re,Tensor:()=>le,env:()=>F,registerBackend:()=>K});var We=g(()=>{U(),ae(),ht(),Te(),L(),oe(),st(),H(),me()}),Je=g(()=>{}),ut={};b(ut,{default:()=>kt});var mt,vt,kt,At=g(()=>{var e;Oh(),ar(),Rr(),mt="ort-wasm-proxy-worker",vt=((e=globalThis.self)==null?void 0:e.name)===mt,vt&&(self.onmessage=t=>{let{type:s,in:n}=t.data;try{switch(s){case"init-wasm":Ir(n.wasm).then(()=>{Ac(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;Ic(a,i).then(()=>{postMessage({type:s})},o=>{postMessage({type:s,err:o})});break}case"copy-from":{let{buffer:i}=n,a=dr(i);postMessage({type:s,out:a});break}case"create":{let{model:i,options:a}=n;Qp(i,a).then(o=>{postMessage({type:s,out:o})},o=>{postMessage({type:s,err:o})});break}case"release":Xp(n),postMessage({type:s});break;case"run":{let{sessionId:i,inputIndices:a,inputs:o,outputIndices:u,options:p}=n;Jp(i,a,o,u,new Array(u.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},eh([...o,...h]))},h=>{postMessage({type:s,err:h})});break}case"end-profiling":Zp(n),postMessage({type:s});break;default:}}catch(i){postMessage({type:s,err:i})}}),kt=vt?null:t=>new Worker(t??Us,{type:"module",name:mt})}),is={};b(is,{default:()=>Ds});var ws,ks,Ds,sr=g(()=>{var e;ks=(ws=import.meta.url,async function(t={}){function s(){return Ft.buffer!=Rt.buffer&&Es(),Rt}function n(){return Ft.buffer!=Rt.buffer&&Es(),_s}function i(){return Ft.buffer!=Rt.buffer&&Es(),ot}function a(){return Ft.buffer!=Rt.buffer&&Es(),Pt}function o(){return Ft.buffer!=Rt.buffer&&Es(),cs}function u(){return Ft.buffer!=Rt.buffer&&Es(),Ns}function p(){return Ft.buffer!=Rt.buffer&&Es(),vr}function h(){return Ft.buffer!=Rt.buffer&&Es(),Oi}var k,P,d=Object.assign({},t),z=new Promise((l,m)=>{k=l,P=m}),B=typeof window=="object",V=typeof importScripts=="function",Z=V&&self.name=="em-pthread";d.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(d.Fb||(d.Fb=new Map)).set(l,m)},d.unmountExternalData=()=>{delete d.Fb};var ee=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let Q=()=>{let l=(E,D,G)=>(...ge)=>{let Xe=pn,nt=D==null?void 0:D();ge=E(...ge);let wt=D==null?void 0:D();return nt!==wt&&(E=wt,G(nt),D=G=null),pn!=Xe?new Promise((Ct,Wt)=>{Mh={resolve:Ct,reject:Wt}}):ge},m=E=>async(...D)=>{var G;try{if(d.Gb)throw Error("Session already started");let ge=d.Gb={hc:D[0],errors:[]},Xe=await E(...D);if(d.Gb!==ge)throw Error("Session mismatch");(G=d.Hb)==null||G.flush();let nt=ge.errors;if(0Ct),0d._OrtCreateSession,E=>d._OrtCreateSession=E),d._OrtRun=m(l(d._OrtRun,()=>d._OrtRun,E=>d._OrtRun=E)),d._OrtRunWithBinding=m(l(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,E=>d._OrtRunWithBinding=E)),d._OrtBindInput=l(d._OrtBindInput,()=>d._OrtBindInput,E=>d._OrtBindInput=E),Q=void 0};d.jsepInit=(l,m)=>{if(Q==null||Q(),l==="webgpu"){[d.Hb,d.Vb,d.Zb,d.Ob,d.Yb,d.kb,d.$b,d.cc,d.Wb,d.Xb,d.ac]=m;let E=d.Hb;d.jsepRegisterBuffer=(D,G,ge,Xe)=>E.registerBuffer(D,G,ge,Xe),d.jsepGetBuffer=D=>E.getBuffer(D),d.jsepCreateDownloader=(D,G,ge)=>E.createDownloader(D,G,ge),d.jsepOnCreateSession=D=>{E.onCreateSession(D)},d.jsepOnReleaseSession=D=>{E.onReleaseSession(D)},d.jsepOnRunStart=D=>E.onRunStart(D),d.dc=(D,G)=>{E.upload(D,G)}}else if(l==="webnn"){[d.Hb,d.bc,d.Pb,d.jsepEnsureTensor,d.ec,d.jsepDownloadTensor]=m,d.jsepReleaseTensorId=d.Pb;let E=d.Hb;d.jsepOnRunStart=D=>E.onRunStart(D),d.jsepRegisterMLContext=(D,G)=>{E.registerMLContext(D,G)},d.jsepOnReleaseSession=D=>{E.onReleaseSession(D)},d.jsepCreateMLTensorDownloader=(D,G)=>E.createMLTensorDownloader(D,G),d.jsepRegisterMLTensor=(D,G,ge)=>E.registerMLTensor(D,G,ge),d.jsepCreateMLContext=D=>E.createMLContext(D),d.jsepRegisterMLConstant=(D,G,ge,Xe,nt)=>E.registerMLConstant(D,G,ge,Xe,nt,d.Fb)}};var he,pe,Me=Object.assign({},d),De="./this.program",Le=(l,m)=>{throw m},Ye="";(B||V)&&(V?Ye=self.location.href:typeof document<"u"&&document.currentScript&&(Ye=document.currentScript.src),ws&&(Ye=ws),Ye=Ye.startsWith("blob:")?"":Ye.substr(0,Ye.replace(/[?#].*/,"").lastIndexOf("/")+1),V&&(pe=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),he=(l,m,E)=>{var D=new XMLHttpRequest;D.open("GET",l,!0),D.responseType="arraybuffer",D.onload=()=>{D.status==200||D.status==0&&D.response?m(D.response):E()},D.onerror=E,D.send(null)});var at,Et=console.log.bind(console),Xt=console.error.bind(console),Zt=Et,bt=Xt;if(Object.assign(d,Me),Me=null,Z){let l=function(m){try{var E=m.data,D=E.cmd;if(D==="load"){let G=[];self.onmessage=ge=>G.push(ge),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ge of G)l(ge);self.onmessage=l};for(let ge of E.handlers)d[ge]&&!d[ge].proxy||(d[ge]=(...Xe)=>{postMessage({Nb:"callHandler",pc:ge,args:Xe})},ge=="print"&&(Zt=d[ge]),ge=="printErr"&&(bt=d[ge]));Ft=E.wasmMemory,Es(),ss(E.wasmModule)}else if(D==="run"){Th(E.pthread_ptr,0,0,1,0,0),wh(E.pthread_ptr),Pf(),rm(),St||(ef(),St=!0);try{Cf(E.start_routine,E.arg)}catch(G){if(G!="unwind")throw G}}else D==="cancel"?Ia()&&jp(-1):E.target!=="setimmediate"&&(D==="checkMailbox"?St&&Ap():D&&(bt(`worker: received unknown command ${D}`),bt(E)))}catch(G){throw tf(),G}};var ss,St=!1;bt=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:Ia()})},d.instantiateWasm=(m,E)=>new Promise(D=>{ss=G=>{G=new WebAssembly.Instance(G,Jh()),E(G),D()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}d.wasmBinary&&(at=d.wasmBinary);var Ft,bs,Ht,Rt,_s,ot,Pt,cs,Ns,vr,er,un,Oi,Bs=!1;function Es(){var l=Ft.buffer;d.HEAP8=Rt=new Int8Array(l),d.HEAP16=ot=new Int16Array(l),d.HEAPU8=_s=new Uint8Array(l),d.HEAPU16=Pt=new Uint16Array(l),d.HEAP32=cs=new Int32Array(l),d.HEAPU32=Ns=new Uint32Array(l),d.HEAPF32=vr=new Float32Array(l),d.HEAPF64=Oi=new Float64Array(l),d.HEAP64=er=new BigInt64Array(l),d.HEAPU64=un=new BigUint64Array(l)}if(!Z){if(!((Ft=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof ee))throw bt("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");Es()}var Xn=[],Dc=[],ih=[],Lc=0,zc=null;function Hh(){if(--Lc==0&&zc){var l=zc;zc=null,l()}}function Yn(l){throw bt(l="Aborted("+l+")"),Bs=!0,Ht=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),P(l),l}var oh,qh=l=>l.startsWith("data:application/octet-stream;base64,"),Qh=l=>l.startsWith("file://");function Xh(l){if(l==oh&&at)return new Uint8Array(at);if(pe)return pe(l);throw"both async and sync fetching of the wasm failed"}function Yh(l,m,E){return function(D){if(!at&&(B||V)){if(typeof fetch=="function"&&!Qh(D))return fetch(D,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${D}'`;return G.arrayBuffer()}).catch(()=>Xh(D));if(he)return new Promise((G,ge)=>{he(D,Xe=>G(new Uint8Array(Xe)),ge)})}return Promise.resolve().then(()=>Xh(D))}(l).then(D=>WebAssembly.instantiate(D,m)).then(E,D=>{bt(`failed to asynchronously prepare wasm: ${D}`),Yn(D)})}function Jh(){return{a:{O:Ef,Aa:Tf,b:Sf,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:xm,va:$f,F:Af,Q:If,P:Ff,E:Lf,u:zf,q:Bf,G:Rf,A:Kf,R:Hf,ua:qf,ka:Qf,U:Xf,ba:Yf,H:Jf,ja:wh,ta:Zf,t:e_,Ba:t_,x:n_,n:i_,l:a_,c:_h,o:l_,j:c_,w:p_,p:h_,f:m_,s:f_,m:__,e:g_,k:w_,i:y_,h:M_,d:b_,ea:v_,fa:x_,ga:T_,ca:zm,da:Bm,T:E_,g:P_,D:C_,I:k_,M:S_,y:$_,sa:A_,V:I_,v:Nm,z:O_,N:F_,S:D_,za:L_,ya:z_,la:Vm,ma:Wm,$:ch,C:Gm,K:Km,ia:Hm,J:qm,a:Ft,xa:dh,wa:Ym,r:N_}}}var ah={913700:(l,m,E,D,G)=>{if(d===void 0||!d.Fb)return 1;if((l=Hs(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=d.Fb.get(l)))return 2;if(m=Number(m>>>0),E=Number(E>>>0),D=Number(D>>>0),m+E>l.byteLength)return 3;try{let ge=l.subarray(m,m+E);switch(G){case 0:n().set(ge,D>>>0);break;case 1:d.dc(D,ge);break;default:return 4}return 0}catch{return 4}},914415:(l,m,E)=>{d.ec(l,n().subarray(m>>>0,m+E>>>0))},914478:()=>d.bc(),914519:l=>{d.Pb(l)},914555:()=>{d.Wb()},914586:()=>{d.Xb()},914615:()=>{d.ac()},914640:l=>d.Vb(l),914673:l=>d.Zb(l),914705:(l,m,E)=>{d.Ob(Number(l),Number(m),Number(E),!0)},914768:(l,m,E)=>{d.Ob(Number(l),Number(m),Number(E))},914825:()=>typeof wasmOffsetConverter<"u",914882:l=>{d.kb("Abs",l,void 0)},914933:l=>{d.kb("Neg",l,void 0)},914984:l=>{d.kb("Floor",l,void 0)},915037:l=>{d.kb("Ceil",l,void 0)},915089:l=>{d.kb("Reciprocal",l,void 0)},915147:l=>{d.kb("Sqrt",l,void 0)},915199:l=>{d.kb("Exp",l,void 0)},915250:l=>{d.kb("Erf",l,void 0)},915301:l=>{d.kb("Sigmoid",l,void 0)},915356:(l,m,E)=>{d.kb("HardSigmoid",l,{alpha:m,beta:E})},915435:l=>{d.kb("Log",l,void 0)},915486:l=>{d.kb("Sin",l,void 0)},915537:l=>{d.kb("Cos",l,void 0)},915588:l=>{d.kb("Tan",l,void 0)},915639:l=>{d.kb("Asin",l,void 0)},915691:l=>{d.kb("Acos",l,void 0)},915743:l=>{d.kb("Atan",l,void 0)},915795:l=>{d.kb("Sinh",l,void 0)},915847:l=>{d.kb("Cosh",l,void 0)},915899:l=>{d.kb("Asinh",l,void 0)},915952:l=>{d.kb("Acosh",l,void 0)},916005:l=>{d.kb("Atanh",l,void 0)},916058:l=>{d.kb("Tanh",l,void 0)},916110:l=>{d.kb("Not",l,void 0)},916161:(l,m,E)=>{d.kb("Clip",l,{min:m,max:E})},916230:l=>{d.kb("Clip",l,void 0)},916282:(l,m)=>{d.kb("Elu",l,{alpha:m})},916340:l=>{d.kb("Gelu",l,void 0)},916392:l=>{d.kb("Relu",l,void 0)},916444:(l,m)=>{d.kb("LeakyRelu",l,{alpha:m})},916508:(l,m)=>{d.kb("ThresholdedRelu",l,{alpha:m})},916578:(l,m)=>{d.kb("Cast",l,{to:m})},916636:l=>{d.kb("Add",l,void 0)},916687:l=>{d.kb("Sub",l,void 0)},916738:l=>{d.kb("Mul",l,void 0)},916789:l=>{d.kb("Div",l,void 0)},916840:l=>{d.kb("Pow",l,void 0)},916891:l=>{d.kb("Equal",l,void 0)},916944:l=>{d.kb("Greater",l,void 0)},916999:l=>{d.kb("GreaterOrEqual",l,void 0)},917061:l=>{d.kb("Less",l,void 0)},917113:l=>{d.kb("LessOrEqual",l,void 0)},917172:(l,m,E,D,G)=>{d.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},917347:(l,m,E,D,G)=>{d.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},917521:(l,m,E,D,G)=>{d.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},917695:(l,m,E,D,G)=>{d.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},917870:(l,m,E,D,G)=>{d.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918044:(l,m,E,D,G)=>{d.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918217:(l,m,E,D,G)=>{d.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918390:(l,m,E,D,G)=>{d.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918567:(l,m,E,D,G)=>{d.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918747:(l,m,E,D,G)=>{d.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918927:l=>{d.kb("Where",l,void 0)},918980:(l,m,E)=>{d.kb("Transpose",l,{perm:m?Array.from(o().subarray(Number(m)>>>0,Number(E)>>>0)):[]})},919104:(l,m,E,D)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Hs(E),format:D?"NHWC":"NCHW"})},919237:(l,m,E,D)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Hs(E),format:D?"NHWC":"NCHW"})},919370:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He,ls)=>{d.kb("ConvTranspose",l,{format:wt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:D,kernelShape:[G],pads:[ge,Xe],strides:[nt],wIsConst:()=>!!s()[Ct>>>0],outputPadding:Wt?Array.from(o().subarray(Number(Wt)>>>0,Number(ps)>>>0)):[],outputShape:vs?Array.from(o().subarray(Number(vs)>>>0,Number(He)>>>0)):[],activation:Hs(ls)})},919803:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:D,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(ge)>>>0,4+(Number(ge)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Xe)>>>0,2+(Number(Xe)>>>0)>>>0)),wIsConst:()=>!!s()[wt>>>0],outputPadding:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],outputShape:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[],activation:Hs(He)})},920464:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He,ls)=>{d.kb("ConvTranspose",l,{format:wt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:D,kernelShape:[G],pads:[ge,Xe],strides:[nt],wIsConst:()=>!!s()[Ct>>>0],outputPadding:Wt?Array.from(o().subarray(Number(Wt)>>>0,Number(ps)>>>0)):[],outputShape:vs?Array.from(o().subarray(Number(vs)>>>0,Number(He)>>>0)):[],activation:Hs(ls)})},920897:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:D,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(ge)>>>0,4+(Number(ge)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Xe)>>>0,2+(Number(Xe)>>>0)>>>0)),wIsConst:()=>!!s()[wt>>>0],outputPadding:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],outputShape:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[],activation:Hs(He)})},921558:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},921649:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:G,dilations:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[]})},922128:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},922219:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:G,dilations:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[]})},922698:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},922785:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:G,dilations:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[]})},923260:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},923347:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:G,dilations:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[]})},923822:(l,m,E,D,G)=>{d.kb("Gemm",l,{alpha:m,beta:E,transA:D,transB:G})},923926:l=>{d.kb("MatMul",l,void 0)},923980:(l,m,E,D)=>{d.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!E,axis:D})},924088:(l,m,E,D)=>{d.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!E,axis:D})},924196:(l,m)=>{d.kb("Softmax",l,{axis:m})},924259:(l,m)=>{d.kb("Concat",l,{axis:m})},924319:(l,m,E,D,G)=>{d.kb("Split",l,{axis:m,numOutputs:E,splitSizes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},924475:l=>{d.kb("Expand",l,void 0)},924529:(l,m)=>{d.kb("Gather",l,{axis:Number(m)})},924600:(l,m)=>{d.kb("GatherElements",l,{axis:Number(m)})},924679:(l,m)=>{d.kb("GatherND",l,{batch_dims:Number(m)})},924758:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt)=>{d.kb("Resize",l,{antialias:m,axes:E?Array.from(o().subarray(Number(E)>>>0,Number(D)>>>0)):[],coordinateTransformMode:Hs(G),cubicCoeffA:ge,excludeOutside:Xe,extrapolationValue:nt,keepAspectRatioPolicy:Hs(wt),mode:Hs(Ct),nearestMode:Hs(Wt)})},925120:(l,m,E,D,G,ge,Xe)=>{d.kb("Slice",l,{starts:m?Array.from(o().subarray(Number(m)>>>0,Number(E)>>>0)):[],ends:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[],axes:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[]})},925384:l=>{d.kb("Tile",l,void 0)},925436:(l,m,E)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},925550:(l,m,E)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},925664:l=>{d.kb("Range",l,void 0)},925717:(l,m)=>{d.kb("Einsum",l,{equation:Hs(m)})},925798:(l,m,E,D,G)=>{d.kb("Pad",l,{mode:m,value:E,pads:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},925941:(l,m,E,D,G,ge)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!D,format:ge?"NHWC":"NCHW"})},926110:(l,m,E,D,G,ge)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!D,format:ge?"NHWC":"NCHW"})},926279:(l,m,E)=>{d.kb("CumSum",l,{exclusive:Number(m),reverse:Number(E)})},926376:(l,m,E)=>{d.kb("DequantizeLinear",l,{axis:m,blockSize:E})},926466:(l,m,E,D,G)=>{d.kb("GridSample",l,{align_corners:m,mode:Hs(E),padding_mode:Hs(D),format:G?"NHWC":"NCHW"})},926636:(l,m,E,D,G)=>{d.kb("GridSample",l,{align_corners:m,mode:Hs(E),padding_mode:Hs(D),format:G?"NHWC":"NCHW"})},926806:(l,m,E,D,G,ge,Xe,nt,wt)=>{d.kb("Attention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:D,scale:G,doRotary:ge,qkvHiddenSizes:Xe?Array.from(o().subarray(Number(nt)>>>0,Number(nt)+Xe>>>0)):[],pastPresentShareBuffer:!!wt})},927078:l=>{d.kb("BiasAdd",l,void 0)},927133:l=>{d.kb("BiasSplitGelu",l,void 0)},927194:l=>{d.kb("FastGelu",l,void 0)},927250:(l,m,E,D,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He,ls,js)=>{d.kb("Conv",l,{format:ps?"NHWC":"NCHW",auto_pad:m,dilations:E?Array.from(o().subarray(Number(E)>>>0,Number(D)>>>0)):[],group:G,kernel_shape:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],pads:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],strides:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],w_is_const:()=>!!s()[Number(vs)>>>0],activation:Hs(He),activation_params:ls?Array.from(p().subarray(Number(ls)>>>0,Number(js)>>>0)):[]})},927834:l=>{d.kb("Gelu",l,void 0)},927886:(l,m,E,D,G,ge,Xe,nt,wt)=>{d.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:E,scale:D,softcap:G,doRotary:ge,rotaryInterleaved:Xe,smoothSoftmax:nt,localWindowSize:wt})},928103:(l,m,E,D)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!D})},928214:(l,m,E,D)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!D})},928325:(l,m,E,D,G,ge)=>{d.kb("MatMulNBits",l,{k:m,n:E,accuracyLevel:D,bits:G,blockSize:ge})},928452:(l,m,E,D,G,ge)=>{d.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:D,scale:G,doRotary:ge})},928611:(l,m)=>{d.kb("QuickGelu",l,{alpha:m})},928675:(l,m,E,D,G)=>{d.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:E,rotaryEmbeddingDim:D,scale:G})},928814:(l,m,E)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},928916:(l,m,E)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},929018:(l,m,E,D)=>{d.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:E,blockSize:D})},929139:l=>{d.$b(l)},929173:(l,m)=>d.cc(Number(l),Number(m),d.Gb.hc,d.Gb.errors)};function Tf(l,m,E){return Im(async()=>{await d.Yb(Number(l),Number(m),Number(E))})}function Ef(){return typeof wasmOffsetConverter<"u"}function lh(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var uh=l=>{l.terminate(),l.onmessage=()=>{}},Zh=l=>{Jn.length==0&&(im(),nm(Jn[0]));var m=Jn.pop();if(!m)return 6;Di.push(m),dn[l.Bb]=m,m.Bb=l.Bb;var E={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(E,l.nc),0},Fi=0,Rs=(l,m,...E)=>{for(var D=2*E.length,G=Ch(),ge=Ph(8*D),Xe=ge>>>3,nt=0;nt>>0]=wt)}return l=sf(l,0,D,ge,m),Up(G),l};function dh(l){if(Z)return Rs(0,1,l);if(Ht=l,!(0{if(Ht=l,Z)throw em(l),"unwind";dh(l)},Jn=[],Di=[],tm=[],dn={},sm=l=>{var m=l.Bb;delete dn[m],Jn.push(l),Di.splice(Di.indexOf(l),1),l.Bb=0,Eh(m)};function rm(){tm.forEach(l=>l())}var nm=l=>new Promise(m=>{l.onmessage=G=>{var ge=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=Ia()){var Xe=dn[G.targetThread];Xe?Xe.postMessage(G,G.transferList):bt(`Internal error! Worker sent a message "${ge}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else ge==="checkMailbox"?Ap():ge==="spawnThread"?Zh(G):ge==="cleanupThread"?sm(dn[G.thread]):ge==="killThread"?(G=G.thread,ge=dn[G],delete dn[G],uh(ge),Eh(G),Di.splice(Di.indexOf(ge),1),ge.Bb=0):ge==="cancelThread"?dn[G.thread].postMessage({cmd:"cancel"}):ge==="loaded"?(l.loaded=!0,m(l)):ge==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):ge==="callHandler"?d[G.handler](...G.args):ge&&bt(`worker sent an unknown command ${ge}`)},l.onerror=G=>{throw bt(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var E,D=[];for(E of[])d.hasOwnProperty(E)&&D.push(E);l.postMessage({cmd:"load",handlers:D,wasmMemory:Ft,wasmModule:bs})});function im(){var l=new Worker(import.meta.url.startsWith("file:")?new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b):new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Jn.push(l)}var $p=l=>{for(;0{var l=Ia(),m=u()[l+52>>>2>>>0];l=u()[l+56>>>2>>>0],nf(m,m-l),Up(m)},Cf=(l,m)=>{Fi=0,l=of(l,m),0>>=0);throw m>>>=0,E>>>=0,u()[D.Kb+16>>>2>>>0]=0,u()[D.Kb+4>>>2>>>0]=m,u()[D.Kb+8>>>2>>>0]=E,l}function om(l,m,E,D){return Z?Rs(2,1,l,m,E,D):am(l,m,E,D)}function am(l,m,E,D){if(l>>>=0,m>>>=0,E>>>=0,D>>>=0,ee===void 0)return bt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return Z&&G.length===0?om(l,m,E,D):(l={ic:E,Bb:l,Rb:D,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,E)=>{var D=(m>>>=0)+E;for(E=m;l[E]&&!(E>=D);)++E;if(16(G=(240&G)==224?(15&G)<<12|ge<<6|Xe:(7&G)<<18|ge<<12|Xe<<6|63&l[m++])?D+=String.fromCharCode(G):(G-=65536,D+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else D+=String.fromCharCode(G)}return D},Hs=(l,m)=>(l>>>=0)?um(n(),l,m):"";function dm(l,m,E){return Z?Rs(3,1,l,m,E):0}function cm(l,m){if(Z)return Rs(4,1,l,m)}var ph=l=>{for(var m=0,E=0;E=D?m++:2047>=D?m+=2:55296<=D&&57343>=D?(m+=4,++E):m+=3}return m},pm=(l,m,E,D)=>{if(!(0>>=0;D=E+D-1;for(var ge=0;ge=Xe&&(Xe=65536+((1023&Xe)<<10)|1023&l.charCodeAt(++ge)),127>=Xe){if(E>=D)break;m[E++>>>0]=Xe}else{if(2047>=Xe){if(E+1>=D)break;m[E++>>>0]=192|Xe>>6}else{if(65535>=Xe){if(E+2>=D)break;m[E++>>>0]=224|Xe>>12}else{if(E+3>=D)break;m[E++>>>0]=240|Xe>>18,m[E++>>>0]=128|Xe>>12&63}m[E++>>>0]=128|Xe>>6&63}m[E++>>>0]=128|63&Xe}}return m[E>>>0]=0,E-G},$a=(l,m,E)=>pm(l,n(),m,E);function hm(l,m){if(Z)return Rs(5,1,l,m)}function mm(l,m,E){if(Z)return Rs(6,1,l,m,E)}function fm(l,m,E){return Z?Rs(7,1,l,m,E):0}function _m(l,m){if(Z)return Rs(8,1,l,m)}function gm(l,m,E){if(Z)return Rs(9,1,l,m,E)}function wm(l,m,E,D){if(Z)return Rs(10,1,l,m,E,D)}function ym(l,m,E,D){if(Z)return Rs(11,1,l,m,E,D)}function Mm(l,m,E,D){if(Z)return Rs(12,1,l,m,E,D)}function bm(l){if(Z)return Rs(13,1,l)}function vm(l,m){if(Z)return Rs(14,1,l,m)}function xm(l,m,E){if(Z)return Rs(15,1,l,m,E)}var Tm,Zn,$f=()=>{Yn("")},cn=l=>{for(var m="";n()[l>>>0];)m+=Tm[n()[l++>>>0]];return m},hh={},mh={};function Pn(l,m,E={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(D,G,ge={}){var Xe=G.name;if(!D)throw new Zn(`type "${Xe}" must have a positive integer typeid pointer`);if(mh.hasOwnProperty(D)){if(ge.Tb)return;throw new Zn(`Cannot register type '${Xe}' twice`)}mh[D]=G,hh.hasOwnProperty(D)&&(G=hh[D],delete hh[D],G.forEach(nt=>nt()))}(l,m,E)}var Em=(l,m,E)=>{switch(m){case 1:return E?D=>s()[D>>>0]:D=>n()[D>>>0];case 2:return E?D=>i()[D>>>1>>>0]:D=>a()[D>>>1>>>0];case 4:return E?D=>o()[D>>>2>>>0]:D=>u()[D>>>2>>>0];case 8:return E?D=>er[D>>>3]:D=>un[D>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function Af(l,m,E){E>>>=0,Pn(l>>>=0,{name:m=cn(m>>>0),fromWireType:D=>D,toWireType:function(D,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(D=typeof G)=="object"||D==="array"||D==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:ei,readValueFromPointer:Em(m,E,m.indexOf("u")==-1),Eb:null})}var ei=8;function If(l,m,E,D){Pn(l>>>=0,{name:m=cn(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,ge){return ge?E:D},argPackAdvance:ei,readValueFromPointer:function(G){return this.fromWireType(n()[G>>>0])},Eb:null})}var fh=[],Cn=[];function _h(l){9<(l>>>=0)&&--Cn[l+1]==0&&(Cn[l]=void 0,fh.push(l))}var Cr=l=>{if(!l)throw new Zn("Cannot use deleted val. handle = "+l);return Cn[l]},zr=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=fh.pop()||Cn.length;return Cn[m]=l,Cn[m+1]=1,m}};function gh(l){return this.fromWireType(u()[l>>>2>>>0])}var Of={name:"emscripten::val",fromWireType:l=>{var m=Cr(l);return _h(l),m},toWireType:(l,m)=>zr(m),argPackAdvance:ei,readValueFromPointer:gh,Eb:null};function Ff(l){return Pn(l>>>0,Of)}var Df=(l,m)=>{switch(m){case 4:return function(E){return this.fromWireType(p()[E>>>2>>>0])};case 8:return function(E){return this.fromWireType(h()[E>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function Lf(l,m,E){E>>>=0,Pn(l>>>=0,{name:m=cn(m>>>0),fromWireType:D=>D,toWireType:(D,G)=>G,argPackAdvance:ei,readValueFromPointer:Df(m,E),Eb:null})}function zf(l,m,E,D,G){if(l>>>=0,E>>>=0,m=cn(m>>>0),G===-1&&(G=4294967295),G=nt=>nt,D===0){var ge=32-8*E;G=nt=>nt<>>ge}var Xe=m.includes("unsigned")?function(nt,wt){return wt>>>0}:function(nt,wt){return wt};Pn(l,{name:m,fromWireType:G,toWireType:Xe,argPackAdvance:ei,readValueFromPointer:Em(m,E,D!==0),Eb:null})}function Bf(l,m,E){function D(ge){var Xe=u()[ge>>>2>>>0];return ge=u()[ge+4>>>2>>>0],new G(s().buffer,ge,Xe)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Pn(l>>>=0,{name:E=cn(E>>>0),fromWireType:D,argPackAdvance:ei,readValueFromPointer:D},{Tb:!0})}function Rf(l,m){l>>>=0;var E=(m=cn(m>>>0))==="std::string";Pn(l,{name:m,fromWireType:function(D){var G=u()[D>>>2>>>0],ge=D+4;if(E)for(var Xe=ge,nt=0;nt<=G;++nt){var wt=ge+nt;if(nt==G||n()[wt>>>0]==0){if(Xe=Hs(Xe,wt-Xe),Ct===void 0)var Ct=Xe;else Ct+="\0",Ct+=Xe;Xe=wt+1}}else{for(Ct=Array(G),nt=0;nt>>0]);Ct=Ct.join("")}return hn(D),Ct},toWireType:function(D,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var ge=typeof G=="string";if(!(ge||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new Zn("Cannot pass non-string to std::string");var Xe=E&&ge?ph(G):G.length,nt=Np(4+Xe+1),wt=nt+4;if(u()[nt>>>2>>>0]=Xe,E&&ge)$a(G,wt,Xe+1);else if(ge)for(ge=0;ge>>0]=Ct}else for(ge=0;ge>>0]=G[ge];return D!==null&&D.push(hn,nt),nt},argPackAdvance:ei,readValueFromPointer:gh,Eb(D){hn(D)}})}var Pm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Nf=(l,m)=>{for(var E=l>>1,D=E+m/2;!(E>=D)&&a()[E>>>0];)++E;if(32<(E<<=1)-l&&Pm)return Pm.decode(n().slice(l,E));for(E="",D=0;!(D>=m/2);++D){var G=i()[l+2*D>>>1>>>0];if(G==0)break;E+=String.fromCharCode(G)}return E},jf=(l,m,E)=>{if(E??(E=2147483647),2>E)return 0;var D=m;E=(E-=2)<2*l.length?E/2:l.length;for(var G=0;G>>1>>>0]=ge,m+=2}return i()[m>>>1>>>0]=0,m-D},Uf=l=>2*l.length,Vf=(l,m)=>{for(var E=0,D="";!(E>=m/4);){var G=o()[l+4*E>>>2>>>0];if(G==0)break;++E,65536<=G?(G-=65536,D+=String.fromCharCode(55296|G>>10,56320|1023&G)):D+=String.fromCharCode(G)}return D},Wf=(l,m,E)=>{if(m>>>=0,E??(E=2147483647),4>E)return 0;var D=m;E=D+E-4;for(var G=0;G=ge&&(ge=65536+((1023&ge)<<10)|1023&l.charCodeAt(++G)),o()[m>>>2>>>0]=ge,(m+=4)+4>E)break}return o()[m>>>2>>>0]=0,m-D},Gf=l=>{for(var m=0,E=0;E=D&&++E,m+=4}return m};function Kf(l,m,E){if(l>>>=0,m>>>=0,E=cn(E>>>=0),m===2)var D=Nf,G=jf,ge=Uf,Xe=nt=>a()[nt>>>1>>>0];else m===4&&(D=Vf,G=Wf,ge=Gf,Xe=nt=>u()[nt>>>2>>>0]);Pn(l,{name:E,fromWireType:nt=>{for(var wt,Ct=u()[nt>>>2>>>0],Wt=nt+4,ps=0;ps<=Ct;++ps){var vs=nt+4+ps*m;ps!=Ct&&Xe(vs)!=0||(Wt=D(Wt,vs-Wt),wt===void 0?wt=Wt:(wt+="\0",wt+=Wt),Wt=vs+m)}return hn(nt),wt},toWireType:(nt,wt)=>{if(typeof wt!="string")throw new Zn(`Cannot pass non-string to C++ string type ${E}`);var Ct=ge(wt),Wt=Np(4+Ct+m);return u()[Wt>>>2>>>0]=Ct/m,G(wt,Wt+4,Ct+m),nt!==null&&nt.push(hn,Wt),Wt},argPackAdvance:ei,readValueFromPointer:gh,Eb(nt){hn(nt)}})}function Hf(l,m){Pn(l>>>=0,{Ub:!0,name:m=cn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var qf=()=>1;function Qf(l){Th(l>>>0,!V,1,!B,131072,!1),rm()}var Cm=l=>{if(!Bs)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(o(),l>>>2,l).value.then(Ap),l+=128,Atomics.store(o(),l>>>2,1))}var Ap=()=>{var l=Ia();l&&(wh(l),Cm(rf))};function Xf(l,m){(l>>>=0)==m>>>0?setTimeout(Ap):Z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=dn[l])&&l.postMessage({cmd:"checkMailbox"})}var yh=[];function Yf(l,m,E,D,G){for(m>>>=0,D/=2,yh.length=D,E=G>>>0>>>3,G=0;G>>0];return(m?ah[m]:j_[l])(...yh)}function Jf(l){l>>>=0,Z?postMessage({cmd:"cleanupThread",thread:l}):sm(dn[l])}function Zf(l){}var Ip=(l,m)=>{var E=mh[l];if(E===void 0)throw l=Zm(l),E=cn(l),hn(l),new Zn(`${m} has unknown type ${E}`);return E},km=(l,m,E)=>{var D=[];return l=l.toWireType(D,E),D.length&&(u()[m>>>2>>>0]=zr(D)),l};function e_(l,m,E){return m>>>=0,E>>>=0,l=Cr(l>>>0),m=Ip(m,"emval::as"),km(m,E,l)}function t_(l,m){return m>>>=0,l=Cr(l>>>0),(m=Ip(m,"emval::as")).toWireType(null,l)}var Op=l=>{try{l()}catch(m){Yn(m)}},ti=0,pn=null,Sm=0,Fp=[],$m={},Am={},s_=0,Mh=null,r_=[];function Im(l){return function(m){if(!Bs){if(ti===0){var E=!1,D=!1;m((G=0)=>{if(!Bs&&(Sm=G,E=!0,D)){ti=2,Op(()=>uf(pn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var ge=function(){var wt=o()[pn+8>>>2>>>0];return wt=Ut[Am[wt]],--Fi,wt()}()}catch(wt){ge=wt,G=!0}var Xe=!1;if(!pn){var nt=Mh;nt&&(Mh=null,(G?nt.reject:nt.resolve)(ge),Xe=!0)}if(G&&!Xe)throw ge}}),D=!0,E||(ti=1,pn=function(){var G=Np(65548),ge=G+12;u()[G>>>2>>>0]=ge,u()[G+4>>>2>>>0]=ge+65536,ge=Fp[0];var Xe=$m[ge];return Xe===void 0&&(Xe=s_++,$m[ge]=Xe,Am[Xe]=ge),ge=Xe,o()[G+8>>>2>>>0]=ge,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Op(()=>af(pn)))}else ti===2?(ti=0,Op(df),hn(pn),pn=null,r_.forEach(Cm)):Yn(`invalid state: ${ti}`);return Sm}}(m=>{l().then(m)})}function n_(l){return l>>>=0,Im(()=>(l=Cr(l)).then(zr))}var Dp=[];function i_(l,m,E,D){return E>>>=0,D>>>=0,(l=Dp[l>>>0])(null,m=Cr(m>>>0),E,D)}var o_={},Lp=l=>{var m=o_[l];return m===void 0?cn(l):m};function a_(l,m,E,D,G){return E>>>=0,D>>>=0,G>>>=0,(l=Dp[l>>>0])(m=Cr(m>>>0),m[E=Lp(E)],D,G)}var Om=()=>typeof globalThis=="object"?globalThis:Function("return this")();function l_(l){return(l>>>=0)==0?zr(Om()):(l=Lp(l),zr(Om()[l]))}var u_=l=>{var m=Dp.length;return Dp.push(l),m},d_=(l,m)=>{for(var E=Array(l),D=0;D>>2>>>0],"parameter "+D);return E},Fm=(l,m)=>Object.defineProperty(m,"name",{value:l});function c_(l,m,E){var D=(m=d_(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { +`,ge=0,Xe=[];E===0&&Xe.push("obj");for(var nt=["retType"],wt=[D],Ct=0;CtWt.name).join(", ")}) => ${D.name}>`,u_(Fm(E,l))}function p_(l){return l=Lp(l>>>0),zr(d[l])}function h_(l,m){return m>>>=0,l=Cr(l>>>0),m=Cr(m),zr(l[m])}function m_(l){9<(l>>>=0)&&(Cn[l+1]+=1)}function f_(){return zr([])}function __(l){l=Cr(l>>>0);for(var m=Array(l.length),E=0;E>>0))}function w_(){return zr({})}function y_(l){for(var m=Cr(l>>>=0);m.length;){var E=m.pop();m.pop()(E)}_h(l)}function M_(l,m,E){m>>>=0,E>>>=0,l=Cr(l>>>0),m=Cr(m),E=Cr(E),l[m]=E}function b_(l,m){return m>>>=0,l=(l=Ip(l>>>0,"_emval_take_value")).readValueFromPointer(m),zr(l)}function v_(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 Aa=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 x_(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 E=(Aa(l.getFullYear())?Dm:Lm)[l.getMonth()]+l.getDate()-1|0;o()[m+28>>>2>>>0]=E,o()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),E=new Date(l.getFullYear(),6,1).getTimezoneOffset();var D=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(E!=D&&l.getTimezoneOffset()==Math.min(D,E)),o()[m+32>>>2>>>0]=l}function T_(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),E=o()[l+32>>>2>>>0],D=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),ge=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Xe=Math.min(ge,G);return 0>E?o()[l+32>>>2>>>0]=+(G!=ge&&Xe==D):0>>2>>>0]=m.getDay(),E=(Aa(m.getFullYear())?Dm:Lm)[m.getMonth()]+m.getDate()-1|0,o()[l+28>>>2>>>0]=E,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,E,D,G,ge,Xe){return Z?Rs(16,1,l,m,E,D,G,ge,Xe):-52}function Bm(l,m,E,D,G,ge){if(Z)return Rs(17,1,l,m,E,D,G,ge)}function E_(l,m,E,D){l>>>=0,m>>>=0,E>>>=0,D>>>=0;var G=new Date().getFullYear(),ge=new Date(G,0,1),Xe=new Date(G,6,1);G=ge.getTimezoneOffset();var nt=Xe.getTimezoneOffset(),wt=Math.max(G,nt);u()[l>>>2>>>0]=60*wt,o()[m>>>2>>>0]=+(G!=nt),ge=(l=Ct=>Ct.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ge),Xe=l(Xe),nt{bh.length=0;for(var E;E=n()[l++>>>0];){var D=E!=105;m+=(D&=E!=112)&&m%8?4:0,bh.push(E==112?u()[m>>>2>>>0]:E==106?er[m>>>3]:E==105?o()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=D?8:4}return bh};function P_(l,m,E){return l>>>=0,m=Rm(m>>>0,E>>>0),ah[l](...m)}function C_(l,m,E){return l>>>=0,m=Rm(m>>>0,E>>>0),ah[l](...m)}var k_=()=>{},S_=()=>Date.now();function $_(l,m){return bt(Hs(l>>>0,m>>>0))}var Nm,A_=()=>{throw Fi+=1,"unwind"};function I_(){return 4294901760}Nm=()=>performance.timeOrigin+performance.now();var O_=()=>navigator.hardwareConcurrency;function F_(){return Yn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function D_(l){l>>>=0;var m=n().length;if(l<=m||4294901760=E;E*=2){var D=m*(1+.2/E);D=Math.min(D,l+100663296);var G=Math;D=Math.max(l,D);e:{G=(G.min.call(G,4294901760,D+(65536-D%65536)%65536)-Ft.buffer.byteLength+65535)/65536;try{Ft.grow(G),Es();var ge=1;break e}catch{}ge=void 0}if(ge)return!0}return!1}var zp=()=>(Yn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Bc={},jm=l=>{l.forEach(m=>{zp()})};function L_(){var l=Error().stack.toString().split(` +`);return l[0]=="Error"&&l.shift(),jm(l),Bc.Qb=zp(),Bc.fc=l,Bc.Qb}function z_(l,m,E){if(l>>>=0,m>>>=0,Bc.Qb==l)var D=Bc.fc;else(D=Error().stack.toString().split(` +`))[0]=="Error"&&D.shift(),jm(D);for(var G=3;D[G]&&zp()!=l;)++G;for(l=0;l>>2>>>0]=zp();return l}var vh,xh={},Um=()=>{if(!vh){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",_:De};for(l in xh)xh[l]===void 0?delete m[l]:m[l]=xh[l];var E=[];for(l in m)E.push(`${l}=${m[l]}`);vh=E}return vh};function Vm(l,m){if(Z)return Rs(18,1,l,m);l>>>=0,m>>>=0;var E=0;return Um().forEach((D,G)=>{var ge=m+E;for(G=u()[l+4*G>>>2>>>0]=ge,ge=0;ge>>0]=D.charCodeAt(ge);s()[G>>>0]=0,E+=D.length+1}),0}function Wm(l,m){if(Z)return Rs(19,1,l,m);l>>>=0,m>>>=0;var E=Um();u()[l>>>2>>>0]=E.length;var D=0;return E.forEach(G=>D+=G.length+1),u()[m>>>2>>>0]=D,0}function Gm(l){return Z?Rs(20,1,l):52}function Km(l,m,E,D){return Z?Rs(21,1,l,m,E,D):52}function Hm(l,m,E,D){return Z?Rs(22,1,l,m,E,D):70}var B_=[null,[],[]];function qm(l,m,E,D){if(Z)return Rs(23,1,l,m,E,D);m>>>=0,E>>>=0,D>>>=0;for(var G=0,ge=0;ge>>2>>>0],nt=u()[m+4>>>2>>>0];m+=8;for(var wt=0;wt>>0],Wt=B_[l];Ct===0||Ct===10?((l===1?Zt:bt)(um(Wt,0)),Wt.length=0):Wt.push(Ct)}G+=nt}return u()[D>>>2>>>0]=G,0}var Qm=[31,29,31,30,31,30,31,31,30,31,30,31],Xm=[31,28,31,30,31,30,31,31,30,31,30,31],R_=(l,m)=>{s().set(l,m>>>0)};function Ym(l,m,E,D){function G(He,ls,js){for(He=typeof He=="number"?He.toString():He||"";He.lengthpf?-1:0Li-He.getDate())){He.setDate(He.getDate()+ls);break}ls-=Li-He.getDate()+1,He.setDate(1),11>js?He.setMonth(js+1):(He.setMonth(0),He.setFullYear(He.getFullYear()+1))}return js=new Date(He.getFullYear()+1,0,4),ls=nt(new Date(He.getFullYear(),0,4)),js=nt(js),0>=Xe(ls,He)?0>=Xe(js,He)?He.getFullYear()+1:He.getFullYear():He.getFullYear()-1}l>>>=0,m>>>=0,E>>>=0,D>>>=0;var Ct=u()[D+40>>>2>>>0];for(var Wt in D={lc:o()[D>>>2>>>0],kc:o()[D+4>>>2>>>0],Ib:o()[D+8>>>2>>>0],Mb:o()[D+12>>>2>>>0],Jb:o()[D+16>>>2>>>0],Db:o()[D+20>>>2>>>0],vb:o()[D+24>>>2>>>0],Cb:o()[D+28>>>2>>>0],sc:o()[D+32>>>2>>>0],jc:o()[D+36>>>2>>>0],mc:Ct?Hs(Ct):""},E=Hs(E),Ct={"%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"})E=E.replace(new RegExp(Wt,"g"),Ct[Wt]);var ps="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),vs="January February March April May June July August September October November December".split(" ");for(Wt in Ct={"%a":He=>ps[He.vb].substring(0,3),"%A":He=>ps[He.vb],"%b":He=>vs[He.Jb].substring(0,3),"%B":He=>vs[He.Jb],"%C":He=>ge((He.Db+1900)/100|0,2),"%d":He=>ge(He.Mb,2),"%e":He=>G(He.Mb,2," "),"%g":He=>wt(He).toString().substring(2),"%G":wt,"%H":He=>ge(He.Ib,2),"%I":He=>((He=He.Ib)==0?He=12:12{for(var ls=0,js=0;js<=He.Jb-1;ls+=(Aa(He.Db+1900)?Qm:Xm)[js++]);return ge(He.Mb+ls,3)},"%m":He=>ge(He.Jb+1,2),"%M":He=>ge(He.kc,2),"%n":()=>` +`,"%p":He=>0<=He.Ib&&12>He.Ib?"AM":"PM","%S":He=>ge(He.lc,2),"%t":()=>" ","%u":He=>He.vb||7,"%U":He=>ge(Math.floor((He.Cb+7-He.vb)/7),2),"%V":He=>{var ls=Math.floor((He.Cb+7-(He.vb+6)%7)/7);if(2>=(He.vb+371-He.Cb-2)%7&&ls++,ls)ls==53&&((js=(He.vb+371-He.Cb)%7)==4||js==3&&Aa(He.Db)||(ls=1));else{ls=52;var js=(He.vb+7-He.Cb-1)%7;(js==4||js==5&&Aa(He.Db%400-1))&&ls++}return ge(ls,2)},"%w":He=>He.vb,"%W":He=>ge(Math.floor((He.Cb+7-(He.vb+6)%7)/7),2),"%y":He=>(He.Db+1900).toString().substring(2),"%Y":He=>He.Db+1900,"%z":He=>{var ls=0<=(He=He.jc);return He=Math.abs(He)/60,(ls?"+":"-")+("0000"+(He/60*100+He%60)).slice(-4)},"%Z":He=>He.mc,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0"),Ct)E.includes(Wt)&&(E=E.replace(new RegExp(Wt,"g"),Ct[Wt](D)));return Wt=function(He){var ls=Array(ph(He)+1);return pm(He,ls,0,ls.length),ls}(E=E.replace(/\0\0/g,"%")),Wt.length>m?0:(R_(Wt,l),Wt.length-1)}function N_(l,m,E,D){return Ym(l>>>0,m>>>0,E>>>0,D>>>0)}Z||function(){for(var l=d.numThreads-1;l--;)im();Xn.unshift(()=>{Lc++,function(m){Z?m():Promise.all(Jn.map(nm)).then(m)}(()=>Hh())})}();for(var Jm=Array(256),Bp=0;256>Bp;++Bp)Jm[Bp]=String.fromCharCode(Bp);Tm=Jm,Zn=d.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},d.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},Cn.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>Cn.length/2-5-fh.length;var j_=[dh,em,om,dm,cm,hm,mm,fm,_m,gm,wm,ym,Mm,bm,vm,xm,zm,Bm,Vm,Wm,Gm,Km,Hm,qm],Ut=function(){function l(E,D){return Ut=E.exports,Ut=function(){var G=Ut,ge={};for(let[Xe,nt]of Object.entries(G))ge[Xe]=typeof nt=="function"?(...wt)=>{Fp.push(Xe);try{return nt(...wt)}finally{Bs||(Fp.pop(),pn&&ti===1&&Fp.length===0&&(ti=0,Fi+=1,Op(lf),typeof Fibers<"u"&&Fibers.tc()))}}:nt;return ge}(),Ut=function(){var G=Ut,ge=nt=>wt=>nt(wt)>>>0,Xe=nt=>()=>nt()>>>0;return(G=Object.assign({},G)).Da=ge(G.Da),G.gb=Xe(G.gb),G.ib=ge(G.ib),G.emscripten_main_runtime_thread_id=Xe(G.emscripten_main_runtime_thread_id),G.tb=ge(G.tb),G.ub=Xe(G.ub),G}(),tm.push(Ut.jb),Dc.unshift(Ut.Ca),bs=D,Hh(),Ut}var m=Jh();if(Lc++,d.instantiateWasm)try{return d.instantiateWasm(m,l)}catch(E){bt(`Module.instantiateWasm callback failed with error: ${E}`),P(E)}return oh||(oh=d.locateFile?qh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":d.locateFile?d.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ye):Ye+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(E,D){var G=oh;return at||typeof WebAssembly.instantiateStreaming!="function"||qh(G)||Qh(G)||typeof fetch!="function"?Yh(G,E,D):fetch(G,{credentials:"same-origin"}).then(ge=>WebAssembly.instantiateStreaming(ge,E).then(D,function(Xe){return bt(`wasm streaming compile failed: ${Xe}`),bt("falling back to ArrayBuffer instantiation"),Yh(G,E,D)}))}(m,function(E){l(E.instance,E.module)}).catch(P),{}}(),Zm=l=>(Zm=Ut.Da)(l),ef=()=>(ef=Ut.Ea)();d._OrtInit=(l,m)=>(d._OrtInit=Ut.Fa)(l,m),d._OrtGetLastError=(l,m)=>(d._OrtGetLastError=Ut.Ga)(l,m),d._OrtCreateSessionOptions=(l,m,E,D,G,ge,Xe,nt,wt,Ct)=>(d._OrtCreateSessionOptions=Ut.Ha)(l,m,E,D,G,ge,Xe,nt,wt,Ct),d._OrtAppendExecutionProvider=(l,m)=>(d._OrtAppendExecutionProvider=Ut.Ia)(l,m),d._OrtAddFreeDimensionOverride=(l,m,E)=>(d._OrtAddFreeDimensionOverride=Ut.Ja)(l,m,E),d._OrtAddSessionConfigEntry=(l,m,E)=>(d._OrtAddSessionConfigEntry=Ut.Ka)(l,m,E),d._OrtReleaseSessionOptions=l=>(d._OrtReleaseSessionOptions=Ut.La)(l),d._OrtCreateSession=(l,m,E)=>(d._OrtCreateSession=Ut.Ma)(l,m,E),d._OrtReleaseSession=l=>(d._OrtReleaseSession=Ut.Na)(l),d._OrtGetInputOutputCount=(l,m,E)=>(d._OrtGetInputOutputCount=Ut.Oa)(l,m,E),d._OrtGetInputName=(l,m)=>(d._OrtGetInputName=Ut.Pa)(l,m),d._OrtGetOutputName=(l,m)=>(d._OrtGetOutputName=Ut.Qa)(l,m),d._OrtFree=l=>(d._OrtFree=Ut.Ra)(l),d._OrtCreateTensor=(l,m,E,D,G,ge)=>(d._OrtCreateTensor=Ut.Sa)(l,m,E,D,G,ge),d._OrtGetTensorData=(l,m,E,D,G)=>(d._OrtGetTensorData=Ut.Ta)(l,m,E,D,G),d._OrtReleaseTensor=l=>(d._OrtReleaseTensor=Ut.Ua)(l),d._OrtCreateRunOptions=(l,m,E,D)=>(d._OrtCreateRunOptions=Ut.Va)(l,m,E,D),d._OrtAddRunConfigEntry=(l,m,E)=>(d._OrtAddRunConfigEntry=Ut.Wa)(l,m,E),d._OrtReleaseRunOptions=l=>(d._OrtReleaseRunOptions=Ut.Xa)(l),d._OrtCreateBinding=l=>(d._OrtCreateBinding=Ut.Ya)(l),d._OrtBindInput=(l,m,E)=>(d._OrtBindInput=Ut.Za)(l,m,E),d._OrtBindOutput=(l,m,E,D)=>(d._OrtBindOutput=Ut._a)(l,m,E,D),d._OrtClearBoundOutputs=l=>(d._OrtClearBoundOutputs=Ut.$a)(l),d._OrtReleaseBinding=l=>(d._OrtReleaseBinding=Ut.ab)(l),d._OrtRunWithBinding=(l,m,E,D,G)=>(d._OrtRunWithBinding=Ut.bb)(l,m,E,D,G),d._OrtRun=(l,m,E,D,G,ge,Xe,nt)=>(d._OrtRun=Ut.cb)(l,m,E,D,G,ge,Xe,nt),d._OrtEndProfiling=l=>(d._OrtEndProfiling=Ut.db)(l),d._JsepOutput=(l,m,E)=>(d._JsepOutput=Ut.eb)(l,m,E),d._JsepGetNodeName=l=>(d._JsepGetNodeName=Ut.fb)(l);var Rp,Ia=()=>(Ia=Ut.gb)(),hn=d._free=l=>(hn=d._free=Ut.hb)(l),Np=d._malloc=l=>(Np=d._malloc=Ut.ib)(l),Th=(l,m,E,D,G,ge)=>(Th=Ut.lb)(l,m,E,D,G,ge),tf=()=>(tf=Ut.mb)(),sf=(l,m,E,D,G)=>(sf=Ut.nb)(l,m,E,D,G),Eh=l=>(Eh=Ut.ob)(l),jp=l=>(jp=Ut.pb)(l),rf=()=>(rf=Ut.qb)(),nf=(l,m)=>(nf=Ut.rb)(l,m),Up=l=>(Up=Ut.sb)(l),Ph=l=>(Ph=Ut.tb)(l),Ch=()=>(Ch=Ut.ub)(),of=d.dynCall_ii=(l,m)=>(of=d.dynCall_ii=Ut.wb)(l,m),af=l=>(af=Ut.xb)(l),lf=()=>(lf=Ut.yb)(),uf=l=>(uf=Ut.zb)(l),df=()=>(df=Ut.Ab)();function cf(){0Ch(),d.stackRestore=l=>Up(l),d.stackAlloc=l=>Ph(l),d.setValue=function(l,m,E="i8"){switch(E.endsWith("*")&&(E="*"),E){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":er[l>>>3]=BigInt(m);break;case"float":p()[l>>>2>>>0]=m;break;case"double":h()[l>>>3>>>0]=m;break;case"*":u()[l>>>2>>>0]=m;break;default:Yn(`invalid type for setValue: ${E}`)}},d.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 er[l>>>3];case"float":return p()[l>>>2>>>0];case"double":return h()[l>>>3>>>0];case"*":return u()[l>>>2>>>0];default:Yn(`invalid type for getValue: ${m}`)}},d.UTF8ToString=Hs,d.stringToUTF8=$a,d.lengthBytesUTF8=ph,zc=function l(){Rp||cf(),Rp||(zc=l)},cf(),d.PTR_SIZE=4,z}),Ds=ks,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&ks()}),kr,Qr,Us,xr,Nt,Xr,Sr,$r,Yr,cr,Jr,Ar,Br,Rr=g(()=>{Je(),kr=typeof location>"u"?void 0:location.origin,Qr=()=>{var e;return(e=import.meta.url)!=null&&e.startsWith("file:")?new URL(new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b).href,kr).href:import.meta.url},Us=Qr(),xr=()=>{if(Us&&!Us.startsWith("blob:"))return Us.substring(0,Us.lastIndexOf("/")+1)},Nt=(e,t)=>{try{let s=t??Us;return(s?new URL(e,s):new URL(e)).origin===kr}catch{return!1}},Xr=(e,t)=>{let s=t??Us;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},Sr=(e,t)=>`${t??"./"}${e}`,$r=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Yr=async e=>(await import(e)).default,cr=(At(),M(ut)).default,Jr=async()=>{if(!Us)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nt(Us))return[void 0,cr()];let e=await $r(Us);return[e,cr(e)]},Ar=(sr(),M(is)).default,Br=async(e,t,s)=>{if(!e&&!t&&Ar&&Us&&Nt(Us))return[void 0,Ar];{let n="ort-wasm-simd-threaded.jsep.mjs",i=e??Xr(n,t),a=s&&i&&!Nt(i,t),o=a?await $r(i):i??Sr(n,t);return[a?o:void 0,await Yr(o)]}}}),or,it,Tt,Dt,Vs,Nr,Ir,Ms,ar=g(()=>{Rr(),it=!1,Tt=!1,Dt=!1,Vs=()=>{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}},Nr=()=>{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}},Ir=async e=>{if(it)return Promise.resolve();if(Tt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Dt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Tt=!0;let t=e.initTimeout,s=e.numThreads;if(!Nr())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Vs();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,u=(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,[P,d]=await Br(u,a,s>1),z=!1,B=[];if(t>0&&B.push(new Promise(V=>{setTimeout(()=>{z=!0,V()},t)})),B.push(new Promise((V,Z)=>{let ee={numThreads:s};if(k)ee.wasmBinary=k;else if(h||a)ee.locateFile=Q=>h??a+Q;else if(u&&u.indexOf("blob:")!==0)ee.locateFile=Q=>new URL(Q,u).href;else if(P){let Q=xr();Q&&(ee.locateFile=he=>Q+he)}d(ee).then(Q=>{Tt=!1,it=!0,or=Q,V(),P&&URL.revokeObjectURL(P)},Q=>{Tt=!1,Dt=!0,Z(Q)})})),await Promise.race(B),z)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ms=()=>{if(it&&or)return or;throw new Error("WebAssembly is not initialized yet.")}}),Is,Tr,ts,mn=g(()=>{ar(),Is=(e,t)=>{let s=Ms(),n=s.lengthBytesUTF8(e)+1,i=s._malloc(n);return s.stringToUTF8(e,i,n),t.push(i),i},Tr=(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")Tr(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=Ms(),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,"*"),u=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(s)}}}),jr,si=g(()=>{ar(),mn(),jr=e=>{let t=Ms(),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=Is(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&&Tr(e.extra,"",new WeakSet,(o,u)=>{let p=Is(o,n),h=Is(u,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&ts(`Can't set a run config entry: ${o} - ${u}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(o=>t._free(o)),a}}}),An,In,On,Ur,Fn,ri=g(()=>{ar(),mn(),An=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}`)}},In=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},On=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)},Ur=(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 u=Is("deviceType",s),p=Is(o,s);Ms()._OrtAddSessionConfigEntry(e,u,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 u=Is("preferredLayout",s),p=Is(o.preferredLayout,s);Ms()._OrtAddSessionConfigEntry(e,u,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=Is(i,s);Ms()._OrtAppendExecutionProvider(e,a)!==0&&ts(`Can't append execution provider: ${i}.`)}},Fn=e=>{let t=Ms(),s=0,n=[],i=e||{};On(i);try{let a=An(i.graphOptimizationLevel??"all"),o=In(i.executionMode??"sequential"),u=typeof i.logId=="string"?Is(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"?Is(i.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,u,p,h,k),s===0&&ts("Can't create session options."),i.executionProviders&&Ur(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 P=Is("enableGraphCapture",n),d=Is(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,P,d)!==0&&ts(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[P,d]of Object.entries(i.freeDimensionOverrides)){if(typeof P!="string")throw new Error(`free dimension override name must be a string: ${P}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let z=Is(P,n);t._OrtAddFreeDimensionOverride(s,z,d)!==0&&ts(`Can't set a free dimension override: ${P} - ${d}.`)}return i.extra!==void 0&&Tr(i.extra,"",new WeakSet,(P,d)=>{let z=Is(P,n),B=Is(d,n);t._OrtAddSessionConfigEntry(s,z,B)!==0&&ts(`Can't set a session config entry: ${P} - ${d}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&ts("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Vr,fr,lr,fn,Zr,_n,gn,wn,zt=g(()=>{Vr=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}`)}},fr=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}`)}},lr=(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}`)}},Zr=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",gn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",wn=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}`)}}}),yn,Dn=g(()=>{Je(),yn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let 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(u){if(u instanceof RangeError){let p=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw u}let o=0;for(;;){let{done:u,value:p}=await i.read();if(u)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)}}),Ln,zn,Wr,Bn,Mn,Rn,as,Pe=g(()=>{zt(),Ln=["V","I","W","E","F"],zn=(e,t)=>{console.log(`[${Ln[e]},${new Date().toISOString()}]${t}`)},Mn=(e,t)=>{Wr=e,Bn=t},Rn=(e,t)=>{let s=Zr(e),n=Zr(Wr);s>=n&&zn(s,typeof t=="function"?t():t)},as=(...e)=>{Bn&&Rn(...e)}}),C,q=g(()=>{zt(),C=(e,t)=>new(fn(t))(e)}),ue=g(()=>{}),be,$e,Qe,pt,gt,ft,xt,Kt,hs,us=g(()=>{Pe(),ue(),be=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]]),$e=[],Qe=e=>Math.ceil(Number(e)/16)*16,pt=e=>{for(let t=0;t<$e.length;t++){let s=$e[t];if(e<=s)return s}return Math.ceil(e/16)*16},gt=1,ft=()=>gt++,xt=async(e,t,s,n)=>{let i=Qe(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 u=a.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(u,0,s)),p}else return new Uint8Array(u.slice(0,s))}finally{a.destroy()}},Kt=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 be)$e.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=Qe(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 u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=u.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,i)),u.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(u,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([h.finish()]),u.destroy(),as("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=Qe(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 as("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=ft();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),as("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),as("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=pt(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let u=(i?this.freeBuffers:this.freeUniformBuffers).get(s);u?u.length>0?n=u.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:ft(),type:0,buffer:n};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),as("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 as("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 xt(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=be.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&&(as("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},hs=(...e)=>new Kt(...e)}),Fs,Bt,rs=g(()=>{Fs=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}},Bt=e=>new Fs(e)}),rr,Ws,ze,Js,Or,Ss,qs,Ot=g(()=>{rr=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Ws=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 u=rr.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(u===void 0)return;[o[a-2],o[a-1]]=u}for(let u=s?3:1;u<=a;u++){let p=n-u<0?1:e[n-u],h=i-u<0?1:t[i-u];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)o[a-u]=Math.max(p,h);else{if(k>1)return;o[a-u]=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}},ze=class Vp{static size(t){return Vp.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 Vp.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 Vp.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])}},Js=class Rc{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 u=0;u=n.length?n.push(s[u+2]):n[u]=s[u+2];for(let u=0;u=n[u]||o[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,n,i,a,o,u){if(u){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(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{zt(),Ot(),nr=64,_r=(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}`)}},ms=(e,t=1)=>{let s=_r(e,t);return typeof s=="string"?s:s[0]},$s=(e,t=1)=>{let s=_r(e,t);return typeof s=="string"?s:s[1]},yt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:ze.computeStrides(s)})}),t},qt=e=>e%4===0?4:e%2===0?2:1,Ls=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,As=(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,$t=(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,en=(e,t,s,n,i)=>{let a=typeof s=="number",o=a?s:s.length,u=[...new Array(o).keys()],p=o<2?"u32":o<=4?`vec${o}`:`array`,h=_r(t,i),k=typeof h=="string"?h:h[1],P=typeof h=="string"?h:h[0],d={indices:p,value:k,storage:P,tensor:t},z=ot=>typeof ot=="string"?ot:`${ot}u`,B={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},V=a?"uniforms.":"",Z=`${V}${e}_shape`,ee=`${V}${e}_strides`,Q="";for(let ot=0;ot ${d.indices} { + var indices: ${d.indices}; + var current = offset; + ${Q} + return indices; + }`,pe=ot=>(B.offsetToIndices=!0,o<2?ot:`o2i_${e}(${ot})`),Me=[];if(o>=2)for(let ot=o-1;ot>=0;ot--)Me.push(`${$t(ee,ot,o)} * (indices[${ot}])`);let De=o<2?"":` + fn i2o_${e}(indices: ${d.indices}) -> u32 { + return ${Me.join("+")}; + }`,Le=ot=>(B.indicesToOffset=!0,o<2?ot:`i2o_${e}(${ot})`),Ye=(...ot)=>o===0?"0u":`${d.indices}(${ot.map(z).join(",")})`,at=(ot,Pt)=>o<2?`${ot}`:`${$t(ot,Pt,o)}`,Et=(ot,Pt,cs)=>o<2?`${ot}=${cs};`:`${$t(ot,Pt,o)}=${cs};`,Xt={},Zt=(ot,Pt)=>{B.broadcastedIndicesToOffset=!0;let cs=`${Pt.name}broadcastedIndicesTo${e}Offset`;if(cs in Xt)return`${cs}(${ot})`;let Ns=[];for(let vr=o-1;vr>=0;vr--){let er=Pt.indicesGet("outputIndices",vr+Pt.rank-o);Ns.push(`${at(ee,vr)} * (${er} % ${at(Z,vr)})`)}return Xt[cs]=`fn ${cs}(outputIndices: ${Pt.type.indices}) -> u32 { + return ${Ns.length>0?Ns.join("+"):"0u"}; + }`,`${cs}(${ot})`},bt=(ot,Pt)=>(()=>{if(d.storage===d.value)return`${e}[${ot}]=${Pt};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${ot}]=vec2(u32(${Pt}), select(0u, 0xFFFFFFFFu, ${Pt} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${ot}]=vec2(u32(${Pt}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${ot}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Pt}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),ss=ot=>(()=>{if(d.storage===d.value)return`${e}[${ot}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${ot}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${ot}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${ot}] & 0xFFu), bool(${e}[${ot}] & 0xFF00u), bool(${e}[${ot}] & 0xFF0000u), bool(${e}[${ot}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),St=o<2?"":` + fn get_${e}ByIndices(indices: ${d.indices}) -> ${k} { + return ${ss(`i2o_${e}(indices)`)}; + }`,Ft=o<2?"":(()=>{let ot=u.map(cs=>`d${cs}: u32`).join(", "),Pt=u.map(cs=>`d${cs}`).join(", ");return` + fn get_${e}(${ot}) -> ${k} { + return get_${e}ByIndices(${Ye(Pt)}); + }`})(),bs=(...ot)=>{if(ot.length!==o)throw new Error(`indices length must be ${o}`);let Pt=ot.map(z).join(",");return o===0?ss("0u"):o===1?ss(Pt[0]):(B.get=!0,B.getByIndices=!0,B.indicesToOffset=!0,`get_${e}(${Pt})`)},Ht=ot=>o<2?ss(ot):(B.getByIndices=!0,B.indicesToOffset=!0,`get_${e}ByIndices(${ot})`),Rt=o<2?"":` + fn set_${e}ByIndices(indices: ${d.indices}, value: ${k}) { + ${bt(`i2o_${e}(indices)`,"value")} + }`,_s=o<2?"":(()=>{let ot=u.map(cs=>`d${cs}: u32`).join(", "),Pt=u.map(cs=>`d${cs}`).join(", ");return` + fn set_${e}(${ot}, value: ${k}) { + set_${e}ByIndices(${Ye(Pt)}, value); + }`})();return{impl:()=>{let ot=[],Pt=!1;return B.offsetToIndices&&(ot.push(he),Pt=!0),B.indicesToOffset&&(ot.push(De),Pt=!0),B.broadcastedIndicesToOffset&&(Object.values(Xt).forEach(cs=>ot.push(cs)),Pt=!0),B.set&&(ot.push(_s),Pt=!0),B.setByIndices&&(ot.push(Rt),Pt=!0),B.get&&(ot.push(Ft),Pt=!0),B.getByIndices&&(ot.push(St),Pt=!0),!a&&Pt&&ot.unshift(`const ${Z} = ${d.indices}(${s.join(",")});`,`const ${ee} = ${d.indices}(${ze.computeStrides(s).join(",")});`),ot.join(` +`)},type:d,offsetToIndices:pe,indicesToOffset:Le,broadcastedIndicesToOffset:Zt,indices:Ye,indicesGet:at,indicesSet:Et,set:(...ot)=>{if(ot.length!==o+1)throw new Error(`indices length must be ${o}`);let Pt=ot[o];if(typeof Pt!="string")throw new Error("value must be string");let cs=ot.slice(0,o).map(z).join(",");return o===0?bt("0u",Pt):o===1?bt(cs[0],Pt):(B.set=!0,B.setByIndices=!0,B.indicesToOffset=!0,`set_${e}(${cs}, ${Pt})`)},setByOffset:bt,setByIndices:(ot,Pt)=>o<2?bt(ot,Pt):(B.setByIndices=!0,B.indicesToOffset=!0,`set_${e}ByIndices(${ot}, ${Pt});`),get:bs,getByOffset:ss,getByIndices:Ht,usage:n,name:e,strides:ee,shape:Z,rank:o}},qe=(e,t,s,n=1)=>en(e,t,s,"input",n),It=(e,t,s,n=1)=>en(e,t,s,"output",n),Da=(e,t,s)=>en(e,t,s,"atomicOutput",1),zi=(e,t,s,n=1)=>en(e,t,s,"internal",n),La=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=nr){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])}},za=(e,t)=>new La(e,t)}),Ba,Bi,Ri,Ra,Na,Ni,pr,ja,ji,Gr=g(()=>{zt(),Ot(),rs(),Yt(),Ba=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},Bi=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Ri=(e,t)=>ze.sortBasedOnPerm(e,Bi(e.length,t)),Ra=(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=Bi(n,t),a=Ri(e.dims,i),o=e.dims,u=a,p=n<2||Ni(i,e.dims),h;if(p)return h=B=>{let V=qe("input",s,o,4),Z=It("output",s,u,4);return` + ${B.registerUniform("output_size","u32").declareVariables(V,Z)} + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let B=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(B/64/4)},programUniforms:[{type:12,data:Math.ceil(B/4)}]}},getShaderSource:h};let{newShape:k,newPerm:P}=Na(e.dims,i),d=ze.areEqual(P,[2,3,1]),z=ze.areEqual(P,[3,1,2]);if(k.length===2||d||z){o=d?[k[0],k[1]*k[2]]:z?[k[0]*k[1],k[2]]:k,u=[o[1],o[0]];let B=16;return h=V=>{let Z=qe("a",s,o.length),ee=It("output",s,u.length);return` + ${V.registerUniform("output_size","u32").declareVariables(Z,ee)} + var tile : array, ${B}>; + ${V.mainStart([B,B,1])} + let stride = (uniforms.output_shape[1] - 1) / ${B} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${B}u + local_id.x; + let input_row = workgroup_id_x * ${B}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 * ${B}u + local_id.x; + let output_row = workgroup_id_y * ${B}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${ee.setByIndices(`${ee.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let V=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/B),y:Math.ceil(u[0]/B)},programUniforms:[{type:12,data:V},...yt(o,u)]}},getShaderSource:h}}return h=B=>{let V=qe("a",s,o.length),Z=It("output",s,u.length);return` + ${B.registerUniform("output_size","u32").declareVariables(V,Z)} + + ${Ra(i,n,V,Z)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${Z.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${Z.setByOffset("global_idx",V.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let B=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...yt(o,u)]}},getShaderSource:h}},ja=(e,t)=>{Ba(e.inputs,t.perm),e.compute(pr(e.inputs[0],t.perm))},ji=e=>Bt({perm:e.perm})}),ni,Ua,Va,Wa,Ga,Ka,Ha,qa,Ui,Qa,hr,tn,Xa,Vc,Ya,Wc,Ja,Vi,Za,el,tl,Gc=g(()=>{zt(),Ot(),Yt(),ai(),Gr(),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"},Ua={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"},Va={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)"},Ga=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let a=0;ae[a]);return[s,i]},Ha=(e,t)=>{let s=e.length+t.length,n=[],i=0;for(let a=0;a{for(let s=0;s{let s=[];if(!qa(e,t)){for(let n=0;ns.push(n))}return s},Qa=(e,t,s,n,i,a,o)=>{let u=s[0].dims,p=ze.size(a),h=ze.size(o),k=qe("_A",s[0].dataType,u),P=It("output",i,a),d=64;p===1&&(d=256);let z=` + var aBestValues : array; + `,B=V=>` + ${V.registerUniform("reduceSize","u32").declareVariables(k,P)} + ${z} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${V.mainStart(d)} + + let outputIndex = global_idx / ${d}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Va[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${d}) { + let candidate = f32(${k.getByOffset("offset + k")}); + bestValue = ${ni[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${d}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 = ${Ua[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${P.setByOffset("outputIndex",`${n==="mean"?`${P.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${P.type.storage}(${Wa[n]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${t};${d}`,inputDependencies:["type"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},hr=(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((z,B)=>B));let o=ze.normalizeAxes(a,e.inputs[0].dims.length),u=o,p=e.inputs[0],h=Ui(u,e.inputs[0].dims.length);h.length>0&&(p=e.compute(pr(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],u=Ga(u.length,p.dims.length));let[k,P]=Ka(p.dims,u),d=k;i.keepDims&&(d=Ha(k,o)),e.compute(Qa(t,i.cacheKey,[p],n,e.inputs[0].dataType,d,P),{inputs:[p]})},tn=(e,t)=>{hr(e,"ReduceMeanShared",t,"mean")},Xa=(e,t)=>{hr(e,"ReduceL1Shared",t,"l1")},Vc=(e,t)=>{hr(e,"ReduceL2Shared",t,"l2")},Ya=(e,t)=>{hr(e,"ReduceLogSumExpShared",t,"logSumExp")},Wc=(e,t)=>{hr(e,"ReduceMaxShared",t,"max")},Ja=(e,t)=>{hr(e,"ReduceMinShared",t,"min")},Vi=(e,t)=>{hr(e,"ReduceProdShared",t,"prod")},Za=(e,t)=>{hr(e,"ReduceSumShared",t,"sum")},el=(e,t)=>{hr(e,"ReduceSumSquareShared",t,"sumSquare")},tl=(e,t)=>{hr(e,"ReduceLogSumShared",t,"logSum")}}),gr,ii,oi,Wi,wr,Gi,sl,rl,Ki,nl,il,Hi,ol,al,qi,yr,ll,Qi,ul,dl,Xi,cl,pl,Yi,hl,ml,ai=g(()=>{zt(),Ot(),rs(),Yt(),Gc(),gr=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,u=!1)=>{let p=[],h=s[0].dims,k=h.length,P=ze.normalizeAxes(i,k),d=!u&&P.length===0;h.forEach((V,Z)=>{d||P.indexOf(Z)>=0?o&&p.push(1):p.push(V)});let z=p.length,B=ze.size(p);return{name:e,shaderCache:t,getShaderSource:V=>{let Z=[],ee=qe("_A",s[0].dataType,k),Q=It("output",a,z),he=n(ee,Q,P),pe=he[2];for(let Me=0,De=0;Me=0?(o&&De++,pe=`for(var j${Me}: u32 = 0; j${Me} < ${h[Me]}; j${Me}++) { + ${he[2].includes("last_index")?`let last_index = j${Me};`:""} + ${ee.indicesSet("input_indices",Me,`j${Me}`)} + ${pe} + }`):(Z.push(`${ee.indicesSet("input_indices",Me,Q.indicesGet("output_indices",De))};`),De++);return` + + ${V.registerUniform("output_size","u32").declareVariables(ee,Q)} + + ${V.mainStart()} + ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${ee.type.indices}; + let output_indices = ${Q.offsetToIndices("global_idx")}; + + ${Z.join(` +`)} + ${he[0]} // init ops for reduce max/min + ${he[1]} + ${pe} + ${he[3]} + ${he.length===4?Q.setByOffset("global_idx","value"):he.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...yt(h,p)]})}},Wi=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),Bt({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},wr=(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]})},Gi=(e,t)=>{gr(e.inputs),wr(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},sl=(e,t)=>{gr(e.inputs),wr(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},rl=(e,t)=>{gr(e.inputs),wr(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);"])},Ki=(e,t)=>{gr(e.inputs),wr(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},nl=(e,t)=>{gr(e.inputs),wr(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")});`,""]})},il=(e,t)=>{gr(e.inputs),wr(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});`]})},Hi=(e,t)=>{gr(e.inputs),wr(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")});`,""]})},ol=(e,t)=>{gr(e.inputs),wr(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},al=(e,t)=>{gr(e.inputs),wr(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},qi=(e,t)=>{gr(e.inputs),wr(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;`,""])},yr=(e,t,s)=>{if(t.length===0)return s;let n=1,i=1;for(let a=0;a1024},ll=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?il(e,t):tn(e,t)},Qi=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?sl(e,t):Xa(e,t)},ul=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?rl(e,t):Vc(e,t)},dl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ki(e,t):Ya(e,t)},Xi=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?nl(e,t):Wc(e,t)},cl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hi(e,t):Ja(e,t)},pl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ol(e,t):Vi(e,t)},Yi=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?al(e,t):Za(e,t)},hl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qi(e,t):el(e,t)},ml=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gi(e,t):tl(e,t)}}),Ji,fl,Zi,eo,Kc=g(()=>{zt(),rs(),ai(),Ji=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.")},fl=(e,t)=>{Ji(e.inputs);let s=(n,i,a)=>{let o=[];for(let u=0;u=0||a.length===0)&&o.push(`input_indices[${u}] = 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]})},Zi=(e,t)=>{Ji(e.inputs);let s=(n,i,a)=>{let o=[];for(let u=0;u=0||a.length===0)&&o.push(`input_indices[${u}] = 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]})},eo=e=>Bt(e)}),to,li,_l,so,gl,Nn,ro,wl,no=g(()=>{zt(),Ot(),ue(),Yt(),to=(e,t)=>{let s=e[0],n=e[1],i=e[2],a=e[3],o=e[4],u=e[5];if(o&&u)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 P=i.dims[0]/3,d=P,z=d;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let he of t.qkvHiddenSizes)if(he%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");P=t.qkvHiddenSizes[0],d=t.qkvHiddenSizes[1],z=t.qkvHiddenSizes[2]}let B=h;if(P!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==P+d+z)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let V=0;if(o){if(d!==z)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]!==d/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(V=o.dims[3])}let Z=B+V,ee=-1,Q=0;if(a)throw new Error("Mask not supported");if(o)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==p||u.dims[1]!==t.numHeads||u.dims[2]!==h||u.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:V,kvSequenceLength:B,totalSequenceLength:Z,maxSequenceLength:ee,inputHiddenSize:k,hiddenSize:P,vHiddenSize:z,headSize:Math.floor(P/t.numHeads),vHeadSize:Math.floor(z/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; + `,_l=(e,t,s,n,i,a,o,u)=>{let p=qt(o?1:a),h=64,k=a/p;k{let Q=It("x",e.dataType,e.dims,p),he=[Q],pe=o?qe("seq_lens",o.dataType,o.dims):void 0;pe&&he.push(pe);let Me=u?qe("total_sequence_length_input",u.dataType,u.dims):void 0;Me&&he.push(Me);let De=$s(e.dataType),Le=[{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; + ${ee.registerUniforms(Le).declareVariables(...he)} + ${ee.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(pe,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 = ${B}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${B}(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 = ${B}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${B}(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}(${De}(1.0) / ${De}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${B}(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}(${De}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${z};${p}`,inputDependencies:V},getShaderSource:Z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/h),y:i,z:t*s},programUniforms:d})}},so=(e,t,s,n,i,a,o,u,p)=>{let h=o+a.kvSequenceLength,k=[a.batchSize,a.numHeads,a.sequenceLength,h],P=e>1&&n,d=a.kvNumHeads?a.kvNumHeads:a.numHeads,z=P?[a.batchSize,d,h,a.headSize]:void 0,B=a.nReps?a.nReps:1,V=a.scale===0?1/Math.sqrt(a.headSize):a.scale,Z=qt(a.headSize),ee=a.headSize/Z,Q=12,he={x:Math.ceil(h/Q),y:Math.ceil(a.sequenceLength/Q),z:a.batchSize*a.numHeads},pe=[{type:12,data:a.sequenceLength},{type:12,data:ee},{type:12,data:h},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:V},{type:12,data:o},{type:12,data:a.kvSequenceLength},{type:12,data:B}],Me=P&&n&&ze.size(n.dims)>0,De=["type","type"];Me&&De.push("type"),i&&De.push("type"),u&&De.push("type"),p&&De.push("type");let Le=[{dims:k,dataType:t.dataType,gpuDataType:0}];P&&Le.push({dims:z,dataType:t.dataType,gpuDataType:0});let Ye=at=>{let Et=qe("q",t.dataType,t.dims,Z),Xt=qe("key",s.dataType,s.dims,Z),Zt=[Et,Xt];if(Me){let Rt=qe("past_key",n.dataType,n.dims,Z);Zt.push(Rt)}i&&Zt.push(qe("attention_bias",i.dataType,i.dims));let bt=u?qe("seq_lens",u.dataType,u.dims):void 0;bt&&Zt.push(bt);let ss=p?qe("total_sequence_length_input",p.dataType,p.dims):void 0;ss&&Zt.push(ss);let St=It("output",t.dataType,k),Ft=[St];P&&Ft.push(It("present_key",t.dataType,z,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}>; + ${at.registerUniforms(Ht).declareVariables(...Zt,...Ft)} + ${at.mainStart([Q,Q,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${B===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${B===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(bt,ss,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${Me&&P?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${P?"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&&P?` + 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]; + }`} + ${P?`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] = ${St.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:De},getRunData:()=>({outputs:Le,dispatchGroup:he,programUniforms:pe}),getShaderSource:Ye}},gl=(e,t,s,n,i,a,o=void 0,u=void 0)=>{let p=a+i.kvSequenceLength,h=i.nReps?i.nReps:1,k=i.vHiddenSize*h,P=e>1&&n,d=i.kvNumHeads?i.kvNumHeads:i.numHeads,z=P?[i.batchSize,d,p,i.headSize]:void 0,B=[i.batchSize,i.sequenceLength,k],V=12,Z={x:Math.ceil(i.vHeadSize/V),y:Math.ceil(i.sequenceLength/V),z:i.batchSize*i.numHeads},ee=[{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=P&&n&&ze.size(n.dims)>0,he=["type","type"];Q&&he.push("type"),o&&he.push("type"),u&&he.push("type");let pe=[{dims:B,dataType:t.dataType,gpuDataType:0}];P&&pe.push({dims:z,dataType:t.dataType,gpuDataType:0});let Me=De=>{let Le=qe("probs",t.dataType,t.dims),Ye=qe("v",s.dataType,s.dims),at=[Le,Ye];Q&&at.push(qe("past_value",n.dataType,n.dims));let Et=o?qe("seq_lens",o.dataType,o.dims):void 0;o&&at.push(Et);let Xt=u?qe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&at.push(Xt);let Zt=[It("output",t.dataType,B)];P&&Zt.push(It("present_value",t.dataType,z));let bt=[{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 = ${V}u; + var tileQ: array<${Le.type.value}, ${V*V}>; + var tileV: array<${Le.type.value}, ${V*V}>; + ${De.registerUniforms(bt).declareVariables(...at,...Zt)} + ${De.mainStart([V,V,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,Xt,!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&&P?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${P?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${Le.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&&P?` + 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]; + }`} + ${P?` + 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:he},getRunData:()=>({outputs:pe,dispatchGroup:Z,programUniforms:ee}),getShaderSource:Me}},Nn=(e,t,s,n,i,a,o,u,p,h,k=void 0,P=void 0)=>{let d=Math.min(e.outputCount,1+(o?1:0)+(u?1:0)),z=d>1?h.pastSequenceLength:0,B=z+h.kvSequenceLength,V=p&&ze.size(p.dims)>0?p:void 0,Z=[t,s];d>1&&o&&ze.size(o.dims)>0&&Z.push(o),V&&Z.push(V),k&&Z.push(k),P&&Z.push(P);let ee=e.compute(so(d,t,s,o,V,h,z,k,P),{inputs:Z,outputs:d>1?[-1,1]:[-1]})[0];e.compute(_l(ee,h.batchSize,h.numHeads,z,h.sequenceLength,B,k,P),{inputs:k&&P?[ee,k,P]:[ee],outputs:[]});let Q=[ee,n];d>1&&u&&ze.size(u.dims)>0&&Q.push(u),k&&Q.push(k),P&&Q.push(P),e.compute(gl(d,ee,n,u,h,z,k,P),{inputs:Q,outputs:d>1?[0,2]:[0]})},ro=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,o=12,u={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=P=>{let d=It("output_q",p[0].dataType,s),z=It("output_k",p[0].dataType,s),B=It("output_v",p[0].dataType,s),V=qe("input",p[0].dataType,p[0].dims),Z=qe("weight",p[1].dataType,p[1].dims),ee=qe("bias",p[2].dataType,p[2].dims),Q=V.type.storage,he=[{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}>; + ${P.registerUniforms(he).declareVariables(V,Z,ee,d,z,B)} + ${P.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:u,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},wl=(e,t)=>{let s=to(e.inputs,t),[n,i,a]=ro(e,s);return Nn(e,n,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),io,yl,Ml,oo,Hc=g(()=>{We(),zt(),Ot(),rs(),Yt(),io=(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((u,p)=>{if(u!==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")},yl=(e,t)=>{let{epsilon:s,spatial:n,format:i}=t,a=e[0].dims,o=n?qt(a[a.length-1]):1,u=i==="NHWC"&&a.length>1?o:1,p=ze.size(a)/o,h=n,k=h?a.length:a,P=qe("x",e[0].dataType,e[0].dims,o),d=qe("scale",e[1].dataType,e[1].dims,u),z=qe("bias",e[2].dataType,e[2].dims,u),B=qe("inputMean",e[3].dataType,e[3].dims,u),V=qe("inputVar",e[4].dataType,e[4].dims,u),Z=It("y",e[0].dataType,k,o),ee=()=>{let he="";if(n)he=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")he=` + ${Z.indicesSet("outputIndices","0","0")} + let cOffset = ${Z.indicesToOffset("outputIndices")};`;else{he=`var cIndices = ${d.type.indices}(0); + cIndices[0] = outputIndices[${a.length-1}];`;for(let pe=1;pe` + const epsilon = ${s}; + ${he.registerUniform("outputSize","u32").declareVariables(P,d,z,B,V,Z)} + ${he.mainStart()} + ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${Z.offsetToIndices(`global_idx * ${o}`)}; + ${ee()} + let scale = ${d.getByOffset("cOffset")}; + let bias = ${z.getByOffset("cOffset")}; + let inputMean = ${B.getByOffset("cOffset")}; + let inputVar = ${V.getByOffset("cOffset")}; + let x = ${P.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},...yt(a)]:[{type:12,data:p}]})}},Ml=e=>Bt(e),oo=(e,t)=>{let{inputs:s,outputCount:n}=e,i=Ml({...t,outputCount:n});if(F.webgpu.validateInputContent&&io(s,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(yl(s,i))}}),bl,ao,vl,qc=g(()=>{Ot(),Yt(),bl=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")},ao=e=>{let t=e[0].dims,s=e[0].dims[2],n=ze.size(t)/4,i=e[0].dataType,a=qe("input",i,t,4),o=qe("bias",i,[s],4),u=qe("residual",i,t,4),p=It("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,u,p)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${a.getByOffset("global_idx")} + + ${o.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx","value")} + }`}},vl=e=>{bl(e.inputs),e.compute(ao(e.inputs))}}),lo,ds,xl,uo,Tl,El,co,Pl,Cl,po,kl,Sl,$l,Al,ho,Il,jn,mo,ui,Ol,fo,Fl,Dl,_o,Ll,zl,go,Bl,Rl,wo,Nl,jl,yo,Ul,Vl,Mo,Wl,di,bo,Gl,Kl,Hl,vo,ql,Ql,xo=g(()=>{zt(),Ot(),rs(),Yt(),lo=(e,t,s,n,i,a,o)=>{let u=Math.ceil(t/4),p="";typeof i=="string"?p=`${i}(a)`:p=i("a");let h=qe("inputData",s,[u],4),k=It("outputData",n,[u],4),P=[{name:"vec_size",type:"u32"}];return o&&P.push(...o),` + ${e.registerUniforms(P).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,u)=>{let p=[{type:12,data:Math.ceil(ze.size(e.dims)/4)}];return o&&p.push(...o),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:h=>lo(h,ze.size(e.dims),e.dataType,a,s,n,u),getRunData:h=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(ze.size(h[0].dims)/64/4)},programUniforms:p})}},xl=e=>{e.compute(ds(e.inputs[0],"Abs","abs"))},uo=e=>{e.compute(ds(e.inputs[0],"Acos","acos"))},Tl=e=>{e.compute(ds(e.inputs[0],"Acosh","acosh"))},El=e=>{e.compute(ds(e.inputs[0],"Asin","asin"))},co=e=>{e.compute(ds(e.inputs[0],"Asinh","asinh"))},Pl=e=>{e.compute(ds(e.inputs[0],"Atan","atan"))},Cl=e=>{e.compute(ds(e.inputs[0],"Atanh","atanh"))},po=e=>Bt(e),kl=(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))},Sl=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 Bt({min:t,max:s})},$l=(e,t)=>{let s=t||Sl(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]})},Al=e=>{e.compute(ds(e.inputs[0],"Ceil","ceil"))},ho=e=>{e.compute(ds(e.inputs[0],"Cos","cos"))},Il=e=>{e.compute(ds(e.inputs[0],"Cosh","cosh"))},jn=e=>Bt(e),mo=(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)); +}`,Ol=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,ui(t)))},fo=e=>{e.compute(ds(e.inputs[0],"Exp","exp"))},Fl=e=>{e.compute(ds(e.inputs[0],"Floor","floor"))},Dl=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)))},_o=(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))},Ll=e=>{e.compute(ds(e.inputs[0],"Not",t=>`!${t}`))},zl=e=>{e.compute(ds(e.inputs[0],"Neg",t=>`-${t}`))},go=e=>{e.compute(ds(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Bl=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))`))},Rl=e=>{e.compute(ds(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},wo=e=>Bt(e),Nl=(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))},jl=e=>{e.compute(ds(e.inputs[0],"Sin","sin"))},yo=e=>{e.compute(ds(e.inputs[0],"Sinh","sinh"))},Ul=e=>{e.compute(ds(e.inputs[0],"Sqrt","sqrt"))},Vl=e=>{e.compute(ds(e.inputs[0],"Tan","tan"))},Mo=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Wl=e=>{e.compute(ds(e.inputs[0],"Tanh",Mo))},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 ${Mo("v")}; +} +`,bo=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Gl=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"FastGelu",bo,di(t),void 0,e.inputs[0].dataType))},Kl=(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},Hl=e=>{e.compute(ds(e.inputs[0],"Log","log"))},vo=(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; +} +`,ql=e=>`quick_gelu_impl(${e})`,Ql=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"QuickGelu",ql,vo(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Xl,To,Yl,Qc=g(()=>{Ot(),Yt(),xo(),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=qe("input",e[0].dataType,e[0].dims,4),n=qe("bias",e[0].dataType,[e[0].dims[2]],4),i=It("output",e[0].dataType,t,4),a=ze.size(t)/4,o=ms(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${u.declareVariables(s,n,i)} + + ${ui(o)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Yl=e=>{Xl(e.inputs),e.compute(To(e.inputs))}}),Jl,Zl,mr,eu,tu,Eo,su,ru,Po,nu,iu,Co,ou,Xc=g(()=>{zt(),Ot(),Yt(),Jl=(e,t,s,n,i,a,o,u,p,h,k,P)=>{let d,z;typeof u=="string"?d=z=(Q,he)=>`${u}((${Q}),(${he}))`:typeof u=="function"?d=z=u:(d=u.scalar,z=u.vector);let B=It("outputData",k,n.length,4),V=qe("aData",p,t.length,4),Z=qe("bData",h,s.length,4),ee;if(i)if(a){let Q=ze.size(t)===1,he=ze.size(s)===1,pe=t.length>0&&t[t.length-1]%4===0,Me=s.length>0&&s[s.length-1]%4===0;Q||he?ee=B.setByOffset("global_idx",z(Q?`${V.type.value}(${V.getByOffset("0")}.x)`:V.getByOffset("global_idx"),he?`${Z.type.value}(${Z.getByOffset("0")}.x)`:Z.getByOffset("global_idx"))):ee=` + let outputIndices = ${B.offsetToIndices("global_idx * 4u")}; + let offsetA = ${V.broadcastedIndicesToOffset("outputIndices",B)}; + let offsetB = ${Z.broadcastedIndicesToOffset("outputIndices",B)}; + ${B.setByOffset("global_idx",z(o||pe?V.getByOffset("offsetA / 4u"):`${V.type.value}(${V.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||Me?Z.getByOffset("offsetB / 4u"):`${Z.type.value}(${Z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else ee=B.setByOffset("global_idx",z(V.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=(he,pe,Me="")=>{let De=`aData[indexA${pe}][componentA${pe}]`,Le=`bData[indexB${pe}][componentB${pe}]`;return` + let outputIndices${pe} = ${B.offsetToIndices(`global_idx * 4u + ${pe}u`)}; + let offsetA${pe} = ${V.broadcastedIndicesToOffset(`outputIndices${pe}`,B)}; + let offsetB${pe} = ${Z.broadcastedIndicesToOffset(`outputIndices${pe}`,B)}; + let indexA${pe} = offsetA${pe} / 4u; + let indexB${pe} = offsetB${pe} / 4u; + let componentA${pe} = offsetA${pe} % 4u; + let componentB${pe} = offsetB${pe} % 4u; + ${he}[${pe}] = ${Me}(${d(De,Le)}); + `};k===9?ee=` + 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));`:ee=` + ${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(V,Z,B)} + + ${P??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${ee} + }`},Zl=(e,t,s,n,i,a,o=s.dataType)=>{let u=s.dims.map(V=>Number(V)??1),p=n.dims.map(V=>Number(V)??1),h=!ze.areEqual(u,p),k=u,P=ze.size(u),d=!1,z=!1,B=[h];if(h){let V=Ws.calcShape(u,p,!1);if(!V)throw new Error("Can't perform binary op on the given tensors");k=V.slice(),P=ze.size(k);let Z=ze.size(u)===1,ee=ze.size(p)===1,Q=u.length>0&&u[u.length-1]%4===0,he=p.length>0&&p[p.length-1]%4===0;B.push(Z),B.push(ee),B.push(Q),B.push(he);let pe=1;for(let Me=1;MeV.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:V=>Jl(V,u,p,k,d,h,z,i,s.dataType,n.dataType,o,a),getRunData:()=>({outputs:[{dims:k,dataType:o}],dispatchGroup:{x:Math.ceil(P/64/4)},programUniforms:[{type:12,data:Math.ceil(ze.size(k)/4)},...yt(u,p,k)]})}},mr=(e,t,s,n,i,a)=>{e.compute(Zl(t,i??"",e.inputs[0],e.inputs[1],s,n,a))},eu=e=>{mr(e,"Add",(t,s)=>`${t}+${s}`)},tu=e=>{mr(e,"Div",(t,s)=>`${t}/${s}`)},Eo=e=>{mr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},su=e=>{mr(e,"Mul",(t,s)=>`${t}*${s}`)},ru=e=>{let t=qe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;mr(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)); + } + `)},Po=e=>{mr(e,"Sub",(t,s)=>`${t}-${s}`)},nu=e=>{mr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},iu=e=>{mr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},Co=e=>{mr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},ou=e=>{mr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),ko,au,lu,ci,uu,du,cu=g(()=>{zt(),Ot(),rs(),Yt(),ko=(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,u)=>{if(u!==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")})}})},au=(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; + }`,lu=(e,t)=>{let s=e.length,n=[];for(let i=0;i{let i=ze.size(s),a=new Array(e.length),o=new Array(e.length),u=0,p=[],h=[],k=[{type:12,data:i}];for(let V=0;V`uniforms.sizeInConcatAxis${V}`).join(","),B=V=>` + + ${(()=>{V.registerUniform("outputSize","u32");for(let Z=0;Z(${z}); + ${d} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${lu(o,P)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:k}),getShaderSource:B}},uu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=ze.normalizeAxis(t.axis,n.length);ko(s,i);let a=n.slice();a[i]=s.reduce((u,p)=>u+(p.dims.length>i?p.dims[i]:0),0);let o=s.filter(u=>ze.size(u.dims)>0);e.compute(ci(o,i,a,s[0].dataType),{inputs:o})},du=e=>Bt({axis:e.axis})}),Kr,sn,Hr,So,rn=g(()=>{zt(),Ot(),Kr=(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}`)}},sn=(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})},Hr=(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"})},So=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)||[Ss,qs];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}}}),Qs,$o,Ao=g(()=>{Qs=(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.`)}},$o=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),pu,Yc=g(()=>{pu=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)); +} +`}),bn,Io,Oo=g(()=>{zt(),Ot(),Yt(),rn(),bn=(e,t,s,n,i)=>{let a=n-s;return` + ${Array.from({length:s}).map((o,u)=>` + if (${$t(t.shape,u,t.rank)} != 1) { + ${t.indicesSet(e,u,$t(i,u+a,n))} + } else { + ${t.indicesSet(e,u,0)} + }`).join("")} +`},Io=(e,t,s,n,i=!1,a)=>{let o=e[0].dims,u=e[1].dims,p=o[o.length-2],h=u[u.length-1],k=o[o.length-1],P=qt(h),d=qt(k),z=qt(p),B=ze.size(s)/P/z,V=e.length>2,Z=n?n.slice(0,-2):s.slice(0,-2),ee=[ze.size(Z),p,h],Q=[{type:12,data:B},{type:12,data:p},{type:12,data:h},{type:12,data:k}];sn(t,Q),Q.push(...yt(Z,o,u)),V&&Q.push(...yt(e[2].dims)),Q.push(...yt(ee));let he=pe=>{let Me=zi("batch_dims",e[0].dataType,Z.length),De=qe("a",e[0].dataType,o.length,d),Le=qe("b",e[1].dataType,u.length,P),Ye=It("output",e[0].dataType,ee.length,P),at=ms(Ye.type.tensor),Et=Kr(t,Ye.type.value,at),Xt=[De,Le],Zt="";if(V){let St=i?P:1;Xt.push(qe("bias",e[2].dataType,e[2].dims.length,St)),Zt=`${i?`value += bias[col / ${St}];`:`value += ${Ye.type.value}(bias[row + i]);`}`}let bt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Hr(t,bt);let ss=()=>{let St=`var a_data: ${De.type.value};`;for(let Ft=0;Ft; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { + ${ss()} + } + for (var i = 0u; i < ${z}u; i++) { + var value = values[i]; + ${Zt} + ${Et} + let cur_indices = ${Ye.type.indices}(batch, row + i, col); + let offset = ${Ye.indicesToOffset("cur_indices")}; + ${Ye.setByOffset(`offset / ${P}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${P};${d};${z};${i}`,inputDependencies:V?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:Q}),getShaderSource:he}}}),Fo,hu,Do,pi,mu,Lo,zo,hi,Bo=g(()=>{zt(),Ot(),Yt(),rn(),Oo(),Ao(),Fo=(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":""}); + `,hu=(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];"} + }`,Do=(e,t,s="f32",n,i=!1,a=32,o=!1,u=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=i?p:a,P=i?a:p,d=k/t[0],z=a/t[1];if(!((i&&d===4&&e[1]===4||!i&&(d===3||d===4))&&k%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${d} 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/d}>, ${P}>; +var mm_Bsub: array, ${h/e[0]}>, ${a}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${d}; +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(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${z}; + 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; + ${Fo(i,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${z}; 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]; + ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${hu(i,d)} + } + + 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":""}); + `,mu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Lo=(e,t,s="f32",n,i=!1,a=32,o=!1,u=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],P=i?h:a,d=i?a:h;if(!(d%t[1]===0&&P%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${P} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let z=d/t[1],B=P/t[0],V=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 < ${d}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${P}; 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) * ${z}; +let tileColA = i32(localId.x) * ${B}; +let tileRowB = i32(localId.y) * ${V}; +// 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 < ${z}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${B}; 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 < ${V}; 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) { + ${mu(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, ${d}>; + 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(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${u}`:"0"}; + + var acc : array, rowPerThread>; + ${Z} + } +`},zo=(e,t,s,n,i=!1)=>{let[a,o,u,p]=n,h=ms(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Qs(e,h)} { + var value = ${Qs(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${o.type.indices}; + ${bn("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}) -> ${Qs(e,h)} { + var value = ${Qs(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${u.type.indices}; + ${bn("bIndices",u,u.rank-2,a.rank,"batchIndices")} + ${u.indicesSet("bIndices",u.rank-2,"u32(row)")} + ${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")} + value = ${u.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Qs(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]":`${Qs(e,h)}(bias[row])`};`:""} + ${s} + ${p.setByIndices("vec3(coords)","value")} + } + } + `},hi=(e,t,s,n,i=!1,a)=>{let o=e[0].dims,u=e[1].dims,p=o.slice(0,-2),h=u.slice(0,-2),k=n?n.slice(0,-2):s.slice(0,-2),P=ze.size(k),d=o[o.length-2],z=o[o.length-1],B=u[u.length-1],V=z%4===0&&B%4===0,Z=d<=8?[4,1,1]:[4,4,1],ee=[8,8,1],Q=[Math.ceil(B/ee[0]/Z[0]),Math.ceil(d/ee[1]/Z[1]),Math.ceil(P/ee[2]/Z[2])],he=V?4:1,pe=[...p,d,z/he],Me=pe.length,De=[...h,z,B/he],Le=De.length,Ye=[P,d,B/he],at=[{type:6,data:d},{type:6,data:B},{type:6,data:z}];sn(t,at),at.push(...yt(k,pe,De));let Et=["rank","rank"],Xt=e.length>2;Xt&&(at.push(...yt(e[2].dims)),Et.push("rank")),at.push(...yt(Ye));let Zt=bt=>{let ss=k.length,St=zi("batchDims",e[0].dataType,ss,1),Ft=ms(e[0].dataType),bs=qe("a",e[0].dataType,Me,he),Ht=qe("b",e[1].dataType,Le,he),Rt=It("result",e[0].dataType,Ye.length,he),_s=[bs,Ht];if(Xt){let vr=i?he:1;_s.push(qe("bias",e[2].dataType,e[2].dims.length,vr))}let ot=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Hr(t,ot);let Pt=ms(Rt.type.tensor),cs=Kr(t,Rt.type.value,Pt),Ns=zo(he,Xt,cs,[St,bs,Ht,Rt],i);return` + ${bt.registerUniforms(ot).registerInternalVariables(St).declareVariables(..._s,Rt)} + ${Ns} + ${V?Do(Z,ee,Ft,St):Lo(Z,ee,Ft,St)} + `};return{name:"MatMul",shaderCache:{hint:`${Z};${t.activation};${V};${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:at}),getShaderSource:Zt}}}),Ro,fu,Jc=g(()=>{zt(),Pe(),Yt(),rn(),Ao(),Yc(),Bo(),Ro=(e,t,s,n,i=!1,a,o=4,u=4,p=4,h="f32")=>{let k=at=>{switch(at){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 ${at} is not supported.`)}},P=at=>{switch(at){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 ${at} is not supported.`)}},d=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,z=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,B=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",V=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Z=e?"row":"col",ee=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 = ${ee} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${ee} / 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 = ${ee} % inChannels; + var resData = ${Qs(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 < ${B} && xCol >= 0 && xCol < ${V}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${k(o)} + } + return resData;`,he=e?t&&n?` + let col = colIn * ${o}; + ${Q}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${Q} + } + return ${Qs(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 ${Qs(o,h)}(0.0);`,pe=e?n&&s?P(u):` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${P(u)} + } + return ${Qs(u,h)}(0.0);`:` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${P(u)} + } + return ${Qs(u,h)}(0.0);`,Me=Qs(p,h),De=Qs(e?o:u,h),Le=Qs(e?u:o,h),Ye=Kr(a,Me,h);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${De} { + ${e?he:pe} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Le} { + ${e?pe:he} + } + + 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])"}; + ${z} + ${$o(i)} + ${Ye} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},fu=(e,t,s,n,i,a,o,u,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],P=s[0],d=h?s[2]:s[3],z=h?s[1]:s[2],B=h?s[3]:s[1],V=h&&(k%4===0||k%3===0)&&B%4===0,Z=h?B:d*z,ee=h?d*z:B,Q=[8,8,1],he=n<=8?[4,1,1]:[4,4,1],pe=[Math.ceil(Z/Q[0]/he[0]),Math.ceil(ee/Q[1]/he[1]),Math.ceil(P/Q[2]/he[2])];as("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${pe}`);let Me=V?h&&k%4!==0?3:4:1,De=Q[1]*he[1],Le=Q[0]*he[0],Ye=Math.max(Q[0]*Me,Q[1]),at=n%De===0,Et=i%Le===0,Xt=a%Ye===0,Zt=V?[Me,4,4]:[1,1,1],bt=[{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}];sn(t,bt),bt.push(...yt(e[0].dims,e[1].dims));let ss=["rank","rank"];o&&(bt.push(...yt(e[2].dims)),ss.push("rank")),bt.push(...yt(s));let St=Ft=>{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}];Hr(t,bs);let Ht=V?4:1,Rt=ms(e[0].dataType),_s=` + fn setOutputAtIndex(flatIndex : i32, value : ${V?`vec4<${Rt}>`:Rt}) { + result[flatIndex] = ${V?`vec4<${Rt}>`:Rt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${V?`vec4<${Rt}>`:Rt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${V?"/ 4":""}, value); + }`,ot=qe("x",e[0].dataType,e[0].dims.length,Me===3?1:Me),Pt=qe("w",e[1].dataType,e[1].dims.length,Ht),cs=[ot,Pt],Ns=It("result",e[0].dataType,s.length,Ht);if(o){let vr=qe("bias",e[2].dataType,e[2].dims.length,Ht);cs.push(vr),_s+=` + fn getBiasByOutputCoords(coords : vec4) -> ${V?`vec4<${Rt}>`:Rt} { + return bias[coords.${h?"w":"y"}${V?"/ 4":""}]; + }`}return` + ${pu("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 }; + ${Ft.registerUniforms(bs).declareVariables(...cs,Ns)} + ${_s} + ${Ro(h,at,Et,Xt,o,t,Zt[0],Zt[1],Zt[2],Rt)} + ${V?Do(he,Q,Rt,void 0,!h,Ye):Lo(he,Q,Rt,void 0,!h,Ye,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Me};${V};${at};${Et};${Xt};${De};${Le};${Ye}`,inputDependencies:ss},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:pe[0],y:pe[1],z:pe[2]},programUniforms:bt}),getShaderSource:St}}}),No,jo,Un,_u,Uo,mi,gu,wu,Zc=g(()=>{zt(),Pe(),Ot(),Yt(),rn(),Ao(),No=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,Un=(e,t)=>t<=1?e:e+(e-1)*(t-1),_u=(e,t,s,n=1)=>{let i=Un(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)},Uo=(e,t,s,n,i)=>{i==null&&(i=_u(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,u,p,h)=>{let k,P,d,z;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let B=Uo([t,s,n,1],[u,p,h],1,[i,a,o],e);P=B[0],d=B[1],z=B[2]}else if(Array.isArray(e)){if(!e.every((V,Z,ee)=>V===ee[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 B=Uo([t,s,n,1],[u,p,h],1,[i,a,o],e[0]);P=B[0],d=B[1],z=B[2]}else if(e==="SAME_UPPER"){P=Math.ceil(t/i),d=Math.ceil(s/a),z=Math.ceil(n/o);let B=(P-1)*i+u-t,V=(d-1)*a+p-s,Z=(z-1)*o+h-n,ee=Math.floor(B/2),Q=B-ee,he=Math.floor(V/2),pe=V-he,Me=Math.floor(Z/2),De=Z-Me;k={top:he,bottom:pe,left:Me,right:De,front:ee,back:Q}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:P,outHeight:d,outWidth:z}},gu=(e,t,s,n,i,a=!1,o="channelsLast")=>{let u,p,h,k,P;if(o==="channelsLast")[u,p,h,k,P]=e;else if(o==="channelsFirst")[u,P,p,h,k]=e;else throw new Error(`Unknown dataFormat ${o}`);let[d,,z,B,V]=t,[Z,ee,Q]=jo(s),[he,pe,Me]=jo(n),De=Un(z,he),Le=Un(B,pe),Ye=Un(V,Me),{padInfo:at,outDepth:Et,outHeight:Xt,outWidth:Zt}=mi(i,p,h,k,Z,ee,Q,De,Le,Ye),bt=a?d*P:d,ss=[0,0,0,0,0];return o==="channelsFirst"?ss=[u,bt,Et,Xt,Zt]:o==="channelsLast"&&(ss=[u,Et,Xt,Zt,bt]),{batchSize:u,dataFormat:o,inDepth:p,inHeight:h,inWidth:k,inChannels:P,outDepth:Et,outHeight:Xt,outWidth:Zt,outChannels:bt,padInfo:at,strideDepth:Z,strideHeight:ee,strideWidth:Q,filterDepth:z,filterHeight:B,filterWidth:V,effectiveFilterDepth:De,effectiveFilterHeight:Le,effectiveFilterWidth:Ye,dilationDepth:he,dilationHeight:pe,dilationWidth:Me,inShape:e,outShape:ss,filterShape:t}},wu=(e,t,s,n,i,a)=>{let o=a==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],p={x:s.map((Z,ee)=>ee)},h=[Math.ceil(No(p.x.map(Z=>s[Z]))/u[0]),1,1];as("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,P=ze.size(s),d=[{type:12,data:P},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];sn(t,d),d.push(...yt(e[0].dims,e[1].dims));let z=["rank","rank"],B=e.length===3;B&&(d.push(...yt(e[2].dims)),z.push("rank")),d.push(...yt(s));let V=Z=>{let ee=[{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}];Hr(t,ee);let Q=1,he=ms(e[0].dataType),pe=qe("x",e[0].dataType,e[0].dims.length,k),Me=qe("W",e[1].dataType,e[1].dims.length,Q),De=[pe,Me],Le=It("result",e[0].dataType,s.length,Q),Ye="";if(B){let Xt=qe("bias",e[2].dataType,e[2].dims.length,Q);De.push(Xt),Ye+=` + fn getBiasByOutputCoords(coords : array) -> ${he} { + return bias[${o?$t("coords",4,5):$t("coords",1,5)}]; + }`}let at=Qs(k,he),Et=Kr(t,at,he);return` + ${Ye} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${pe.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(ee).declareVariables(...De,Le)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Le.offsetToIndices("global_idx")}; + let batch = ${$t("coords",0,pe.rank)}; + let d2 = ${o?$t("coords",pe.rank-1,pe.rank):$t("coords",1,pe.rank)}; + let xFRCCorner = vec3(${o?$t("coords",1,pe.rank):$t("coords",2,pe.rank)}, + ${o?$t("coords",2,pe.rank):$t("coords",3,pe.rank)}, + ${o?$t("coords",3,pe.rank):$t("coords",4,pe.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${o?$t("uniforms.x_shape",1,pe.rank):$t("uniforms.x_shape",2,pe.rank)}; + let xShapeZ = ${o?$t("uniforms.x_shape",2,pe.rank):$t("uniforms.x_shape",3,pe.rank)}; + let xShapeW = ${o?$t("uniforms.x_shape",3,pe.rank):$t("uniforms.x_shape",4,pe.rank)}; + let xShapeU = ${o?$t("uniforms.x_shape",4,pe.rank):$t("uniforms.x_shape",1,pe.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); + } + } + } + } + ${B?"value = value + getBiasByOutputCoords(coords)":""}; + ${Et} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${o};${k};${B}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:d}),getShaderSource:V}}}),yu,Mu,bu=g(()=>{zt(),Ot(),Yt(),rn(),yu=(e,t,s,n)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",o=e[0].dims,u=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],k=h/t.group,P=p&&k>=4?qt(h):1,d=ze.size(s)/P,z=[{type:12,data:d},{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}];sn(t,z),z.push(...yt(o,[u[0],u[1],u[2],u[3]/P]));let B=i?["rank","rank","rank"]:["rank","rank"];z.push(...yt([s[0],s[1],s[2],s[3]/P]));let V=Z=>{let ee=It("output",e[0].dataType,s.length,P),Q=ms(ee.type.tensor),he=Kr(t,ee.type.value,Q),pe=qe("x",e[0].dataType,o.length),Me=qe("w",e[1].dataType,u.length,P),De=[pe,Me];i&&De.push(qe("b",e[2].dataType,e[2].dims,P));let Le=[{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"}];Hr(t,Le);let Ye=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 = ${pe.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 = ${pe.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${Me.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${Z.registerUniforms(Le).declareVariables(...De,ee)} + + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${ee.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 * ${P} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; + + var value: ${ee.type.value} = ${ee.type.value}(0); + ${Ye} + ${a} + ${he} + ${ee.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${P}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:z}),getShaderSource:V}},Mu=(e,t,s,n)=>{let i=e.length>2,a=qt(s[3]),o=qt(s[2]),u=ze.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],P=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];sn(t,P),P.push(...yt(p,h,k));let d=(o-1)*t.strides[1]+h[1],z=B=>{let V=It("output",e[0].dataType,k.length,a),Z=ms(V.type.tensor),ee=Kr(t,V.type.value,Z),Q=qe("x",e[0].dataType,p.length,a),he=qe("w",e[1].dataType,h.length,a),pe=[Q,he];i&&pe.push(qe("b",e[2].dataType,e[2].dims,a));let Me=i?"value += b[output_channel];":"",De=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Hr(t,De),` + ${B.registerUniforms(De).declareVariables(...pe,V)} + ${B.mainStart()} + ${B.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}, ${d}>; + var values: array<${V.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 < ${d}; 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 = ${he.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} + ${ee} + ${V.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${o};${d};${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(u/64)},programUniforms:P}),getShaderSource:z}}}),vu,fi,Vo,_i,Wo,Go,xu,Ko,Ho,ep=g(()=>{Ot(),Jc(),Zc(),Bo(),bu(),rn(),Oo(),Gr(),vu=(e,t,s,n,i,a)=>{let o=e[0],u=e.slice(a?1:2,a?3:4),p=u.length,h=t[0],k=t.slice(2).map((d,z)=>d+(d-1)*(s[z]-1)),P=u.map((d,z)=>d+n[z]+n[z+p]).map((d,z)=>Math.floor((d-k[z]+i[z])/i[z]));return P.splice(0,0,o),P.splice(a?3:1,0,h),P},fi=[2,3,1,0],Vo=(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=So(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,a=e.group,o=e.kernel_shape,u=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:i,group:a,kernelShape:o,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Go=(e,t,s,n)=>{let i=s.format==="NHWC",a=vu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,i);if(s.group!==1){let De=[t[0]];if(i){let Le=e.kernelCustomData.wT??e.compute(pr(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Le),De.push(Le)}else De.push(t[1]);t.length===3&&De.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(Mu(De,s,a,n),{inputs:De}):e.compute(yu(De,s,a,n),{inputs:De});return}let o=t.length===3,u=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],P=t[1].dims[3],d=a[i?1:2],z=a[i?2:3],B=a[i?3:1],V=i&&k===u&&P===p&&s.pads[0]===0&&s.pads[1]===0;if(V||k===1&&P===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 De=a[0],Le,Ye,at,Et=[];if(i){let bt=e.kernelCustomData.wT??e.compute(pr(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=bt),V){let ss=u*p*h;Le=t[0].reshape([1,De,ss]),Ye=bt.reshape([1,ss,B]),at=[1,De,B]}else Le=t[0].reshape([De,u*p,h]),Ye=bt.reshape([1,h,B]),at=[De,d*z,B];Et.push(Le),Et.push(Ye)}else Le=t[0].reshape([De,h,u*p]),Ye=t[1].reshape([1,B,h]),at=[De,B,d*z],Et.push(Ye),Et.push(Le);o&&Et.push(t[2]);let Xt=at[2],Zt=Et[0].dims[Et[0].dims.length-1];Xt<8&&Zt<8?e.compute(Io(Et,s,a,at,i,n),{inputs:Et}):e.compute(hi(Et,s,a,at,i,n),{inputs:Et});return}let Z=!0,ee=e.kernelCustomData.wT??e.compute(pr(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ee);let Q=[t[0],ee];o&&Q.push(t[2]);let he=i?d*z:B,pe=i?B:d*z,Me=k*P*h;e.compute(fu(Q,s,a,he,pe,Me,o,Z,n),{inputs:Q})},xu=(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),u=[1].concat(t.kernelShape),p=_i({...t,pads:i,strides:a,dilations:o,kernelShape:u},n);Go(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Ko=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",i=_i(s,t),a=s.autoPad==="NOTSET"?s.pads:s.autoPad,o=gu(t[0].dims,t[1].dims,s.strides,s.dilations,a,!1,n);e.compute(wu(t,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],n))},Ho=(e,t)=>{if(Vo(e.inputs,t),e.inputs[0].dims.length===3)xu(e,t);else if(e.inputs[0].dims.length===5)Ko(e,e.inputs,t);else{let s=_i(t,e.inputs);Go(e,e.inputs,s)}}}),qo,tp=g(()=>{zt(),Pe(),Ot(),Yt(),qo=(e,t,s)=>{let n=e.length>2,i=t.outputShape,a=t.format==="NHWC",o=t.group,u=e[1].dims,p=u[2]/o,h=u[3],k=a?qt(p):1,P=a?qt(h):1,d=a?h===1?k:P:1,z=ze.size(i)/P,B=[Math.ceil(z/64),1,1];as("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${B}`);let V=["rank","rank"],Z=[t.strides[0],t.strides[1]],ee=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],Q=[t.dilations[0],t.dilations[1]],he=[ee[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),ee[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],pe=[he[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),he[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Me=[{type:12,data:z},{type:12,data:Z},{type:12,data:ee},{type:12,data:Q},{type:12,data:he},{type:6,data:pe},{type:12,data:p},{type:12,data:h},...yt(e[0].dims,e[1].dims)];n&&(Me.push(...yt(e[2].dims)),V.push("rank")),Me.push(...yt(i));let De=Le=>{let Ye=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:Z.length},{name:"filter_dims",type:"u32",length:ee.length},{name:"dilations",type:"u32",length:ee.length},{name:"effective_filter_dims",type:"u32",length:he.length},{name:"pads",type:"i32",length:pe.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],at=ms(e[0].dataType),Et=a?1:2,Xt=a?2:3,Zt=a?3:1,bt=qe("W",e[1].dataType,e[1].dims.length,d),ss=qe("Dy",e[0].dataType,e[0].dims.length,k),St=[ss,bt];n&&St.push(qe("bias",e[2].dataType,[i[Zt]].length,P));let Ft=It("result",e[0].dataType,i.length,P),bs=()=>{let Rt="";if(k===1)Rt+=` + let w_offset = ${bt.indicesToOffset(`${bt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${bt.getByOffset(`w_offset / ${d}`)}; + dotProd = dotProd + xValue * wValue;`;else if(h===1)Rt+=` + let wValue = ${bt.getByOffset(`${bt.indicesToOffset(`${bt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${d}`)}; + dotProd = dotProd + dot(xValue, wValue);`;else for(let _s=0;_s(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 = ${Ft.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 = (${at}(dyRCorner) + ${at}(wR)) / ${at}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${at}(uniforms.Dy_shape[${Et}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + wR = wR + uniforms.strides[0] - 1; + 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 = (${at}(dyCCorner) + ${at}(wC)) / ${at}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${at}(uniforms.Dy_shape[${Xt}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + wC = wC + uniforms.strides.y - 1; + 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 + ${k}) { + let xValue = ${a?ss.getByOffset(`${ss.indicesToOffset(`${ss.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${k}`):ss.get("batch","inputChannel","idyR","idyC")}; + ${bs()} + inputChannel = inputChannel + ${k}; + } + } + } + let value = dotProd${n?` + bias[d1 / ${P}]`:""}; + ${Ft.setByOffset("global_idx","value")}; + `;return` + ${Le.registerUniforms(Ye).declareVariables(...St,Ft)} + ${Le.mainStart()} + ${Le.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${Ht}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}${d}${P}${h===1}`,inputDependencies:V},getRunData:()=>({dispatchGroup:{x:B[0],y:B[1],z:B[2]},outputs:[{dims:s?s(i):i,dataType:e[0].dataType}],programUniforms:Me}),getShaderSource:De}}}),Tu,Qo,Eu,Xo,Yo,Pu,Jo,Cu,ku,Su=g(()=>{tp(),rn(),Gr(),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)},Eu=(e,t,s,n,i,a,o,u,p,h)=>{let k=e.length-2,P=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((P,d)=>P*d,1)===0){s.length=0;for(let P=2;PP+d,0)===0){let P=t[0].dims.length-2;p=new Array(P).fill(1)}let h=e.strides.slice();if(h.reduce((P,d)=>P+d,0)===0){let P=t[0].dims.length-2;h=new Array(P).fill(1)}Eu(u,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},Yo=e=>{let t=So(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,u=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,P=e.outputShape;return{autoPad:n,format:s,dilations:i,group:a,kernelShape:o,outputPadding:k,outputShape:P,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Pu=(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,u)=>o+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((o,u)=>o+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((o,u)=>o+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((o,u)=>o+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Jo=(e,t,s,n)=>{let i=e.kernelCustomData.wT??e.compute(pr(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(qo(a,s,n),{inputs:a})},Cu=(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 u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],o=[1].concat(o),a=[1].concat(a),i=[1].concat(i);let p=Xo({...t,pads:u,strides:o,dilations:a,kernelShape:i},n);Jo(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},ku=(e,t)=>{if(Pu(e.inputs,t),e.inputs[0].dims.length===3)Cu(e,t);else{let s=Xo(t,e.inputs);Jo(e,e.inputs,s)}}}),$u,Au,Iu,sp=g(()=>{zt(),Ot(),rs(),Yt(),$u=(e,t,s,n)=>{let i=ze.size(t),a=t.length,o=qe("input",e,a),u=It("output",e,a),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=ze.normalizeAxis(p,a),k=P=>{let d=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,z=$t("uniforms.input_shape","uniforms.axis",a),B=n.reverse?d+(n.exclusive?" + 1":""):"0",V=n.reverse?z:d+(n.exclusive?"":" + 1");return` + ${P.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,u)} + ${P.mainStart()} + ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${B}; + let last : i32 = ${V}; + for (var i : i32 = first; i < last; i++) { + ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${o.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:h},...yt(t,t)]}),getShaderSource:k}},Au=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute($u(n,s,i,t),{inputs:[0]})},Iu=e=>{let t=e.exclusive===1,s=e.reverse===1;return Bt({exclusive:t,reverse:s})}}),Ou,Fu,Zo,Du,Lu,zu=g(()=>{zt(),Ot(),rs(),Yt(),Ou=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.")},Fu=(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,u,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],u=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],u=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let P=e.reshape(o),d=P.dims.length,z=e.dataType,B=qe("a",z,d),V=It("output",z,d),Z=ee=>` + ${ee.registerUniform("output_size","u32").declareVariables(B,V)} + + ${Fu(u,d,B,V)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${V.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${V.setByOffset("global_idx",B.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:ee=>{let Q=p?[s,n*h,i*h,a/h**2]:[s,a/h**2,n*h,i*h],he=ze.size(Q),pe=P.dims,Me=ze.sortBasedOnPerm(pe,u);return{outputs:[{dims:Q,dataType:ee[0].dataType}],dispatchGroup:{x:Math.ceil(he/64)},programUniforms:[{type:12,data:he},...yt(pe,Me)]}},getShaderSource:Z}},Du=(e,t)=>{Ou(e.inputs),e.compute(Zo(e.inputs[0],t))},Lu=e=>Bt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),gi,Vn,Fr,Bu,Ru,Nu,ju,wi,Uu,Vu,Wu,rp=g(()=>{zt(),Ot(),rs(),Yt(),gi="[a-zA-Z]|\\.\\.\\.",Vn="("+gi+")+",Fr="^"+Vn+"$",Bu="("+Vn+",)*"+Vn,Ru="^"+Bu+"$",Nu=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)}},ju=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(Ru)))throw new Error("Invalid LHS term");if(s.split(",").forEach((a,o)=>{let u=e[o].dims.slice();if(!a.match(RegExp(Fr)))throw new Error("Invalid LHS term");let p=this.processTerm(a,!0,u,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(Vn)))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=[],u=0;if(!e.match(RegExp(Fr))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(gi,"g")),h=new Nu(n);return p==null||p.forEach((k,P)=>{if(k==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let d=i-p.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(o=s.slice(u,u+d),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 z=0;ze+"_max",Uu=(e,t,s,n)=>{let i=e.map(h=>h.length).map((h,k)=>qe(`input${k}`,t,h)),a=ze.size(n),o=It("output",t,n.length),u=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let k=[],P="var prod = 1.0;",d="var sum = 0.0;",z="sum += prod;",B=[],V=[],Z=[],ee=[],Q=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((pe,Me)=>{var De;if(s.rhs.symbolToIndices.has(Me)){let Le=(De=s.rhs.symbolToIndices.get(Me))==null?void 0:De[0];Le!==void 0&&s.lhs.forEach((Ye,at)=>{if(pe.inputIndices.includes(at)){let Et=Ye.symbolToIndices.get(Me);if(Et===void 0)throw new Error("Invalid symbol error");Et.forEach(Xt=>{k.push(`${i[at].indicesSet(`input${at}Indices`,Xt,o.indicesGet("outputIndices",Le))}`)})}})}else s.lhs.forEach((Le,Ye)=>{if(pe.inputIndices.includes(Ye)){let at=Le.symbolToIndices.get(Me);if(at===void 0)throw new Error("Invalid symbol error");at.forEach(Et=>{B.push(`${i[Ye].indicesSet(`input${Ye}Indices`,Et,`${Me}`)}`)}),ee.push(`prod *= ${i[Ye].getByIndices(`input${Ye}Indices`)};`)}}),V.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${wi(Me)}; ${Me}++) {`),Z.push("}")});let he=Q?[...k,`let sum = ${i.map((pe,Me)=>pe.getByIndices(`input${Me}Indices`)).join(" * ")};`]:[...k,d,...V,...B,P,...ee,z,...Z];return` + ${h.registerUniforms(u.map(pe=>({name:`${wi(pe)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${o.offsetToIndices("global_idx")}; + ${i.map((pe,Me)=>`var input${Me}Indices: ${i[Me].type.indices};`).join(` +`)} + ${he.join(` +`)}; + ${o.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=u.filter(P=>s.symbolToInfo.has(P)).map(P=>{var d;return{type:12,data:((d=s.symbolToInfo.get(P))==null?void 0:d.dimValue)||0}});h.push({type:12,data:a});let k=e.map((P,d)=>[...yt(P)]).reduce((P,d)=>P.concat(d),h);return k.push(...yt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:k}},getShaderSource:p}},Vu=(e,t)=>{let s=new ju(e.inputs,t.equation),n=s.outputDims,i=e.inputs.map((a,o)=>a.dims);e.compute(Uu(i,e.inputs[0].dataType,s,n))},Wu=e=>{let t=e.equation.replace(/\s+/g,"");return Bt({equation:t})}}),yi,ea,Gu,Ku,Wn,np=g(()=>{zt(),Ot(),Yt(),yi=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),Ku=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=Gu(t,s),i=e[0].dataType,a=i===9||ze.size(t)===1,o=i===9||t.length>0&&t[t.length-1]%4===0?4:1,u=a||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(ze.size(n)/u),h=P=>{let d=qe("input",i,t.length,o),z=It("output",i,n.length,u),B;if(i===9){let V=(Z,ee,Q="")=>` + let outputIndices${ee} = ${z.offsetToIndices(`outputOffset + ${ee}u`)}; + let offset${ee} = ${d.broadcastedIndicesToOffset(`outputIndices${ee}`,z)}; + let index${ee} = offset${ee} / 4u; + let component${ee} = offset${ee} % 4u; + ${Z}[${ee}] = ${Q}(${d.getByOffset(`index${ee}`)}[component${ee}]); + `;B=` + let outputOffset = global_idx * ${u}; + var data = vec4(0); + ${V("data",0,"u32")} + ${V("data",1,"u32")} + ${V("data",2,"u32")} + ${V("data",3,"u32")} + ${z.setByOffset("global_idx","data")} + }`}else B=` + let outputIndices = ${z.offsetToIndices(`global_idx * ${u}`)}; + let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",z)}; + let data = ${z.type.value}(${d.getByOffset(`inputOffset / ${o}`)}); + ${z.setByOffset("global_idx","data")} + }`;return` + ${P.registerUniform("vec_size","u32").declareVariables(d,z)} + ${P.mainStart()} + ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${B}`},k=[{type:12,data:p},...yt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${o}${u}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},Wn=e=>{yi(e.inputs),e.compute(Ku(e.inputs),{inputs:[0]})}}),Hu,qu,ip=g(()=>{zt(),Ot(),Yt(),xo(),Hu=e=>{let t=e[0].dataType,s=ze.size(e[0].dims),n=ze.size(e[1].dims),i=n%4===0,a=o=>{let u=qe("x",t,[1],4),p=qe("bias",t,[1],4),h=It("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],P=z=>` + let bias${z}_offset: u32 = (global_idx * 4 + ${z}) % uniforms.bias_size; + let bias${z} = ${p.getByOffset(`bias${z}_offset / 4`)}[bias${z}_offset % 4];`,d=i?` + let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${P(0)}${P(1)}${P(2)}${P(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(k).declareVariables(u,p,h)} + + ${di($s(t))} + + ${o.mainStart(nr)} + ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${d} + let x_in = x + bias; + ${h.setByOffset("global_idx",bo("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/nr/4)}})}},qu=e=>{e.inputs.length<2||ze.size(e.inputs[1].dims)===0?Gl(e):e.compute(Hu(e.inputs))}}),Mi,Qu,Xu,Yu,Hp=g(()=>{zt(),Ot(),rs(),Yt(),Mi=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Qu=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,a=ze.normalizeAxis(t.axis,i),o=s.slice(0);o.splice(a,1,...n);let u=s[a],p=e[0].dataType===9?4:1,h=Math.ceil(ze.size(o)/p),k=[{type:12,data:h},{type:6,data:u},{type:12,data:a},...yt(e[0].dims,e[1].dims,o)],P=d=>{let z=qe("data",e[0].dataType,e[0].dims.length,p),B=qe("inputIndices",e[1].dataType,e[1].dims.length),V=It("output",e[0].dataType,o.length,p),Z=Q=>{let he=n.length,pe=`var indicesIndices${Q} = ${B.type.indices}(0);`;for(let Me=0;Me1?`indicesIndices${Q}[${Me}]`:`indicesIndices${Q}`} = ${o.length>1?`outputIndices${Q}[uniforms.axis + ${Me}]`:`outputIndices${Q}`};`;pe+=` + var idx${Q} = ${B.getByIndices(`indicesIndices${Q}`)}; + if (idx${Q} < 0) { + idx${Q} = idx${Q} + uniforms.axisDimLimit; + } + var dataIndices${Q} : ${z.type.indices}; + `;for(let Me=0,De=0;Me1?`dataIndices${Q}[${Me}]`:`dataIndices${Q}`} = u32(idx${Q});`,De+=he):(pe+=`${i>1?`dataIndices${Q}[${Me}]`:`dataIndices${Q}`} = ${o.length>1?`outputIndices${Q}[${De}]`:`outputIndices${Q}`};`,De++);return pe},ee;if(e[0].dataType===9){let Q=(he,pe,Me="")=>` + let outputIndices${pe} = ${V.offsetToIndices(`outputOffset + ${pe}u`)}; + ${Z(pe)}; + let offset${pe} = ${z.indicesToOffset(`dataIndices${pe}`)}; + let index${pe} = offset${pe} / 4u; + let component${pe} = offset${pe} % 4u; + ${he}[${pe}] = ${Me}(${z.getByOffset(`index${pe}`)}[component${pe}]); + `;ee=` + 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")} + ${V.setByOffset("global_idx","value")} + `}else ee=` + let outputIndices = ${V.offsetToIndices("global_idx")}; + ${Z("")}; + let value = ${z.getByIndices("dataIndices")}; + ${V.setByOffset("global_idx","value")}; + `;return` + ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(z,B,V)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${ee} + }`};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:P}},Xu=e=>Bt({axis:e.axis}),Yu=(e,t)=>{let s=e.inputs;Mi(s),e.compute(Qu(e.inputs,t))}}),Ju,Zu,ed,Gn=g(()=>{zt(),Ot(),Yt(),Ju=(e,t,s,n,i,a,o,u,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:u},{type:12,data:p}],k=[a];h.push(...yt(t.dims,k));let P=d=>{let z=qe("indices_data",t.dataType,t.dims.length),B=It("input_slice_offsets_data",12,1,1),V=[z,B],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` + ${d.registerUniforms(Z).declareVariables(...V)} + ${d.mainStart()} + ${d.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:P},{inputs:[t],outputs:[-1]})[0]},Zu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=s[0].dataType,a=s[1].dims,o=a[a.length-1],u=ze.sizeToDimension(a,a.length-1),p=ze.sizeFromDimension(n,t.batchDims+o),h=ze.sizeToDimension(n,t.batchDims),k=ze.sizeFromDimension(n,t.batchDims),P=u/h,d=new Array(o),z=p;for(let pe=0;pen.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(V)),ee=ze.size(Z),Q=[{type:12,data:ee},{type:12,data:p},...yt(s[0].dims,B.dims,Z)],he=pe=>{let Me=qe("data",s[0].dataType,s[0].dims.length),De=qe("slice_offsets",12,B.dims.length),Le=It("output",s[0].dataType,Z.length);return` + ${pe.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Me,De,Le)} + ${pe.mainStart()} + ${pe.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(ee/64)},programUniforms:Q}),getShaderSource:he},{inputs:[s[0],B]})},ed=e=>({batchDims:e.batch_dims,cacheKey:""})}),td,sd,rd,nd,op=g(()=>{zt(),Ot(),rs(),Yt(),td=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=ze.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((u,p)=>p===s?Math.ceil(u/n)===a.dims[p]:u===a.dims[p]).reduce((u,p)=>u&&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((u,p)=>u===a.dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},sd=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,a=ze.normalizeAxis(t.gatherAxis,i),o=ze.normalizeAxis(t.quantizeAxis,i),u=s.slice(0);u.splice(a,1,...n);let p=ze.size(u),h=e[2].dataType,k=e[0].dataType===22,P=[{type:12,data:p},{type:12,data:o},{type:12,data:a},{type:12,data:t.blockSize},...yt(...e.map((z,B)=>z.dims),u)],d=z=>{let B=qe("data",e[0].dataType,e[0].dims.length),V=qe("inputIndices",e[1].dataType,e[1].dims.length),Z=qe("scales",e[2].dataType,e[2].dims.length),ee=e.length>3?qe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,Q=It("output",h,u.length),he=[B,V,Z];ee&&he.push(ee);let pe=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${z.registerUniforms(pe).declareVariables(...he,Q)} + ${z.mainStart()} + let output_indices = ${Q.offsetToIndices("global_idx")}; + var indices_indices = ${V.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")}; + ${V.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${Q.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${B.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${Q.indicesGet("output_indices","i")}; + ${B.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${V.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${s[a]}; + } + ${B.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { + let index = ${Q.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${B.indicesSet("data_indices","i","index")}; + } + let data_offset = ${B.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${B.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")}; + ${ee?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${ee.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${ee.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((z,B)=>B!==1).map(z=>z.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(z,B)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:P}),getShaderSource:d}},rd=(e,t)=>{let s=e.inputs;td(s,t),e.compute(sd(e.inputs,t))},nd=e=>Bt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),id,od,bi,ap,lp=g(()=>{zt(),Ot(),rs(),Yt(),id=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.`)},od=(e,t)=>{let s=e[0].dims,n=e[0].dataType,i=s.length,a=e[1].dims,o=e[1].dataType,u=ze.normalizeAxis(t.axis,i),p=s[u],h=a.slice(0),k=ze.size(h),P=qe("input",n,i),d=qe("indicesInput",o,a.length),z=It("output",n,h.length),B=[{type:12,data:k},{type:6,data:p},{type:12,data:u}];return B.push(...yt(s,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:B}),getShaderSource:V=>` + ${V.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(P,d,z)} + ${V.mainStart()} + ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${z.offsetToIndices("global_idx")}; + + var idx = ${d.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${P.type.indices}(outputIndices); + ${P.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${P.getByIndices("inputIndices")}; + + ${z.setByOffset("global_idx","value")}; + }`}},bi=e=>Bt({axis:e.axis}),ap=(e,t)=>{let s=e.inputs;id(s),e.compute(od(e.inputs,t))}}),ad,ld,ud,dd,cd=g(()=>{zt(),Ot(),Yt(),ad=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")},ld=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[i,a,o]=Or.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[i,a];if(!u)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(a/p),k=Math.ceil(i/p),P=!0,d=ze.size(u),z=[{type:12,data:P?h:d},{type:12,data:i},{type:12,data:a},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],B=["type","type"];e.length===3&&(z.push(...yt(e[2].dims)),B.push("rank")),z.push(...yt(u));let V=ee=>{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 he=t.alpha===1?"":"value *= uniforms.alpha;",pe=qe("a",e[0].dataType,e[0].dims),Me=qe("b",e[1].dataType,e[1].dims),De=pe.type.value,Le=null,Ye=[pe,Me];e.length===3&&(Le=qe("c",e[2].dataType,e[2].dims.length),Ye.push(Le));let at=It("output",e[0].dataType,u.length);Ye.push(at);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` + ${ee.registerUniforms(Et).declareVariables(...Ye)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${De}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${Q} + } + + ${he} + ${Le!=null?`let cOffset = ${Le.broadcastedIndicesToOffset("vec2(m, n)",at)}; value += ${De}(uniforms.beta) * ${Le.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},Z=ee=>{let Q=qe("a",e[0].dataType,e[0].dims),he=qe("b",e[1].dataType,e[1].dims),pe=null,Me=[Q,he];e.length===3&&(pe=qe("c",e[2].dataType,e[2].dims.length),Me.push(pe));let De=It("output",e[0].dataType,u.length);Me.push(De);let Le=[{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"}],Ye="",at="";t.transA&&t.transB?(at=` + 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] = ${he.type.value}(0); + } + `,Ye="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(at=` + 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] = ${he.type.value}(0); + } + `,Ye="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(at=` + 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] = ${he.type.value}(0); + } + `,Ye="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(at=` + 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] = ${he.type.value}(0); + } + `,Ye="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Et=t.alpha===1?"":"value *= uniforms.alpha;";return` + ${ee.registerUniforms(Le).declareVariables(...Me)} + var tile_a: array, ${p}>; + var tile_b: array, ${p}>; + ${ee.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 = ${De.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${at} + k_start = k_start + ${p}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${p}; k++) { + ${Ye} + } + workgroupBarrier(); + } + + ${Et} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${pe!=null?`let cOffset = ${pe.broadcastedIndicesToOffset("vec2(m, n)",De)}; value += ${De.type.value}(uniforms.beta) * ${pe.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return P?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:z}),getShaderSource:Z}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:z}),getShaderSource:V}},ud=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}`}},dd=(e,t)=>{ad(e.inputs),e.compute(ld(e.inputs,t))}}),Er,Dr,qr,nn,pd,ta,hd,md,vi,fd,_d,gd,wd,sa,ra=g(()=>{zt(),Ot(),rs(),Yt(),[Er,Dr,qr,nn]=[0,1,2,3],pd=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")},ta=` + 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; + } +`,hd=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; + } +`,md=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)); + `} + } +`,vi=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); + }`:""} +`,fd=(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[${Er}] = batch; + indices[${Dr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${qr}] = u32(r); + indices[${nn}] = u32(c); + } + `;case"border":return` + indices[${qr}] = u32(clamp(r, 0, H - 1)); + indices[${nn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${qr}] = 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")}; + } +`,_d=(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[${Er}], indices[${Dr}], 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[${Er}], indices[${Dr}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Er}], indices[${Dr}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Er}], indices[${Dr}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Er}], indices[${Dr}], 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[${Er}], indices[${Dr}], 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")}`,gd=(e,t)=>{let s=qe("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=qe("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]],[Er,Dr,qr,nn]=[0,3,1,2]);let o=It("output",e[0].dataType,a.length),u=s.type.value,p=ze.size(a),h=[{type:12,data:p},...yt(e[0].dims,n,a)],k=P=>` + ${P.registerUniform("output_size","u32").declareVariables(s,i,o)} + ${ta} + ${hd(u)} + ${md(t)} + ${vi(t)} + ${fd(s,u,t)} + + ${P.mainStart()} + ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${qr}]); + 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[${Er}], indices[${qr}], 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); + + ${_d(o,u,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:P=>{let d=ze.size(a);return{outputs:[{dims:a,dataType:P[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}},getShaderSource:k}},wd=(e,t)=>{pd(e.inputs),e.compute(gd(e.inputs,t))},sa=e=>Bt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),ir,yd,Md,xi,bd,Kn,na,vd=g(()=>{zt(),Ot(),rs(),ue(),no(),Yt(),Gr(),ir=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,yd=(e,t)=>{let s=e[0],n=ir(e,1),i=ir(e,2),a=ir(e,3),o=ir(e,4),u=ir(e,5),p=ir(e,6),h=ir(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],P=s.dims[1],d=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],z=P,B=0,V=0,Z=Math.floor(d/t.numHeads);if(p&&h&&ze.size(p.dims)&&ze.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');B=p.dims[2],V=p.dims[2]}else if(p&&ze.size(p.dims)||h&&ze.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee;if(n&&ze.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)');ee=2,z=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.');ee=5,z=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');ee=0,z=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');ee=3}if(a&&ze.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=B+z,he=0;if(o&&ze.size(o.dims)>0){he=8;let Le=o.dims;throw Le.length===1?Le[0]===k?he=1:Le[0]===3*k+2&&(he=3):Le.length===2&&Le[0]===k&&Le[1]===Q&&(he=5),he===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let pe=!1,Me=d;if(i&&ze.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(z!==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(z!==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],pe=!0}}let De=!1;if(o&&ze.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(u&&ze.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==k||u.dims[1]!==t.numHeads||u.dims[2]!==P||u.dims[3]!==Q)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:P,pastSequenceLength:B,kvSequenceLength:z,totalSequenceLength:Q,maxSequenceLength:V,inputHiddenSize:0,hiddenSize:d,vHiddenSize:Me,headSize:Z,vHeadSize:Math.floor(Me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:he,scale:t.scale,broadcastResPosBias:De,passPastInKv:pe,qkvFormat:ee}},Md=e=>Bt({...e}),xi=Bt({perm:[0,2,1,3]}),bd=(e,t,s,n,i,a,o)=>{let u=[n,i,a],p=ze.size(u),h=[{type:12,data:p},{type:12,data:o},{type:12,data:a}],k=P=>{let d=It("qkv_with_bias",t.dataType,u),z=qe("qkv",t.dataType,u),B=qe("bias",s.dataType,u),V=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${P.registerUniforms(V).declareVariables(z,B,d)} + ${P.mainStart()} + ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,s],outputs:[-1]})[0]},Kn=(e,t,s,n,i,a,o,u)=>{let p=a;if(o&&ze.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=bd(e,a,o,t,n,s*i,u),p=p.reshape([t,n,s,i]),s===1||n===1?p:e.compute(pr(p,xi.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(pr(p,xi.perm),{inputs:[p],outputs:[-1]})[0]},na=(e,t)=>{let s=yd(e.inputs,t),n=e.inputs[0],i=ir(e.inputs,1),a=ir(e.inputs,2),o=ir(e.inputs,3),u=ir(e.inputs,4),p=ir(e.inputs,5),h=ir(e.inputs,6),k=ir(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 P=i&&a&&i.dims.length===4&&a.dims.length===4,d=Kn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,o,0);if(P)return Nn(e,d,i,a,u,void 0,h,k,p,s);if(!i||!a)throw new Error("key and value must be provided");let z=Kn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,i,o,s.hiddenSize),B=Kn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,a,o,2*s.hiddenSize);Nn(e,d,z,B,u,void 0,h,k,p,s)}}),xd,ia,up,dp,Ti,oa,Td,Ed=g(()=>{zt(),Ot(),rs(),Yt(),xd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ia=(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),Bt({numOutputs:n,axis:t.axis,splitSizes:s})},up=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${$t("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,dp=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=ze.size(s),i=e[0].dataType,a=ze.normalizeAxis(t.axis,s.length),o=new Array(t.numOutputs),u=qe("input",i,s.length),p=new Array(t.numOutputs),h=[],k=[],P=0,d=[{type:12,data:n}];for(let B=0;B` + ${B.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(u,...o)} + ${up(p.length)} + ${dp(o)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",a)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${$t("uniforms.size_in_split_axis","output_number - 1u",p.length)}; + ${u.indicesSet("indices",a,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:z,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:d})}},oa=(e,t)=>{xd(e.inputs);let s=e.inputs.length===1?t:ia(e.inputs,t);e.compute(Ti(e.inputs,s),{inputs:[0]})},Td=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 Bt({axis:t,numOutputs:n,splitSizes:s})}}),aa,Pd,la,ua,cp=g(()=>{rs(),no(),vd(),Ed(),Gr(),aa=(e,t)=>{if(t.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");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 u=!1,p=s.dims[0],h=s.dims[1],k=s.dims.length===3?u?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],P=h,d=0,z=!n||n.dims.length===0,B=Math.floor(z?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);z&&(k=B*t.numHeads);let V=a&&a.dims.length!==0,Z=o&&o.dims.length!==0;if(V&&a.dims.length===4&&a.dims[0]===p&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===B)throw new Error("BSNH pastKey/pastValue is not supported");if(V&&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');d=a.dims[2]}else if(V||Z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee=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"');P=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==B)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.');P=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==B)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');P=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');ee=3}let Q=0,he=!1,pe=t.kvNumHeads?B*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(P!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');pe=i.dims[2]}else{if(P!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');pe=i.dims[1]*i.dims[3],he=!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:d,kvSequenceLength:P,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:pe,headSize:B,vHeadSize:Math.floor(pe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:Q,scale:t.scale,broadcastResPosBias:!1,passPastInKv:he,qkvFormat:ee}},Pd=Bt({perm:[0,2,1,3]}),la=(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(pr(n,Pd.perm),{inputs:[n],outputs:[-1]})[0]),n},ua=(e,t)=>{var Z;let s=aa(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,u=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,P=Bt({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,k*s.headSize,k*s.headSize]}),[d,z,B]=!i&&!a?e.compute(Ti([n],P),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,a],V=Kn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,d,void 0,0);Nn(e,V,la(e,z,s),la(e,B,s),void 0,void 0,o,u,void 0,s,p,h)}}),da,ca,Cd,kd,pp=g(()=>{zt(),Ot(),Gr(),Yt(),da=(e,t,s,n,i,a,o,u)=>{let p=qt(a),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,P=i*o,d=64;P===1&&(d=256);let z=[i,o,a/p],B=[i,o,2],V=["rank","type","type"],Z=[];Z.push(...yt(z,B));let ee=Q=>{let he=qe("x",t.dataType,3,p),pe=qe("scale",s.dataType,s.dims),Me=qe("bias",n.dataType,n.dims),De=It("output",1,3,2),Le=[he,pe,Me,De];return` + var workgroup_shared : array<${k}, ${d}>; + const workgroup_size = ${d}u; + ${Q.declareVariables(...Le)} + ${Q.mainStart(d)} + 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}(${he.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(${u})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${u};${d}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:B,dataType:1}],dispatchGroup:{x:P},programUniforms:Z}),getShaderSource:ee},{inputs:[t,s,n],outputs:[-1]})[0]},ca=(e,t,s)=>{let n=t[0].dims,i=n,a=2,o=n[0],u=n[1],p=ze.sizeFromDimension(n,a),h=qt(p),k=ze.size(i)/h,P=da(e,t[0],t[1],t[2],o,p,u,s.epsilon),d=[o,u,p/h],z=[o,u],B=["type","none"],V=Z=>{let ee=qe("x",t[0].dataType,d.length,h),Q=qe("scale_shift",1,z.length,2),he=It("output",t[0].dataType,d.length,h),pe=[ee,Q,he];return` + ${Z.registerUniform("output_size","u32").declareVariables(...pe)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${he.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${Q.getByIndices("vec2(batch, channel)")}; + let value = ${ee.getByOffset("global_idx")} * ${he.type.value}(scale_shift.x) + ${he.type.value}(scale_shift.y); + ${he.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...yt(d,z,d)]}),getShaderSource:V},{inputs:[t[0],P]})},Cd=(e,t,s)=>{let n=t[0].dims,i=n,a=n[0],o=n[n.length-1],u=ze.sizeFromDimension(n,1)/o,p=qt(o),h=ze.size(i)/p,k=[{type:12,data:u},{type:12,data:Math.floor(o/p)}],P=["type","type"],d=!1,z=[0,n.length-1];for(let ee=0;een[z[Q]])),V=da(e,B,t[1],t[2],a,u,o,s.epsilon),Z=ee=>{let Q=ms(t[0].dataType),he=p===1?"vec2f":`mat${p}x2f`,pe=Le=>{let Ye=Le===0?"x":"y",at=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${Q}(${at}(scale.${Ye}))`;case 2:return`vec2<${Q}>(${at}(scale[0].${Ye}, scale[1].${Ye}))`;case 4:return`vec4<${Q}>(${at}(scale[0].${Ye}, scale[1].${Ye}, scale[2].${Ye}, scale[3].${Ye}))`;default:throw new Error(`Not supported compoents ${p}`)}},Me=qe("input",t[0].dataType,t[0].dims,p),De=It("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<${he}>; + @group(0) @binding(2) var output : array<${De.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${ee.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], ${pe(0)}, ${pe(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:Z},{inputs:[t[0],V]})},kd=(e,t)=>{t.format==="NHWC"?Cd(e,e.inputs,t):ca(e,e.inputs,t)}}),Sd,$d,Ad,hp=g(()=>{zt(),Ot(),Yt(),Sd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},$d=(e,t,s)=>{let n=t.simplified,i=e[0].dims,a=e[1],o=!n&&e[2],u=i,p=ze.normalizeAxis(t.axis,i.length),h=ze.sizeToDimension(i,p),k=ze.sizeFromDimension(i,p),P=ze.size(a.dims),d=o?ze.size(o.dims):0;if(P!==k||o&&d!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. + Size of scale and bias (if provided) must match this. + Got scale size of ${P} and bias size of ${d}`);let z=[];for(let Me=0;Me1,Q=s>2,he=Me=>{let De=ms(e[0].dataType),Le=[qe("x",e[0].dataType,e[0].dims,B),qe("scale",a.dataType,a.dims,B)];o&&Le.push(qe("bias",o.dataType,o.dims,B)),Le.push(It("output",e[0].dataType,u,B)),ee&&Le.push(It("mean_data_output",1,z)),Q&&Le.push(It("inv_std_output",1,z));let Ye=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${Me.registerUniforms(Ye).declareVariables(...Le)} + ${Me.mainStart()} + ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Ls("f32",B)}; + var mean_square_vector = ${Ls("f32",B)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${As(De,B,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Gs("mean_vector",B)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Gs("mean_square_vector",B)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${As(De,B,"x[j + offset]")}; + let f32scale = ${As(De,B,"scale[j]")}; + output[j + offset] = ${Le[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${o?`+ ${As(De,B,"bias[j]")}`:""} + ); + } + + ${ee?"mean_data_output[global_idx] = mean":""}; + ${Q?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},pe=[{dims:u,dataType:e[0].dataType}];return ee&&pe.push({dims:z,dataType:1}),Q&&pe.push({dims:z,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${B};${s};${n}`,inputDependencies:V},getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:Z}),getShaderSource:he}},Ad=(e,t)=>{Sd(e.inputs),e.compute($d(e.inputs,t,e.outputCount))}}),Id,Od,Fd=g(()=>{Ot(),Oo(),Bo(),Id=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.")},Od=e=>{Id(e.inputs);let t=Ws.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(Io(e.inputs,{activation:""},t));else{let i=t[t.length-2],a=ze.size(e.inputs[0].dims.slice(0,-2)),o=ze.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&i===1&&o===1){let u=e.inputs[0].reshape([1,a,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,a,s],k=[u,p];e.compute(hi(k,{activation:""},t,h),{inputs:k})}else e.compute(hi(e.inputs,{activation:""},t))}}}),Dd,Ld,pa,zd,Bd,ys=g(()=>{zt(),Ot(),rs(),Yt(),Dd=(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(!ze.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 u=e[2].dims;if(ze.size(u)!==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(ze.size(p)!==h)throw new Error("zeroPoints input size error.")}},Ld=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],a=t.k,o=t.n,u=s.slice(0,n-2),p=ze.size(u),h=e[1].dims[2]/4,k=e[0].dataType,P=qt(t.k),d=qt(h),z=qt(o),B=u.concat([i,o]),V=i>1&&o/z%2===0?2:1,Z=ze.size(B)/z/V,ee=64,Q=[],he=[p,i,a/P],pe=ze.convertShape(e[1].dims).slice();pe.splice(-1,1,h/d),Q.push(...yt(he)),Q.push(...yt(pe)),Q.push(...yt(e[2].dims)),e.length===4&&Q.push(...yt(ze.convertShape(e[3].dims)));let Me=[p,i,o/z];Q.push(...yt(Me));let De=Le=>{let Ye=he.length,at=qe("a",e[0].dataType,Ye,P),Et=qe("b",12,pe.length,d),Xt=qe("scales",e[2].dataType,e[2].dims.length),Zt=[at,Et,Xt],bt=e.length===4?qe("zero_points",12,e[3].dims.length):void 0;bt&&Zt.push(bt);let ss=Me.length,St=It("output",e[0].dataType,ss,z),Ft=ms(e[0].dataType),bs=(()=>{switch(P){case 1:return`array<${Ft}, 8>`;case 2:return`mat4x2<${Ft}>`;case 4:return`mat2x4<${Ft}>`;default:throw new Error(`${P}-component is not supported.`)}})(),Ht=()=>{let ot=` + // reuse a data + var input_offset = ${at.indicesToOffset(`${at.type.indices}(batch, row, word_offset)`)}; + var a_data: ${bs}; + for (var j: u32 = 0; j < ${8/P}; j++) { + a_data[j] = ${at.getByOffset("input_offset")}; + input_offset++; + } + `;for(let Pt=0;Pt> 4) & b_mask); + b_quantized_values = ${bs}(${Array.from({length:4},(cs,Ns)=>`${Ft}(b_value_lower[${Ns}]), ${Ft}(b_value_upper[${Ns}])`).join(", ")}); + b_dequantized_values = ${P===1?`${bs}(${Array.from({length:8},(cs,Ns)=>`(b_quantized_values[${Ns}] - ${bt?`zero_point${Pt}`:"zero_point"}) * scale${Pt}`).join(", ")});`:`(b_quantized_values - ${bs}(${Array(8).fill(`${bt?`zero_point${Pt}`:"zero_point"}`).join(",")})) * scale${Pt};`}; + workgroup_shared[local_id.x * ${V} + ${Math.floor(Pt/z)}]${z>1?`[${Pt%z}]`:""} += ${Array.from({length:8/P},(cs,Ns)=>`${P===1?`a_data[${Ns}] * b_dequantized_values[${Ns}]`:`dot(a_data[${Ns}], b_dequantized_values[${Ns}])`}`).join(" + ")}; + `;return ot},Rt=()=>{let ot=` + var col_index = col * ${z}; + ${bt?` + 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 = ${Ft}(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 = ${bt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${Pt} = ${Ft}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return ot},_s=()=>{let ot=`col_index = col * ${z};`;for(let Pt=0;Pt; + var b_value_upper: vec4; + var b_quantized_values: ${bs}; + var b_dequantized_values: ${bs};`,ot};return` + var workgroup_shared: array<${St.type.value}, ${V*ee}>; + ${Le.declareVariables(...Zt,St)} + ${Le.mainStart([ee,1,1])} + let output_indices = ${St.offsetToIndices(`(global_idx / ${ee}) * ${V}`)}; + 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 += ${ee}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/P}; + ${Rt()} + for (var word: u32 = 0; word < ${h}; word += ${d}) { + ${_s()} + for (var i: u32 = 0; i < ${d}; i++) { + ${Ht()} + word_offset += ${8/P}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${V}) { + var output_value: ${St.type.value} = ${St.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${ee}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${V}; + } + ${St.setByIndices(`${St.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${P};${d};${z};${V};${ee}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:k}],dispatchGroup:{x:Z},programUniforms:Q}),getShaderSource:De}},pa=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],a=t.k,o=t.n,u=s.slice(0,n-2),p=ze.size(u),h=e[1].dims[2]/4,k=e[0].dataType,P=qt(t.k),d=qt(h),z=u.concat([i,o]),B=128,V=o%8===0?8:o%4===0?4:1,Z=B/V,ee=Z*d*8,Q=ee/P,he=ee/t.blockSize,pe=ze.size(z)/V,Me=[],De=[p,i,a/P],Le=ze.convertShape(e[1].dims).slice();Le.splice(-1,1,h/d),Me.push(...yt(De)),Me.push(...yt(Le)),Me.push(...yt(e[2].dims)),e.length===4&&Me.push(...yt(ze.convertShape(e[3].dims)));let Ye=[p,i,o];Me.push(...yt(Ye));let at=Et=>{let Xt=De.length,Zt=qe("a",e[0].dataType,Xt,P),bt=qe("b",12,Le.length,d),ss=qe("scales",e[2].dataType,e[2].dims.length),St=[Zt,bt,ss],Ft=e.length===4?qe("zero_points",12,e[3].dims.length):void 0;Ft&&St.push(Ft);let bs=Ye.length,Ht=It("output",e[0].dataType,bs),Rt=ms(e[0].dataType),_s=()=>{switch(P){case 1:return` + let a_data0 = vec4<${Rt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${Rt}>(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<${Rt}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${Rt}>(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(`${P}-component is not supported.`)}};return` + var sub_a: array<${Zt.type.value}, ${Q}>; + var inter_results: array, ${V}>; + ${Et.declareVariables(...St,Ht)} + ${Et.mainStart([Z,V,1])} + let output_indices = ${Ht.offsetToIndices(`workgroup_index * ${V}`)}; + 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) / ${he} + 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 += ${B}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${Zt.getByIndices(`${Zt.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${Zt.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${he} + local_id.x; + ${Ft?` + 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 = ${Ft.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${Rt}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Rt}(8);`} + let scale = ${ss.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${bt.getByIndices(`${bt.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize/P}; + for (var i: u32 = 0; i < ${d}; i++) { + ${_s()} + let b_value = ${d===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<${Rt}>(${Array.from({length:4},(ot,Pt)=>`${Rt}(b_value_lower[${Pt}]), ${Rt}(b_value_upper[${Pt}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${Rt}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ot,Pt)=>`${`dot(a_data${Pt}, b_dequantized_values[${Pt}])`}`).join(" + ")}; + word_offset += ${8/P}; + } + workgroupBarrier(); + } + + if (local_idx < ${V}) { + 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};${P};${d};${Z};${V}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:z,dataType:k}],dispatchGroup:{x:pe},programUniforms:Me}),getShaderSource:at}},zd=(e,t)=>{Dd(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(pa(e.inputs,t)):e.compute(Ld(e.inputs,t))},Bd=e=>Bt(e)}),mp,fp,_p,ha,Rd,Nd,jd,Ud,ma,Vd=g(()=>{zt(),Ot(),Yt(),mp=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].")}},fp=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,s)}; + if (k < 0) { + break; + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + break; + } + offset += k * i32(${$t("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]; + } + `},_p=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${$t("uniforms.x_shape",i,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${$t("uniforms.x_shape",i,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},ha=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + k = i32(${$t("uniforms.x_shape",i,t)}) - 1; + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Rd=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,s)}; + if (k < 0) { + k += i32(${$t("uniforms.x_shape",i,t)}]); + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + k -= i32(${$t("uniforms.x_shape",i,t)}); + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Nd=(e,t,s)=>{switch(s.mode){case 0:return fp(e,t,s.pads.length);case 1:return _p(e,t,s.pads.length);case 2:return ha(e,t,s.pads.length);case 3:return Rd(e,t,s.pads.length);default:throw new Error("Invalid mode")}},jd=(e,t)=>{let s=ze.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=ze.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(...yt(e[0].dims,s));let u=["rank"],p=h=>{let k=It("output",e[0].dataType,s.length),P=qe("x",e[0].dataType,n.length),d=P.type.value,z=Nd(k,n.length,t),B=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&B.push({name:"constant_value",type:o?d:"f32"}),` + ${h.registerUniforms(B).declareVariables(P,k)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + + var value = ${d}(0); + ${z} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${o}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(s)/64)},programUniforms:a}),getShaderSource:p}},Ud=(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 u=e[3].getBigInt64Array();for(let p=0;pa[Number(p)]=Number(u));let o=[];return a.forEach(u=>o.push(u)),{mode:t.mode,value:n,pads:o}}else return t},ma=(e,t)=>{mp(e.inputs);let s=Ud(e.inputs,t);e.compute(jd(e.inputs,s),{inputs:[0]})}}),Ei,fa,_a,Pi,Wd,gp,Gd,ga,wa,Kd,Hd,ya,qd,Qd,Ma,Xd,Yd,Jd,wp,yp=g(()=>{We(),zt(),Ot(),Yt(),Ei=e=>{if(F.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},fa=(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(),u=t.strides.slice(),p=a?t.dilations.slice():[],h=t.pads.slice();Js.adjustPoolAttributes(s,i,o,u,p,h);let k=Js.computePoolOutputShape(s,i,u,p,o,h,t.autoPad),P=Object.assign({},t);a?Object.assign(P,{kernelShape:o,strides:u,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(P,{kernelShape:o,strides:u,pads:h,cacheKey:t.cacheKey});let d=k.slice();return d.push(d.splice(1,1)[0]),[P,n?d:k]},_a=(e,t)=>{let s=t.format==="NHWC",n=ze.size(e),i=ze.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 u=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],P=!!(h+k);a.push({type:12,data:u},{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 d=!1;if(t.kernelShape.length===2){let z=t.kernelShape[t.kernelShape.length-2],B=t.strides[t.strides.length-2],V=t.pads[t.pads.length/2-2],Z=t.pads[t.pads.length-2];d=!!(V+Z),a.push({type:12,data:z},{type:12,data:B},{type:12,data:V},{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,P,d]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=ze.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),o.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,k)=>h+k);return[a,o,!!p,!1,!1]}},Pi=(e,t,s,n,i,a,o,u,p,h,k,P)=>{let d=i.format==="NHWC",z=t.type.value,B=It("output",t.type.tensor,n);if(i.kernelShape.length<=2){let V="",Z="",ee="",Q=s-(d?2:1);if(k?V=` + 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} + }`:V=` + 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 he=s-(d?3:2);P?Z=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${he}] = indices[${he}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${he}] < 0 || xIndices[${he}] >= uniforms.x_shape[${he}]) { + pad += i32(uniforms.kw); + continue; + } + `:Z=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${he}] = indices[${he}] * uniforms.sh - uniforms.phStart + j; + `,ee=` + } + `}return` + ${e.registerUniforms(p).declareVariables(t,B)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${B.offsetToIndices("global_idx")}; + var xIndices = ${B.offsetToIndices("global_idx")}; + + var value = ${z}(${u}); + var pad = 0; + ${Z} + ${V} + ${ee} + ${o} + + output[global_idx] = value; + }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let V=i.kernelShape.length,Z=i.pads.length,ee="";return h?ee=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:ee=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + `,` + ${e.registerUniforms(p).declareVariables(t,B)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${B.offsetToIndices("global_idx")}; + var xIndices = ${B.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${z}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${V-1}u; j++) { + offsets[j] = offset / ${$t("uniforms.kernelStrides","j",V)}; + offset -= offsets[j] * ${$t("uniforms.kernelStrides","j",V)}; + } + offsets[${V-1}] = offset; + + isPad = false; + for (var j = ${s-V}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${$t("uniforms.strides",`j - ${s-V}u`,V)} + + offsets[j - ${s-V}u] - ${$t("uniforms.pads","j - 2u",Z)}; + ${ee} + } + ${o} + + output[global_idx] = value; + }`}},Wd=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,gp=e=>`${Wd(e)};${e.countIncludePad}`,Gd=e=>`${Wd(e)};${e.storageOrder};${e.dilations}`,ga=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}),wa=(e,t,s,n)=>{let[i,a]=fa(t,n,s),o=qe("x",t.dataType,t.dims.length),u=o.type.value,p="value += x_val;",h="";i.countIncludePad?h+=`value /= ${u}(uniforms.kernelSize);`:h+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[k,P,d,z,B]=_a(a,i);k.push(...yt(t.dims,a));let V=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${d};${z};${B}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ze.size(a)/64)},programUniforms:k}),getShaderSource:Z=>Pi(Z,o,t.dims.length,a.length,i,p,h,0,P,d,z,B)}},Kd=e=>{let t=e.count_include_pad!==0,s=ga(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:gp(n)}},Hd=(e,t)=>{Ei(e.inputs),e.compute(wa("AveragePool",e.inputs[0],!1,t))},ya={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},qd=e=>{let t=e.format;return{format:t,...ya,cacheKey:t}},Qd=(e,t)=>{Ei(e.inputs),e.compute(wa("GlobalAveragePool",e.inputs[0],!0,t))},Ma=(e,t,s,n)=>{let[i,a]=fa(t,n,s),o=` + value = max(x_val, value); + `,u="",p=qe("x",t.dataType,t.dims.length),h=["rank"],[k,P,d,z,B]=_a(a,i);return k.push(...yt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${d};${z};${B}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ze.size(a)/64)},programUniforms:k}),getShaderSource:V=>Pi(V,p,t.dims.length,a.length,i,o,u,t.dataType===10?-65504:-1e5,P,d,z,B)}},Xd=(e,t)=>{Ei(e.inputs),e.compute(Ma("MaxPool",e.inputs[0],!1,t))},Yd=e=>{let t=e.storage_order,s=e.dilations,n=ga(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:Gd(i)}},Jd=e=>{let t=e.format;return{format:t,...ya,cacheKey:t}},wp=(e,t)=>{Ei(e.inputs),e.compute(Ma("GlobalMaxPool",e.inputs[0],!0,t))}}),Zd,ec,tc,sc,Mp=g(()=>{zt(),Ot(),rs(),Yt(),Zd=(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)].")}},ec=(e,t)=>{let s=ze.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,a=e[0].dims,o=e[1].dataType,u=ze.size(a),p=n===3||n===2,h=p?[Math.ceil(ze.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,P=e.length>2?e[2]:void 0,d=P?p?[Math.ceil(ze.size(P.dims)/4)]:P.dims:void 0,z=k.length===0||k.length===1&&k[0]===1,B=z===!1&&k.length===1,V=qt(u),Z=z&&(!p||V===4),ee=Z?V:1,Q=Z&&!p?V:1,he=qe("input",p?12:n,h.length,Q),pe=qe("scale",o,k.length),Me=P?qe("zero_point",p?12:n,d.length):void 0,De=It("output",o,a.length,ee),Le=[he,pe];Me&&Le.push(Me);let Ye=[h,k];P&&Ye.push(d);let at=[{type:12,data:u/ee},{type:12,data:s},{type:12,data:t.blockSize},...yt(...Ye,a)],Et=Xt=>{let Zt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${Xt.registerUniforms(Zt).declareVariables(...Le,De)} + ${Xt.mainStart()} + ${Xt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${De.offsetToIndices("global_idx")}; + + // Set input x + ${p?` + let input = ${he.getByOffset("global_idx / 4")}; + let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${ee===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${he.getByOffset("global_idx")};`}; + + // Set scale input + ${z?`let scale_value= ${pe.getByOffset("0")}`:B?` + let scale_index = ${De.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${pe.getByOffset("scale_index")};`:` + var scale_indices: ${pe.type.indices} = output_indices; + let index = ${pe.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${pe.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${pe.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${Me?z?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")}`:B?p?` + let zero_point_index = ${De.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 = ${De.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${Me.getByOffset("zero_point_index")};`:p?` + let zero_point_offset = ${pe.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":he.type.value}(0);`}; + // Compute and write output + ${De.setByOffset("global_idx",`${De.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(u/ee/64),y:1,z:1},programUniforms:at})}},tc=(e,t)=>{Zd(e.inputs,t),e.compute(ec(e.inputs,t))},sc=e=>Bt({axis:e.axis,blockSize:e.blockSize})}),bp,ba,rc,vp=g(()=>{We(),zt(),Yt(),bp=(e,t,s)=>{let n=e===t,i=et&&s>0;if(n||i||a)throw new Error("Range these inputs' contents are invalid.")},ba=(e,t,s,n)=>{let i=Math.abs(Math.ceil((t-e)/s)),a=[i],o=i,u=[{type:12,data:o},{type:n,data:e},{type:n,data:s},...yt(a)],p=h=>{let k=It("output",n,a.length),P=k.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:P},{name:"delta",type:P}];return` + ${h.registerUniforms(d).declareVariables(k)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${P}(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:u})}},rc=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]),F.webgpu.validateInputContent&&bp(t,s,n),e.compute(ba(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),nc,ic,oc,ac,xp=g(()=>{zt(),Ot(),rs(),Yt(),nc=(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.`)}},ic=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s,a=1,o=Math.ceil(ze.size(n)/a),u=n[n.length-1],p=ze.sizeFromDimension(s,u),h=[{type:12,data:o},{type:12,data:u},{type:12,data:p},...yt(e[1].dims,e[2].dims,i)],k=P=>{let d=qe("indices",e[1].dataType,e[1].dims.length),z=qe("updates",e[2].dataType,e[2].dims.length,a),B=t.reduction!=="none"&&t.reduction!==""?Da("output",e[0].dataType,i.length):It("output",e[0].dataType,i.length,a);return` + ${P.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(d,z,B)} + ${P.mainStart()} + ${P.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]; + ${nc(t.reduction,"output[data_offset + i]","value",B.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}},oc=e=>Bt({reduction:e.reduction}),ac=(e,t)=>{e.compute(ic(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),lc,uc,dc,cc,pc,hc,mc,fc,_c,gc,wc,va,yc,Mc,bc,vc,xc,Tc,Ec,Tp=g(()=>{zt(),Ot(),rs(),Yt(),lc=(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")}},uc=(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},dc=(e,t,s,n,i,a)=>{let[o,u,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(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].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");lc(n,t),t.axes.length>0&&uc(n,t.axes,h).forEach((k,P)=>n[P]=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")},cc=(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`)}})()+"}",pc=(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`)}})()+"}",hc=(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},mc=(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},fc=(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},_c=(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 = ${$t("uniforms.scales","i",n)}; + var roi_low = ${$t("uniforms.roi","i",i)}; + var roi_hi = ${$t("uniforms.roi",`i + ${t.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${$t("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${$t("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; + }`,gc=(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 = ${$t("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${$t("uniforms.roi","i",a)}; + var roi_hi = ${$t("uniforms.roi",`i + ${s.length}`,a)}; + var input_shape_i = ${$t("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${$t("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; + }`,wc=(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 >= ${$t("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,va=(e,t,s,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",s,"batch")}; +`:"",yc=(e,t,s,n,i)=>{let[a,o,u,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",u,`max(0, min(col, ${s[u]} - 1))`)}; + ${va(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[${u}]; + ${n?`if (row < 0 || row > (${s[o]} - 1) || col < 0 || col > (${s[u]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${s[o]} - 1)); + col = max(0, min(col, ${s[u]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${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,u,p,h)=>{let k=s.length===2,[P,d]=k?[0,1]:[2,3],z=e.type.value,B=V=>{let Z=V===P?"row":"col";return` + fn ${Z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${z} { + var output_index = ${t.indicesGet("output_indices",V)}; + var originalIdx: ${z} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[V]}, + ${n[V]}, ${s[V]}, ${a[V]}, ${a[V]} + ${s.length}); + var fractOriginalIdx: ${z} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${s[V]} - 1))) { + return ${p}; + } + var data: array<${z}, 4> = array<${z}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${Z}: ${z} = originalIdx + ${z}(i); + if (${Z} < 0 || ${Z} >= ${s[V]}) { + ${h?`coefs[i + 1] = 0.0; + continue;`:u?`return ${p};`:`${Z} = max(0, min(${Z}, ${s[V]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",V,`u32(${Z})`)}; + data[i + 1] = ${V===P?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${B(P)}; + ${B(d)}; + fn getCubicInterpolationCoefs(s: ${z}) -> array<${z}, 4> { + var absS = abs(s); + var coeffs: array<${z}, 4> = array<${z}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${z} = 1.0 - absS; + var twoMinusAbsS: ${z} = 2.0 - absS; + var onePlusAbsS: ${z} = 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<${z}, 4>, coefs: array<${z}, 4>) -> ${z} { + var coefsSum: ${z} = 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}) -> ${z} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},bc=(e,t,s,n,i)=>{let[a,o,u,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",u,`max(0, min(height, ${s[u]} - 1))`)}; + ${e.indicesSet("input_indices",p,`max(0, min(width, ${s[p]} - 1))`)}; + ${va(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[${u}]; + var width:${k} = originalIndices[${p}]; + ${n?`if (depth < 0 || depth > (${s[o]} - 1) || height < 0 || height > (${s[u]} - 1) || width < 0 || (width > ${s[p]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${s[o]} - 1)); + height = max(0, min(height, ${s[u]} - 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); + }`},vc=(e,t,s,n,i,a)=>{let o=e.dims,u=hc(a,t.axes,o.length),p=mc(o,n,i,t.axes),h=n.slice();n.length===0&&(h=o.map((Q,he)=>Q===0?1:p[he]/Q),t.keepAspectRatioPolicy!=="stretch"&&(p=fc(o,h,t)));let k=It("output",e.dataType,p.length),P=qe("input",e.dataType,o.length),d=ze.size(p),z=o.length===p.length&&o.every((Q,he)=>Q===p[he]),B=t.coordinateTransformMode==="tf_crop_and_resize",V=t.extrapolationValue,Z=P.type.value,ee=Q=>` + ${z?"":` + ${cc(t.coordinateTransformMode,Z)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${wc(P,o)}; + ${pc(t.nearestMode,s,Z)}; + ${gc(P,k,o,p,h.length,u.length,B)}; + `;case"linear":return` + ${_c(k,o,p,h.length,u.length)}; + ${(()=>{if(o.length===2||o.length===4)return`${yc(P,k,o,B,V)}`;if(o.length===3||o.length===5)return`${bc(P,k,o,B,V)}`;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(P,k,o,p,h,u,t.cubicCoeffA,B,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",u.length).declareVariables(P,k)} + ${Q.mainStart()} + ${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${z?"output[global_idx] = input[global_idx];":` + let output_indices = ${k.offsetToIndices("global_idx")}; + var input_indices: ${P.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${P.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:""}|${u.length>0?u:""}|${z}|${o}`,inputDependencies:["rank"]},getShaderSource:ee,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:h},{type:1,data:u},...yt(o,p)]})}},xc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Tc=(e,t)=>{let s=[],n=[],i=[],a=xc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");dc(e.inputs,t,a,s,n,i),e.compute(vc(e.inputs[0],t,a,s,n,i),{inputs:[0]})},Ec=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,o=e.extrapolationValue,u=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return Bt({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:a,extrapolationValue:o,keepAspectRatioPolicy:u,mode:p,nearestMode:h})}}),Pc,Ep,Qt,Pp=g(()=>{zt(),Ot(),rs(),Yt(),Pc=(e,t)=>{let[s,n,i,a]=e,{numHeads:o,rotaryEmbeddingDim:u}=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(!ze.areEqual(n.dims,[])&&!ze.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(!ze.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>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],P=ze.sizeFromDimension(s.dims,1)/h,d=u===0?i.dims[1]*2:P/o;if(u>d)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(d/2!==i.dims[1]&&u/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Ep=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:i,scale:a}=t,o=e[0].dims[0],u=ze.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=u/p,k=e[2].dims[1],P=i===0?k*2:h/n,d=new Array(o,p,h/P,P-k),z=ze.computeStrides(d),B=[{type:1,data:a},{type:12,data:d},{type:12,data:z},...e[0].dims.length===3?new Array({type:12,data:[u,h,P,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,P,p*P,1]}):[],...yt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],V=Z=>{let ee=qe("input",e[0].dataType,e[0].dims.length),Q=qe("position_ids",e[1].dataType,e[1].dims.length),he=qe("cos_cache",e[2].dataType,e[2].dims.length),pe=qe("sin_cache",e[3].dataType,e[3].dims.length),Me=It("output",e[0].dataType,e[0].dims.length);return Z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:z.length},{name:"input_output_strides",type:"u32",length:z.length}]),` + ${Z.declareVariables(ee,Q,he,pe,Me)} + + ${Z.mainStart(nr)} + let half_rotary_emb_dim = uniforms.${he.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",It("",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 = ${ee.getByOffset("i")} * ${he.get("position_id","bsnh[3]")} - + ${ee.getByOffset("j")} * ${pe.get("position_id","bsnh[3]")}; + ${Me.setByOffset("i","re")} + let im = ${ee.getByOffset("i")} * ${pe.get("position_id","bsnh[3]")} + + ${ee.getByOffset("j")} * ${he.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",ee.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Bt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:V,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(d)/nr)},programUniforms:B})}},Qt=(e,t)=>{Pc(e.inputs,t),e.compute(Ep(e.inputs,t))}}),Ks,Xs,tr,vn=g(()=>{zt(),Ot(),Yt(),Ks=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")}},Xs=(e,t,s,n)=>{let i=t.simplified,a=e[0].dims,o=ze.size(a),u=a,p=o,h=a.slice(-1)[0],k=n?a.slice(0,-1).concat(1):[],P=!i&&e.length>3,d=e.length>4,z=n&&s>1,B=n&&s>2,V=s>3,Z=64,ee=qt(h),Q=[{type:12,data:p},{type:12,data:ee},{type:12,data:h},{type:1,data:t.epsilon}],he=Me=>{let De=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Le=[qe("x",e[0].dataType,e[0].dims,ee),qe("skip",e[1].dataType,e[1].dims,ee),qe("gamma",e[2].dataType,e[2].dims,ee)];P&&Le.push(qe("beta",e[3].dataType,e[3].dims,ee)),d&&Le.push(qe("bias",e[4].dataType,e[4].dims,ee)),Le.push(It("output",e[0].dataType,u,ee)),z&&Le.push(It("mean_output",1,k)),B&&Le.push(It("inv_std_output",1,k)),V&&Le.push(It("input_skip_bias_sum",e[0].dataType,u,ee));let Ye=ms(e[0].dataType),at=ms(1,ee);return` + + ${Me.registerUniforms(De).declareVariables(...Le)} + var sum_shared : array<${at}, ${Z}>; + var sum_squared_shared : array<${at}, ${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 = ${d?"bias[offset1d + i]":Ye+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${V?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${As(Ye,ee,"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",ee)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Gs("square_sum",ee)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${z?"mean_output[global_idx] = mean;":""} + ${B?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${i?"":`- ${Ye}(mean)`}) * + ${Ye}(inv_std_dev) * gamma[offset1d + i] + ${P?"+ beta[offset1d + i]":""}; + } + }`},pe=[{dims:u,dataType:e[0].dataType}];return s>1&&pe.push({dims:k,dataType:1}),s>2&&pe.push({dims:k,dataType:1}),s>3&&pe.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${ee};${z};${B};${V}`,inputDependencies:e.map((Me,De)=>"type")},getShaderSource:he,getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:Q})}},tr=(e,t)=>{Ks(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(Xs(e.inputs,t,e.outputCount,!1),{outputs:s})}}),Cp,Hn,Cc,f,T,j,_e,Oe,Fe=g(()=>{zt(),Ot(),rs(),Yt(),Cp=(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`)})},Hn=(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},Cc=(e,t)=>{if(e.length>1){let s=Hn(e,1),n=Hn(e,2),i=Hn(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),Bt({starts:s,ends:n,axes:i})}else return t},f=(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]]))},T=(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 = ${$t("uniforms.input_shape","i",s.length)}; + let steps_i = ${$t("uniforms.steps","i",s.length)}; + let signs_i = ${$t("uniforms.signs","i",s.length)}; + let starts_i = ${$t("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; + }`,j=(e,t)=>{let s=e[0].dims,n=ze.size(s),i=t.axes.length>0?ze.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],a=Hn(e,4);a.forEach(ee=>ee!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((ee,Q)=>f(ee,Q,s,i,a)),u=t.ends.map((ee,Q)=>f(ee,Q,s,i,a));if(i.length!==o.length||i.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==s.length)for(let ee=0;eeMath.sign(ee));a.forEach((ee,Q,he)=>{if(ee<0){let pe=(u[Q]-o[Q])/ee,Me=o[Q],De=Me+pe*a[Q];o[Q]=De,u[Q]=Me,he[Q]=-ee}});let h=s.slice(0);i.forEach((ee,Q)=>{h[ee]=Math.ceil((u[ee]-o[ee])/a[ee])});let k={dims:h,dataType:e[0].dataType},P=It("output",e[0].dataType,h.length),d=qe("input",e[0].dataType,e[0].dims.length),z=ze.size(h),B=[{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}],V=[{type:12,data:z},{type:12,data:o},{type:6,data:p},{type:12,data:a},...yt(e[0].dims,h)],Z=ee=>` + ${ee.registerUniforms(B).declareVariables(d,P)} + ${T(d,P,s)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${P.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${P.setByOffset("global_idx",d.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:V})}},_e=(e,t)=>{Cp(e.inputs,t);let s=Cc(e.inputs,t);e.compute(j(e.inputs,s),{inputs:[0]})},Oe=e=>{let t=e.starts,s=e.ends,n=e.axes;return Bt({starts:t,ends:s,axes:n})}}),et,rt,_t,Mt,jt=g(()=>{zt(),Ot(),rs(),Gr(),Yt(),et=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},rt=(e,t)=>{let s=e.inputs[0],n=s.dims,i=ze.size(n),a=n.length,o=ze.normalizeAxis(t.axis,a),u=oYe),h[o]=a-1,h[a-1]=o,p=e.compute(pr(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let k=p.dims,P=k[a-1],d=i/P,z=qt(P),B=P/z,V=64;d===1&&(V=256);let Z=(Le,Ye)=>Ye===4?`max(max(${Le}.x, ${Le}.y), max(${Le}.z, ${Le}.w))`:Ye===2?`max(${Le}.x, ${Le}.y)`:Ye===3?`max(max(${Le}.x, ${Le}.y), ${Le}.z)`:Le,ee=qe("x",p.dataType,p.dims,z),Q=It("result",p.dataType,p.dims,z),he=ee.type.value,pe=ms(p.dataType)==="f32"?`var threadMax = ${he}(-3.402823e+38f);`:`var threadMax = ${he}(-65504.0h);`,Me=Le=>` + var rowMaxShared : ${he}; + var rowSumShared : ${he}; + var threadShared : array<${he}, ${V}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${he} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${he}) { + let index = row * row_stride + col; + result[index] = value; + } + ${Le.registerUniform("packedCols","i32").declareVariables(ee,Q)} + ${Le.mainStart(V)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${V}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${pe} + 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 = ${he}(${Z("threadShared[0]",z)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${he}(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 = ${he}(${Gs("threadShared[0]",z)}); + } + 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); + } + }`,De=e.compute({name:"Softmax",shaderCache:{hint:`${z};${V}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:B}]}),getShaderSource:Me},{inputs:[p],outputs:[u?-1:0]})[0];u&&e.compute(pr(De,h),{inputs:[De]})},_t=(e,t)=>{et(e.inputs),rt(e,t)},Mt=e=>Bt({axis:e.axis})}),Vt,Lt,Gt,es,ns,Jt=g(()=>{zt(),Ot(),Yt(),Vt=e=>Array.from(e.getBigInt64Array(),Number),Lt=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(Vt(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")},Gt=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??Vt(e[1]),i=Gt(s,n),a=ze.size(i),o=e[0].dataType,u=qe("input",o,s.length),p=It("output",o,i.length),h=k=>` + const inputShape = ${u.indices(...s)}; + ${k.registerUniform("output_size","u32").declareVariables(u,p)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; + + ${u.indicesSet("input_indices","i","input_dim_value")} + } + ${p.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...yt(e[0].dims,i)]}),getShaderSource:h}},ns=e=>{Lt(e.inputs),e.compute(es(e.inputs),{inputs:[0]})}}),os,Cs,xs,fs=g(()=>{zt(),Ot(),Yt(),os=(e,t,s,n,i)=>{let a=It("output_data",i,s.length,4),o=qe("a_data",t[1].dataType,t[1].dims.length,4),u=qe("b_data",t[2].dataType,t[2].dims.length,4),p=qe("c_data",t[0].dataType,t[0].dims.length,4),h,k=(P,d,z)=>`select(${d}, ${P}, ${z})`;if(!n)h=a.setByOffset("global_idx",k(o.getByOffset("global_idx"),u.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let P=(d,z,B="")=>{let V=`a_data[index_a${z}][component_a${z}]`,Z=`b_data[index_b${z}][component_b${z}]`,ee=`bool(c_data[index_c${z}] & (0xffu << (component_c${z} * 8)))`;return` + let output_indices${z} = ${a.offsetToIndices(`global_idx * 4u + ${z}u`)}; + let offset_a${z} = ${o.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let offset_b${z} = ${u.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let offset_c${z} = ${p.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let index_a${z} = offset_a${z} / 4u; + let index_b${z} = offset_b${z} / 4u; + let index_c${z} = offset_c${z} / 4u; + let component_a${z} = offset_a${z} % 4u; + let component_b${z} = offset_b${z} % 4u; + let component_c${z} = offset_c${z} % 4u; + ${d}[${z}] = ${B}(${k(V,Z,ee)}); + `};i===9?h=` + var data = vec4(0); + ${P("data",0,"u32")} + ${P("data",1,"u32")} + ${P("data",2,"u32")} + ${P("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` + ${P("output_data[global_idx]",0)} + ${P("output_data[global_idx]",1)} + ${P("output_data[global_idx]",2)} + ${P("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(p,o,u,a)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h} + }`},Cs=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,i=e[1].dataType,a=!(ze.areEqual(t,s)&&ze.areEqual(s,n)),o=t,u=ze.size(t);if(a){let h=Ws.calcShape(Ws.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");o=h,u=ze.size(o)}let p=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>os(h,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:p},...yt(n,t,s,o)]})}},xs=e=>{e.compute(Cs(e.inputs))}}),Ps,Os=g(()=>{Kc(),no(),Hc(),qc(),Qc(),Xc(),cu(),ep(),Su(),sp(),zu(),rp(),np(),ip(),Hp(),Gn(),op(),lp(),cd(),ra(),cp(),pp(),hp(),Fd(),ys(),vd(),Vd(),yp(),Mp(),vp(),xp(),ai(),Tp(),Pp(),vn(),Fe(),jt(),Ed(),Jt(),Gr(),xo(),fs(),Ps=new Map([["Abs",[xl]],["Acos",[uo]],["Acosh",[Tl]],["Add",[eu]],["ArgMax",[Zi,eo]],["ArgMin",[fl,eo]],["Asin",[El]],["Asinh",[co]],["Atan",[Pl]],["Atanh",[Cl]],["Attention",[wl]],["AveragePool",[Hd,Kd]],["BatchNormalization",[oo]],["BiasAdd",[vl]],["BiasSplitGelu",[Yl]],["Cast",[kl,po]],["Ceil",[Al]],["Clip",[$l]],["Concat",[uu,du]],["Conv",[Ho,Wo]],["ConvTranspose",[ku,Yo]],["Cos",[ho]],["Cosh",[Il]],["CumSum",[Au,Iu]],["DepthToSpace",[Du,Lu]],["DequantizeLinear",[tc,sc]],["Div",[tu]],["Einsum",[Vu,Wu]],["Elu",[mo,jn]],["Equal",[Eo]],["Erf",[Ol]],["Exp",[fo]],["Expand",[Wn]],["FastGelu",[qu]],["Floor",[Fl]],["FusedConv",[Ho,Wo]],["Gather",[Yu,Xu]],["GatherElements",[ap,bi]],["GatherBlockQuantized",[rd,nd]],["GatherND",[Zu,ed]],["Gelu",[Dl]],["Gemm",[dd,ud]],["GlobalAveragePool",[Qd,qd]],["GlobalMaxPool",[wp,Jd]],["Greater",[nu]],["GreaterOrEqual",[Co]],["GridSample",[wd,sa]],["GroupQueryAttention",[ua]],["HardSigmoid",[Nl,wo]],["InstanceNormalization",[kd]],["LayerNormalization",[Ad]],["LeakyRelu",[_o,jn]],["Less",[iu]],["LessOrEqual",[ou]],["Log",[Hl]],["MatMul",[Od]],["MatMulNBits",[zd,Bd]],["MaxPool",[Xd,Yd]],["Mul",[su]],["MultiHeadAttention",[na,Md]],["Neg",[zl]],["Not",[Ll]],["Pad",[ma]],["Pow",[ru]],["QuickGelu",[Ql,jn]],["Range",[rc]],["Reciprocal",[go]],["ReduceMin",[cl]],["ReduceMean",[ll]],["ReduceMax",[Xi]],["ReduceSum",[Yi]],["ReduceProd",[pl]],["ReduceL1",[Qi]],["ReduceL2",[ul]],["ReduceLogSum",[ml]],["ReduceLogSumExp",[dl]],["ReduceSumSquare",[hl]],["Relu",[Bl]],["Resize",[Tc,Ec]],["RotaryEmbedding",[Qt]],["ScatterND",[ac,oc]],["Sigmoid",[Rl]],["Sin",[jl]],["Sinh",[yo]],["Slice",[_e,Oe]],["SkipLayerNormalization",[tr]],["Split",[oa,Td]],["Sqrt",[Ul]],["Softmax",[_t,Mt]],["Sub",[Po]],["Tan",[Vl]],["Tanh",[Wl]],["ThresholdedRelu",[Kl,jn]],["Tile",[ns]],["Transpose",[ja,ji]],["Where",[xs]]])}),Zs,Ys=g(()=>{We(),Pe(),Yt(),Zs=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){Ne(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let h of t)u.push({binding:u.length,resource:{buffer:h.buffer}});for(let h of s)u.push({binding:u.length,resource:{buffer:h.buffer}});i&&u.push({binding:u.length,resource:i});let p=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,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(),Re(e.programInfo.name)}dispose(){}build(e,t){Ne(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=za(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${n.join(` +`)} +${i.additionalImplementations} +${a}`,u=s.createShaderModule({code:o,label:e.name});as("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let p=s.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Re(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]}}}),Mr,xn,xa,ur,Pr,kc=g(()=>{We(),zt(),Pe(),q(),us(),Os(),Ys(),Mr=(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+`:${Mr(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},xa=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},ur=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]}},Pr=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 ur(this.device),this.adapterInfo=new xa(t.info||await t.requestAdapterInfo()),this.gpuDataManager=hs(this),this.programManager=new Zs(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Mn(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;Ne(),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=z);let V=Number(z-this.queryTimeBase),Z=Number(B-this.queryTimeBase);if(!Number.isSafeInteger(V)||!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:P.map(ee=>({dims:ee.dims,dataType:fr(ee.dataType)})),outputsMetadata:d.map(ee=>({dims:ee.dims,dataType:fr(ee.dataType)})),kernelId:o,kernelType:p,kernelName:h,programName:k,startTime:V,endTime:Z});else{let ee="";P.forEach((he,pe)=>{ee+=`input[${pe}]: [${he.dims}] | ${fr(he.dataType)}, `});let Q="";d.forEach((he,pe)=>{Q+=`output[${pe}]: [${he.dims}] | ${fr(he.dataType)}, `}),console.log(`[profiling] kernel "${o}|${p}|${h}|${k}" ${ee}${Q}execution time: ${Z-V} ns`)}Ue("GPU",`${k}::${z}::${B}`)}e.unmap(),this.pendingQueries.delete(e)}),Re()}run(e,t,s,n,i,a){Ne(e.name);let o=[];for(let Q=0;Qhe):s;if(k.length!==u.length)throw new Error(`Output size ${k.length} must be equal to ${u.length}.`);let P=[],d=[];for(let Q=0;Q=a)throw new Error(`Invalid output index: ${k[Q]}`);if(k[Q]===-3)continue;let he=k[Q]===-1,pe=k[Q]===-2,Me=he||pe?i(u[Q].dataType,u[Q].dims):n(k[Q],u[Q].dataType,u[Q].dims);if(P.push(Me),Me.data===0)continue;let De=this.gpuDataManager.get(Me.data);if(!De)throw new Error(`no GPU data for output: ${Me.data}`);if(he&&this.temporaryData.push(De),pe){let Le=this.kernelPersistentData.get(this.currentKernelId);Le||(Le=[],this.kernelPersistentData.set(this.currentKernelId,Le)),Le.push(De)}d.push(De)}if(o.length!==t.length||d.length!==P.length){if(d.length===0)return Re(e.name),P;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let z;if(h){let Q=0,he=[];h.forEach(Le=>{let Ye=typeof Le.data=="number"?[Le.data]:Le.data;if(Ye.length===0)return;let at=Le.type===10?2:4,Et,Xt;Le.type===10?(Xt=Ye.length>4?16:Ye.length>2?8:Ye.length*at,Et=Ye.length>4?16:at*Ye.length):(Xt=Ye.length<=2?Ye.length*at:16,Et=16),Q=Math.ceil(Q/Xt)*Xt,he.push(Q);let Zt=Le.type===10?8:4;Q+=Ye.length>4?Math.ceil(Ye.length/Zt)*Et:Ye.length*at});let pe=16;Q=Math.ceil(Q/pe)*pe;let Me=new ArrayBuffer(Q);h.forEach((Le,Ye)=>{let at=he[Ye],Et=typeof Le.data=="number"?[Le.data]:Le.data;if(Le.type===6)new Int32Array(Me,at,Et.length).set(Et);else if(Le.type===12)new Uint32Array(Me,at,Et.length).set(Et);else if(Le.type===10)new Uint16Array(Me,at,Et.length).set(Et);else if(Le.type===1)new Float32Array(Me,at,Et.length).set(Et);else throw new Error(`Unsupported uniform type: ${fr(Le.type)}`)});let De=this.gpuDataManager.create(Q,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(De.buffer,0,Me,0,Q),this.gpuDataManager.release(De.id),z={offset:0,size:Q,buffer:De.buffer}}let B=this.programManager.normalizeDispatchGroupSize(p),V=B[1]===1&&B[2]===1,Z=xn(e,t,V),ee=this.programManager.getArtifact(Z);if(ee||(ee=this.programManager.build(e,B),this.programManager.setArtifact(Z,ee),as("info",()=>`[artifact] key: ${Z}, programName: ${e.name}`)),h&&ee.uniformVariablesInfo){if(h.length!==ee.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${ee.uniformVariablesInfo.length}, got ${h.length} in program "${ee.programInfo.name}".`);for(let Q=0;Q`[ProgramManager] run "${e.name}" (key=${Z}) with ${B[0]}x${B[1]}x${B[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let Q={kernelId:this.currentKernelId,programName:ee.programInfo.name,inputTensorViews:t,outputTensorViews:P};this.pendingKernels.push(Q),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(Q)}return this.programManager.run(ee,o,d,B,z),Re(e.name),P}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=Ps.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,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),as("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),o(t,u[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 xt(this,e,t);return C(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(){as("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(){as("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){as("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()}}}),Ci,qn,ki,Ts,zs,Lr,on,Tn,Ta=g(()=>{Pe(),Ci=1,qn=()=>Ci++,ki=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ts=(e,t)=>{let s=ki.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},zs=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 Ts(this.dataType,this.tensorShape)}destroy(){as("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)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((n,i)=>n===s[i])}},Lr=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,n){if(this.wrapper){if(this.wrapper.canReuseTensor(e,t,s))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Ts(t,s))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 i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,s,i,!0,!0),n&&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 as("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()}},on=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=qn();return this.tensorTrackersById.set(e,new Lr(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){as("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(this.backend.currentContext,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){as("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=qn(),a=new zs({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(i,new Lr(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,s,n,i){let a=this.backend.currentSessionId,o=this.backend.currentContext;for(let[p,h]of this.freeTensors.entries())if(h.canReuseTensor(o,e,t)){as("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=a,k}as("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let u=await o.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:i});return new zs({sessionId:a,context:o,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Tn=(...e)=>new on(...e)}),Si,Ea,Pa,qp=g(()=>{zt(),ar(),q(),Ta(),Pe(),Si=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Ea=(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])},Pa=class{constructor(e){this.tensorManager=Tn(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],Mn(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=>Ea(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){as("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let i=Si.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,s,n)}uploadTensor(e,t){if(!Ms().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");as("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 C(s,t)}}registerMLTensor(e,t,s){let n=Si.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,n,s);return as("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 u=a.get(o);if(!u)throw new Error(`File with name ${o} not found in preloaded files.`);if(t+s>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=u.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 as("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),n.constant(i,h)}flush(){}}}),Ca={};b(Ca,{init:()=>Sc});var En,ka,Sc,$c=g(()=>{zt(),kc(),Pe(),Ot(),qp(),En=class wf{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=ze.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=ze.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=ze.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=ze.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(ze.size(t)!==ze.size(this.dims))throw new Error("Invalid new shape");return new wf(this.module,this.dataType,this.data,t)}},ka=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 u=[];for(let p=0;ptypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(u,p,h)=>new En(this.module,p,this.output(u,h),h),a=(u,p)=>{let h=lr(u,p);if(!h)throw new Error(`Unsupported data type: ${u}`);let k=h>0?this.backend.gpuDataManager.create(h).id:0;return new En(this.module,u,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 Pr;await a.initialize(s,n),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,u,p,h=!1)=>{if(h)as("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(u)}, size=${Number(p)}`),a.memcpy(Number(o),Number(u));else{as("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(u)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(p));a.upload(Number(u),k)}},async(o,u,p)=>{as("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${u}, size=${p}`),await a.download(Number(o),()=>t.HEAPU8.subarray(Number(u)>>>0,Number(u+p)>>>0))},(o,u,p)=>a.createKernel(o,Number(u),p,t.UTF8ToString(t._JsepGetNodeName(Number(u)))),o=>a.releaseKernel(o),(o,u,p,h)=>{as("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${o}, contextDataOffset=${u}`);let k=new ka(t,a,Number(u));return a.computeKernel(Number(o),k,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new Pa(s);i("webnn",[a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,u,p,h)=>a.ensureTensor(o,u,p,h),(o,u)=>{a.uploadTensor(o,u)},async(o,u)=>a.downloadTensor(o,u)])}}}),$i,Ac,Ic,an,ln,dr,Qp,Xp,Yp,Jp,Zp,eh,Oh=g(()=>{si(),ri(),zt(),ar(),mn(),Dn(),$i=(e,t)=>{Ms()._OrtInit(e,t)!==0&&ts("Can't initialize onnxruntime.")},Ac=async e=>{$i(e.wasm.numThreads,Zr(e.logLevel))},Ic=async(e,t)=>{{let s=($c(),M(Ca)).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",Ms(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Ms(),e)}}},an=new Map,ln=e=>{let t=Ms(),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)}},dr=e=>{let t=Ms(),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]},Qp=async(e,t)=>{var P,d,z;let s,n,i=Ms();Array.isArray(e)?[s,n]=e:e.buffer===i.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=dr(e);let a=0,o=0,u=0,p=[],h=[],k=[];try{if([o,p]=Fn(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let Me=[];for(let De of t.externalData){let Le=typeof De=="string"?De:De.path;Me.push(yn(typeof De=="string"?De:De.data).then(Ye=>{i.mountExternalData(Le,Ye)}))}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 De=Me,Le=De==null?void 0:De.context,Ye=De==null?void 0:De.gpuDevice,at=De==null?void 0:De.deviceType,Et=De==null?void 0:De.powerPreference;Le?i.currentContext=Le:Ye?i.currentContext=await i.jsepCreateMLContext(Ye):i.currentContext=await i.jsepCreateMLContext({deviceType:at,powerPreference:Et})}else i.currentContext=await i.jsepCreateMLContext();break}a=await i._OrtCreateSession(s,n,o),a===0&&ts("Can't create a session."),(P=i.jsepOnCreateSession)==null||P.call(i),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[B,V]=ln(a),Z=!!(t!=null&&t.enableGraphCapture),ee=[],Q=[],he=[];for(let Me=0;MeMe==="gpu-buffer"||Me==="ml-tensor")&&(u=i._OrtCreateBinding(a),u===0&&ts("Can't create IO binding."),pe={handle:u,outputPreferredLocations:he,outputPreferredLocationsEncoded:he.map(Me=>wn(Me))}),an.set(a,[a,h,k,pe,Z,!1]),[a,ee,Q]}catch(B){throw h.forEach(V=>i._OrtFree(V)),k.forEach(V=>i._OrtFree(V)),u!==0&&i._OrtReleaseBinding(u)!==0&&ts("Can't release IO binding."),a!==0&&i._OrtReleaseSession(a)!==0&&ts("Can't release session."),B}finally{i._free(s),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&ts("Can't release session options."),p.forEach(B=>i._free(B)),(z=i.unmountExternalData)==null||z.call(i)}},Xp=e=>{var p;let t=Ms(),s=an.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,a,o,u]=s;o&&(u&&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."),an.delete(e)},Yp=(e,t,s,n,i,a=!1)=>{if(!e){t.push(0);return}let o=Ms(),u=o.PTR_SIZE,p=e[0],h=e[1],k=e[3],P,d;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 V=e[2].gpuBuffer;d=lr(Vr(p),h);let Z=o.jsepRegisterBuffer;if(!Z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');P=Z(n,i,V,d)}else if(k==="ml-tensor"){let V=e[2].mlTensor;d=lr(Vr(p),h);let Z=o.jsepRegisterMLTensor;if(!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');P=Z(V,Vr(p),h)}else{let V=e[2];if(Array.isArray(V)){d=u*V.length,P=o._malloc(d),s.push(P);for(let Z=0;Zo.setValue(B+ee*u,Z,u===4?"i32":"i64"));let V=o._OrtCreateTensor(Vr(p),P,d,B,h.length,wn(k));V===0&&ts(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(V)}finally{o.stackRestore(z)}},Jp=async(e,t,s,n,i,a)=>{var Xt,Zt;let o=Ms(),u=o.PTR_SIZE,p=an.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],P=p[2],d=p[3],z=p[4],B=p[5],V=t.length,Z=n.length,ee=0,Q=[],he=[],pe=[],Me=[],De=o.stackSave(),Le=o.stackAlloc(V*u),Ye=o.stackAlloc(V*u),at=o.stackAlloc(Z*u),Et=o.stackAlloc(Z*u);try{(Xt=o.jsepOnRunStart)==null||Xt.call(o,h),[ee,Q]=jr(a);for(let St=0;StBs*Es,1);_s=fr(cs);let Oi=d==null?void 0:d.outputPreferredLocations[n[St]];if(_s==="string"){if(Oi==="gpu-buffer"||Oi==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Bs=[];for(let Es=0;Es0){let Bs=o.jsepGetBuffer;if(!Bs)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Es=Bs(ot),Xn=lr(cs,un);if(Xn===void 0||!_n(_s))throw new Error(`Unsupported data type: ${_s}`);Rt=!0,ss.push([_s,er,{gpuBuffer:Es,download:o.jsepCreateDownloader(Es,Xn,_s),dispose:()=>{o._OrtReleaseTensor(Ft)!==0&&ts("Can't release tensor.")}},"gpu-buffer"])}else if(Oi==="ml-tensor"&&un>0){let Bs=o.jsepEnsureTensor;if(!Bs)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(lr(cs,un)===void 0||!gn(_s))throw new Error(`Unsupported data type: ${_s}`);let Es=await Bs(ot,cs,er,!1);Rt=!0,ss.push([_s,er,{mlTensor:Es,download:o.jsepCreateMLTensorDownloader(ot,_s),dispose:()=>{o.jsepReleaseTensorId(ot),o._OrtReleaseTensor(Ft)}},"ml-tensor"])}else{let Bs=fn(_s),Es=new Bs(un);new Uint8Array(Es.buffer,Es.byteOffset,Es.byteLength).set(o.HEAPU8.subarray(ot,ot+Es.byteLength)),ss.push([_s,er,Es,"cpu"])}}finally{o.stackRestore(bs),_s==="string"&&ot&&o._free(ot),Rt||o._OrtReleaseTensor(Ft)}}return d&&!z&&(o._OrtClearBoundOutputs(d.handle)!==0&&ts("Can't clear bound outputs."),an.set(e,[h,k,P,d,z,!1])),ss}finally{o.stackRestore(De),he.forEach(bt=>o._OrtReleaseTensor(bt)),pe.forEach(bt=>o._OrtReleaseTensor(bt)),Me.forEach(bt=>o._free(bt)),ee!==0&&o._OrtReleaseRunOptions(ee),Q.forEach(bt=>o._free(bt))}},Zp=e=>{let t=Ms(),s=an.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)},eh=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Qn,br,Sa,Oc,Fc,kp,th,Sp,Ai,Ii,Fh,Dh,Lh,zh,Bh,Rh,Nh,jh,Uh=g(()=>{We(),Oh(),ar(),Rr(),Qn=()=>!!F.wasm.proxy&&typeof document<"u",Sa=!1,Oc=!1,Fc=!1,Sp=new Map,Ai=(e,t)=>{let s=Sp.get(e);s?s.push(t):Sp.set(e,[t])},Ii=()=>{if(Sa||!Oc||Fc||!br)throw new Error("worker not ready")},Fh=e=>{switch(e.data.type){case"init-wasm":Sa=!1,e.data.err?(Fc=!0,th[1](e.data.err)):(Oc=!0,th[0]()),kp&&(URL.revokeObjectURL(kp),kp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Sp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Dh=async()=>{if(!Oc){if(Sa)throw new Error("multiple calls to 'initWasm()' detected.");if(Fc)throw new Error("previous call to 'initWasm()' failed.");if(Sa=!0,Qn())return new Promise((e,t)=>{br==null||br.terminate(),Jr().then(([s,n])=>{var i;try{br=n,br.onerror=o=>t(o),br.onmessage=Fh,th=[e,t];let a={type:"init-wasm",in:F};!a.in.wasm.wasmPaths&&(s||(i=import.meta.url)!=null&&i.startsWith("file:"))&&(a.in.wasm.wasmPaths={wasm:new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href}),br.postMessage(a),kp=s}catch(a){t(a)}},t)});try{await Ir(F.wasm),await Ac(F),Oc=!0}catch(e){throw Fc=!0,e}finally{Sa=!1}}},Lh=async e=>{if(Qn())return Ii(),new Promise((t,s)=>{Ai("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:F}};br.postMessage(n)});await Ic(F,e)},zh=async e=>Qn()?(Ii(),new Promise((t,s)=>{Ai("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};br.postMessage(n,[e.buffer])})):dr(e),Bh=async(e,t)=>{if(Qn()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ii(),new Promise((s,n)=>{Ai("create",[s,n]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),br.postMessage(i,a)})}else return Qp(e,t)},Rh=async e=>{if(Qn())return Ii(),new Promise((t,s)=>{Ai("release",[t,s]);let n={type:"release",in:e};br.postMessage(n)});Xp(e)},Nh=async(e,t,s,n,i,a)=>{if(Qn()){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 Ii(),new Promise((o,u)=>{Ai("run",[o,u]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:a}};br.postMessage(h,eh(p))})}else return Jp(e,t,s,n,i,a)},jh=async e=>{if(Qn())return Ii(),new Promise((t,s)=>{Ai("end-profiling",[t,s]);let n={type:"end-profiling",in:e};br.postMessage(n)});Zp(e)}}),sh,Vh,Wh,Mf=g(()=>{We(),Uh(),zt(),Je(),Dn(),sh=(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()}`)}},Vh=e=>{switch(e[3]){case"cpu":return new le(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 le.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!gn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:i}=e[2];return le.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Wh=class{async fetchModelAndCopyToWasmMemory(e){return zh(await yn(e))}async loadModel(e,t){Ne();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await Bh(s,t),Re()}async dispose(){return Rh(this.sessionId)}async run(e,t,s){Ne();let n=[],i=[];Object.entries(e).forEach(P=>{let d=P[0],z=P[1],B=this.inputNames.indexOf(d);if(B===-1)throw new Error(`invalid input '${d}'`);n.push(z),i.push(B)});let a=[],o=[];Object.entries(t).forEach(P=>{let d=P[0],z=P[1],B=this.outputNames.indexOf(d);if(B===-1)throw new Error(`invalid output '${d}'`);a.push(z),o.push(B)});let u=n.map((P,d)=>sh(P,()=>`input "${this.inputNames[i[d]]}"`)),p=a.map((P,d)=>P?sh(P,()=>`output "${this.outputNames[o[d]]}"`):null),h=await Nh(this.sessionId,i,u,o,p,s),k={};for(let P=0;Pnh,initializeFlags:()=>rh,wasmBackend:()=>Kh});var rh,nh,Kh,bf=g(()=>{We(),Uh(),Mf(),rh=()=>{if((typeof F.wasm.initTimeout!="number"||F.wasm.initTimeout<0)&&(F.wasm.initTimeout=0),F.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 F.wasm.proxy!="boolean"&&(F.wasm.proxy=!1),typeof F.wasm.trace!="boolean"&&(F.wasm.trace=!1),typeof F.wasm.numThreads!="number"||!Number.isInteger(F.wasm.numThreads)||F.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)F.wasm.numThreads=1;else{let e=typeof navigator>"u"?N("node:os").cpus().length:navigator.hardwareConcurrency;F.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},nh=class{async init(e){rh(),await Dh(),await Lh(e)}async createInferenceSessionHandler(e,t){let s=new Wh;return await s.loadModel(e,t),Promise.resolve(s)}},Kh=new nh});We(),We(),We();var vf="1.21.0-dev.20250114-228dd16893",xf=Ae;{let e=(bf(),M(Gh)).wasmBackend;K("webgpu",e,5),K("webnn",e,5),K("cpu",e,10),K("wasm",e,10)}Object.defineProperty(F.versions,"web",{value:vf,enumerable:!0});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */},"./src/backends/onnx.js":(Ee,$,r)=>{var _;r.r($),r.d($,{Tensor:()=>N.Tensor,createInferenceSession:()=>ne,deviceToExecutionProviders:()=>K,isONNXProxy:()=>X,isONNXTensor:()=>W});var I=r("./src/env.js"),R=r("?2ce3"),Y=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96"),N=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=R??(_||(_=r.t(R,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=Y,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 O=M.InferenceSession;function K(A=null){if(!A)return y;switch(A){case"auto":return b;case"gpu":return b.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(b.includes(A))return[g[A]??A];throw new Error(`Unsupported device: "${A}". Should be one of: ${b.join(", ")}.`)}let te=null;async function ne(A,S,w){te&&await te;const x=O.create(A,S);te??(te=x);const F=await x;return F.config=w,F}function W(A){return A instanceof M.Tensor}const U=M==null?void 0:M.env;U!=null&&U.wasm&&(U.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${I.env.version}/dist/`,U.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(U.wasm.numThreads=1)),U!=null&&U.webgpu&&(U.webgpu.powerPreference="high-performance");function X(){var A;return(A=U==null?void 0:U.wasm)==null?void 0:A.proxy}I.env.backends.onnx=U},"./src/base/feature_extraction_utils.js":(Ee,$,r)=>{r.r($),r.d($,{FeatureExtractor:()=>Y,validate_audio_inputs:()=>N});var _=r("./src/utils/constants.js"),I=r("./src/utils/generic.js"),R=r("./src/utils/hub.js");class Y extends I.Callable{constructor(b){super(),this.config=b}static async from_pretrained(b,y){const M=await(0,R.getModelJSON)(b,_.FEATURE_EXTRACTOR_NAME,!0,y);return new this(M)}}function N(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":(Ee,$,r)=>{r.r($),r.d($,{ImageProcessor:()=>A,center_to_corners_format:()=>M,post_process_instance_segmentation:()=>X,post_process_object_detection:()=>v,post_process_panoptic_segmentation:()=>U,post_process_semantic_segmentation:()=>O});var _=r("./src/utils/generic.js"),I=r("./src/utils/tensor.js"),R=r("./src/utils/maths.js");r("./src/utils/image.js");var Y=r("./src/utils/core.js"),N=r("./src/utils/hub.js"),g=r("./src/utils/constants.js");function b(S,w,x=0,F=null){const ae=S/w;let ie=(0,R.bankers_round)(ae)*w;return F!==null&&ie>F&&(ie=Math.floor(ae)*w),iew&&J.push(ke)}else{let ke=(0,R.max)(ye.data)[1];if(ke===re-1||(de=(0,R.softmax)(ye.data),de[ke]Ze*Se[(se+1)%2])),Ie.boxes.push(Be),Ie.classes.push(ke),Ie.scores.push(de[ke])}}xe.push(Ie)}return xe}function O(S,w=null){const x=S.logits,F=x.dims[0];if(w!==null&&w.length!==F)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ae=[];for(let ie=0;ieSe[J]&&(Se[J]=ye[J],Ie[J]=Ge)}const Ce=new Array(we.dims[0]);for(let Ge=0;GeGe!==void 0);ae.push({segmentation:ce,labels:tt})}return ae}function K(S,w,x,F){const ae=[],ie=[],ve=[];for(let we=0;wex&&(ae.push(xe),ie.push(Ie),ve.push(ce))}return[ae,ie,ve]}function te(S,w,x,F=.5,ae=.8){const ie=[];let ve=0,we=0;const re=w[x].data;for(let ce=0;ce=F&&++we;let xe=ve>0&&we>0;return xe&&(xe=ve/we>ae),[xe,ie]}function ne(S,w,x,F,ae,ie=null,ve=null){const[we,re]=ve??S[0].dims,xe=new I.Tensor("int32",new Int32Array(we*re),[we,re]),ce=[];if(ve!==null)for(let Ge=0;GeIe[de]&&(Se[de]=Ge,Ie[de]=J[de])}let Ce=0;const tt=xe.data;for(let Ge=0;Ge200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(S,w)/Math.min(S,w)}`);let ie=Math.round(S/x)*x,ve=Math.round(w/x)*x;if(ie*ve>ae){const we=Math.sqrt(S*w/ae);ie=Math.floor(S/we/x)*x,ve=Math.floor(w/we/x)*x}else if(ie*veie?xe=Math.floor(ie*re/ae):ie>ae&&(re=Math.floor(ae*xe/ie)),await w.resize(xe,re,{resample:F}))}async crop_margin(w,x=200){const F=w.clone().grayscale(),ae=(0,R.min)(F.data)[0],ve=(0,R.max)(F.data)[0]-ae;if(ve===0)return w;const we=x/255;let re=F.width,xe=F.height,ce=0,Se=0;const Ie=F.data;for(let Ce=0;Cethis.preprocess(ie)));return{pixel_values:(0,I.stack)(F.map(ie=>ie.pixel_values),0),original_sizes:F.map(ie=>ie.original_size),reshaped_input_sizes:F.map(ie=>ie.reshaped_input_size)}}static async from_pretrained(w,x){const F=await(0,N.getModelJSON)(w,g.IMAGE_PROCESSOR_NAME,!0,x);return new this(F)}}},"./src/base/processing_utils.js":(Ee,$,r)=>{r.r($),r.d($,{Processor:()=>Y});var _=r("./src/utils/constants.js"),I=r("./src/utils/generic.js"),R=r("./src/utils/hub.js");class Y 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)}decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.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,R.getModelJSON)(g,_.PROCESSOR_NAME,!0,b):{},Promise.all(this.classes.filter(v=>v in this).map(async v=>{const O=await this[v].from_pretrained(g,b);return[v.replace(/_class$/,""),O]})).then(Object.fromEntries)]);return new this(y,M)}}fe(Y,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),fe(Y,"uses_processor_config",!1)},"./src/configs.js":(Ee,$,r)=>{r.r($),r.d($,{AutoConfig:()=>b,PretrainedConfig:()=>g,getKeyValueShapes:()=>N});var _=r("./src/utils/core.js"),I=r("./src/utils/hub.js");async function R(y,M){return await(0,I.getModelJSON)(y,"config.json",!0,M)}function Y(y){const M={};let v={};switch(y.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":v=Y(y.text_config);break;case"moondream1":v=Y(y.phi_config);break;case"musicgen":v=Y(y.decoder);break;case"multi_modality":v=Y(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 K=Y(y.decoder),te="num_decoder_layers"in K,ne=(0,_.pick)(y,["model_type","is_encoder_decoder"]);return te?(ne.num_decoder_layers=K.num_decoder_layers,ne.num_decoder_heads=K.num_decoder_heads,ne.decoder_hidden_size=K.decoder_hidden_size,ne.num_encoder_layers=K.num_encoder_layers,ne.num_encoder_heads=K.num_encoder_heads,ne.encoder_hidden_size=K.encoder_hidden_size):(ne.num_layers=K.num_layers,ne.num_heads=K.num_heads,ne.hidden_size=K.hidden_size),ne}const O={...v,...(0,_.pick)(y,["model_type","multi_query","is_encoder_decoder"])};for(const K in M)O[K]=y[M[K]];return O}function N(y,{prefix:M="past_key_values",batch_size:v=1}={}){const O={},K=y.normalized_config;if(K.is_encoder_decoder&&"num_encoder_heads"in K&&"num_decoder_heads"in K){const te=K.encoder_dim_kv??K.encoder_hidden_size/K.num_encoder_heads,ne=K.decoder_dim_kv??K.decoder_hidden_size/K.num_decoder_heads,W=[v,K.num_encoder_heads,0,te],U=[v,K.num_decoder_heads,0,ne];for(let X=0;X{var F,ae;r.r($),r.d($,{apis:()=>ne,env:()=>w});var _=r("?569f"),I=r("?3f59"),R=r("?154a");const Y="3.3.1",N=typeof window<"u"&&typeof window.document<"u",g=typeof self<"u"&&((F=self.constructor)==null?void 0:F.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",O=v&&((ae=process==null?void 0:process.release)==null?void 0:ae.name)==="node",K=!x(_),te=!x(I),ne=Object.freeze({IS_BROWSER_ENV:N,IS_WEBWORKER_ENV:g,IS_WEB_CACHE_AVAILABLE:b,IS_WEBGPU_AVAILABLE:y,IS_WEBNN_AVAILABLE:M,IS_PROCESS_AVAILABLE:v,IS_NODE_ENV:O,IS_FS_AVAILABLE:K,IS_PATH_AVAILABLE:te}),W=K&&te;let U="./";if(W){const ie=Object(import.meta).url;ie?U=I.dirname(I.dirname(R.fileURLToPath(ie))):typeof __dirname<"u"&&(U=I.dirname(__dirname))}const X=W?I.join(U,"/.cache/"):null,A="/models/",S=W?I.join(U,A):A,w={version:Y,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(N||g),localModelPath:S,useFS:K,useBrowserCache:b,useFSCache:K,cacheDir:X,useCustomCache:!1,customCache:null};function x(ie){return Object.keys(ie).length===0}},"./src/generation/configuration_utils.js":(Ee,$,r)=>{r.r($),r.d($,{GenerationConfig:()=>I});var _=r("./src/utils/core.js");class I{constructor(Y){fe(this,"max_length",20);fe(this,"max_new_tokens",null);fe(this,"min_length",0);fe(this,"min_new_tokens",null);fe(this,"early_stopping",!1);fe(this,"max_time",null);fe(this,"do_sample",!1);fe(this,"num_beams",1);fe(this,"num_beam_groups",1);fe(this,"penalty_alpha",null);fe(this,"use_cache",!0);fe(this,"temperature",1);fe(this,"top_k",50);fe(this,"top_p",1);fe(this,"typical_p",1);fe(this,"epsilon_cutoff",0);fe(this,"eta_cutoff",0);fe(this,"diversity_penalty",0);fe(this,"repetition_penalty",1);fe(this,"encoder_repetition_penalty",1);fe(this,"length_penalty",1);fe(this,"no_repeat_ngram_size",0);fe(this,"bad_words_ids",null);fe(this,"force_words_ids",null);fe(this,"renormalize_logits",!1);fe(this,"constraints",null);fe(this,"forced_bos_token_id",null);fe(this,"forced_eos_token_id",null);fe(this,"remove_invalid_values",!1);fe(this,"exponential_decay_length_penalty",null);fe(this,"suppress_tokens",null);fe(this,"streamer",null);fe(this,"begin_suppress_tokens",null);fe(this,"forced_decoder_ids",null);fe(this,"guidance_scale",null);fe(this,"num_return_sequences",1);fe(this,"output_attentions",!1);fe(this,"output_hidden_states",!1);fe(this,"output_scores",!1);fe(this,"return_dict_in_generate",!1);fe(this,"pad_token_id",null);fe(this,"bos_token_id",null);fe(this,"eos_token_id",null);fe(this,"encoder_no_repeat_ngram_size",0);fe(this,"decoder_start_token_id",null);fe(this,"generation_kwargs",{});Object.assign(this,(0,_.pick)(Y,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Ee,$,r)=>{r.r($),r.d($,{ClassifierFreeGuidanceLogitsProcessor:()=>W,ForcedBOSTokenLogitsProcessor:()=>g,ForcedEOSTokenLogitsProcessor:()=>b,LogitsProcessor:()=>R,LogitsProcessorList:()=>N,LogitsWarper:()=>Y,MinLengthLogitsProcessor:()=>K,MinNewTokensLengthLogitsProcessor:()=>te,NoBadWordsLogitsProcessor:()=>ne,NoRepeatNGramLogitsProcessor:()=>v,RepetitionPenaltyLogitsProcessor:()=>O,SuppressTokensAtBeginLogitsProcessor:()=>y,TemperatureLogitsWarper:()=>U,TopKLogitsWarper:()=>A,TopPLogitsWarper:()=>X,WhisperTimeStampLogitsProcessor:()=>M});var _=r("./src/utils/generic.js");r("./src/utils/tensor.js");var I=r("./src/utils/maths.js");class R extends _.Callable{_call(w,x){throw Error("`_call` should be implemented in a subclass")}}class Y extends _.Callable{_call(w,x){throw Error("`_call` should be implemented in a subclass")}}class N extends _.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,x){let F=x;for(const ae of this.processors)F=ae(w,F);return F}[Symbol.iterator](){return this.processors.values()}}class g extends R{constructor(w){super(),this.bos_token_id=w}_call(w,x){for(let F=0;F=1&&ie[ie.length-1]>=this.timestamp_begin,we=ie.length<2||ie[ie.length-2]>=this.timestamp_begin;if(ve&&(we?ae.subarray(this.timestamp_begin).fill(-1/0):ae.subarray(0,this.eos_token_id).fill(-1/0)),w[F].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Se=this.timestamp_begin+this.max_initial_timestamp_index;ae.subarray(Se+1).fill(-1/0)}const re=(0,I.log_softmax)(ae),xe=Math.log(re.subarray(this.timestamp_begin).map(Math.exp).reduce((Se,Ie)=>Se+Ie)),ce=(0,I.max)(re.subarray(0,this.timestamp_begin))[0];xe>ce&&ae.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class v extends R{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const x=w.length,F=[];for(let ie=0;ie1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,x){if(x.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 ${x.dims[0]} for the logits and ${w.length} for the input ids.`);const F=w.length,ae=x.slice([0,F],null),ie=x.slice([F,x.dims[0]],null);for(let ve=0;ve1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger(F)||F<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${F}`);this.top_p=w,this.filter_value=x,this.min_tokens_to_keep=F}}class A extends Y{constructor(w,{filter_value:x=-1/0,min_tokens_to_keep:F=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,F),this.filter_value=x}}},"./src/generation/logits_sampler.js":(Ee,$,r)=>{r.r($),r.d($,{LogitsSampler:()=>Y});var _=r("./src/utils/generic.js"),I=r("./src/utils/tensor.js"),R=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class Y 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 O=M.dims.at(-1),K=M.data;if(v===-1)K=K.slice(-O);else{let te=v*O;K=K.slice(te,te+O)}return K}randomSelect(M){let v=0;for(let K=0;K1)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 N(M)}}class N extends Y{async sample(M){const v=(0,R.max)(M.data)[1];return[[BigInt(v),0]]}}class g extends Y{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[O,K]=await(0,I.topk)(M,v),te=(0,R.softmax)(O.data);return Array.from({length:this.generation_config.num_beams},()=>{const ne=this.randomSelect(te);return[K.data[ne],Math.log(te[ne])]})}}class b extends Y{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[O,K]=await(0,I.topk)(M,v),te=(0,R.softmax)(O.data);return Array.from({length:this.generation_config.num_beams},(ne,W)=>[K.data[W],Math.log(te[W])])}}},"./src/generation/stopping_criteria.js":(Ee,$,r)=>{r.r($),r.d($,{EosTokenCriteria:()=>N,InterruptableStoppingCriteria:()=>g,MaxLengthCriteria:()=>Y,StoppingCriteria:()=>I,StoppingCriteriaList:()=>R});var _=r("./src/utils/generic.js");class I extends _.Callable{_call(y,M){throw Error("StoppingCriteria needs to be subclassed")}}class R extends _.Callable{constructor(){super(),this.criteria=[]}push(y){this.criteria.push(y)}extend(y){y instanceof R?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 O of this.criteria){const K=O(y,M);for(let te=0;teM.length>=this.max_length)}}class N extends I{constructor(y){super(),Array.isArray(y)||(y=[y]),this.eos_token_id=y}_call(y,M){return y.map(v=>{const O=v.at(-1);return this.eos_token_id.some(K=>O==K)})}}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":(Ee,$,r)=>{r.r($),r.d($,{BaseStreamer:()=>Y,TextStreamer:()=>g,WhisperTextStreamer:()=>b});var _=r("./src/utils/core.js"),I=r("./src/tokenizers.js"),R=r("./src/env.js");class Y{put(M){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const N=R.apis.IS_PROCESS_AVAILABLE?y=>process.stdout.write(y):y=>console.log(y);class g extends Y{constructor(M,{skip_prompt:v=!1,callback_function:O=null,token_callback_function:K=null,skip_special_tokens:te=!0,decode_kwargs:ne={},...W}={}){super(),this.tokenizer=M,this.skip_prompt=v,this.callback_function=O??N,this.token_callback_function=K,this.decode_kwargs={skip_special_tokens:te,...ne,...W},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(M){var te;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];(te=this.token_callback_function)==null||te.call(this,v),this.token_cache=(0,_.mergeArrays)(this.token_cache,v);const O=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let K;O.endsWith(` +`)?(K=O.slice(this.print_len),this.token_cache=[],this.print_len=0):O.length>0&&(0,I.is_chinese_char)(O.charCodeAt(O.length-1))?(K=O.slice(this.print_len),this.print_len+=K.length):(K=O.slice(this.print_len,O.lastIndexOf(" ")+1),this.print_len+=K.length),this.on_finalized_text(K,!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 O,K;M.length>0&&((O=this.callback_function)==null||O.call(this,M)),v&&this.callback_function===N&&R.apis.IS_PROCESS_AVAILABLE&&((K=this.callback_function)==null||K.call(this,` +`))}}class b extends g{constructor(M,{skip_prompt:v=!1,callback_function:O=null,token_callback_function:K=null,on_chunk_start:te=null,on_chunk_end:ne=null,on_finalize:W=null,time_precision:U=.02,skip_special_tokens:X=!0,decode_kwargs:A={}}={}){super(M,{skip_prompt:v,skip_special_tokens:X,callback_function:O,token_callback_function:K,decode_kwargs:A}),this.timestamp_begin=M.timestamp_begin,this.on_chunk_start=te,this.on_chunk_end=ne,this.on_finalize=W,this.time_precision=U,this.waiting_for_timestamp=!1}put(M){var O,K;if(M.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const v=M[0];if(v.length===1){const te=Number(v[0])-this.timestamp_begin;if(te>=0){const ne=te*this.time_precision;this.waiting_for_timestamp?(O=this.on_chunk_end)==null||O.call(this,ne):(K=this.on_chunk_start)==null||K.call(this,ne),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":(Ee,$,r)=>{r.r($),r.d($,{ASTForAudioClassification:()=>Bi,ASTModel:()=>Ba,ASTPreTrainedModel:()=>Yt,AlbertForMaskedLM:()=>as,AlbertForQuestionAnswering:()=>Rn,AlbertForSequenceClassification:()=>Mn,AlbertModel:()=>Bn,AlbertPreTrainedModel:()=>Wr,AutoModel:()=>ba,AutoModelForAudioClassification:()=>va,AutoModelForAudioFrameClassification:()=>Mc,AutoModelForCTC:()=>wc,AutoModelForCausalLM:()=>xp,AutoModelForDepthEstimation:()=>Tc,AutoModelForDocumentQuestionAnswering:()=>bc,AutoModelForImageClassification:()=>cc,AutoModelForImageFeatureExtraction:()=>Pc,AutoModelForImageMatting:()=>vc,AutoModelForImageSegmentation:()=>pc,AutoModelForImageToImage:()=>xc,AutoModelForMaskGeneration:()=>gc,AutoModelForMaskedLM:()=>lc,AutoModelForNormalEstimation:()=>Ec,AutoModelForObjectDetection:()=>fc,AutoModelForPoseEstimation:()=>Tp,AutoModelForQuestionAnswering:()=>uc,AutoModelForSemanticSegmentation:()=>hc,AutoModelForSeq2SeqLM:()=>nc,AutoModelForSequenceClassification:()=>rc,AutoModelForSpeechSeq2Seq:()=>ic,AutoModelForTextToSpectrogram:()=>oc,AutoModelForTextToWaveform:()=>ac,AutoModelForTokenClassification:()=>vp,AutoModelForUniversalSegmentation:()=>mc,AutoModelForVision2Seq:()=>dc,AutoModelForXVector:()=>yc,AutoModelForZeroShotObjectDetection:()=>_c,BartForConditionalGeneration:()=>Kt,BartForSequenceClassification:()=>hs,BartModel:()=>xt,BartPretrainedModel:()=>ft,BaseModelOutput:()=>je,BeitForImageClassification:()=>lu,BeitModel:()=>au,BeitPreTrainedModel:()=>ko,BertForMaskedLM:()=>Ue,BertForQuestionAnswering:()=>Re,BertForSequenceClassification:()=>Ve,BertForTokenClassification:()=>Ne,BertModel:()=>Te,BertPreTrainedModel:()=>le,BlenderbotForConditionalGeneration:()=>Js,BlenderbotModel:()=>ze,BlenderbotPreTrainedModel:()=>Ws,BlenderbotSmallForConditionalGeneration:()=>qs,BlenderbotSmallModel:()=>Ss,BlenderbotSmallPreTrainedModel:()=>Or,BloomForCausalLM:()=>Dl,BloomModel:()=>Fl,BloomPreTrainedModel:()=>fo,CLIPModel:()=>Xa,CLIPPreTrainedModel:()=>tn,CLIPSegForImageSegmentation:()=>rl,CLIPSegModel:()=>sl,CLIPSegPreTrainedModel:()=>Gi,CLIPTextModel:()=>Vc,CLIPTextModelWithProjection:()=>Ya,CLIPVisionModel:()=>Wc,CLIPVisionModelWithProjection:()=>Ja,CamembertForMaskedLM:()=>Xr,CamembertForQuestionAnswering:()=>Yr,CamembertForSequenceClassification:()=>Sr,CamembertForTokenClassification:()=>$r,CamembertModel:()=>Nt,CamembertPreTrainedModel:()=>xr,CausalLMOutput:()=>vn,CausalLMOutputWithPast:()=>Cp,ChineseCLIPModel:()=>gr,ChineseCLIPPreTrainedModel:()=>Gc,ClapAudioModelWithProjection:()=>gd,ClapModel:()=>fd,ClapPreTrainedModel:()=>vi,ClapTextModelWithProjection:()=>_d,CodeGenForCausalLM:()=>fl,CodeGenModel:()=>Ji,CodeGenPreTrainedModel:()=>ai,CohereForCausalLM:()=>qc,CohereModel:()=>vl,CoherePreTrainedModel:()=>ao,ConvBertForMaskedLM:()=>kt,ConvBertForQuestionAnswering:()=>ws,ConvBertForSequenceClassification:()=>At,ConvBertForTokenClassification:()=>is,ConvBertModel:()=>vt,ConvBertPreTrainedModel:()=>mt,ConvNextForImageClassification:()=>ep,ConvNextModel:()=>Ho,ConvNextPreTrainedModel:()=>Ko,ConvNextV2ForImageClassification:()=>Tu,ConvNextV2Model:()=>tp,ConvNextV2PreTrainedModel:()=>qo,DPTForDepthEstimation:()=>Un,DPTModel:()=>jo,DPTPreTrainedModel:()=>No,DebertaForMaskedLM:()=>Ar,DebertaForQuestionAnswering:()=>or,DebertaForSequenceClassification:()=>Br,DebertaForTokenClassification:()=>Rr,DebertaModel:()=>Jr,DebertaPreTrainedModel:()=>cr,DebertaV2ForMaskedLM:()=>Dt,DebertaV2ForQuestionAnswering:()=>Ir,DebertaV2ForSequenceClassification:()=>Vs,DebertaV2ForTokenClassification:()=>Nr,DebertaV2Model:()=>Tt,DebertaV2PreTrainedModel:()=>it,DecisionTransformerModel:()=>Sd,DecisionTransformerPreTrainedModel:()=>pp,DeiTForImageClassification:()=>Oo,DeiTModel:()=>Io,DeiTPreTrainedModel:()=>bn,DepthAnythingForDepthEstimation:()=>Uo,DepthAnythingPreTrainedModel:()=>_u,DepthProForDepthEstimation:()=>Mu,DepthProPreTrainedModel:()=>yu,DetrForObjectDetection:()=>du,DetrForSegmentation:()=>cu,DetrModel:()=>uu,DetrObjectDetectionOutput:()=>Kr,DetrPreTrainedModel:()=>ci,DetrSegmentationOutput:()=>sn,Dinov2ForImageClassification:()=>Xo,Dinov2Model:()=>Eu,Dinov2PreTrainedModel:()=>Qo,Dinov2WithRegistersForImageClassification:()=>Jo,Dinov2WithRegistersModel:()=>Pu,Dinov2WithRegistersPreTrainedModel:()=>Yo,DistilBertForMaskedLM:()=>mn,DistilBertForQuestionAnswering:()=>ts,DistilBertForSequenceClassification:()=>Is,DistilBertForTokenClassification:()=>Tr,DistilBertModel:()=>ar,DistilBertPreTrainedModel:()=>Ms,DonutSwinModel:()=>xu,DonutSwinPreTrainedModel:()=>Go,EfficientNetForImageClassification:()=>xd,EfficientNetModel:()=>vd,EfficientNetPreTrainedModel:()=>na,ElectraForMaskedLM:()=>sr,ElectraForQuestionAnswering:()=>Us,ElectraForSequenceClassification:()=>kr,ElectraForTokenClassification:()=>Qr,ElectraModel:()=>Ds,ElectraPreTrainedModel:()=>ks,EsmForMaskedLM:()=>An,EsmForSequenceClassification:()=>In,EsmForTokenClassification:()=>On,EsmModel:()=>si,EsmPreTrainedModel:()=>jr,ExaoneForCausalLM:()=>_l,ExaoneModel:()=>li,ExaonePreTrainedModel:()=>to,FalconForCausalLM:()=>md,FalconModel:()=>hd,FalconPreTrainedModel:()=>ta,FastViTForImageClassification:()=>Qc,FastViTModel:()=>Yl,FastViTPreTrainedModel:()=>To,Florence2ForConditionalGeneration:()=>Ga,Florence2PreTrainedModel:()=>Wa,GLPNForDepthEstimation:()=>Wo,GLPNModel:()=>_i,GLPNPreTrainedModel:()=>Vo,GPT2LMHeadModel:()=>il,GPT2Model:()=>nl,GPT2PreTrainedModel:()=>Ki,GPTBigCodeForCausalLM:()=>ml,GPTBigCodeModel:()=>hl,GPTBigCodePreTrainedModel:()=>Yi,GPTJForCausalLM:()=>pl,GPTJModel:()=>cl,GPTJPreTrainedModel:()=>Xi,GPTNeoForCausalLM:()=>ll,GPTNeoModel:()=>yr,GPTNeoPreTrainedModel:()=>qi,GPTNeoXForCausalLM:()=>dl,GPTNeoXModel:()=>ul,GPTNeoXPreTrainedModel:()=>Qi,Gemma2ForCausalLM:()=>El,Gemma2Model:()=>Tl,Gemma2PreTrainedModel:()=>uo,GemmaForCausalLM:()=>xl,GemmaModel:()=>ds,GemmaPreTrainedModel:()=>lo,GraniteForCausalLM:()=>bl,GraniteModel:()=>Hc,GranitePreTrainedModel:()=>oo,GroundingDinoForObjectDetection:()=>ku,GroundingDinoPreTrainedModel:()=>Cu,GroupViTModel:()=>Xl,GroupViTPreTrainedModel:()=>xo,HieraForImageClassification:()=>Do,HieraModel:()=>hu,HieraPreTrainedModel:()=>Fo,HubertForCTC:()=>Zu,HubertForSequenceClassification:()=>ed,HubertModel:()=>Ju,HubertPreTrainedModel:()=>Hp,IJepaForImageClassification:()=>Vl,IJepaModel:()=>Ul,IJepaPreTrainedModel:()=>yo,Idefics3ForConditionalGeneration:()=>Ui,Idefics3PreTrainedModel:()=>qa,ImageMattingOutput:()=>Hn,JAISLMHeadModel:()=>al,JAISModel:()=>ol,JAISPreTrainedModel:()=>Hi,JinaCLIPModel:()=>oi,JinaCLIPPreTrainedModel:()=>ii,JinaCLIPTextModel:()=>Wi,JinaCLIPVisionModel:()=>wr,LlamaForCausalLM:()=>Kc,LlamaModel:()=>eo,LlamaPreTrainedModel:()=>Zi,LlavaForConditionalGeneration:()=>ni,LlavaOnevisionForConditionalGeneration:()=>Ua,LlavaPreTrainedModel:()=>Gr,LongT5ForConditionalGeneration:()=>$e,LongT5Model:()=>be,LongT5PreTrainedModel:()=>ue,M2M100ForConditionalGeneration:()=>Vn,M2M100Model:()=>gi,M2M100PreTrainedModel:()=>zu,MBartForCausalLM:()=>rr,MBartForConditionalGeneration:()=>Bt,MBartForSequenceClassification:()=>rs,MBartModel:()=>Fs,MBartPreTrainedModel:()=>us,MPNetForMaskedLM:()=>Zr,MPNetForQuestionAnswering:()=>wn,MPNetForSequenceClassification:()=>_n,MPNetForTokenClassification:()=>gn,MPNetModel:()=>fn,MPNetPreTrainedModel:()=>lr,MT5ForConditionalGeneration:()=>gt,MT5Model:()=>pt,MT5PreTrainedModel:()=>Qe,MarianMTModel:()=>Lu,MarianModel:()=>Du,MarianPreTrainedModel:()=>Zo,MaskFormerForInstanceSegmentation:()=>fi,MaskFormerModel:()=>vu,MaskFormerPreTrainedModel:()=>bu,MaskedLMOutput:()=>Xs,MgpstrForSceneTextRecognition:()=>Od,MgpstrModelOutput:()=>hp,MgpstrPreTrainedModel:()=>Id,MistralForCausalLM:()=>Dr,MistralModel:()=>Er,MistralPreTrainedModel:()=>cd,MobileBertForMaskedLM:()=>ri,MobileBertForQuestionAnswering:()=>fr,MobileBertForSequenceClassification:()=>Vr,MobileBertModel:()=>Fn,MobileBertPreTrainedModel:()=>Ur,MobileLLMForCausalLM:()=>Nn,MobileLLMModel:()=>gl,MobileLLMPreTrainedModel:()=>so,MobileNetV1ForImageClassification:()=>Ed,MobileNetV1Model:()=>Td,MobileNetV1PreTrainedModel:()=>oa,MobileNetV2ForImageClassification:()=>la,MobileNetV2Model:()=>Pd,MobileNetV2PreTrainedModel:()=>aa,MobileNetV3ForImageClassification:()=>da,MobileNetV3Model:()=>cp,MobileNetV3PreTrainedModel:()=>ua,MobileNetV4ForImageClassification:()=>kd,MobileNetV4Model:()=>Cd,MobileNetV4PreTrainedModel:()=>ca,MobileViTForImageClassification:()=>tu,MobileViTModel:()=>eu,MobileViTPreTrainedModel:()=>mr,MobileViTV2ForImageClassification:()=>ru,MobileViTV2Model:()=>su,MobileViTV2PreTrainedModel:()=>Eo,ModelOutput:()=>Ke,ModernBertForMaskedLM:()=>ct,ModernBertForSequenceClassification:()=>lt,ModernBertForTokenClassification:()=>ht,ModernBertModel:()=>dt,ModernBertPreTrainedModel:()=>st,Moondream1ForConditionalGeneration:()=>Va,MoonshineForConditionalGeneration:()=>ja,MoonshineModel:()=>pr,MoonshinePreTrainedModel:()=>Ni,MptForCausalLM:()=>zl,MptModel:()=>Ll,MptPreTrainedModel:()=>_o,MultiModalityCausalLM:()=>Ad,MultiModalityPreTrainedModel:()=>$d,MusicgenForCausalLM:()=>dp,MusicgenForConditionalGeneration:()=>Ti,MusicgenModel:()=>up,MusicgenPreTrainedModel:()=>ia,NomicBertModel:()=>oe,NomicBertPreTrainedModel:()=>L,OPTForCausalLM:()=>Rl,OPTModel:()=>Bl,OPTPreTrainedModel:()=>go,Olmo2ForCausalLM:()=>Ml,Olmo2Model:()=>yl,Olmo2PreTrainedModel:()=>io,OlmoForCausalLM:()=>no,OlmoModel:()=>wl,OlmoPreTrainedModel:()=>ro,OpenELMForCausalLM:()=>Cl,OpenELMModel:()=>Pl,OpenELMPreTrainedModel:()=>co,OwlViTForObjectDetection:()=>iu,OwlViTModel:()=>nu,OwlViTPreTrainedModel:()=>Po,Owlv2ForObjectDetection:()=>Xc,Owlv2Model:()=>ou,Owlv2PreTrainedModel:()=>Co,PaliGemmaForConditionalGeneration:()=>Ha,PaliGemmaPreTrainedModel:()=>Ka,PatchTSMixerForPrediction:()=>Bd,PatchTSMixerModel:()=>zd,PatchTSMixerPreTrainedModel:()=>pa,PatchTSTForPrediction:()=>Ld,PatchTSTModel:()=>Dd,PatchTSTPreTrainedModel:()=>Fd,Phi3ForCausalLM:()=>Ol,Phi3Model:()=>ui,Phi3PreTrainedModel:()=>mo,Phi3VForCausalLM:()=>hr,Phi3VPreTrainedModel:()=>Qa,PhiForCausalLM:()=>jn,PhiModel:()=>Il,PhiPreTrainedModel:()=>ho,PreTrainedModel:()=>se,PretrainedMixin:()=>ys,PvtForImageClassification:()=>Gl,PvtModel:()=>bo,PvtPreTrainedModel:()=>di,PyAnnoteForAudioFrameClassification:()=>Vu,PyAnnoteModel:()=>Uu,PyAnnotePreTrainedModel:()=>wi,QuestionAnsweringModelOutput:()=>tr,Qwen2ForCausalLM:()=>Sl,Qwen2Model:()=>kl,Qwen2PreTrainedModel:()=>po,Qwen2VLForConditionalGeneration:()=>Al,Qwen2VLPreTrainedModel:()=>$l,RTDetrForObjectDetection:()=>rn,RTDetrModel:()=>So,RTDetrObjectDetectionOutput:()=>Qs,RTDetrPreTrainedModel:()=>Hr,ResNetForImageClassification:()=>Lo,ResNetModel:()=>mu,ResNetPreTrainedModel:()=>pi,RoFormerForMaskedLM:()=>Ae,RoFormerForQuestionAnswering:()=>ut,RoFormerForSequenceClassification:()=>We,RoFormerForTokenClassification:()=>Je,RoFormerModel:()=>me,RoFormerPreTrainedModel:()=>H,RobertaForMaskedLM:()=>_r,RobertaForQuestionAnswering:()=>yt,RobertaForSequenceClassification:()=>ms,RobertaForTokenClassification:()=>$s,RobertaModel:()=>nr,RobertaPreTrainedModel:()=>Ot,SamImageSegmentationOutput:()=>Fu,SamModel:()=>Ou,SamPreTrainedModel:()=>sp,SapiensForDepthEstimation:()=>wu,SapiensForNormalEstimation:()=>Zc,SapiensForSemanticSegmentation:()=>gu,SapiensPreTrainedModel:()=>mi,SegformerForImageClassification:()=>yd,SegformerForSemanticSegmentation:()=>Md,SegformerModel:()=>ir,SegformerPreTrainedModel:()=>ra,Seq2SeqLMOutput:()=>Ep,SequenceClassifierOutput:()=>Qt,SiglipModel:()=>Za,SiglipPreTrainedModel:()=>Vi,SiglipTextModel:()=>el,SiglipVisionModel:()=>tl,SpeechT5ForSpeechToText:()=>lp,SpeechT5ForTextToSpeech:()=>ad,SpeechT5HifiGan:()=>ld,SpeechT5Model:()=>ap,SpeechT5PreTrainedModel:()=>bi,SqueezeBertForMaskedLM:()=>Dn,SqueezeBertForQuestionAnswering:()=>zn,SqueezeBertForSequenceClassification:()=>Ln,SqueezeBertModel:()=>yn,SqueezeBertPreTrainedModel:()=>zt,StableLmForCausalLM:()=>Kn,StableLmModel:()=>bd,StableLmPreTrainedModel:()=>xi,Starcoder2ForCausalLM:()=>pd,Starcoder2Model:()=>nn,Starcoder2PreTrainedModel:()=>qr,StyleTextToSpeech2Model:()=>od,StyleTextToSpeech2PreTrainedModel:()=>id,Swin2SRForImageSuperResolution:()=>Jc,Swin2SRModel:()=>fu,Swin2SRPreTrainedModel:()=>Ro,SwinForImageClassification:()=>Bo,SwinModel:()=>hi,SwinPreTrainedModel:()=>zo,T5ForConditionalGeneration:()=>q,T5Model:()=>C,T5PreTrainedModel:()=>Pe,TableTransformerForObjectDetection:()=>pu,TableTransformerModel:()=>Ao,TableTransformerObjectDetectionOutput:()=>Yc,TableTransformerPreTrainedModel:()=>$o,TokenClassifierOutput:()=>Ks,TrOCRForCausalLM:()=>dd,TrOCRPreTrainedModel:()=>ud,UniSpeechForCTC:()=>Gu,UniSpeechForSequenceClassification:()=>Ku,UniSpeechModel:()=>ea,UniSpeechPreTrainedModel:()=>yi,UniSpeechSatForAudioFrameClassification:()=>ip,UniSpeechSatForCTC:()=>Hu,UniSpeechSatForSequenceClassification:()=>qu,UniSpeechSatModel:()=>np,UniSpeechSatPreTrainedModel:()=>Wn,ViTForImageClassification:()=>jl,ViTMAEModel:()=>Hl,ViTMAEPreTrainedModel:()=>Kl,ViTMSNForImageClassification:()=>Ql,ViTMSNModel:()=>ql,ViTMSNPreTrainedModel:()=>vo,ViTModel:()=>Nl,ViTPreTrainedModel:()=>wo,VisionEncoderDecoderModel:()=>ji,VitMatteForImageMatting:()=>Zl,VitMattePreTrainedModel:()=>Jl,VitPoseForPoseEstimation:()=>Wl,VitPosePreTrainedModel:()=>Mo,VitsModel:()=>sa,VitsModelOutput:()=>Cc,VitsPreTrainedModel:()=>wd,Wav2Vec2BertForCTC:()=>Xu,Wav2Vec2BertForSequenceClassification:()=>Yu,Wav2Vec2BertModel:()=>Qu,Wav2Vec2BertPreTrainedModel:()=>Mi,Wav2Vec2ForAudioFrameClassification:()=>ju,Wav2Vec2ForCTC:()=>Ru,Wav2Vec2ForSequenceClassification:()=>Nu,Wav2Vec2Model:()=>Bu,Wav2Vec2PreTrainedModel:()=>Fr,WavLMForAudioFrameClassification:()=>op,WavLMForCTC:()=>sd,WavLMForSequenceClassification:()=>rd,WavLMForXVector:()=>nd,WavLMModel:()=>td,WavLMPreTrainedModel:()=>Gn,WeSpeakerResNetModel:()=>rp,WeSpeakerResNetPreTrainedModel:()=>Wu,WhisperForConditionalGeneration:()=>Na,WhisperModel:()=>Ra,WhisperPreTrainedModel:()=>Ri,XLMForQuestionAnswering:()=>en,XLMForSequenceClassification:()=>Gs,XLMForTokenClassification:()=>$t,XLMModel:()=>Ls,XLMPreTrainedModel:()=>qt,XLMRobertaForMaskedLM:()=>Da,XLMRobertaForQuestionAnswering:()=>za,XLMRobertaForSequenceClassification:()=>zi,XLMRobertaForTokenClassification:()=>La,XLMRobertaModel:()=>It,XLMRobertaPreTrainedModel:()=>qe,XLMWithLMHeadModel:()=>As,XVectorOutput:()=>Pp,YolosForObjectDetection:()=>Au,YolosModel:()=>$u,YolosObjectDetectionOutput:()=>Iu,YolosPreTrainedModel:()=>Su});var _=r("./src/configs.js"),I=r("./src/backends/onnx.js"),R=r("./src/utils/dtypes.js"),Y=r("./src/utils/generic.js"),N=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"),O=r("./src/utils/image.js"),K=r("./src/utils/maths.js"),te=r("./src/generation/stopping_criteria.js"),ne=r("./src/generation/logits_sampler.js"),W=r("./src/env.js"),U=r("./src/models/whisper/generation_whisper.js"),X=r("./src/models/whisper/common_whisper.js");const A={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},S=new Map,w=new Map,x=new Map;async function F(f,T,j){var xs;const _e=((xs=j.config)==null?void 0:xs["transformers.js_config"])??{};let Oe=j.device??_e.device;Oe&&typeof Oe!="string"&&(Oe.hasOwnProperty(T)?Oe=Oe[T]:(console.warn(`device not specified for "${T}". Using the default device.`),Oe=null));const Fe=Oe??(W.apis.IS_NODE_ENV?"cpu":"wasm"),et=(0,I.deviceToExecutionProviders)(Fe);let rt=j.dtype??_e.dtype;if(typeof rt!="string"&&(rt&&rt.hasOwnProperty(T)?rt=rt[T]:(rt=R.DEFAULT_DEVICE_DTYPE_MAPPING[Fe]??R.DATA_TYPES.fp32,console.warn(`dtype not specified for "${T}". Using the default dtype (${rt}) for this device (${Fe}).`))),rt===R.DATA_TYPES.auto){let fs=_e.dtype;typeof fs!="string"&&(fs=fs[T]),fs&&fs!==R.DATA_TYPES.auto&&R.DATA_TYPES.hasOwnProperty(fs)?rt=fs:rt=R.DEFAULT_DEVICE_DTYPE_MAPPING[Fe]??R.DATA_TYPES.fp32}const _t=rt;if(R.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(_t)){if(_t===R.DATA_TYPES.fp16&&Fe==="webgpu"&&!await(0,R.isWebGpuFp16Supported)())throw new Error(`The device (${Fe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${_t}. Should be one of: ${Object.keys(R.DATA_TYPES).join(", ")}`);const Mt=_e.kv_cache_dtype?typeof _e.kv_cache_dtype=="string"?_e.kv_cache_dtype:_e.kv_cache_dtype[_t]??"float32":void 0;if(Mt&&!["float32","float16"].includes(Mt))throw new Error(`Invalid kv_cache_dtype: ${Mt}. Should be one of: float32, float16`);const jt={dtype:_t,kv_cache_dtype:Mt},Vt=R.DEFAULT_DTYPE_SUFFIX_MAPPING[_t],Lt=`${j.subfolder??""}/${T}${Vt}.onnx`,Gt={...j.session_options};Gt.executionProviders??(Gt.executionProviders=et);const es=_e.free_dimension_overrides;es?Gt.freeDimensionOverrides??(Gt.freeDimensionOverrides=es):Fe.startsWith("webnn")&&!Gt.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 ns=(0,g.getModelFile)(f,Lt,!0,j),Jt=j.use_external_data_format??_e.use_external_data_format;let os=[];if(Jt&&(Jt===!0||typeof Jt=="object"&&Jt.hasOwnProperty(T)&&Jt[T]===!0)){if(W.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const fs=`${T}${Vt}.onnx_data`,Ps=`${j.subfolder??""}/${fs}`;os.push(new Promise(async(Os,Zs)=>{const Ys=await(0,g.getModelFile)(f,Ps,!0,j);Os({path:fs,data:Ys})}))}else Gt.externalData!==void 0&&(os=Gt.externalData.map(async fs=>{if(typeof fs.data=="string"){const Ps=await(0,g.getModelFile)(f,fs.data,!0,j);return{...fs,data:Ps}}return fs}));if(os.length>0&&(Gt.externalData=await Promise.all(os)),Fe==="webgpu"){const fs=(0,_.getKeyValueShapes)(j.config,{prefix:"present"});if(Object.keys(fs).length>0&&!(0,I.isONNXProxy)()){const Ps={};for(const Os in fs)Ps[Os]="gpu-buffer";Gt.preferredOutputLocation=Ps}}return{buffer:await ns,session_options:Gt,session_config:jt}}async function ae(f,T,j){return Object.fromEntries(await Promise.all(Object.keys(T).map(async _e=>{const{buffer:Oe,session_options:Fe,session_config:et}=await F(f,T[_e],j),rt=await(0,I.createInferenceSession)(Oe,Fe,et);return[_e,rt]})))}async function ie(f,T,j){return Object.fromEntries(await Promise.all(Object.keys(T).map(async _e=>{const Oe=await(0,g.getModelJSON)(f,T[_e],!1,j);return[_e,Oe]})))}function ve(f,T){const j=Object.create(null),_e=[];for(const et of f.inputNames){const rt=T[et];if(!(rt instanceof v.Tensor)){_e.push(et);continue}j[et]=(0,I.isONNXProxy)()?rt.clone():rt}if(_e.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${_e.join(", ")}.`);const Oe=Object.keys(T).length,Fe=f.inputNames.length;if(Oe>Fe){let et=Object.keys(T).filter(rt=>!f.inputNames.includes(rt));console.warn(`WARNING: Too many inputs were provided (${Oe} > ${Fe}). The following inputs will be ignored: "${et.join(", ")}".`)}return j}async function we(f,T){const j=ve(f,T);try{const _e=Object.fromEntries(Object.entries(j).map(([Fe,et])=>[Fe,et.ort_tensor]));let Oe=await f.run(_e);return Oe=re(Oe),Oe}catch(_e){const Oe=Object.fromEntries(Object.entries(j).map(([Fe,{type:et,dims:rt,data:_t}])=>[Fe,{type:et,dims:rt,data:_t}]));throw console.error(`An error occurred during model execution: "${_e}".`),console.error("Inputs given to model:",Oe),_e}}function re(f){for(let T in f)(0,I.isONNXTensor)(f[T])?f[T]=new v.Tensor(f[T]):typeof f[T]=="object"&&re(f[T]);return f}function xe(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(T=>T.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(T=>BigInt(T))),[f.length,f[0].length])}else return new v.Tensor("int64",BigInt64Array.from(f.map(T=>BigInt(T))),[1,f.length])}function ce(f){return new v.Tensor("bool",[f],[1])}async function Se(f,T){let{encoder_outputs:j,input_ids:_e,decoder_input_ids:Oe,...Fe}=T;if(!j){const rt=(0,N.pick)(T,f.sessions.model.inputNames);j=(await Ie(f,rt)).last_hidden_state}return Fe.input_ids=Oe,Fe.encoder_hidden_states=j,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Fe.encoder_attention_mask=T.attention_mask),await Ce(f,Fe,!0)}async function Ie(f,T){const j=f.sessions.model,_e=(0,N.pick)(T,j.inputNames);if(j.inputNames.includes("inputs_embeds")&&!_e.inputs_embeds){if(!T.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");_e.inputs_embeds=await f.encode_text({input_ids:T.input_ids})}if(j.inputNames.includes("token_type_ids")&&!_e.token_type_ids){if(!_e.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");_e.token_type_ids=(0,v.zeros_like)(_e.input_ids)}if(j.inputNames.includes("pixel_mask")&&!_e.pixel_mask){if(!_e.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const Oe=_e.pixel_values.dims;_e.pixel_mask=(0,v.ones)([Oe[0],Oe[2],Oe[3]])}return await we(j,_e)}async function Ce(f,T,j=!1){const _e=f.sessions[j?"decoder_model_merged":"model"],{past_key_values:Oe,...Fe}=T;if(_e.inputNames.includes("use_cache_branch")&&(Fe.use_cache_branch=ce(!!Oe)),_e.inputNames.includes("position_ids")&&Fe.attention_mask&&!Fe.position_ids){const rt=f.config.model_type==="paligemma"?1:0;Fe.position_ids=J(Fe,Oe,rt)}f.addPastKeyValues(Fe,Oe);const et=(0,N.pick)(Fe,_e.inputNames);return await we(_e,et)}function tt({image_token_id:f,inputs_embeds:T,image_features:j,input_ids:_e,attention_mask:Oe}){const Fe=_e.tolist().map(Mt=>Mt.reduce((jt,Vt,Lt)=>(Vt==f&&jt.push(Lt),jt),[])),et=Fe.reduce((Mt,jt)=>Mt+jt.length,0),rt=j.dims[0];if(et!==rt)throw new Error(`Image features and image tokens do not match: tokens: ${et}, features ${rt}`);let _t=0;for(let Mt=0;MtFe.dims[1])){if(Oert==f.config.image_token_index)){const rt=f.config.num_image_tokens;if(!rt)throw new Error("`num_image_tokens` is missing in the model configuration.");const _t=Fe.dims[1]-(Oe-rt);j.input_ids=Fe.slice(null,[-_t,null]),j.attention_mask=(0,v.ones)([1,Oe+_t])}}}return j}function ke(f,T,j,_e){return j.past_key_values&&(T=T.map(Oe=>[Oe.at(-1)])),{...j,decoder_input_ids:xe(T)}}function Be(f,...T){return f.config.is_encoder_decoder?ke(f,...T):de(f,...T)}function Ze(f,T,j,_e){const Oe=!!j.past_key_values;return _e.guidance_scale!==null&&_e.guidance_scale>1&&(Oe?j.input_ids=(0,v.cat)([j.input_ids,j.input_ids],0):(j.input_ids=(0,v.cat)([j.input_ids,(0,v.full_like)(j.input_ids,BigInt(_e.pad_token_id))],0),j.attention_mask=(0,v.cat)([j.attention_mask,(0,v.full_like)(j.attention_mask,0n)],0))),(Oe||!j.pixel_values)&&(j.pixel_values=(0,v.full)([0,0,3,384,384],1)),Oe&&(j.images_seq_mask=new v.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),j.images_emb_mask=new v.Tensor("bool",new Array(0).fill(!1),[1,1,0])),j}class se extends Y.Callable{constructor(j,_e,Oe){super();fe(this,"main_input_name","input_ids");fe(this,"forward_params",["input_ids","attention_mask"]);this.config=j,this.sessions=_e,this.configs=Oe;const Fe=x.get(this.constructor),et=S.get(Fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,et){case A.DecoderOnly:this.can_generate=!0,this._forward=Ce,this._prepare_inputs_for_generation=de;break;case A.Seq2Seq:case A.Vision2Seq:case A.Musicgen:this.can_generate=!0,this._forward=Se,this._prepare_inputs_for_generation=ke;break;case A.EncoderDecoder:this._forward=Se;break;case A.ImageTextToText:this.can_generate=!0,this._forward=Ge,this._prepare_inputs_for_generation=Be;break;case A.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Be;break;case A.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Ze;break;default:this._forward=Ie;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var _e;const j=[];for(const Oe of Object.values(this.sessions))(_e=Oe==null?void 0:Oe.handler)!=null&&_e.dispose&&j.push(Oe.handler.dispose());return await Promise.all(j)}static async from_pretrained(j,{progress_callback:_e=null,config:Oe=null,cache_dir:Fe=null,local_files_only:et=!1,revision:rt="main",model_file_name:_t=null,subfolder:Mt="onnx",device:jt=null,dtype:Vt=null,use_external_data_format:Lt=null,session_options:Gt={}}={}){let es={progress_callback:_e,config:Oe,cache_dir:Fe,local_files_only:et,revision:rt,model_file_name:_t,subfolder:Mt,device:jt,dtype:Vt,use_external_data_format:Lt,session_options:Gt};const ns=x.get(this),Jt=S.get(ns);Oe=es.config=await _.AutoConfig.from_pretrained(j,es);let os;if(Jt===A.DecoderOnly)os=await Promise.all([ae(j,{model:es.model_file_name??"model"},es),ie(j,{generation_config:"generation_config.json"},es)]);else if(Jt===A.Seq2Seq||Jt===A.Vision2Seq)os=await Promise.all([ae(j,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},es),ie(j,{generation_config:"generation_config.json"},es)]);else if(Jt===A.MaskGeneration)os=await Promise.all([ae(j,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},es)]);else if(Jt===A.EncoderDecoder)os=await Promise.all([ae(j,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},es)]);else if(Jt===A.ImageTextToText){const Cs={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Oe.is_encoder_decoder&&(Cs.model="encoder_model"),os=await Promise.all([ae(j,Cs,es),ie(j,{generation_config:"generation_config.json"},es)])}else if(Jt===A.Musicgen)os=await Promise.all([ae(j,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},es),ie(j,{generation_config:"generation_config.json"},es)]);else if(Jt===A.MultiModality)os=await Promise.all([ae(j,{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"},es),ie(j,{generation_config:"generation_config.json"},es)]);else if(Jt===A.Phi3V)os=await Promise.all([ae(j,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},es),ie(j,{generation_config:"generation_config.json"},es)]);else{if(Jt!==A.EncoderOnly){const Cs=ns??(Oe==null?void 0:Oe.model_type);Cs!=="custom"&&console.warn(`Model type for '${Cs}' not found, assuming encoder-only architecture. Please report this at ${b.GITHUB_ISSUE_URL}.`)}os=await Promise.all([ae(j,{model:es.model_file_name??"model"},es)])}return new this(Oe,...os)}async _call(j){return await this.forward(j)}async forward(j){return await this._forward(this,j)}get generation_config(){var j;return((j=this.configs)==null?void 0:j.generation_config)??null}_get_logits_warper(j){const _e=new y.LogitsProcessorList;return j.temperature!==null&&j.temperature!==1&&_e.push(new y.TemperatureLogitsWarper(j.temperature)),j.top_k!==null&&j.top_k!==0&&_e.push(new y.TopKLogitsWarper(j.top_k)),j.top_p!==null&&j.top_p<1&&_e.push(new y.TopPLogitsWarper(j.top_p)),_e}_get_logits_processor(j,_e,Oe=null){const Fe=new y.LogitsProcessorList;if(j.repetition_penalty!==null&&j.repetition_penalty!==1&&Fe.push(new y.RepetitionPenaltyLogitsProcessor(j.repetition_penalty)),j.no_repeat_ngram_size!==null&&j.no_repeat_ngram_size>0&&Fe.push(new y.NoRepeatNGramLogitsProcessor(j.no_repeat_ngram_size)),j.bad_words_ids!==null&&Fe.push(new y.NoBadWordsLogitsProcessor(j.bad_words_ids,j.eos_token_id)),j.min_length!==null&&j.eos_token_id!==null&&j.min_length>0&&Fe.push(new y.MinLengthLogitsProcessor(j.min_length,j.eos_token_id)),j.min_new_tokens!==null&&j.eos_token_id!==null&&j.min_new_tokens>0&&Fe.push(new y.MinNewTokensLengthLogitsProcessor(_e,j.min_new_tokens,j.eos_token_id)),j.forced_bos_token_id!==null&&Fe.push(new y.ForcedBOSTokenLogitsProcessor(j.forced_bos_token_id)),j.forced_eos_token_id!==null&&Fe.push(new y.ForcedEOSTokenLogitsProcessor(j.max_length,j.forced_eos_token_id)),j.begin_suppress_tokens!==null){const et=_e>1||j.forced_bos_token_id===null?_e:_e+1;Fe.push(new y.SuppressTokensAtBeginLogitsProcessor(j.begin_suppress_tokens,et))}return j.guidance_scale!==null&&j.guidance_scale>1&&Fe.push(new y.ClassifierFreeGuidanceLogitsProcessor(j.guidance_scale)),Oe!==null&&Fe.extend(Oe),Fe}_prepare_generation_config(j,_e,Oe=M.GenerationConfig){const Fe={...this.config};for(const rt of["decoder","generator","text_config"])rt in Fe&&Object.assign(Fe,Fe[rt]);const et=new Oe(Fe);return Object.assign(et,this.generation_config??{}),j&&Object.assign(et,j),_e&&Object.assign(et,(0,N.pick)(_e,Object.getOwnPropertyNames(et))),et}_get_stopping_criteria(j,_e=null){const Oe=new te.StoppingCriteriaList;return j.max_length!==null&&Oe.push(new te.MaxLengthCriteria(j.max_length,this.config.max_position_embeddings??null)),j.eos_token_id!==null&&Oe.push(new te.EosTokenCriteria(j.eos_token_id)),_e&&Oe.extend(_e),Oe}_validate_model_class(){if(!this.can_generate){const j=[Vd,Pi,ma,ha],_e=x.get(this.constructor),Oe=new Set,Fe=this.config.model_type;for(const rt of j){const _t=rt.get(Fe);_t&&Oe.add(_t[0])}let et=`The current model class (${_e}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Oe.size>0&&(et+=` Please use the following class instead: ${[...Oe].join(", ")}`),Error(et)}}prepare_inputs_for_generation(...j){return this._prepare_inputs_for_generation(this,...j)}_update_model_kwargs_for_generation({generated_input_ids:j,outputs:_e,model_inputs:Oe,is_encoder_decoder:Fe}){return Oe.past_key_values=this.getPastKeyValues(_e,Oe.past_key_values),Oe.input_ids=new v.Tensor("int64",j.flat(),[j.length,1]),Fe||(Oe.attention_mask=(0,v.cat)([Oe.attention_mask,(0,v.ones)([Oe.attention_mask.dims[0],1])],1)),Oe.position_ids=null,Oe}_prepare_model_inputs({inputs:j,bos_token_id:_e,model_kwargs:Oe}){const Fe=(0,N.pick)(Oe,this.forward_params),et=this.main_input_name;if(et in Fe){if(j)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Fe[et]=j;return{inputs_tensor:Fe[et],model_inputs:Fe,model_input_name:et}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:j,model_inputs:_e,model_input_name:Oe,generation_config:Fe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!_e.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:rt,pixel_values:_t,attention_mask:Mt,...jt}=_e,Vt=await this._prepare_inputs_embeds(_e);_e={...jt,...(0,N.pick)(Vt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:et}=await Ie(this,_e);if(Fe.guidance_scale!==null&&Fe.guidance_scale>1)et=(0,v.cat)([et,(0,v.full_like)(et,0)],0),"attention_mask"in _e&&(_e.attention_mask=(0,v.cat)([_e.attention_mask,(0,v.zeros_like)(_e.attention_mask)],0));else if(_e.decoder_input_ids){const rt=xe(_e.decoder_input_ids).dims[0];if(rt!==et.dims[0]){if(et.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${et.dims[0]}) than the decoder inputs (${rt}).`);et=(0,v.cat)(Array.from({length:rt},()=>et),0)}}return _e.encoder_outputs=et,_e}_prepare_decoder_input_ids_for_generation({batch_size:j,model_input_name:_e,model_kwargs:Oe,decoder_start_token_id:Fe,bos_token_id:et,generation_config:rt}){let{decoder_input_ids:_t,...Mt}=Oe;if(!(_t instanceof v.Tensor)){if(_t)Array.isArray(_t[0])||(_t=Array.from({length:j},()=>_t));else if(Fe??(Fe=et),this.config.model_type==="musicgen")_t=Array.from({length:j*this.config.decoder.num_codebooks},()=>[Fe]);else if(Array.isArray(Fe)){if(Fe.length!==j)throw new Error(`\`decoder_start_token_id\` expcted to have length ${j} but got ${Fe.length}`);_t=Fe}else _t=Array.from({length:j},()=>[Fe]);_t=xe(_t)}return Oe.decoder_attention_mask=(0,v.ones_like)(_t),{input_ids:_t,model_inputs:Mt}}async generate({inputs:j=null,generation_config:_e=null,logits_processor:Oe=null,stopping_criteria:Fe=null,streamer:et=null,...rt}){this._validate_model_class(),_e=this._prepare_generation_config(_e,rt);let{inputs_tensor:_t,model_inputs:Mt,model_input_name:jt}=this._prepare_model_inputs({inputs:j,model_kwargs:rt});const Vt=this.config.is_encoder_decoder;Vt&&("encoder_outputs"in Mt||(Mt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:_t,model_inputs:Mt,model_input_name:jt,generation_config:_e})));let Lt;Vt?{input_ids:Lt,model_inputs:Mt}=this._prepare_decoder_input_ids_for_generation({batch_size:Mt[jt].dims.at(0),model_input_name:jt,model_kwargs:Mt,decoder_start_token_id:_e.decoder_start_token_id,bos_token_id:_e.bos_token_id,generation_config:_e}):Lt=Mt[jt];let Gt=Lt.dims.at(-1);_e.max_new_tokens!==null&&(_e.max_length=Gt+_e.max_new_tokens);const es=this._get_logits_processor(_e,Gt,Oe),ns=this._get_stopping_criteria(_e,Fe),Jt=Mt[jt].dims.at(0),os=ne.LogitsSampler.getSampler(_e),Cs=new Array(Jt).fill(0),xs=Lt.tolist();et&&et.put(xs);let fs,Ps={};for(;;){if(Mt=this.prepare_inputs_for_generation(xs,Mt,_e),fs=await this.forward(Mt),_e.output_attentions&&_e.return_dict_in_generate){const ur=this.getAttentions(fs);for(const Pr in ur)Pr in Ps||(Ps[Pr]=[]),Ps[Pr].push(ur[Pr])}const Ys=fs.logits.slice(null,-1,null),Mr=es(xs,Ys),xn=[];for(let ur=0;urur))break;Mt=this._update_model_kwargs_for_generation({generated_input_ids:xn,outputs:fs,model_inputs:Mt,is_encoder_decoder:Vt})}et&&et.end();const Os=this.getPastKeyValues(fs,Mt.past_key_values,!0),Zs=new v.Tensor("int64",xs.flat(),[xs.length,xs[0].length]);if(_e.return_dict_in_generate)return{sequences:Zs,past_key_values:Os,...Ps};for(const Ys of Object.values(fs))Ys.location==="gpu-buffer"&&Ys.dispose();return Zs}getPastKeyValues(j,_e,Oe=!1){const Fe=Object.create(null);for(const et in j)if(et.startsWith("present")){const rt=et.replace("present","past_key_values"),_t=et.includes("encoder");if(_t&&_e?Fe[rt]=_e[rt]:Fe[rt]=j[et],_e&&(!_t||Oe)){const Mt=_e[rt];Mt.location==="gpu-buffer"&&Mt.dispose()}}return Fe}getAttentions(j){const _e={};for(const Oe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Fe in j)Fe.startsWith(Oe)&&(Oe in _e||(_e[Oe]=[]),_e[Oe].push(j[Fe]));return _e}addPastKeyValues(j,_e){var Oe,Fe,et;if(_e)Object.assign(j,_e);else{const rt=this.sessions.decoder_model_merged??this.sessions.model,_t=((Oe=rt==null?void 0:rt.config)==null?void 0:Oe.kv_cache_dtype)??"float32",Mt=_t==="float16"?new Uint16Array:[],jt=((et=(Fe=j[this.main_input_name]??j.attention_mask)==null?void 0:Fe.dims)==null?void 0:et[0])??1,Vt=(0,_.getKeyValueShapes)(this.config,{batch_size:jt});for(const Lt in Vt)j[Lt]=new v.Tensor(_t,Mt,Vt[Lt])}}async encode_image({pixel_values:j}){const _e=(await we(this.sessions.vision_encoder,{pixel_values:j})).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 (${_e.dims[1]}).`),this.config.num_image_tokens=_e.dims[1]),_e}async encode_text({input_ids:j}){return(await we(this.sessions.embed_tokens,{input_ids:j})).inputs_embeds}}class Ke{}class je extends Ke{constructor({last_hidden_state:T,hidden_states:j=null,attentions:_e=null}){super(),this.last_hidden_state=T,this.hidden_states=j,this.attentions=_e}}class le extends se{}class Te extends le{}class Ue extends le{async _call(T){return new Xs(await super._call(T))}}class Ve extends le{async _call(T){return new Qt(await super._call(T))}}class Ne extends le{async _call(T){return new Ks(await super._call(T))}}class Re extends le{async _call(T){return new tr(await super._call(T))}}class st extends se{}class dt extends st{}class ct extends st{async _call(T){return new Xs(await super._call(T))}}class lt extends st{async _call(T){return new Qt(await super._call(T))}}class ht extends st{async _call(T){return new Ks(await super._call(T))}}class L extends se{}class oe extends L{}class H extends se{}class me extends H{}class Ae extends H{async _call(T){return new Xs(await super._call(T))}}class We extends H{async _call(T){return new Qt(await super._call(T))}}class Je extends H{async _call(T){return new Ks(await super._call(T))}}class ut extends H{async _call(T){return new tr(await super._call(T))}}class mt extends se{}class vt extends mt{}class kt extends mt{async _call(T){return new Xs(await super._call(T))}}class At extends mt{async _call(T){return new Qt(await super._call(T))}}class is extends mt{async _call(T){return new Ks(await super._call(T))}}class ws extends mt{async _call(T){return new tr(await super._call(T))}}class ks extends se{}class Ds extends ks{}class sr extends ks{async _call(T){return new Xs(await super._call(T))}}class kr extends ks{async _call(T){return new Qt(await super._call(T))}}class Qr extends ks{async _call(T){return new Ks(await super._call(T))}}class Us extends ks{async _call(T){return new tr(await super._call(T))}}class xr extends se{}class Nt extends xr{}class Xr extends xr{async _call(T){return new Xs(await super._call(T))}}class Sr extends xr{async _call(T){return new Qt(await super._call(T))}}class $r extends xr{async _call(T){return new Ks(await super._call(T))}}class Yr extends xr{async _call(T){return new tr(await super._call(T))}}class cr extends se{}class Jr extends cr{}class Ar extends cr{async _call(T){return new Xs(await super._call(T))}}class Br extends cr{async _call(T){return new Qt(await super._call(T))}}class Rr extends cr{async _call(T){return new Ks(await super._call(T))}}class or extends cr{async _call(T){return new tr(await super._call(T))}}class it extends se{}class Tt extends it{}class Dt extends it{async _call(T){return new Xs(await super._call(T))}}class Vs extends it{async _call(T){return new Qt(await super._call(T))}}class Nr extends it{async _call(T){return new Ks(await super._call(T))}}class Ir extends it{async _call(T){return new tr(await super._call(T))}}class Ms extends se{}class ar extends Ms{}class Is extends Ms{async _call(T){return new Qt(await super._call(T))}}class Tr extends Ms{async _call(T){return new Ks(await super._call(T))}}class ts extends Ms{async _call(T){return new tr(await super._call(T))}}class mn extends Ms{async _call(T){return new Xs(await super._call(T))}}class jr extends se{}class si extends jr{}class An extends jr{async _call(T){return new Xs(await super._call(T))}}class In extends jr{async _call(T){return new Qt(await super._call(T))}}class On extends jr{async _call(T){return new Ks(await super._call(T))}}class Ur extends se{}class Fn extends Ur{}class ri extends Ur{async _call(T){return new Xs(await super._call(T))}}class Vr extends Ur{async _call(T){return new Qt(await super._call(T))}}class fr extends Ur{async _call(T){return new tr(await super._call(T))}}class lr extends se{}class fn extends lr{}class Zr extends lr{async _call(T){return new Xs(await super._call(T))}}class _n extends lr{async _call(T){return new Qt(await super._call(T))}}class gn extends lr{async _call(T){return new Ks(await super._call(T))}}class wn extends lr{async _call(T){return new tr(await super._call(T))}}class zt extends se{}class yn extends zt{}class Dn extends zt{async _call(T){return new Xs(await super._call(T))}}class Ln extends zt{async _call(T){return new Qt(await super._call(T))}}class zn extends zt{async _call(T){return new tr(await super._call(T))}}class Wr extends se{}class Bn extends Wr{}class Mn extends Wr{async _call(T){return new Qt(await super._call(T))}}class Rn extends Wr{async _call(T){return new tr(await super._call(T))}}class as extends Wr{async _call(T){return new Xs(await super._call(T))}}class Pe extends se{constructor(){super(...arguments);fe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class C extends Pe{}class q extends Pe{}class ue extends se{}class be extends ue{}class $e extends ue{}class Qe extends se{}class pt extends Qe{}class gt extends Qe{}class ft extends se{}class xt extends ft{}class Kt extends ft{}class hs extends ft{async _call(T){return new Qt(await super._call(T))}}class us extends se{}class Fs extends us{}class Bt extends us{}class rs extends us{async _call(T){return new Qt(await super._call(T))}}class rr extends us{}class Ws extends se{}class ze extends Ws{}class Js extends Ws{}class Or extends se{}class Ss extends Or{}class qs extends Or{}class Ot extends se{}class nr extends Ot{}class _r extends Ot{async _call(T){return new Xs(await super._call(T))}}class ms extends Ot{async _call(T){return new Qt(await super._call(T))}}class $s extends Ot{async _call(T){return new Ks(await super._call(T))}}class yt extends Ot{async _call(T){return new tr(await super._call(T))}}class qt extends se{}class Ls extends qt{}class As extends qt{async _call(T){return new Xs(await super._call(T))}}class Gs extends qt{async _call(T){return new Qt(await super._call(T))}}class $t extends qt{async _call(T){return new Ks(await super._call(T))}}class en extends qt{async _call(T){return new tr(await super._call(T))}}class qe extends se{}class It extends qe{}class Da extends qe{async _call(T){return new Xs(await super._call(T))}}class zi extends qe{async _call(T){return new Qt(await super._call(T))}}class La extends qe{async _call(T){return new Ks(await super._call(T))}}class za extends qe{async _call(T){return new tr(await super._call(T))}}class Yt extends se{}class Ba extends Yt{}class Bi extends Yt{}class Ri extends se{constructor(){super(...arguments);fe(this,"requires_attention_mask",!1);fe(this,"main_input_name","input_features");fe(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ra extends Ri{}class Na extends Ri{_prepare_generation_config(T,j){return super._prepare_generation_config(T,j,U.WhisperGenerationConfig)}_retrieve_init_tokens(T){const j=[T.decoder_start_token_id];let _e=T.language;const Oe=T.task;if(T.is_multilingual){_e||(console.warn("No language specified - defaulting to English (en)."),_e="en");const et=`<|${(0,X.whisper_language_to_code)(_e)}|>`;j.push(T.lang_to_id[et]),j.push(T.task_to_id[Oe??"transcribe"])}else if(_e||Oe)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!T.return_timestamps&&T.no_timestamps_token_id&&j.at(-1)!==T.no_timestamps_token_id?j.push(T.no_timestamps_token_id):T.return_timestamps&&j.at(-1)===T.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),j.pop()),j.filter(Fe=>Fe!=null)}async generate({inputs:T=null,generation_config:j=null,logits_processor:_e=null,stopping_criteria:Oe=null,...Fe}){j=this._prepare_generation_config(j,Fe);const et=Fe.decoder_input_ids??this._retrieve_init_tokens(j);if(j.return_timestamps&&(_e??(_e=new y.LogitsProcessorList),_e.push(new y.WhisperTimeStampLogitsProcessor(j,et))),j.begin_suppress_tokens&&(_e??(_e=new y.LogitsProcessorList),_e.push(new y.SuppressTokensAtBeginLogitsProcessor(j.begin_suppress_tokens,et.length))),j.return_token_timestamps){if(!j.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.");j.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),j.output_attentions=!0,j.return_dict_in_generate=!0}const rt=await super.generate({inputs:T,generation_config:j,logits_processor:_e,decoder_input_ids:et,...Fe});return j.return_token_timestamps&&(rt.token_timestamps=this._extract_token_timestamps(rt,j.alignment_heads,j.num_frames)),rt}_extract_token_timestamps(T,j,_e=null,Oe=.02){if(!T.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`.");_e==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 Fe=this.config.median_filter_width;Fe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Fe=7);const et=T.cross_attentions,rt=Array.from({length:this.config.decoder_layers},(ns,Jt)=>(0,v.cat)(et.map(os=>os[Jt]),2)),_t=(0,v.stack)(j.map(([ns,Jt])=>{if(ns>=rt.length)throw new Error(`Layer index ${ns} is out of bounds for cross attentions (length ${rt.length}).`);return _e?rt[ns].slice(null,Jt,null,[0,_e]):rt[ns].slice(null,Jt)})).transpose(1,0,2,3),[Mt,jt]=(0,v.std_mean)(_t,-2,0,!0),Vt=_t.clone();for(let ns=0;nsos[Zs+1]-os[Zs]),fs=(0,N.mergeArrays)([1],xs).map(Os=>!!Os),Ps=[];for(let Os=0;OsLt.findIndex(Gt=>Gt==Fe)),_t=rt.every(Lt=>Lt===-1),Mt=rt.every(Lt=>Lt!==-1);if(!_t&&!Mt)throw new Error("Every input should contain either 0 or 1 image token.");if(_t)return{inputs_embeds:T,attention_mask:Oe};const jt=[],Vt=[];for(let Lt=0;LtArray.from({length:T.dims[0]},xs=>Array.from({length:T.dims[1]},fs=>1))),es=j?j.tolist():[],ns=_e?_e.tolist():[];let Jt=0,os=0;for(let Cs=0;CsLt[Cs][zs]==1),Ps=xs.reduce((Ts,zs,Lr)=>(zs==_t&&Ts.push(Lr),Ts),[]).map(Ts=>xs[Ts+1]),Os=Ps.filter(Ts=>Ts==et).length,Zs=Ps.filter(Ts=>Ts==rt).length;let Ys=[],Mr=0,xn=Os,xa=Zs;for(let Ts=0;Tsdr>Mr&&ln==et),Lr=xs.findIndex((ln,dr)=>dr>Mr&&ln==rt),on=xn>0&&zs!==-1?zs:xs.length+1,Tn=xa>0&&Lr!==-1?Lr:xs.length+1;let Ta,Si,Ea,Pa;on0?(0,K.max)(Ys.at(-1))[0]+1:0;Ys.push(Array.from({length:3*ka},(ln,dr)=>Sc+dr%ka));const $c=ka+Sc,$i=qp*Ca*En,Ac=Array.from({length:$i},(ln,dr)=>$c+Math.floor(dr/(Ca*En))),Ic=Array.from({length:$i},(ln,dr)=>$c+Math.floor(dr/En)%Ca),an=Array.from({length:$i},(ln,dr)=>$c+dr%En);Ys.push([Ac,Ic,an].flat()),Mr=Ta+$i}if(Mr0?(0,K.max)(Ys.at(-1))[0]+1:0,zs=xs.length-Mr;Ys.push(Array.from({length:3*zs},(Lr,on)=>Ts+on%zs))}const ur=Ys.reduce((Ts,zs)=>Ts+zs.length,0),Pr=new Array(ur);let kc=0;for(let Ts=0;Ts<3;++Ts)for(let zs=0;zsVt[Jt%Vt.length]),es=Array.from({length:Lt[0]},(ns,Jt)=>(0,K.max)(Vt.subarray(Lt[1]*Jt,Lt[1]*(Jt+1)))[0]+1n+BigInt(Lt[1]));return[new v.Tensor("int64",Gt,[3,...Lt]),new v.Tensor("int64",es,[es.length,1])]}else{const[Vt,Lt]=T.dims,Gt=BigInt64Array.from({length:3*Vt*Lt},(es,ns)=>BigInt(Math.floor(ns%Lt/Vt)));return[new v.Tensor("int64",Gt,[3,...T.dims]),(0,v.zeros)([Vt,1])]}}async encode_image({pixel_values:T,image_grid_thw:j}){return(await we(this.sessions.vision_encoder,{pixel_values:T,grid_thw:j})).image_features}_merge_input_ids_with_image_features(T){return tt({image_token_id:this.config.image_token_id,...T})}prepare_inputs_for_generation(T,j,_e){if(j.attention_mask&&!j.position_ids)if(!j.past_key_values)[j.position_ids,j.rope_deltas]=this.get_rope_index(j.input_ids,j.image_grid_thw,j.video_grid_thw,j.attention_mask);else{j.pixel_values=null;const Oe=BigInt(Object.values(j.past_key_values)[0].dims.at(-2)),Fe=j.rope_deltas.map(et=>Oe+et);j.position_ids=(0,v.stack)([Fe,Fe,Fe],0)}return j}}class ho extends se{}class Il extends ho{}class jn extends ho{}class mo extends se{}class ui extends mo{}class Ol extends mo{}class fo extends se{}class Fl extends fo{}class Dl extends fo{}class _o extends se{}class Ll extends _o{}class zl extends _o{}class go extends se{}class Bl extends go{}class Rl extends go{}class wo extends se{}class Nl extends wo{}class jl extends wo{async _call(T){return new Qt(await super._call(T))}}class yo extends se{}class Ul extends yo{}class Vl extends yo{async _call(T){return new Qt(await super._call(T))}}class Mo extends se{}class Wl extends Mo{}class di extends se{}class bo extends di{}class Gl extends di{async _call(T){return new Qt(await super._call(T))}}class Kl extends se{}class Hl extends Kl{}class vo extends se{}class ql extends vo{}class Ql extends vo{async _call(T){return new Qt(await super._call(T))}}class xo extends se{}class Xl extends xo{}class To extends se{}class Yl extends To{}class Qc extends To{async _call(T){return new Qt(await super._call(T))}}class Jl extends se{}class Zl extends Jl{async _call(T){return new Hn(await super._call(T))}}class mr extends se{}class eu extends mr{}class tu extends mr{async _call(T){return new Qt(await super._call(T))}}class Eo extends se{}class su extends Eo{}class ru extends Eo{async _call(T){return new Qt(await super._call(T))}}class Po extends se{}class nu extends Po{}class iu extends Po{}class Co extends se{}class ou extends Co{}class Xc extends Co{}class ko extends se{}class au extends ko{}class lu extends ko{async _call(T){return new Qt(await super._call(T))}}class ci extends se{}class uu extends ci{}class du extends ci{async _call(T){return new Kr(await super._call(T))}}class cu extends ci{async _call(T){return new sn(await super._call(T))}}class Kr extends Ke{constructor({logits:T,pred_boxes:j}){super(),this.logits=T,this.pred_boxes=j}}class sn extends Ke{constructor({logits:T,pred_boxes:j,pred_masks:_e}){super(),this.logits=T,this.pred_boxes=j,this.pred_masks=_e}}class Hr extends se{}class So extends Hr{}class rn extends Hr{async _call(T){return new Qs(await super._call(T))}}class Qs extends Ke{constructor({logits:T,pred_boxes:j}){super(),this.logits=T,this.pred_boxes=j}}class $o extends se{}class Ao extends $o{}class pu extends $o{async _call(T){return new Yc(await super._call(T))}}class Yc extends Kr{}class bn extends se{}class Io extends bn{}class Oo extends bn{async _call(T){return new Qt(await super._call(T))}}class Fo extends se{}class hu extends Fo{}class Do extends Fo{async _call(T){return new Qt(await super._call(T))}}class pi extends se{}class mu extends pi{}class Lo extends pi{async _call(T){return new Qt(await super._call(T))}}class zo extends se{}class hi extends zo{}class Bo extends zo{async _call(T){return new Qt(await super._call(T))}}class Ro extends se{}class fu extends Ro{}class Jc extends Ro{}class No extends se{}class jo extends No{}class Un extends No{}class _u extends se{}class Uo extends _u{}class mi extends se{}class gu extends mi{}class wu extends mi{}class Zc extends mi{}class yu extends se{}class Mu extends yu{}class bu extends se{}class vu extends bu{}class fi extends bu{}class Vo extends se{}class _i extends Vo{}class Wo extends Vo{}class Go extends se{}class xu extends Go{}class Ko extends se{}class Ho extends Ko{}class ep extends Ko{async _call(T){return new Qt(await super._call(T))}}class qo extends se{}class tp extends qo{}class Tu extends qo{async _call(T){return new Qt(await super._call(T))}}class Qo extends se{}class Eu extends Qo{}class Xo extends Qo{async _call(T){return new Qt(await super._call(T))}}class Yo extends se{}class Pu extends Yo{}class Jo extends Yo{async _call(T){return new Qt(await super._call(T))}}class Cu extends se{}class ku extends Cu{}class Su extends se{}class $u extends Su{}class Au extends Su{async _call(T){return new Iu(await super._call(T))}}class Iu extends Ke{constructor({logits:T,pred_boxes:j}){super(),this.logits=T,this.pred_boxes=j}}class sp extends se{}class Ou extends sp{async get_image_embeddings({pixel_values:T}){return await Ie(this,{pixel_values:T})}async forward(T){if((!T.image_embeddings||!T.image_positional_embeddings)&&(T={...T,...await this.get_image_embeddings(T)}),!T.input_labels&&T.input_points){const _e=T.input_points.dims.slice(0,-1),Oe=_e.reduce((Fe,et)=>Fe*et,1);T.input_labels=new v.Tensor("int64",new BigInt64Array(Oe).fill(1n),_e)}const j={image_embeddings:T.image_embeddings,image_positional_embeddings:T.image_positional_embeddings};return T.input_points&&(j.input_points=T.input_points),T.input_labels&&(j.input_labels=T.input_labels),T.input_boxes&&(j.input_boxes=T.input_boxes),await we(this.sessions.prompt_encoder_mask_decoder,j)}async _call(T){return new Fu(await super._call(T))}}class Fu extends Ke{constructor({iou_scores:T,pred_masks:j}){super(),this.iou_scores=T,this.pred_masks=j}}class Zo extends se{}class Du extends Zo{}class Lu extends Zo{}class zu extends se{}class gi extends zu{}class Vn extends zu{}class Fr extends se{}class Bu extends Fr{}class Ru extends Fr{async _call(T){return new vn(await super._call(T))}}class Nu extends Fr{async _call(T){return new Qt(await super._call(T))}}class ju extends Fr{async _call(T){return new Ks(await super._call(T))}}class wi extends se{}class Uu extends wi{}class Vu extends wi{async _call(T){return new Ks(await super._call(T))}}class Wu extends se{}class rp extends Wu{}class yi extends se{}class ea extends yi{}class Gu extends yi{async _call(T){return new vn(await super._call(T))}}class Ku extends yi{async _call(T){return new Qt(await super._call(T))}}class Wn extends se{}class np extends Wn{}class Hu extends Wn{async _call(T){return new vn(await super._call(T))}}class qu extends Wn{async _call(T){return new Qt(await super._call(T))}}class ip extends Wn{async _call(T){return new Ks(await super._call(T))}}class Mi extends se{}class Qu extends Mi{}class Xu extends Mi{async _call(T){return new vn(await super._call(T))}}class Yu extends Mi{async _call(T){return new Qt(await super._call(T))}}class Hp extends se{}class Ju extends Fr{}class Zu extends Fr{async _call(T){return new vn(await super._call(T))}}class ed extends Fr{async _call(T){return new Qt(await super._call(T))}}class Gn extends se{}class td extends Gn{}class sd extends Gn{async _call(T){return new vn(await super._call(T))}}class rd extends Gn{async _call(T){return new Qt(await super._call(T))}}class nd extends Gn{async _call(T){return new Pp(await super._call(T))}}class op extends Gn{async _call(T){return new Ks(await super._call(T))}}class id extends se{}class od extends id{}class bi extends se{}class ap extends bi{}class lp extends bi{}class ad extends bi{async generate_speech(T,j,{threshold:_e=.5,minlenratio:Oe=0,maxlenratio:Fe=20,vocoder:et=null}={}){const rt={input_ids:T},{encoder_outputs:_t,encoder_attention_mask:Mt}=await Ie(this,rt),jt=_t.dims[1]/this.config.reduction_factor,Vt=Math.floor(jt*Fe),Lt=Math.floor(jt*Oe),Gt=this.config.num_mel_bins;let es=[],ns=null,Jt=null,os=0;for(;;){++os;const fs=ce(!!Jt);let Ps;Jt?Ps=Jt.output_sequence_out:Ps=new v.Tensor("float32",new Float32Array(Gt),[1,1,Gt]);let Os={use_cache_branch:fs,output_sequence:Ps,encoder_attention_mask:Mt,speaker_embeddings:j,encoder_hidden_states:_t};this.addPastKeyValues(Os,ns),Jt=await we(this.sessions.decoder_model_merged,Os),ns=this.getPastKeyValues(Jt,ns);const{prob:Zs,spectrum:Ys}=Jt;if(es.push(Ys),os>=Lt&&(Array.from(Zs.data).filter(Mr=>Mr>=_e).length>0||os>=Vt))break}const Cs=(0,v.cat)(es),{waveform:xs}=await we(et.sessions.model,{spectrogram:Cs});return{spectrogram:Cs,waveform:xs}}}class ld extends se{constructor(){super(...arguments);fe(this,"main_input_name","spectrogram")}}class ud extends se{}class dd extends ud{}class cd extends se{}class Er extends cd{}class Dr extends cd{}class qr extends se{}class nn extends qr{}class pd extends qr{}class ta extends se{}class hd extends ta{}class md extends ta{}class vi extends se{}class fd extends vi{}class _d extends vi{static async from_pretrained(T,j={}){return super.from_pretrained(T,{...j,model_file_name:j.model_file_name??"text_model"})}}class gd extends vi{static async from_pretrained(T,j={}){return super.from_pretrained(T,{...j,model_file_name:j.model_file_name??"audio_model"})}}class wd extends se{}class sa extends wd{async _call(T){return new Cc(await super._call(T))}}class ra extends se{}class ir extends ra{}class yd extends ra{}class Md extends ra{}class xi extends se{}class bd extends xi{}class Kn extends xi{}class na extends se{}class vd extends na{}class xd extends na{async _call(T){return new Qt(await super._call(T))}}class ia extends se{}class up extends ia{}class dp extends ia{}class Ti extends se{constructor(){super(...arguments);fe(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(j){const[_e,Oe]=j.dims,Fe=this.config.decoder.num_codebooks,et=Oe-Fe;let rt=0;for(let jt=0;jt0&&Gt<=et&&(j.data[rt++]=j.data[jt])}const _t=Math.floor(_e/Fe),Mt=rt/(_t*Fe);return new v.Tensor(j.type,j.data.slice(0,rt),[_t,Fe,Mt])}prepare_inputs_for_generation(j,_e,Oe){let Fe=structuredClone(j);for(let rt=0;rt=_t&&(Fe[rt][_t]=BigInt(this.config.decoder.pad_token_id));return Oe.guidance_scale!==null&&Oe.guidance_scale>1&&(Fe=Fe.concat(Fe)),super.prepare_inputs_for_generation(Fe,_e,Oe)}async generate(j){const _e=await super.generate(j),Oe=this._apply_and_filter_by_delay_pattern_mask(_e).unsqueeze_(0),{audio_values:Fe}=await we(this.sessions.encodec_decode,{audio_codes:Oe});return Fe}}class oa extends se{}class Td extends oa{}class Ed extends oa{async _call(T){return new Qt(await super._call(T))}}class aa extends se{}class Pd extends aa{}class la extends aa{async _call(T){return new Qt(await super._call(T))}}class ua extends se{}class cp extends ua{}class da extends ua{async _call(T){return new Qt(await super._call(T))}}class ca extends se{}class Cd extends ca{}class kd extends ca{async _call(T){return new Qt(await super._call(T))}}class pp extends se{}class Sd extends pp{}class $d extends se{}class Ad extends $d{constructor(...j){super(...j);fe(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(j){const _e=this._generation_mode??"text";let Oe;if(_e==="text"||!j.past_key_values){const Mt=this.sessions.prepare_inputs_embeds,jt=(0,N.pick)(j,Mt.inputNames);Oe=await we(Mt,jt)}else{const Mt=this.sessions.gen_img_embeds,jt=(0,N.pick)({image_ids:j.input_ids},Mt.inputNames);Oe=await we(Mt,jt)}const Fe={...j,...Oe},et=await Ce(this,Fe),rt=this.sessions[_e==="text"?"lm_head":"gen_head"];if(!rt)throw new Error(`Unable to find "${rt}" generation head`);const _t=await we(rt,(0,N.pick)(et,rt.inputNames));return{...Oe,...et,..._t}}async generate(j){return this._generation_mode="text",super.generate(j)}async generate_images(j){this._generation_mode="image";const _e=(j.inputs??j[this.main_input_name]).dims[1],Fe=(await super.generate(j)).slice(null,[_e,null]),et=this.sessions.image_decode,{decoded_image:rt}=await we(et,{generated_tokens:Fe}),_t=rt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Mt=[];for(const jt of _t){const Vt=O.RawImage.fromTensor(jt);Mt.push(Vt)}return Mt}}class hp extends Ke{constructor({char_logits:T,bpe_logits:j,wp_logits:_e}){super(),this.char_logits=T,this.bpe_logits=j,this.wp_logits=_e}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Id extends se{}class Od extends Id{async _call(T){return new hp(await super._call(T))}}class Fd extends se{}class Dd extends Fd{}class Ld extends Fd{}class pa extends se{}class zd extends pa{}class Bd extends pa{}class ys{static async from_pretrained(T,{progress_callback:j=null,config:_e=null,cache_dir:Oe=null,local_files_only:Fe=!1,revision:et="main",model_file_name:rt=null,subfolder:_t="onnx",device:Mt=null,dtype:jt=null,use_external_data_format:Vt=null,session_options:Lt={}}={}){const Gt={progress_callback:j,config:_e,cache_dir:Oe,local_files_only:Fe,revision:et,model_file_name:rt,subfolder:_t,device:Mt,dtype:jt,use_external_data_format:Vt,session_options:Lt};if(Gt.config=await _.AutoConfig.from_pretrained(T,Gt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const es of this.MODEL_CLASS_MAPPINGS){const ns=es.get(Gt.config.model_type);if(ns)return await ns[1].from_pretrained(T,Gt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Gt.config.model_type}", attempting to construct from base class.`),await se.from_pretrained(T,Gt);throw Error(`Unsupported model type: ${Gt.config.model_type}`)}}fe(ys,"MODEL_CLASS_MAPPINGS",null),fe(ys,"BASE_IF_FAIL",!1);const mp=new Map([["bert",["BertModel",Te]],["modernbert",["ModernBertModel",dt]],["nomic_bert",["NomicBertModel",oe]],["roformer",["RoFormerModel",me]],["electra",["ElectraModel",Ds]],["esm",["EsmModel",si]],["convbert",["ConvBertModel",vt]],["camembert",["CamembertModel",Nt]],["deberta",["DebertaModel",Jr]],["deberta-v2",["DebertaV2Model",Tt]],["mpnet",["MPNetModel",fn]],["albert",["AlbertModel",Bn]],["distilbert",["DistilBertModel",ar]],["roberta",["RobertaModel",nr]],["xlm",["XLMModel",Ls]],["xlm-roberta",["XLMRobertaModel",It]],["clap",["ClapModel",fd]],["clip",["CLIPModel",Xa]],["clipseg",["CLIPSegModel",sl]],["chinese_clip",["ChineseCLIPModel",gr]],["siglip",["SiglipModel",Za]],["jina_clip",["JinaCLIPModel",oi]],["mobilebert",["MobileBertModel",Fn]],["squeezebert",["SqueezeBertModel",yn]],["wav2vec2",["Wav2Vec2Model",Bu]],["wav2vec2-bert",["Wav2Vec2BertModel",Qu]],["unispeech",["UniSpeechModel",ea]],["unispeech-sat",["UniSpeechSatModel",np]],["hubert",["HubertModel",Ju]],["wavlm",["WavLMModel",td]],["audio-spectrogram-transformer",["ASTModel",Ba]],["vits",["VitsModel",sa]],["pyannote",["PyAnnoteModel",Uu]],["wespeaker-resnet",["WeSpeakerResNetModel",rp]],["detr",["DetrModel",uu]],["rt_detr",["RTDetrModel",So]],["table-transformer",["TableTransformerModel",Ao]],["vit",["ViTModel",Nl]],["ijepa",["IJepaModel",Ul]],["pvt",["PvtModel",bo]],["vit_msn",["ViTMSNModel",ql]],["vit_mae",["ViTMAEModel",Hl]],["groupvit",["GroupViTModel",Xl]],["fastvit",["FastViTModel",Yl]],["mobilevit",["MobileViTModel",eu]],["mobilevitv2",["MobileViTV2Model",su]],["owlvit",["OwlViTModel",nu]],["owlv2",["Owlv2Model",ou]],["beit",["BeitModel",au]],["deit",["DeiTModel",Io]],["hiera",["HieraModel",hu]],["convnext",["ConvNextModel",Ho]],["convnextv2",["ConvNextV2Model",tp]],["dinov2",["Dinov2Model",Eu]],["dinov2_with_registers",["Dinov2WithRegistersModel",Pu]],["resnet",["ResNetModel",mu]],["swin",["SwinModel",hi]],["swin2sr",["Swin2SRModel",fu]],["donut-swin",["DonutSwinModel",xu]],["yolos",["YolosModel",$u]],["dpt",["DPTModel",jo]],["glpn",["GLPNModel",_i]],["hifigan",["SpeechT5HifiGan",ld]],["efficientnet",["EfficientNetModel",vd]],["decision_transformer",["DecisionTransformerModel",Sd]],["patchtst",["PatchTSTForPrediction",Dd]],["patchtsmixer",["PatchTSMixerForPrediction",zd]],["mobilenet_v1",["MobileNetV1Model",Td]],["mobilenet_v2",["MobileNetV2Model",Pd]],["mobilenet_v3",["MobileNetV3Model",cp]],["mobilenet_v4",["MobileNetV4Model",Cd]],["maskformer",["MaskFormerModel",vu]],["mgp-str",["MgpstrForSceneTextRecognition",Od]],["style_text_to_speech_2",["StyleTextToSpeech2Model",od]]]),fp=new Map([["t5",["T5Model",C]],["longt5",["LongT5Model",be]],["mt5",["MT5Model",pt]],["bart",["BartModel",xt]],["mbart",["MBartModel",Fs]],["marian",["MarianModel",Du]],["whisper",["WhisperModel",Ra]],["m2m_100",["M2M100Model",gi]],["blenderbot",["BlenderbotModel",ze]],["blenderbot-small",["BlenderbotSmallModel",Ss]]]),_p=new Map([["bloom",["BloomModel",Fl]],["jais",["JAISModel",ol]],["gpt2",["GPT2Model",nl]],["gptj",["GPTJModel",cl]],["gpt_bigcode",["GPTBigCodeModel",hl]],["gpt_neo",["GPTNeoModel",yr]],["gpt_neox",["GPTNeoXModel",ul]],["codegen",["CodeGenModel",Ji]],["llama",["LlamaModel",eo]],["exaone",["ExaoneModel",li]],["olmo",["OlmoModel",wl]],["olmo2",["Olmo2Model",yl]],["mobilellm",["MobileLLMModel",gl]],["granite",["GraniteModel",Hc]],["cohere",["CohereModel",vl]],["gemma",["GemmaModel",ds]],["gemma2",["Gemma2Model",Tl]],["openelm",["OpenELMModel",Pl]],["qwen2",["Qwen2Model",kl]],["phi",["PhiModel",Il]],["phi3",["Phi3Model",ui]],["mpt",["MptModel",Ll]],["opt",["OPTModel",Bl]],["mistral",["MistralModel",Er]],["starcoder2",["Starcoder2Model",nn]],["falcon",["FalconModel",hd]],["stablelm",["StableLmModel",bd]]]),ha=new Map([["speecht5",["SpeechT5ForSpeechToText",lp]],["whisper",["WhisperForConditionalGeneration",Na]],["moonshine",["MoonshineForConditionalGeneration",ja]]]),Rd=new Map([["speecht5",["SpeechT5ForTextToSpeech",ad]]]),Nd=new Map([["vits",["VitsModel",sa]],["musicgen",["MusicgenForConditionalGeneration",Ti]]]),jd=new Map([["bert",["BertForSequenceClassification",Ve]],["modernbert",["ModernBertForSequenceClassification",lt]],["roformer",["RoFormerForSequenceClassification",We]],["electra",["ElectraForSequenceClassification",kr]],["esm",["EsmForSequenceClassification",In]],["convbert",["ConvBertForSequenceClassification",At]],["camembert",["CamembertForSequenceClassification",Sr]],["deberta",["DebertaForSequenceClassification",Br]],["deberta-v2",["DebertaV2ForSequenceClassification",Vs]],["mpnet",["MPNetForSequenceClassification",_n]],["albert",["AlbertForSequenceClassification",Mn]],["distilbert",["DistilBertForSequenceClassification",Is]],["roberta",["RobertaForSequenceClassification",ms]],["xlm",["XLMForSequenceClassification",Gs]],["xlm-roberta",["XLMRobertaForSequenceClassification",zi]],["bart",["BartForSequenceClassification",hs]],["mbart",["MBartForSequenceClassification",rs]],["mobilebert",["MobileBertForSequenceClassification",Vr]],["squeezebert",["SqueezeBertForSequenceClassification",Ln]]]),Ud=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",ht]],["roformer",["RoFormerForTokenClassification",Je]],["electra",["ElectraForTokenClassification",Qr]],["esm",["EsmForTokenClassification",On]],["convbert",["ConvBertForTokenClassification",is]],["camembert",["CamembertForTokenClassification",$r]],["deberta",["DebertaForTokenClassification",Rr]],["deberta-v2",["DebertaV2ForTokenClassification",Nr]],["mpnet",["MPNetForTokenClassification",gn]],["distilbert",["DistilBertForTokenClassification",Tr]],["roberta",["RobertaForTokenClassification",$s]],["xlm",["XLMForTokenClassification",$t]],["xlm-roberta",["XLMRobertaForTokenClassification",La]]]),ma=new Map([["t5",["T5ForConditionalGeneration",q]],["longt5",["LongT5ForConditionalGeneration",$e]],["mt5",["MT5ForConditionalGeneration",gt]],["bart",["BartForConditionalGeneration",Kt]],["mbart",["MBartForConditionalGeneration",Bt]],["marian",["MarianMTModel",Lu]],["m2m_100",["M2M100ForConditionalGeneration",Vn]],["blenderbot",["BlenderbotForConditionalGeneration",Js]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",qs]]]),Vd=new Map([["bloom",["BloomForCausalLM",Dl]],["gpt2",["GPT2LMHeadModel",il]],["jais",["JAISLMHeadModel",al]],["gptj",["GPTJForCausalLM",pl]],["gpt_bigcode",["GPTBigCodeForCausalLM",ml]],["gpt_neo",["GPTNeoForCausalLM",ll]],["gpt_neox",["GPTNeoXForCausalLM",dl]],["codegen",["CodeGenForCausalLM",fl]],["llama",["LlamaForCausalLM",Kc]],["exaone",["ExaoneForCausalLM",_l]],["olmo",["OlmoForCausalLM",no]],["olmo2",["Olmo2ForCausalLM",Ml]],["mobilellm",["MobileLLMForCausalLM",Nn]],["granite",["GraniteForCausalLM",bl]],["cohere",["CohereForCausalLM",qc]],["gemma",["GemmaForCausalLM",xl]],["gemma2",["Gemma2ForCausalLM",El]],["openelm",["OpenELMForCausalLM",Cl]],["qwen2",["Qwen2ForCausalLM",Sl]],["phi",["PhiForCausalLM",jn]],["phi3",["Phi3ForCausalLM",Ol]],["mpt",["MptForCausalLM",zl]],["opt",["OPTForCausalLM",Rl]],["mbart",["MBartForCausalLM",rr]],["mistral",["MistralForCausalLM",Dr]],["starcoder2",["Starcoder2ForCausalLM",pd]],["falcon",["FalconForCausalLM",md]],["trocr",["TrOCRForCausalLM",dd]],["stablelm",["StableLmForCausalLM",Kn]],["phi3_v",["Phi3VForCausalLM",hr]]]),Ei=new Map([["multi_modality",["MultiModalityCausalLM",Ad]]]),fa=new Map([["bert",["BertForMaskedLM",Ue]],["modernbert",["ModernBertForMaskedLM",ct]],["roformer",["RoFormerForMaskedLM",Ae]],["electra",["ElectraForMaskedLM",sr]],["esm",["EsmForMaskedLM",An]],["convbert",["ConvBertForMaskedLM",kt]],["camembert",["CamembertForMaskedLM",Xr]],["deberta",["DebertaForMaskedLM",Ar]],["deberta-v2",["DebertaV2ForMaskedLM",Dt]],["mpnet",["MPNetForMaskedLM",Zr]],["albert",["AlbertForMaskedLM",as]],["distilbert",["DistilBertForMaskedLM",mn]],["roberta",["RobertaForMaskedLM",_r]],["xlm",["XLMWithLMHeadModel",As]],["xlm-roberta",["XLMRobertaForMaskedLM",Da]],["mobilebert",["MobileBertForMaskedLM",ri]],["squeezebert",["SqueezeBertForMaskedLM",Dn]]]),_a=new Map([["bert",["BertForQuestionAnswering",Re]],["roformer",["RoFormerForQuestionAnswering",ut]],["electra",["ElectraForQuestionAnswering",Us]],["convbert",["ConvBertForQuestionAnswering",ws]],["camembert",["CamembertForQuestionAnswering",Yr]],["deberta",["DebertaForQuestionAnswering",or]],["deberta-v2",["DebertaV2ForQuestionAnswering",Ir]],["mpnet",["MPNetForQuestionAnswering",wn]],["albert",["AlbertForQuestionAnswering",Rn]],["distilbert",["DistilBertForQuestionAnswering",ts]],["roberta",["RobertaForQuestionAnswering",yt]],["xlm",["XLMForQuestionAnswering",en]],["xlm-roberta",["XLMRobertaForQuestionAnswering",za]],["mobilebert",["MobileBertForQuestionAnswering",fr]],["squeezebert",["SqueezeBertForQuestionAnswering",zn]]]),Pi=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ji]],["idefics3",["Idefics3ForConditionalGeneration",Ui]]]),Wd=new Map([["llava",["LlavaForConditionalGeneration",ni]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Ua]],["moondream1",["Moondream1ForConditionalGeneration",Va]],["florence2",["Florence2ForConditionalGeneration",Ga]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Al]],["idefics3",["Idefics3ForConditionalGeneration",Ui]],["paligemma",["PaliGemmaForConditionalGeneration",Ha]]]),gp=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ji]]]),Gd=new Map([["vit",["ViTForImageClassification",jl]],["ijepa",["IJepaForImageClassification",Vl]],["pvt",["PvtForImageClassification",Gl]],["vit_msn",["ViTMSNForImageClassification",Ql]],["fastvit",["FastViTForImageClassification",Qc]],["mobilevit",["MobileViTForImageClassification",tu]],["mobilevitv2",["MobileViTV2ForImageClassification",ru]],["beit",["BeitForImageClassification",lu]],["deit",["DeiTForImageClassification",Oo]],["hiera",["HieraForImageClassification",Do]],["convnext",["ConvNextForImageClassification",ep]],["convnextv2",["ConvNextV2ForImageClassification",Tu]],["dinov2",["Dinov2ForImageClassification",Xo]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Jo]],["resnet",["ResNetForImageClassification",Lo]],["swin",["SwinForImageClassification",Bo]],["segformer",["SegformerForImageClassification",yd]],["efficientnet",["EfficientNetForImageClassification",xd]],["mobilenet_v1",["MobileNetV1ForImageClassification",Ed]],["mobilenet_v2",["MobileNetV2ForImageClassification",la]],["mobilenet_v3",["MobileNetV3ForImageClassification",da]],["mobilenet_v4",["MobileNetV4ForImageClassification",kd]]]),ga=new Map([["detr",["DetrForObjectDetection",du]],["rt_detr",["RTDetrForObjectDetection",rn]],["table-transformer",["TableTransformerForObjectDetection",pu]],["yolos",["YolosForObjectDetection",Au]]]),wa=new Map([["owlvit",["OwlViTForObjectDetection",iu]],["owlv2",["Owlv2ForObjectDetection",Xc]],["grounding-dino",["GroundingDinoForObjectDetection",ku]]]),Kd=new Map([["detr",["DetrForSegmentation",cu]],["clipseg",["CLIPSegForImageSegmentation",rl]]]),Hd=new Map([["segformer",["SegformerForSemanticSegmentation",Md]],["sapiens",["SapiensForSemanticSegmentation",gu]]]),ya=new Map([["detr",["DetrForSegmentation",cu]],["maskformer",["MaskFormerForInstanceSegmentation",fi]]]),qd=new Map([["sam",["SamModel",Ou]]]),Qd=new Map([["wav2vec2",["Wav2Vec2ForCTC",Ru]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Xu]],["unispeech",["UniSpeechForCTC",Gu]],["unispeech-sat",["UniSpeechSatForCTC",Hu]],["wavlm",["WavLMForCTC",sd]],["hubert",["HubertForCTC",Zu]]]),Ma=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Nu]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Yu]],["unispeech",["UniSpeechForSequenceClassification",Ku]],["unispeech-sat",["UniSpeechSatForSequenceClassification",qu]],["wavlm",["WavLMForSequenceClassification",rd]],["hubert",["HubertForSequenceClassification",ed]],["audio-spectrogram-transformer",["ASTForAudioClassification",Bi]]]),Xd=new Map([["wavlm",["WavLMForXVector",nd]]]),Yd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",ip]],["wavlm",["WavLMForAudioFrameClassification",op]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ju]],["pyannote",["PyAnnoteForAudioFrameClassification",Vu]]]),Jd=new Map([["vitmatte",["VitMatteForImageMatting",Zl]]]),wp=new Map([["patchtst",["PatchTSTForPrediction",Ld]],["patchtsmixer",["PatchTSMixerForPrediction",Bd]]]),yp=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Jc]]]),Zd=new Map([["dpt",["DPTForDepthEstimation",Un]],["depth_anything",["DepthAnythingForDepthEstimation",Uo]],["glpn",["GLPNForDepthEstimation",Wo]],["sapiens",["SapiensForDepthEstimation",wu]],["depth_pro",["DepthProForDepthEstimation",Mu]]]),ec=new Map([["sapiens",["SapiensForNormalEstimation",Zc]]]),tc=new Map([["vitpose",["VitPoseForPoseEstimation",Wl]]]),sc=new Map([["clip",["CLIPVisionModelWithProjection",Ja]],["siglip",["SiglipVisionModel",tl]],["jina_clip",["JinaCLIPVisionModel",wr]]]),Mp=[[mp,A.EncoderOnly],[fp,A.EncoderDecoder],[_p,A.DecoderOnly],[jd,A.EncoderOnly],[Ud,A.EncoderOnly],[ma,A.Seq2Seq],[ha,A.Seq2Seq],[Vd,A.DecoderOnly],[Ei,A.MultiModality],[fa,A.EncoderOnly],[_a,A.EncoderOnly],[Pi,A.Vision2Seq],[Wd,A.ImageTextToText],[Gd,A.EncoderOnly],[Kd,A.EncoderOnly],[ya,A.EncoderOnly],[Hd,A.EncoderOnly],[Jd,A.EncoderOnly],[wp,A.EncoderOnly],[yp,A.EncoderOnly],[Zd,A.EncoderOnly],[ec,A.EncoderOnly],[tc,A.EncoderOnly],[ga,A.EncoderOnly],[wa,A.EncoderOnly],[qd,A.MaskGeneration],[Qd,A.EncoderOnly],[Ma,A.EncoderOnly],[Rd,A.Seq2Seq],[Nd,A.EncoderOnly],[Xd,A.EncoderOnly],[Yd,A.EncoderOnly],[sc,A.EncoderOnly]];for(const[f,T]of Mp)for(const[j,_e]of f.values())S.set(j,T),x.set(_e,j),w.set(j,_e);const bp=[["MusicgenForConditionalGeneration",Ti,A.Musicgen],["Phi3VForCausalLM",hr,A.Phi3V],["CLIPTextModelWithProjection",Ya,A.EncoderOnly],["SiglipTextModel",el,A.EncoderOnly],["JinaCLIPTextModel",Wi,A.EncoderOnly],["ClapTextModelWithProjection",_d,A.EncoderOnly],["ClapAudioModelWithProjection",gd,A.EncoderOnly]];for(const[f,T,j]of bp)S.set(f,j),x.set(T,f),w.set(f,T);class ba extends ys{}fe(ba,"MODEL_CLASS_MAPPINGS",Mp.map(T=>T[0])),fe(ba,"BASE_IF_FAIL",!0);class rc extends ys{}fe(rc,"MODEL_CLASS_MAPPINGS",[jd]);class vp extends ys{}fe(vp,"MODEL_CLASS_MAPPINGS",[Ud]);class nc extends ys{}fe(nc,"MODEL_CLASS_MAPPINGS",[ma]);class ic extends ys{}fe(ic,"MODEL_CLASS_MAPPINGS",[ha]);class oc extends ys{}fe(oc,"MODEL_CLASS_MAPPINGS",[Rd]);class ac extends ys{}fe(ac,"MODEL_CLASS_MAPPINGS",[Nd]);class xp extends ys{}fe(xp,"MODEL_CLASS_MAPPINGS",[Vd]);class lc extends ys{}fe(lc,"MODEL_CLASS_MAPPINGS",[fa]);class uc extends ys{}fe(uc,"MODEL_CLASS_MAPPINGS",[_a]);class dc extends ys{}fe(dc,"MODEL_CLASS_MAPPINGS",[Pi]);class cc extends ys{}fe(cc,"MODEL_CLASS_MAPPINGS",[Gd]);class pc extends ys{}fe(pc,"MODEL_CLASS_MAPPINGS",[Kd]);class hc extends ys{}fe(hc,"MODEL_CLASS_MAPPINGS",[Hd]);class mc extends ys{}fe(mc,"MODEL_CLASS_MAPPINGS",[ya]);class fc extends ys{}fe(fc,"MODEL_CLASS_MAPPINGS",[ga]);class _c extends ys{}fe(_c,"MODEL_CLASS_MAPPINGS",[wa]);class gc extends ys{}fe(gc,"MODEL_CLASS_MAPPINGS",[qd]);class wc extends ys{}fe(wc,"MODEL_CLASS_MAPPINGS",[Qd]);class va extends ys{}fe(va,"MODEL_CLASS_MAPPINGS",[Ma]);class yc extends ys{}fe(yc,"MODEL_CLASS_MAPPINGS",[Xd]);class Mc extends ys{}fe(Mc,"MODEL_CLASS_MAPPINGS",[Yd]);class bc extends ys{}fe(bc,"MODEL_CLASS_MAPPINGS",[gp]);class vc extends ys{}fe(vc,"MODEL_CLASS_MAPPINGS",[Jd]);class xc extends ys{}fe(xc,"MODEL_CLASS_MAPPINGS",[yp]);class Tc extends ys{}fe(Tc,"MODEL_CLASS_MAPPINGS",[Zd]);class Ec extends ys{}fe(Ec,"MODEL_CLASS_MAPPINGS",[ec]);class Tp extends ys{}fe(Tp,"MODEL_CLASS_MAPPINGS",[tc]);class Pc extends ys{}fe(Pc,"MODEL_CLASS_MAPPINGS",[sc]);class Ep extends Ke{constructor({logits:T,past_key_values:j,encoder_outputs:_e,decoder_attentions:Oe=null,cross_attentions:Fe=null}){super(),this.logits=T,this.past_key_values=j,this.encoder_outputs=_e,this.decoder_attentions=Oe,this.cross_attentions=Fe}}class Qt extends Ke{constructor({logits:T,...j}){super(),this.logits=T;const _e=Object.values(j);_e.length>0&&(this.attentions=_e)}}class Pp extends Ke{constructor({logits:T,embeddings:j}){super(),this.logits=T,this.embeddings=j}}class Ks extends Ke{constructor({logits:T}){super(),this.logits=T}}class Xs extends Ke{constructor({logits:T}){super(),this.logits=T}}class tr extends Ke{constructor({start_logits:T,end_logits:j}){super(),this.start_logits=T,this.end_logits=j}}class vn extends Ke{constructor({logits:T}){super(),this.logits=T}}class Cp extends Ke{constructor({logits:T,past_key_values:j}){super(),this.logits=T,this.past_key_values=j}}class Hn extends Ke{constructor({alphas:T}){super(),this.alphas=T}}class Cc extends Ke{constructor({waveform:T,spectrogram:j}){super(),this.waveform=T,this.spectrogram=j}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(Ee,$,r)=>{r.r($),r.d($,{ASTFeatureExtractor:()=>R});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var I=r("./src/utils/audio.js");class R extends _.FeatureExtractor{constructor(N){super(N);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($),r.d($,{AutoFeatureExtractor:()=>Y});var _=r("./src/utils/constants.js"),I=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var R=r("./src/models/feature_extractors.js");class Y{static async from_pretrained(g,b={}){const y=await(0,I.getModelJSON)(g,_.FEATURE_EXTRACTOR_NAME,!0,b),M=y.feature_extractor_type,v=R[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":(Ee,$,r)=>{r.r($),r.d($,{AutoImageProcessor:()=>N});var _=r("./src/utils/constants.js"),I=r("./src/utils/hub.js"),R=r("./src/base/image_processors_utils.js"),Y=r("./src/models/image_processors.js");class N{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 O=Y[v];return O||(v!==void 0&&console.warn(`Image processor type '${v}' not found, assuming base ImageProcessor. Please report this at ${_.GITHUB_ISSUE_URL}.`),O=R.ImageProcessor),new O(M)}}},"./src/models/auto/processing_auto.js":(Ee,$,r)=>{r.r($),r.d($,{AutoProcessor:()=>b});var _=r("./src/utils/constants.js"),I=r("./src/utils/hub.js"),R=r("./src/base/processing_utils.js"),Y=r("./src/models/processors.js"),N=r("./src/models/image_processors.js"),g=r("./src/models/feature_extractors.js");class b{static async from_pretrained(M,v={}){const O=await(0,I.getModelJSON)(M,_.IMAGE_PROCESSOR_NAME,!0,v),{image_processor_type:K,feature_extractor_type:te,processor_class:ne}=O;if(ne&&Y[ne])return Y[ne].from_pretrained(M,v);if(!K&&!te)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const W={};if(K){const X=N[K];if(!X)throw new Error(`Unknown image_processor_type: '${K}'.`);W.image_processor=new X(O)}if(te){const X=N[te];if(X)W.image_processor=new X(O);else{const A=g[te];if(!A)throw new Error(`Unknown feature_extractor_type: '${te}'.`);W.feature_extractor=new A(O)}}const U={};return new R.Processor(U,W)}}},"./src/models/beit/image_processing_beit.js":(Ee,$,r)=>{r.r($),r.d($,{BeitFeatureExtractor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(Ee,$,r)=>{r.r($),r.d($,{BitImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(Ee,$,r)=>{r.r($),r.d($,{ChineseCLIPFeatureExtractor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(Ee,$,r)=>{r.r($),r.d($,{ClapFeatureExtractor:()=>R});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var I=r("./src/utils/audio.js");class R extends _.FeatureExtractor{constructor(N){super(N),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(N,g,b,y){let M;const v=N.length-g;if(v>0)if(b==="rand_trunc"){const O=Math.floor(Math.random()*(v+1));N=N.subarray(O,O+g),M=await this._extract_fbank_features(N,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${b}" not implemented`);else{if(v<0){let O=new Float64Array(g);if(O.set(N),y==="repeat")for(let K=N.length;K{r.r($),r.d($,{CLIPFeatureExtractor:()=>R,CLIPImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/convnext/image_processing_convnext.js":(Ee,$,r)=>{r.r($),r.d($,{ConvNextFeatureExtractor:()=>R,ConvNextImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{constructor(N){super(N),this.crop_pct=this.config.crop_pct??.875}async resize(N){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(N,{shortest_edge:y});N=await N.resize(M,v,{resample:this.resample}),N=await N.center_crop(g,g)}else N=await N.resize(g,g,{resample:this.resample});return N}}class R extends I{}},"./src/models/deit/image_processing_deit.js":(Ee,$,r)=>{r.r($),r.d($,{DeiTFeatureExtractor:()=>R,DeiTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/detr/image_processing_detr.js":(Ee,$,r)=>{r.r($),r.d($,{DetrFeatureExtractor:()=>Y,DetrImageProcessor:()=>R});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class R 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 Y extends R{}},"./src/models/donut/image_processing_donut.js":(Ee,$,r)=>{r.r($),r.d($,{DonutFeatureExtractor:()=>R,DonutImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{pad_image(N,g,b,y={}){const[M,v,O]=g;let K=this.image_mean;Array.isArray(this.image_mean)||(K=new Array(O).fill(K));let te=this.image_std;Array.isArray(te)||(te=new Array(O).fill(K));const ne=K.map((W,U)=>-W/te[U]);return super.pad_image(N,g,b,{center:!0,constant_values:ne,...y})}}class R extends I{}},"./src/models/dpt/image_processing_dpt.js":(Ee,$,r)=>{r.r($),r.d($,{DPTFeatureExtractor:()=>R,DPTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/efficientnet/image_processing_efficientnet.js":(Ee,$,r)=>{r.r($),r.d($,{EfficientNetImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{constructor(Y){super(Y),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(N=>N*N))}}},"./src/models/feature_extractors.js":(Ee,$,r)=>{r.r($),r.d($,{ASTFeatureExtractor:()=>_.ASTFeatureExtractor,ClapFeatureExtractor:()=>I.ClapFeatureExtractor,ImageFeatureExtractor:()=>v.ImageProcessor,MoonshineFeatureExtractor:()=>R.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>Y.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>N.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"),R=r("./src/models/moonshine/feature_extraction_moonshine.js"),Y=r("./src/models/pyannote/feature_extraction_pyannote.js"),N=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":(Ee,$,r)=>{r.r($),r.d($,{Florence2Processor:()=>Y});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js");class Y 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 O=M==="ocr"?"quad_boxes":"bboxes",K=g.matchAll(this.regexes[O]),te=[],ne=[];for(const[W,U,...X]of K)te.push(U?U.trim():te.at(-1)??""),ne.push(X.map((A,S)=>(Number(A)+.5)/this.size_per_bin*y[S%2]));v={labels:te,[O]:ne};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}}}fe(Y,"tokenizer_class",R.AutoTokenizer),fe(Y,"image_processor_class",I.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(Ee,$,r)=>{r.r($),r.d($,{GLPNFeatureExtractor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(Ee,$,r)=>{r.r($),r.d($,{GroundingDinoImageProcessor:()=>R});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class R extends _.ImageProcessor{async _call(N){const g=await super._call(N),b=g.pixel_values.dims,y=(0,I.ones)([b[0],b[2],b[3]]);return{...g,pixel_mask:y}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(Ee,$,r)=>{r.r($),r.d($,{GroundingDinoProcessor:()=>g});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js"),Y=r("./src/base/image_processors_utils.js");function N(b,y){const v=b.dims.at(-1)-1,O=b.tolist();O.fill(!1,0,1),O.fill(!1,v);const K=y.tolist();return O.map((te,ne)=>te?ne:null).filter(te=>te!==null).map(te=>K[te])}class g extends _.Processor{async _call(y,M,v={}){const O=y?await this.image_processor(y,v):{};return{...M?this.tokenizer(M,v):{},...O}}post_process_grounded_object_detection(y,M,{box_threshold:v=.25,text_threshold:O=.25,target_sizes:K=null}={}){const{logits:te,pred_boxes:ne}=y,W=te.dims[0];if(K!==null&&K.length!==W)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const U=te.dims.at(1),X=te.sigmoid(),A=X.max(-1).tolist(),S=ne.tolist().map(x=>x.map(F=>(0,Y.center_to_corners_format)(F))),w=[];for(let x=0;xre.map((xe,ce)=>xe*F[(ce+1)%2])));const ae=A[x],ie=[],ve=[],we=[];for(let re=0;re{r.r($),r.d($,{Idefics3ImageProcessor:()=>R});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class R extends _.ImageProcessor{constructor(N){super(N),this.do_image_splitting=N.do_image_splitting??!0,this.max_image_size=N.max_image_size}get_resize_for_vision_encoder(N,g){let[b,y]=N.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(N,{do_image_splitting:g=null,return_row_col_info:b=!1}={}){let y;if(!Array.isArray(N))y=[[N]];else{if(N.length===0||!N[0])throw new Error("No images provided.");Array.isArray(N[0])?y=N:y=[N]}let M=[],v=[],O=[];const K=[],te=[];for(const x of y){let F=await Promise.all(x.map(ve=>this.preprocess(ve)));K.push(...F.map(ve=>ve.original_size)),te.push(...F.map(ve=>ve.reshaped_input_size)),F.forEach(ve=>ve.pixel_values.unsqueeze_(0));const{longest_edge:ae}=this.max_image_size;let ie;if(g??this.do_image_splitting){let ve=new Array(F.length),we=new Array(F.length);ie=await Promise.all(F.map(async(re,xe)=>{const ce=this.get_resize_for_vision_encoder(re.pixel_values,ae),Se=await(0,I.interpolate_4d)(re.pixel_values,{size:[ce.height,ce.width]}),{frames:Ie,num_splits_h:Ce,num_splits_w:tt}=await this.split_image(Se,this.max_image_size);return ve[xe]=Ce,we[xe]=tt,(0,I.cat)(Ie,0)})),v.push(ve),O.push(we)}else{const ve=[ae,ae];ie=await Promise.all(F.map(we=>(0,I.interpolate_4d)(we.pixel_values,{size:ve}))),v.push(new Array(F.length).fill(0)),O.push(new Array(F.length).fill(0))}M.push((0,I.cat)(ie,0))}const ne=M.length,[W,U,X,A]=M[0].dims;let S,w;if(ne===1)S=M[0].unsqueeze_(0),w=(0,I.full)([ne,W,X,A],!0);else{const x=Math.max(...M.map(ie=>ie.dims.at(0)));w=(0,I.full)([ne,x,X,A],!0);const F=w.data,ae=x*X*A;for(let ie=0;ieb||O>y){K=Math.ceil(v/b),te=Math.ceil(O/y);const ne=Math.ceil(v/K),W=Math.ceil(O/te);for(let A=0;A{r.r($),r.d($,{Idefics3Processor:()=>y});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js");r("./src/utils/image.js");var Y=r("./src/utils/core.js");function N(M,v,O,K,te,ne){let W="";for(let U=0;U`+te.repeat(M);W+=` +`}return W+=` +${K}${ne}`+te.repeat(M)+`${K}`,W}function g(M,v,O,K){return`${v}${K}`+O.repeat(M)+`${v}`}function b(M,v,O,K,te,ne){return M===0&&v===0?g(O,K,te,ne):N(O,M,v,K,te,ne)}class y extends _.Processor{constructor(){super(...arguments);fe(this,"fake_image_token","");fe(this,"image_token","");fe(this,"global_img_token","")}async _call(O,K=null,te={}){te.return_row_col_info??(te.return_row_col_info=!0);let ne;K&&(ne=await this.image_processor(K,te)),Array.isArray(O)||(O=[O]);const W=ne.rows??[new Array(O.length).fill(0)],U=ne.cols??[new Array(O.length).fill(0)],X=this.config.image_seq_len,A=[],S=[];for(let x=0;xb(xe,ie[ce],X,this.fake_image_token,this.image_token,this.global_img_token)),we=F.split(this.image_token);if(we.length===0)throw new Error("The image token should be present in the text.");let re=we[0];for(let xe=0;xe{r.r($),r.d($,{BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BitImageProcessor:()=>I.BitImageProcessor,CLIPFeatureExtractor:()=>Y.CLIPFeatureExtractor,CLIPImageProcessor:()=>Y.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>R.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>N.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>N.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:()=>O.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>K.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>te.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>W.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>U.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>X.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>A.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>A.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>S.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>S.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>w.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>w.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>x.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>x.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>F.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>F.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>ae.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>ae.MobileViTImageProcessor,NougatImageProcessor:()=>ie.NougatImageProcessor,OwlViTFeatureExtractor:()=>we.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>we.OwlViTImageProcessor,Owlv2ImageProcessor:()=>ve.Owlv2ImageProcessor,Phi3VImageProcessor:()=>re.Phi3VImageProcessor,PvtImageProcessor:()=>xe.PvtImageProcessor,Qwen2VLImageProcessor:()=>ce.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Se.RTDetrImageProcessor,SamImageProcessor:()=>Ie.SamImageProcessor,SegformerFeatureExtractor:()=>Ce.SegformerFeatureExtractor,SegformerImageProcessor:()=>Ce.SegformerImageProcessor,SiglipImageProcessor:()=>tt.SiglipImageProcessor,Swin2SRImageProcessor:()=>Ge.Swin2SRImageProcessor,VLMImageProcessor:()=>ne.VLMImageProcessor,ViTFeatureExtractor:()=>ye.ViTFeatureExtractor,ViTImageProcessor:()=>ye.ViTImageProcessor,VitMatteImageProcessor:()=>J.VitMatteImageProcessor,VitPoseImageProcessor:()=>de.VitPoseImageProcessor,YolosFeatureExtractor:()=>ke.YolosFeatureExtractor,YolosImageProcessor:()=>ke.YolosImageProcessor});var _=r("./src/models/beit/image_processing_beit.js"),I=r("./src/models/bit/image_processing_bit.js"),R=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),Y=r("./src/models/clip/image_processing_clip.js"),N=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"),O=r("./src/models/glpn/image_processing_glpn.js"),K=r("./src/models/grounding_dino/image_processing_grounding_dino.js"),te=r("./src/models/idefics3/image_processing_idefics3.js"),ne=r("./src/models/janus/image_processing_janus.js"),W=r("./src/models/jina_clip/image_processing_jina_clip.js"),U=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),X=r("./src/models/mask2former/image_processing_mask2former.js"),A=r("./src/models/maskformer/image_processing_maskformer.js"),S=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),w=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),x=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),F=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),ae=r("./src/models/mobilevit/image_processing_mobilevit.js"),ie=r("./src/models/nougat/image_processing_nougat.js"),ve=r("./src/models/owlv2/image_processing_owlv2.js"),we=r("./src/models/owlvit/image_processing_owlvit.js"),re=r("./src/models/phi3_v/image_processing_phi3_v.js"),xe=r("./src/models/pvt/image_processing_pvt.js"),ce=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Se=r("./src/models/rt_detr/image_processing_rt_detr.js"),Ie=r("./src/models/sam/image_processing_sam.js"),Ce=r("./src/models/segformer/image_processing_segformer.js"),tt=r("./src/models/siglip/image_processing_siglip.js"),Ge=r("./src/models/swin2sr/image_processing_swin2sr.js"),ye=r("./src/models/vit/image_processing_vit.js"),J=r("./src/models/vitmatte/image_processing_vitmatte.js"),de=r("./src/models/vitpose/image_processing_vitpose.js"),ke=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(Ee,$,r)=>{r.r($),r.d($,{VLMImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{constructor(Y){super({do_pad:!0,pad_size:{width:Y.image_size,height:Y.image_size},...Y}),this.constant_values=this.config.background_color.map(N=>N*this.rescale_factor)}pad_image(Y,N,g,b){return super.pad_image(Y,N,g,{constant_values:this.constant_values,center:!0,...b})}}},"./src/models/janus/processing_janus.js":(Ee,$,r)=>{r.r($),r.d($,{VLChatProcessor:()=>b});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js"),Y=r("./src/utils/core.js"),N=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:O="default"}={}){v?Array.isArray(v)||(v=[v]):v=await Promise.all(M.filter(ie=>ie.images).flatMap(ie=>ie.images).map(ie=>g.RawImage.read(ie)));const K=this.tokenizer,te=K.apply_chat_template(M,{tokenize:!1,add_generation_prompt:!0,chat_template:O}),ne=ie=>K.encode(ie,{add_special_tokens:!1}),W=te.split(this.image_tag),U=W.length-1;if(v.length!==U)throw new Error(`Number of images provided (${v.length}) does not match number of "${this.image_tag}" image tags (${U})`);const[X,A,S]=K.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=ne(W[0]),x=new Array(w.length).fill(!1);for(let ie=1;ie0){const ie=await this.image_processor(v);return ie.pixel_values.unsqueeze_(0),{...ae,...ie}}return ae}}fe(b,"image_processor_class",I.AutoImageProcessor),fe(b,"tokenizer_class",R.AutoTokenizer),fe(b,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(Ee,$,r)=>{r.r($),r.d($,{JinaCLIPImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{constructor(Y){const{resize_mode:N,fill_color:g,interpolation:b,size:y,...M}=Y,v=N==="squash"?{width:y,height:y}:N==="shortest"?{shortest_edge:y}:{longest_edge:y},O=b==="bicubic"?3:2;super({...M,size:v,resample:O,do_center_crop:!0,crop_size:y,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(Ee,$,r)=>{r.r($),r.d($,{JinaCLIPProcessor:()=>Y});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js");class Y 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}}}fe(Y,"tokenizer_class",R.AutoTokenizer),fe(Y,"image_processor_class",I.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(Ee,$,r)=>{r.r($),r.d($,{LlavaOnevisionImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(Ee,$,r)=>{r.r($),r.d($,{Mask2FormerImageProcessor:()=>I});var _=r("./src/models/maskformer/image_processing_maskformer.js");class I extends _.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(Ee,$,r)=>{r.r($),r.d($,{MaskFormerFeatureExtractor:()=>R,MaskFormerImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_panoptic_segmentation(...N){return(0,_.post_process_panoptic_segmentation)(...N)}post_process_instance_segmentation(...N){return(0,_.post_process_instance_segmentation)(...N)}}class R extends I{}},"./src/models/mgp_str/processing_mgp_str.js":(Ee,$,r)=>{r.r($),r.d($,{MgpstrProcessor:()=>g});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js"),Y=r("./src/utils/maths.js");const N={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(!N.hasOwnProperty(M))throw new Error(`Format ${M} is not supported.`);const[v,O]=N[M],K=this[v].bind(this),[te,ne]=y.dims,W=[],U=[],X=y.tolist();for(let S=0;S0?F.reduce((ie,ve)=>ie*ve,1):0;U.push(x),W.push(ae)}return[K(U),W]}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[O,K]=this._decode_helper(y,"char"),[te,ne]=this._decode_helper(M,"bpe"),[W,U]=this._decode_helper(v,"wp"),X=[],A=[];for(let S=0;S{r.r($),r.d($,{MobileNetV1FeatureExtractor:()=>R,MobileNetV1ImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(Ee,$,r)=>{r.r($),r.d($,{MobileNetV2FeatureExtractor:()=>R,MobileNetV2ImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(Ee,$,r)=>{r.r($),r.d($,{MobileNetV3FeatureExtractor:()=>R,MobileNetV3ImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(Ee,$,r)=>{r.r($),r.d($,{MobileNetV4FeatureExtractor:()=>R,MobileNetV4ImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/mobilevit/image_processing_mobilevit.js":(Ee,$,r)=>{r.r($),r.d($,{MobileViTFeatureExtractor:()=>R,MobileViTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/moonshine/feature_extraction_moonshine.js":(Ee,$,r)=>{r.r($),r.d($,{MoonshineFeatureExtractor:()=>R});var _=r("./src/base/feature_extraction_utils.js"),I=r("./src/utils/tensor.js");class R extends _.FeatureExtractor{async _call(N){(0,_.validate_audio_inputs)(N,"MoonshineFeatureExtractor"),N instanceof Float64Array&&(N=new Float32Array(N));const g=[1,N.length];return{input_values:new I.Tensor("float32",N,g)}}}},"./src/models/moonshine/processing_moonshine.js":(Ee,$,r)=>{r.r($),r.d($,{MoonshineProcessor:()=>Y});var _=r("./src/models/auto/feature_extraction_auto.js"),I=r("./src/tokenizers.js"),R=r("./src/base/processing_utils.js");class Y extends R.Processor{async _call(g){return await this.feature_extractor(g)}}fe(Y,"tokenizer_class",I.AutoTokenizer),fe(Y,"feature_extractor_class",_.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(Ee,$,r)=>{r.r($),r.d($,{NougatImageProcessor:()=>I});var _=r("./src/models/donut/image_processing_donut.js");class I extends _.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(Ee,$,r)=>{r.r($),r.d($,{Owlv2ImageProcessor:()=>I});var _=r("./src/models/owlvit/image_processing_owlvit.js");class I extends _.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(Ee,$,r)=>{r.r($),r.d($,{OwlViTFeatureExtractor:()=>R,OwlViTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_object_detection(...N){return(0,_.post_process_object_detection)(...N)}}class R extends I{}},"./src/models/owlvit/processing_owlvit.js":(Ee,$,r)=>{r.r($),r.d($,{OwlViTProcessor:()=>Y});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js");class Y extends _.Processor{}fe(Y,"tokenizer_class",R.AutoTokenizer),fe(Y,"image_processor_class",I.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(Ee,$,r)=>{r.r($),r.d($,{PaliGemmaProcessor:()=>g});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js");const Y="";function N(b,y,M,v,O){return`${v.repeat(M*O)}${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 O=this.tokenizer.bos_token,K=this.image_processor.config.image_seq_length;let te;M.some(U=>U.includes(Y))?te=M.map(U=>{const X=U.replaceAll(Y,Y.repeat(K)),A=X.lastIndexOf(Y),S=A===-1?0:A+Y.length;return X.slice(0,S)+O+X.slice(S)+` +`}):(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."),te=M.map(U=>N(U,O,K,Y,y.length)));const ne=this.tokenizer(te,v);return{...await this.image_processor(y,v),...ne}}}fe(g,"tokenizer_class",R.AutoTokenizer),fe(g,"image_processor_class",I.AutoImageProcessor),fe(g,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(Ee,$,r)=>{r.r($),r.d($,{Phi3VImageProcessor:()=>y});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");const R=336,Y=[2,3],{ceil:N,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,O){const{num_img_tokens:K}=this.config;return g((g(O/R)*g(v/R)+1)*K+1+(g(O/R)+1)*b(K))}get_resize_output_image_size(v,O){const K=this._num_crops,[te,ne]=v.size;let W=te/ne,U=1;for(;U*Math.ceil(U/W)<=K;)U+=1;U-=1;const X=Math.floor(U*336),A=Math.floor(X/W);return[X,A]}pad_image(v,O,K,te={}){const[ne,W]=O,U=R*N(ne/R),X=R*N(W/R),A=[1,1,1].map((S,w)=>(S-this.image_mean[w])/this.image_std[w]);return super.pad_image(v,O,{width:X,height:U},{center:!0,constant_values:A,...te})}async _call(v,{num_crops:O=null}={}){if(this._num_crops=O??(O=this.config.num_crops),O<4||b(O)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(v)||(v=[v]);const K=v.length,te=await Promise.all(v.map(x=>this.preprocess(x))),ne=te.map(x=>x.original_size),W=te.map(x=>x.reshaped_input_size),U=[];for(const{pixel_values:x}of te){x.unsqueeze_(0);const[F,ae]=x.dims.slice(-2),ie=await(0,I.interpolate_4d)(x,{size:[R,R],mode:"bicubic"});if(O>0){const ve=[],we=b(O),re=g(ae/we),xe=g(F/we);for(let Se=0;Sex.map(F=>R*N(F/R))),S=new I.Tensor("int64",A.flat(),[K,2]),w=A.map(([x,F])=>this.calc_num_image_tokens_from_image_size(F,x));return{pixel_values:X,original_sizes:ne,reshaped_input_sizes:W,image_sizes:S,num_img_tokens:w}}}},"./src/models/phi3_v/processing_phi3_v.js":(Ee,$,r)=>{r.r($),r.d($,{Phi3VProcessor:()=>g});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js");r("./src/utils/image.js");const Y="<|image|>",N=/<\|image_\d+\|>/g;class g extends _.Processor{async _call(y,M=null,{padding:v=!0,truncation:O=!0,num_crops:K=null}={}){Array.isArray(y)||(y=[y]);let te,ne;if(M){ne=await this.image_processor(M,{num_crops:K});const{num_img_tokens:W}=ne,U=y.map((A,S)=>A.split(N).join(Y.repeat(W[S])));te=this.tokenizer(U,{padding:v,truncation:O});const X=this.tokenizer.model.convert_tokens_to_ids([Y])[0];te.input_ids.map_(A=>A==X?-A:A)}else te=this.tokenizer(y);return{...te,...ne}}}fe(g,"image_processor_class",I.AutoImageProcessor),fe(g,"tokenizer_class",R.AutoTokenizer)},"./src/models/processors.js":(Ee,$,r)=>{r.r($),r.d($,{Florence2Processor:()=>_.Florence2Processor,GroundingDinoProcessor:()=>I.GroundingDinoProcessor,Idefics3Processor:()=>R.Idefics3Processor,JinaCLIPProcessor:()=>N.JinaCLIPProcessor,MgpstrProcessor:()=>g.MgpstrProcessor,MoonshineProcessor:()=>b.MoonshineProcessor,OwlViTProcessor:()=>y.OwlViTProcessor,PaliGemmaProcessor:()=>v.PaliGemmaProcessor,Phi3VProcessor:()=>M.Phi3VProcessor,PyAnnoteProcessor:()=>O.PyAnnoteProcessor,Qwen2VLProcessor:()=>K.Qwen2VLProcessor,SamProcessor:()=>te.SamProcessor,SpeechT5Processor:()=>ne.SpeechT5Processor,VLChatProcessor:()=>Y.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>W.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>U.WhisperProcessor});var _=r("./src/models/florence2/processing_florence2.js"),I=r("./src/models/grounding_dino/processing_grounding_dino.js"),R=r("./src/models/idefics3/processing_idefics3.js"),Y=r("./src/models/janus/processing_janus.js"),N=r("./src/models/jina_clip/processing_jina_clip.js"),g=r("./src/models/mgp_str/processing_mgp_str.js"),b=r("./src/models/moonshine/processing_moonshine.js"),y=r("./src/models/owlvit/processing_owlvit.js"),M=r("./src/models/phi3_v/processing_phi3_v.js"),v=r("./src/models/paligemma/processing_paligemma.js"),O=r("./src/models/pyannote/processing_pyannote.js"),K=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),te=r("./src/models/sam/processing_sam.js"),ne=r("./src/models/speecht5/processing_speecht5.js"),W=r("./src/models/wav2vec2/processing_wav2vec2.js"),U=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(Ee,$,r)=>{r.r($),r.d($,{PvtImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(Ee,$,r)=>{r.r($),r.d($,{PyAnnoteFeatureExtractor:()=>Y});var _=r("./src/base/feature_extraction_utils.js"),I=r("./src/utils/tensor.js"),R=r("./src/utils/maths.js");class Y 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 O=[];let K=-1;for(let te=0;te({id:te,start:ne*y,end:W*y,confidence:U/(W-ne)})))}return M}}},"./src/models/pyannote/processing_pyannote.js":(Ee,$,r)=>{r.r($),r.d($,{PyAnnoteProcessor:()=>R});var _=r("./src/base/processing_utils.js"),I=r("./src/models/pyannote/feature_extraction_pyannote.js");class R extends _.Processor{async _call(N){return await this.feature_extractor(N)}post_process_speaker_diarization(...N){return this.feature_extractor.post_process_speaker_diarization(...N)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}fe(R,"feature_extractor_class",I.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(Ee,$,r)=>{r.r($),r.d($,{Qwen2VLImageProcessor:()=>R});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class R extends _.ImageProcessor{async _call(N,...g){const{pixel_values:b,original_sizes:y,reshaped_input_sizes:M}=await super._call(N,...g);let v=b;const{temporal_patch_size:O,merge_size:K,patch_size:te}=this.config;v.dims[0]===1&&(v=(0,I.cat)(Array.from({length:O},()=>v),0));const ne=v.dims[0]/O,W=v.dims[1],U=Math.floor(v.dims[2]/te),X=Math.floor(v.dims[3]/te),A=v.view(ne,O,W,Math.floor(U/K),K,te,Math.floor(X/K),K,te).permute(0,3,6,4,7,2,1,5,8).view(ne*U*X,W*O*te*te),S=new I.Tensor("int64",[ne,U,X],[1,3]);return{pixel_values:A,image_grid_thw:S,original_sizes:y,reshaped_input_sizes:M}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(Ee,$,r)=>{r.r($),r.d($,{Qwen2VLProcessor:()=>Y});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js"),R=r("./src/tokenizers.js");r("./src/utils/image.js");class Y 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 K=this.image_processor.config.merge_size**2,te=0;const ne=v.tolist();g=g.map(W=>{for(;W.includes("<|image_pad|>");){const U=Number(ne[te++].reduce((X,A)=>X*A,1n));W=W.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(U/K)))}return W.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(g),...M}}}fe(Y,"image_processor_class",I.AutoImageProcessor),fe(Y,"tokenizer_class",R.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(Ee,$,r)=>{r.r($),r.d($,{RTDetrImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_object_detection(...Y){return(0,_.post_process_object_detection)(...Y)}}},"./src/models/sam/image_processing_sam.js":(Ee,$,r)=>{r.r($),r.d($,{SamImageProcessor:()=>Y});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/core.js"),R=r("./src/utils/tensor.js");class Y 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 O=0;OM!==b.dims[v]))throw Error(`The first ${y.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new R.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:O=null}={}){const K=[];O=O??this.pad_size;const te=[O.height,O.width];for(let ne=0;neM&&(S[w]=1);X=new R.Tensor("bool",S,X.dims)}K.push(X)}return K}generate_crop_boxes(g,b,{crop_n_layers:y=0,overlap_ratio:M=.3413333333333333,points_per_crop:v=32,crop_n_points_downscale_factor:O=1}={}){}}},"./src/models/sam/processing_sam.js":(Ee,$,r)=>{r.r($),r.d($,{SamProcessor:()=>R});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/image_processing_auto.js");class R extends _.Processor{async _call(...N){return await this.image_processor(...N)}post_process_masks(...N){return this.image_processor.post_process_masks(...N)}reshape_input_points(...N){return this.image_processor.reshape_input_points(...N)}}fe(R,"image_processor_class",I.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(Ee,$,r)=>{r.r($),r.d($,{SeamlessM4TFeatureExtractor:()=>Y});var _=r("./src/base/feature_extraction_utils.js"),I=r("./src/utils/tensor.js"),R=r("./src/utils/audio.js");class Y extends _.FeatureExtractor{constructor(g){super(g);const b=this.config.sampling_rate,y=(0,R.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,R.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 O=await this._extract_fbank_features(g,this.config.max_length);if(M){const[S,w]=O.dims,x=O.data;for(let F=0;F0){const ae=new Float32Array(w*(S+F));ae.set(x),ae.fill(this.config.padding_value,x.length);const ie=S+F;O=new I.Tensor(O.type,ae,[ie,w]),v&&(K=new I.Tensor("int64",new BigInt64Array(ie),[1,ie]),K.data.fill(1n,0,S))}}const[te,ne]=O.dims,W=this.config.stride;if(te%W!==0)throw new Error(`The number of frames (${te}) must be a multiple of the stride (${W}).`);const X=O.view(1,Math.floor(te/W),ne*W),A={input_features:X};if(v){const S=X.dims[1],w=new BigInt64Array(S);if(K){const x=K.data;for(let F=1,ae=0;F{r.r($),r.d($,{SegformerFeatureExtractor:()=>R,SegformerImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_semantic_segmentation(...N){return(0,_.post_process_semantic_segmentation)(...N)}}class R extends I{}},"./src/models/siglip/image_processing_siglip.js":(Ee,$,r)=>{r.r($),r.d($,{SiglipImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(Ee,$,r)=>{r.r($),r.d($,{SpeechT5FeatureExtractor:()=>I});var _=r("./src/base/feature_extraction_utils.js");class I extends _.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(Ee,$,r)=>{r.r($),r.d($,{SpeechT5Processor:()=>Y});var _=r("./src/base/processing_utils.js"),I=r("./src/tokenizers.js"),R=r("./src/models/auto/feature_extraction_auto.js");class Y extends _.Processor{async _call(g){return await this.feature_extractor(g)}}fe(Y,"tokenizer_class",I.AutoTokenizer),fe(Y,"feature_extractor_class",R.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(Ee,$,r)=>{r.r($),r.d($,{Swin2SRImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{pad_image(Y,N,g,b={}){const[y,M,v]=N;return super.pad_image(Y,N,{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":(Ee,$,r)=>{r.r($),r.d($,{ViTFeatureExtractor:()=>R,ViTImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{}class R extends I{}},"./src/models/vitmatte/image_processing_vitmatte.js":(Ee,$,r)=>{r.r($),r.d($,{VitMatteImageProcessor:()=>R});var _=r("./src/base/image_processors_utils.js"),I=r("./src/utils/tensor.js");class R extends _.ImageProcessor{async _call(N,g){Array.isArray(N)||(N=[N]),Array.isArray(g)||(g=[g]);const b=await Promise.all(N.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,O)=>(0,I.cat)([v.pixel_values,y[O].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":(Ee,$,r)=>{r.r($),r.d($,{VitPoseImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_pose_estimation(Y,N,{threshold:g=null}={}){const b=Y.tolist(),[y,M,v,O]=Y.dims,K=[];for(let te=0;te{r.r($),r.d($,{Wav2Vec2FeatureExtractor:()=>R});var _=r("./src/base/feature_extraction_utils.js"),I=r("./src/utils/tensor.js");class R extends _.FeatureExtractor{_zero_mean_unit_var_norm(N){const b=N.reduce((M,v)=>M+v,0)/N.length,y=N.reduce((M,v)=>M+(v-b)**2,0)/N.length;return N.map(M=>(M-b)/Math.sqrt(y+1e-7))}async _call(N){(0,_.validate_audio_inputs)(N,"Wav2Vec2FeatureExtractor"),N instanceof Float64Array&&(N=new Float32Array(N));let g=N;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":(Ee,$,r)=>{r.r($),r.d($,{Wav2Vec2ProcessorWithLM:()=>R});var _=r("./src/base/processing_utils.js"),I=r("./src/models/auto/feature_extraction_auto.js");class R extends _.Processor{async _call(N){return await this.feature_extractor(N)}}fe(R,"feature_extractor_class",I.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(Ee,$,r)=>{r.r($),r.d($,{WeSpeakerFeatureExtractor:()=>R});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var I=r("./src/utils/audio.js");class R extends _.FeatureExtractor{constructor(N){super(N);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)(N,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(N){(0,_.validate_audio_inputs)(N,"WeSpeakerFeatureExtractor");const g=(await this._extract_fbank_features(N)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const b=g.mean(1).data,y=g.data,[M,v,O]=g.dims;for(let K=0;K{r.r($),r.d($,{WHISPER_LANGUAGE_MAPPING:()=>I,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>R,whisper_language_to_code:()=>Y});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(_),R=new Map([..._.map(([N,g])=>[g,N]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Y(N){N=N.toLowerCase();let g=R.get(N);if(g===void 0)if(I.has(N))g=N;else{const y=N.length===2?I.keys():I.values();throw new Error(`Language "${N}" is not supported. Must be one of: ${JSON.stringify(y)}`)}return g}},"./src/models/whisper/feature_extraction_whisper.js":(Ee,$,r)=>{r.r($),r.d($,{WhisperFeatureExtractor:()=>Y});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var I=r("./src/utils/audio.js"),R=r("./src/utils/maths.js");class Y 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,R.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":(Ee,$,r)=>{r.r($),r.d($,{WhisperGenerationConfig:()=>I});var _=r("./src/generation/configuration_utils.js");class I extends _.GenerationConfig{constructor(){super(...arguments);fe(this,"return_timestamps",null);fe(this,"return_token_timestamps",null);fe(this,"num_frames",null);fe(this,"alignment_heads",null);fe(this,"task",null);fe(this,"language",null);fe(this,"no_timestamps_token_id",null);fe(this,"prompt_ids",null);fe(this,"is_multilingual",null);fe(this,"lang_to_id",null);fe(this,"task_to_id",null);fe(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(Ee,$,r)=>{r.r($),r.d($,{WhisperProcessor:()=>Y});var _=r("./src/models/auto/feature_extraction_auto.js"),I=r("./src/tokenizers.js"),R=r("./src/base/processing_utils.js");class Y extends R.Processor{async _call(g){return await this.feature_extractor(g)}}fe(Y,"tokenizer_class",I.AutoTokenizer),fe(Y,"feature_extractor_class",_.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(Ee,$,r)=>{r.r($),r.d($,{YolosFeatureExtractor:()=>R,YolosImageProcessor:()=>I});var _=r("./src/base/image_processors_utils.js");class I extends _.ImageProcessor{post_process_object_detection(...N){return(0,_.post_process_object_detection)(...N)}}class R extends I{}},"./src/ops/registry.js":(Ee,$,r)=>{r.r($),r.d($,{TensorOpRegistry:()=>Y});var _=r("./src/backends/onnx.js"),I=r("./src/utils/tensor.js");const R=async(N,g,b)=>{const y=await(0,_.createInferenceSession)(new Uint8Array(N),g);return async M=>{const v=(0,_.isONNXProxy)(),O=Object.fromEntries(Object.entries(M).map(([te,ne])=>[te,(v?ne.clone():ne).ort_tensor])),K=await y.run(O);return Array.isArray(b)?b.map(te=>new I.Tensor(K[te])):new I.Tensor(K[b])}};class Y{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=R([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,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,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=R([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=R([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=R([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=R([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=R([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=R([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=R([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}}fe(Y,"session_options",{})},"./src/pipelines.js":(Ee,$,r)=>{r.r($),r.d($,{AudioClassificationPipeline:()=>we,AutomaticSpeechRecognitionPipeline:()=>xe,DepthEstimationPipeline:()=>ke,DocumentQuestionAnsweringPipeline:()=>ye,FeatureExtractionPipeline:()=>ie,FillMaskPipeline:()=>X,ImageClassificationPipeline:()=>Se,ImageFeatureExtractionPipeline:()=>ve,ImageSegmentationPipeline:()=>Ie,ImageToImagePipeline:()=>de,ImageToTextPipeline:()=>ce,ObjectDetectionPipeline:()=>tt,Pipeline:()=>te,QuestionAnsweringPipeline:()=>U,SummarizationPipeline:()=>S,Text2TextGenerationPipeline:()=>A,TextClassificationPipeline:()=>ne,TextGenerationPipeline:()=>F,TextToAudioPipeline:()=>J,TokenClassificationPipeline:()=>W,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>re,ZeroShotClassificationPipeline:()=>ae,ZeroShotImageClassificationPipeline:()=>Ce,ZeroShotObjectDetectionPipeline:()=>Ge,pipeline:()=>se});var _=r("./src/tokenizers.js"),I=r("./src/models.js"),R=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var Y=r("./src/utils/generic.js"),N=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(je){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(le=>M.RawImage.read(le)))}async function O(je,le){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(Te=>typeof Te=="string"||Te instanceof URL?(0,b.read_audio)(Te,le):Te instanceof Float64Array?new Float32Array(Te):Te))}function K(je,le){le&&(je=je.map(Re=>Re|0));const[Te,Ue,Ve,Ne]=je;return{xmin:Te,ymin:Ue,xmax:Ve,ymax:Ne}}class te extends Y.Callable{constructor({task:le,model:Te,tokenizer:Ue=null,processor:Ve=null}){super(),this.task=le,this.model=Te,this.tokenizer=Ue,this.processor=Ve}async dispose(){await this.model.dispose()}}class ne extends te{constructor(le){super(le)}async _call(le,{top_k:Te=1}={}){const Ue=this.tokenizer(le,{padding:!0,truncation:!0}),Ve=await this.model(Ue),Ne=this.model.config.problem_type==="multi_label_classification"?dt=>dt.sigmoid():dt=>new y.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),Re=this.model.config.id2label,st=[];for(const dt of Ve.logits){const ct=Ne(dt),lt=await(0,y.topk)(ct,Te),ht=lt[0].tolist(),oe=lt[1].tolist().map((H,me)=>({label:Re?Re[H]:`LABEL_${H}`,score:ht[me]}));Te===1?st.push(...oe):st.push(oe)}return Array.isArray(le)||Te===1?st:st[0]}}class W extends te{constructor(le){super(le)}async _call(le,{ignore_labels:Te=["O"]}={}){const Ue=Array.isArray(le),Ve=this.tokenizer(Ue?le:[le],{padding:!0,truncation:!0}),Re=(await this.model(Ve)).logits,st=this.model.config.id2label,dt=[];for(let ct=0;ctut==this.tokenizer.sep_token_id);dt[ht].map((ut,mt)=>ut==1&&(mt===0||mt>oe&&ct.findIndex(vt=>vt==L[mt])===-1));const H=Ne[ht].tolist(),me=Re[ht].tolist();for(let ut=1;utmt==L[ut])!==-1)&&(H[ut]=-1/0,me[ut]=-1/0);const Ae=(0,g.softmax)(H).map((ut,mt)=>[ut,mt]),We=(0,g.softmax)(me).map((ut,mt)=>[ut,mt]);Ae[0][0]=0,We[0][0]=0;const Je=(0,N.product)(Ae,We).filter(ut=>ut[0][1]<=ut[1][1]).map(ut=>[ut[0][1],ut[1][1],ut[0][0]*ut[1][0]]).sort((ut,mt)=>mt[2]-ut[2]);for(let ut=0;utH==this.tokenizer.mask_token_id);if(ct===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const lt=Ve[st][ct],ht=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(lt.data),lt.dims),Te),L=ht[0].tolist(),oe=ht[1].tolist();Ne.push(oe.map((H,me)=>{const Ae=dt.slice();return Ae[ct]=H,{score:L[me],token:Number(H),token_str:this.tokenizer.decode([H]),sequence:this.tokenizer.decode(Ae,{skip_special_tokens:!0})}}))}return Array.isArray(le)?Ne:Ne[0]}}class A extends te{constructor(Te){super(Te);fe(this,"_key","generated_text")}async _call(Te,Ue={}){Array.isArray(Te)||(Te=[Te]),this.model.config.prefix&&(Te=Te.map(ct=>this.model.config.prefix+ct));const Ve=this.model.config.task_specific_params;Ve&&Ve[this.task]&&Ve[this.task].prefix&&(Te=Te.map(ct=>Ve[this.task].prefix+ct));const Ne=this.tokenizer,Re={padding:!0,truncation:!0};let st;this instanceof w&&"_build_translation_inputs"in Ne?st=Ne._build_translation_inputs(Te,Re,Ue):st=Ne(Te,Re);const dt=await this.model.generate({...st,...Ue});return Ne.batch_decode(dt,{skip_special_tokens:!0}).map(ct=>({[this._key]:ct}))}}class S extends A{constructor(Te){super(Te);fe(this,"_key","summary_text")}}class w extends A{constructor(Te){super(Te);fe(this,"_key","translation_text")}}function x(je){return Array.isArray(je)&&je.every(le=>"role"in le&&"content"in le)}class F extends te{constructor(le){super(le)}async _call(le,Te={}){let Ue=!1,Ve=!1,Ne;if(typeof le=="string")Ne=le=[le];else if(Array.isArray(le)&&le.every(oe=>typeof oe=="string"))Ue=!0,Ne=le;else{if(x(le))le=[le];else if(Array.isArray(le)&&le.every(x))Ue=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Ve=!0,Ne=le.map(oe=>this.tokenizer.apply_chat_template(oe,{tokenize:!1,add_generation_prompt:!0}))}const Re=Te.add_special_tokens??!1,st=Ve?!1:Te.return_full_text??!0;this.tokenizer.padding_side="left";const dt=this.tokenizer(Ne,{add_special_tokens:Re,padding:!0,truncation:!0}),ct=await this.model.generate({...dt,...Te}),lt=this.tokenizer.batch_decode(ct,{skip_special_tokens:!0});let ht;!st&&dt.input_ids.dims.at(-1)>0&&(ht=this.tokenizer.batch_decode(dt.input_ids,{skip_special_tokens:!0}).map(oe=>oe.length));const L=Array.from({length:le.length},oe=>[]);for(let oe=0;oe[Te.toLowerCase(),Ue])),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(le,Te,{hypothesis_template:Ue="This example is {}.",multi_label:Ve=!1}={}){const Ne=Array.isArray(le);Ne||(le=[le]),Array.isArray(Te)||(Te=[Te]);const Re=Te.map(ct=>Ue.replace("{}",ct)),st=Ve||Te.length===1,dt=[];for(const ct of le){const lt=[];for(const oe of Re){const H=this.tokenizer(ct,{text_pair:oe,padding:!0,truncation:!0}),me=await this.model(H);st?lt.push([me.logits.data[this.contradiction_id],me.logits.data[this.entailment_id]]):lt.push(me.logits.data[this.entailment_id])}const L=(st?lt.map(oe=>(0,g.softmax)(oe)[1]):(0,g.softmax)(lt)).map((oe,H)=>[oe,H]).sort((oe,H)=>H[0]-oe[0]);dt.push({sequence:ct,labels:L.map(oe=>Te[oe[1]]),scores:L.map(oe=>oe[0])})}return Ne?dt:dt[0]}}class ie extends te{constructor(le){super(le)}async _call(le,{pooling:Te="none",normalize:Ue=!1,quantize:Ve=!1,precision:Ne="binary"}={}){const Re=this.tokenizer(le,{padding:!0,truncation:!0}),st=await this.model(Re);let dt=st.last_hidden_state??st.logits??st.token_embeddings;if(Te!=="none")if(Te==="mean")dt=(0,y.mean_pooling)(dt,Re.attention_mask);else if(Te==="cls")dt=dt.slice(null,0);else throw Error(`Pooling method '${Te}' not supported.`);return Ue&&(dt=dt.normalize(2,-1)),Ve&&(dt=(0,y.quantize_embeddings)(dt,Ne)),dt}}class ve extends te{constructor(le){super(le)}async _call(le,{pool:Te=null}={}){const Ue=await v(le),{pixel_values:Ve}=await this.processor(Ue),Ne=await this.model({pixel_values:Ve});let Re;if(Te){if(!("pooler_output"in Ne))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Re=Ne.pooler_output}else Re=Ne.last_hidden_state??Ne.logits??Ne.image_embeds;return Re}}class we extends te{constructor(le){super(le)}async _call(le,{top_k:Te=5}={}){const Ue=this.processor.feature_extractor.config.sampling_rate,Ve=await O(le,Ue),Ne=this.model.config.id2label,Re=[];for(const st of Ve){const dt=await this.processor(st),lt=(await this.model(dt)).logits[0],ht=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(lt.data),lt.dims),Te),L=ht[0].tolist(),H=ht[1].tolist().map((me,Ae)=>({label:Ne?Ne[me]:`LABEL_${me}`,score:L[Ae]}));Re.push(H)}return Array.isArray(le)?Re:Re[0]}}class re extends te{constructor(le){super(le)}async _call(le,Te,{hypothesis_template:Ue="This is a sound of {}."}={}){const Ve=!Array.isArray(le);Ve&&(le=[le]);const Ne=Te.map(lt=>Ue.replace("{}",lt)),Re=this.tokenizer(Ne,{padding:!0,truncation:!0}),st=this.processor.feature_extractor.config.sampling_rate,dt=await O(le,st),ct=[];for(const lt of dt){const ht=await this.processor(lt),L=await this.model({...Re,...ht}),oe=(0,g.softmax)(L.logits_per_audio.data);ct.push([...oe].map((H,me)=>({score:H,label:Te[me]})))}return Ve?ct[0]:ct}}class xe extends te{constructor(le){super(le)}async _call(le,Te={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(le,Te);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(le,Te);case"moonshine":return this._call_moonshine(le,Te);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(le,Te){Te.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Te.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ue=!Array.isArray(le);Ue&&(le=[le]);const Ve=this.processor.feature_extractor.config.sampling_rate,Ne=await O(le,Ve),Re=[];for(const st of Ne){const dt=await this.processor(st),lt=(await this.model(dt)).logits[0],ht=[];for(const oe of lt)ht.push((0,g.max)(oe.data)[1]);const L=this.tokenizer.decode(ht);Re.push({text:L})}return Ue?Re[0]:Re}async _call_whisper(le,Te){const Ue=Te.return_timestamps??!1,Ve=Te.chunk_length_s??0,Ne=Te.force_full_sequences??!1;let Re=Te.stride_length_s??null;const st={...Te};Ue==="word"&&(st.return_token_timestamps=!0,st.return_timestamps=!1);const dt=!Array.isArray(le);dt&&(le=[le]);const ct=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,lt=this.processor.feature_extractor.config.hop_length,ht=this.processor.feature_extractor.config.sampling_rate,L=await O(le,ht),oe=[];for(const H of L){let me=[];if(Ve>0){if(Re===null)Re=Ve/6;else if(Ve<=Re)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Je=ht*Ve,ut=ht*Re,mt=Je-2*ut;let vt=0;for(;;){const kt=vt+Je,At=H.subarray(vt,kt),is=await this.processor(At),ws=vt===0,ks=kt>=H.length;if(me.push({stride:[At.length,ws?0:ut,ks?0:ut],input_features:is.input_features,is_last:ks}),ks)break;vt+=mt}}else me=[{stride:[H.length,0,0],input_features:(await this.processor(H)).input_features,is_last:!0}];for(const Je of me){st.num_frames=Math.floor(Je.stride[0]/lt);const ut=await this.model.generate({inputs:Je.input_features,...st});Ue==="word"?(Je.tokens=ut.sequences.tolist()[0],Je.token_timestamps=ut.token_timestamps.tolist()[0].map(mt=>(0,g.round)(mt,2))):Je.tokens=ut[0].tolist(),Je.stride=Je.stride.map(mt=>mt/ht)}const[Ae,We]=this.tokenizer._decode_asr(me,{time_precision:ct,return_timestamps:Ue,force_full_sequences:Ne});oe.push({text:Ae,...We})}return dt?oe[0]:oe}async _call_moonshine(le,Te){const Ue=!Array.isArray(le);Ue&&(le=[le]);const Ve=this.processor.feature_extractor.config.sampling_rate,Ne=await O(le,Ve),Re=[];for(const st of Ne){const dt=await this.processor(st),ct=Math.floor(st.length/Ve)*6,lt=await this.model.generate({max_new_tokens:ct,...Te,...dt}),ht=this.processor.batch_decode(lt,{skip_special_tokens:!0})[0];Re.push({text:ht})}return Ue?Re[0]:Re}}class ce extends te{constructor(le){super(le)}async _call(le,Te={}){const Ue=Array.isArray(le),Ve=await v(le),{pixel_values:Ne}=await this.processor(Ve),Re=[];for(const st of Ne){st.dims=[1,...st.dims];const dt=await this.model.generate({inputs:st,...Te}),ct=this.tokenizer.batch_decode(dt,{skip_special_tokens:!0}).map(lt=>({generated_text:lt.trim()}));Re.push(ct)}return Ue?Re:Re[0]}}class Se extends te{constructor(le){super(le)}async _call(le,{top_k:Te=5}={}){const Ue=await v(le),{pixel_values:Ve}=await this.processor(Ue),Ne=await this.model({pixel_values:Ve}),Re=this.model.config.id2label,st=[];for(const dt of Ne.logits){const ct=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),Te),lt=ct[0].tolist(),L=ct[1].tolist().map((oe,H)=>({label:Re?Re[oe]:`LABEL_${oe}`,score:lt[H]}));st.push(L)}return Array.isArray(le)?st:st[0]}}class Ie extends te{constructor(le){super(le),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(le,{threshold:Te=.5,mask_threshold:Ue=.5,overlap_mask_area_threshold:Ve=.8,label_ids_to_fuse:Ne=null,target_sizes:Re=null,subtask:st=null}={}){if(Array.isArray(le)&&le.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ct=await v(le),lt=ct.map(We=>[We.height,We.width]),{pixel_values:ht,pixel_mask:L}=await this.processor(ct),oe=await this.model({pixel_values:ht,pixel_mask:L});let H=null;if(st!==null)H=this.subtasks_mapping[st];else for(let[We,Je]of Object.entries(this.subtasks_mapping))if(Je in this.processor.image_processor){H=this.processor.image_processor[Je].bind(this.processor.image_processor),st=We;break}const me=this.model.config.id2label,Ae=[];if(st==="panoptic"||st==="instance"){const We=H(oe,Te,Ue,Ve,Ne,Re??lt)[0],Je=We.segmentation;for(const ut of We.segments_info){const mt=new Uint8ClampedArray(Je.data.length);for(let kt=0;ktUe.replace("{}",L)),st=this.tokenizer(Re,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:dt}=await this.processor(Ne),ct=await this.model({...st,pixel_values:dt}),lt=this.model.config.model_type==="siglip"?L=>L.sigmoid().data:L=>(0,g.softmax)(L.data),ht=[];for(const L of ct.logits_per_image){const H=[...lt(L)].map((me,Ae)=>({score:me,label:Te[Ae]}));H.sort((me,Ae)=>Ae.score-me.score),ht.push(H)}return Ve?ht:ht[0]}}class tt extends te{constructor(le){super(le)}async _call(le,{threshold:Te=.9,percentage:Ue=!1}={}){const Ve=Array.isArray(le);if(Ve&&le.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ne=await v(le),Re=Ue?null:Ne.map(oe=>[oe.height,oe.width]),{pixel_values:st,pixel_mask:dt}=await this.processor(Ne),ct=await this.model({pixel_values:st,pixel_mask:dt}),lt=this.processor.image_processor.post_process_object_detection(ct,Te,Re),ht=this.model.config.id2label,L=lt.map(oe=>oe.boxes.map((H,me)=>({score:oe.scores[me],label:ht[oe.classes[me]],box:K(H,!Ue)})));return Ve?L:L[0]}}class Ge extends te{constructor(le){super(le)}async _call(le,Te,{threshold:Ue=.1,top_k:Ve=null,percentage:Ne=!1}={}){const Re=Array.isArray(le),st=await v(le),dt=this.tokenizer(Te,{padding:!0,truncation:!0}),ct=await this.processor(st),lt=[];for(let ht=0;ht({score:We.scores[ut],label:We.labels[ut],box:K(Je,!Ne)}))}else{const We=this.processor.image_processor.post_process_object_detection(me,Ue,oe,!0)[0];Ae=We.boxes.map((Je,ut)=>({score:We.scores[ut],label:Te[We.classes[ut]],box:K(Je,!Ne)}))}Ae.sort((We,Je)=>Je.score-We.score),Ve!==null&&(Ae=Ae.slice(0,Ve)),lt.push(Ae)}return Re?lt:lt[0]}}class ye extends te{constructor(le){super(le)}async _call(le,Te,Ue={}){const Ve=(await v(le))[0],{pixel_values:Ne}=await this.processor(Ve),Re=`${Te}`,st=this.tokenizer(Re,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,dt=await this.model.generate({inputs:Ne,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:st,...Ue}),lt=this.tokenizer.batch_decode(dt)[0].match(/(.*?)<\/s_answer>/);let ht=null;return lt&<.length>=2&&(ht=lt[1].trim()),[{answer:ht}]}}class J extends te{constructor(Te){super(Te);fe(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Te.vocoder??null}async _call(Te,{speaker_embeddings:Ue=null}={}){return this.processor?this._call_text_to_spectrogram(Te,{speaker_embeddings:Ue}):this._call_text_to_waveform(Te)}async _call_text_to_waveform(Te){const Ue=this.tokenizer(Te,{padding:!0,truncation:!0}),{waveform:Ve}=await this.model(Ue),Ne=this.model.config.sampling_rate;return new b.RawAudio(Ve.data,Ne)}async _call_text_to_spectrogram(Te,{speaker_embeddings:Ue}){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 Ue=="string"||Ue instanceof URL)&&(Ue=new Float32Array(await(await fetch(Ue)).arrayBuffer())),Ue instanceof Float32Array)Ue=new y.Tensor("float32",Ue,[1,Ue.length]);else if(!(Ue instanceof y.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Ve}=this.tokenizer(Te,{padding:!0,truncation:!0}),{waveform:Ne}=await this.model.generate_speech(Ve,Ue,{vocoder:this.vocoder}),Re=this.processor.feature_extractor.config.sampling_rate;return new b.RawAudio(Ne.data,Re)}}class de extends te{constructor(le){super(le)}async _call(le){const Te=await v(le),Ue=await this.processor(Te),Ve=await this.model(Ue),Ne=[];for(const Re of Ve.reconstruction){const st=Re.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ne.push(M.RawImage.fromTensor(st))}return Ne.length>1?Ne:Ne[0]}}class ke extends te{constructor(le){super(le)}async _call(le){const Te=await v(le),Ue=await this.processor(Te),{predicted_depth:Ve}=await this.model(Ue),Ne=[];for(let Re=0;Re1?Ne:Ne[0]}}const Be=Object.freeze({"text-classification":{tokenizer:_.AutoTokenizer,pipeline:ne,model:I.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:_.AutoTokenizer,pipeline:W,model:I.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:_.AutoTokenizer,pipeline:U,model:I.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:_.AutoTokenizer,pipeline:X,model:I.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:_.AutoTokenizer,pipeline:S,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:A,model:I.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:_.AutoTokenizer,pipeline:F,model:I.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:_.AutoTokenizer,pipeline:ae,model:I.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:we,model:I.AutoModelForAudioClassification,processor:R.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:_.AutoTokenizer,pipeline:re,model:I.AutoModel,processor:R.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:_.AutoTokenizer,pipeline:xe,model:[I.AutoModelForSpeechSeq2Seq,I.AutoModelForCTC],processor:R.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:_.AutoTokenizer,pipeline:J,model:[I.AutoModelForTextToWaveform,I.AutoModelForTextToSpectrogram],processor:[R.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:_.AutoTokenizer,pipeline:ce,model:I.AutoModelForVision2Seq,processor:R.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Se,model:I.AutoModelForImageClassification,processor:R.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Ie,model:[I.AutoModelForImageSegmentation,I.AutoModelForSemanticSegmentation,I.AutoModelForUniversalSegmentation],processor:R.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:_.AutoTokenizer,pipeline:Ce,model:I.AutoModel,processor:R.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:tt,model:I.AutoModelForObjectDetection,processor:R.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:_.AutoTokenizer,pipeline:Ge,model:I.AutoModelForZeroShotObjectDetection,processor:R.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:_.AutoTokenizer,pipeline:ye,model:I.AutoModelForDocumentQuestionAnswering,processor:R.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:de,model:I.AutoModelForImageToImage,processor:R.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ke,model:I.AutoModelForDepthEstimation,processor:R.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:_.AutoTokenizer,pipeline:ie,model:I.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:R.AutoProcessor,pipeline:ve,model:[I.AutoModelForImageFeatureExtraction,I.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ze=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function se(je,le=null,{progress_callback:Te=null,config:Ue=null,cache_dir:Ve=null,local_files_only:Ne=!1,revision:Re="main",device:st=null,dtype:dt=null,model_file_name:ct=null,session_options:lt={}}={}){je=Ze[je]??je;const ht=Be[je.split("_",1)[0]];if(!ht)throw Error(`Unsupported pipeline: ${je}. Must be one of [${Object.keys(Be)}]`);le||(le=ht.default.model,console.log(`No model specified. Using default model: "${le}".`));const L={progress_callback:Te,config:Ue,cache_dir:Ve,local_files_only:Ne,revision:Re,device:st,dtype:dt,model_file_name:ct,session_options:lt},oe=new Map([["tokenizer",ht.tokenizer],["model",ht.model],["processor",ht.processor]]),H=await Ke(oe,le,L);H.task=je,(0,N.dispatchCallback)(Te,{status:"ready",task:je,model:le});const me=ht.pipeline;return new me(H)}async function Ke(je,le,Te){const Ue=Object.create(null),Ve=[];for(const[Ne,Re]of je.entries()){if(!Re)continue;let st;Array.isArray(Re)?st=new Promise(async(dt,ct)=>{var ht,L;let lt;for(const oe of Re){if(oe===null){dt(null);return}try{dt(await oe.from_pretrained(le,Te));return}catch(H){if((ht=H.message)!=null&&ht.includes("Unsupported model type"))lt=H;else if((L=H.message)!=null&&L.includes("Could not locate file"))lt=H;else{ct(H);return}}}ct(lt)}):st=Re.from_pretrained(le,Te),Ue[Ne]=st,Ve.push(st)}await Promise.all(Ve);for(const[Ne,Re]of Object.entries(Ue))Ue[Ne]=await Re;return Ue}},"./src/tokenizers.js":(Ee,$,r)=>{r.r($),r.d($,{AlbertTokenizer:()=>Sr,AutoTokenizer:()=>as,BartTokenizer:()=>Ir,BertTokenizer:()=>Xr,BlenderbotSmallTokenizer:()=>Ln,BlenderbotTokenizer:()=>Dn,BloomTokenizer:()=>Tr,CLIPTokenizer:()=>gn,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>_n,CodeLlamaTokenizer:()=>jr,CohereTokenizer:()=>Mn,ConvBertTokenizer:()=>Br,DebertaTokenizer:()=>cr,DebertaV2Tokenizer:()=>Jr,DistilBertTokenizer:()=>or,ElectraTokenizer:()=>Dt,EsmTokenizer:()=>Ur,FalconTokenizer:()=>In,GPT2Tokenizer:()=>Nr,GPTNeoXTokenizer:()=>On,GemmaTokenizer:()=>ri,Grok1Tokenizer:()=>Vr,HerbertTokenizer:()=>Ar,LlamaTokenizer:()=>mn,M2M100Tokenizer:()=>fn,MBart50Tokenizer:()=>ar,MBartTokenizer:()=>Ms,MPNetTokenizer:()=>An,MarianTokenizer:()=>zt,MgpstrTokenizer:()=>Rn,MobileBertTokenizer:()=>$r,NllbTokenizer:()=>lr,NougatTokenizer:()=>Wr,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>Fn,RoFormerTokenizer:()=>Rr,RobertaTokenizer:()=>Is,SiglipTokenizer:()=>wn,SpeechT5Tokenizer:()=>zn,SqueezeBertTokenizer:()=>Yr,T5Tokenizer:()=>Vs,TokenizerModel:()=>ve,VitsTokenizer:()=>Bn,Wav2Vec2CTCTokenizer:()=>yn,WhisperTokenizer:()=>Zr,XLMRobertaTokenizer:()=>si,XLMTokenizer:()=>Tt,is_chinese_char:()=>X});var _=r("./src/utils/generic.js"),I=r("./src/utils/core.js"),R=r("./src/utils/hub.js"),Y=r("./src/utils/maths.js"),N=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");async function M(Pe,C){const q=await Promise.all([(0,R.getModelJSON)(Pe,"tokenizer.json",!0,C),(0,R.getModelJSON)(Pe,"tokenizer_config.json",!0,C)]);return C.legacy!==null&&(q[1].legacy=C.legacy),q}function v(Pe,C){const q=[];let ue=0;for(const be of Pe.matchAll(C)){const $e=be[0];ue0&&q.push($e),ue=be.index+$e.length}return ue=19968&&Pe<=40959||Pe>=13312&&Pe<=19903||Pe>=131072&&Pe<=173791||Pe>=173824&&Pe<=177983||Pe>=177984&&Pe<=178207||Pe>=178208&&Pe<=183983||Pe>=63744&&Pe<=64255||Pe>=194560&&Pe<=195103}function A(Pe,C,q){const ue=[];let be=0;for(;bethis.tokens_to_ids.get(q)??this.unk_token_id)}convert_ids_to_tokens(C){return C.map(q=>this.vocab[q]??this.unk_token)}}class we extends ve{constructor(C){super(C),this.tokens_to_ids=K(C.vocab),this.unk_token_id=this.tokens_to_ids.get(C.unk_token),this.unk_token=C.unk_token,this.max_input_chars_per_word=C.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[q,ue]of this.tokens_to_ids)this.vocab[ue]=q}encode(C){const q=[];for(const ue of C){const be=[...ue];if(be.length>this.max_input_chars_per_word){q.push(this.unk_token);continue}let $e=!1,Qe=0;const pt=[];for(;Qe0&&(xt=this.config.continuing_subword_prefix+xt),this.tokens_to_ids.has(xt)){ft=xt;break}--gt}if(ft===null){$e=!0;break}pt.push(ft),Qe=gt}$e?q.push(this.unk_token):q.push(...pt)}return q}}class re extends ve{constructor(C,q){super(C);const ue=C.vocab.length;this.vocab=new Array(ue),this.scores=new Array(ue);for(let be=0;be[be,$e])),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,Y.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(C){const q=C.chars,ue=1;let be=0;for(;be{const Pe=[...Array.from({length:94},(be,$e)=>$e+33),...Array.from({length:12},(be,$e)=>$e+161),...Array.from({length:82},(be,$e)=>$e+174)],C=Pe.slice();let q=0;for(let be=0;be<256;++be)Pe.includes(be)||(Pe.push(be),C.push(256+q),q+=1);const ue=C.map(be=>String.fromCharCode(be));return Object.fromEntries(Pe.map((be,$e)=>[be,ue[$e]]))})(),ce=(0,I.reverseDictionary)(xe);class Se extends ve{constructor(C){super(C),this.tokens_to_ids=K(C.vocab),this.unk_token_id=this.tokens_to_ids.get(C.unk_token),this.unk_token=C.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ue,be]of this.tokens_to_ids)this.vocab[be]=ue;const q=Array.isArray(C.merges[0]);this.merges=q?C.merges:C.merges.map(ue=>ue.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ue,be)=>[JSON.stringify(ue),be])),this.end_of_word_suffix=C.end_of_word_suffix,this.continuing_subword_suffix=C.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(C){if(C.length===0)return[];const q=this.cache.get(C);if(q!==void 0)return q;const ue=Array.from(C);this.end_of_word_suffix&&(ue[ue.length-1]+=this.end_of_word_suffix);let be=[];if(ue.length>1){const $e=new g.PriorityQueue((gt,ft)=>gt.score`<0x${pt.toString(16).toUpperCase().padStart(2,"0")}>`);Qe.every(pt=>this.tokens_to_ids.has(pt))?q.push(...Qe):q.push(this.unk_token)}else q.push(this.unk_token)}return q}}class Ie extends ve{constructor(C,q){super(C),this.tokens_to_ids=K(q.target_lang?C.vocab[q.target_lang]:C.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[ue,be]of this.tokens_to_ids)this.vocab[be]=ue}encode(C){return C}}class Ce extends _.Callable{constructor(C){super(),this.config=C}static fromConfig(C){if(C===null)return null;switch(C.type){case"BertNormalizer":return new Ke(C);case"Precompiled":return new ws(C);case"Sequence":return new se(C);case"Replace":return new tt(C);case"NFC":return new Ge(C);case"NFKC":return new ye(C);case"NFKD":return new J(C);case"Strip":return new de(C);case"StripAccents":return new ke(C);case"Lowercase":return new Be(C);case"Prepend":return new Ze(C);default:throw new Error(`Unknown Normalizer type: ${C.type}`)}}normalize(C){throw Error("normalize should be implemented in subclass.")}_call(C){return this.normalize(C)}}class tt extends Ce{normalize(C){const q=O(this.config.pattern);return q===null?C:C.replaceAll(q,this.config.content)}}class Ge extends Ce{normalize(C){return C=C.normalize("NFC"),C}}class ye extends Ce{normalize(C){return C=C.normalize("NFKC"),C}}class J extends Ce{normalize(C){return C=C.normalize("NFKD"),C}}class de extends Ce{normalize(C){return this.config.strip_left&&this.config.strip_right?C=C.trim():(this.config.strip_left&&(C=C.trimStart()),this.config.strip_right&&(C=C.trimEnd())),C}}class ke extends Ce{normalize(C){return C=W(C),C}}class Be extends Ce{normalize(C){return C=C.toLowerCase(),C}}class Ze extends Ce{normalize(C){return C=this.config.prepend+C,C}}class se extends Ce{constructor(C){super(C),this.normalizers=C.normalizers.map(q=>Ce.fromConfig(q))}normalize(C){return this.normalizers.reduce((q,ue)=>ue.normalize(q),C)}}class Ke extends Ce{_tokenize_chinese_chars(C){const q=[];for(let ue=0;uethis.pre_tokenize_text(ue,q)):this.pre_tokenize_text(C,q)).flat()}_call(C,q){return this.pre_tokenize(C,q)}}class le extends je{constructor(C){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(C,q){return C.trim().match(this.pattern)||[]}}class Te extends je{constructor(C){super(),this.config=C,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=xe,this.text_encoder=new TextEncoder}pre_tokenize_text(C,q){return this.add_prefix_space&&!C.startsWith(" ")&&(C=" "+C),(this.use_regex?C.match(this.pattern)||[]:[C]).map(be=>Array.from(this.text_encoder.encode(be),$e=>this.byte_encoder[$e]).join(""))}}class Ue extends je{constructor(C){super(),this.config=C,this.pattern=O(this.config.pattern,this.config.invert)}pre_tokenize_text(C,q){var ue;return this.pattern===null?[]:this.config.invert?C.match(this.pattern)||[]:((ue=this.config.behavior)==null?void 0:ue.toLowerCase())==="removed"?C.split(this.pattern).filter(be=>be):v(C,this.pattern)}}class Ve extends je{constructor(C){super(),this.config=C,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(C,q){return C.match(this.pattern)||[]}}class Ne extends je{constructor(C){super(),this.config=C;const q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(q,"gu")}pre_tokenize_text(C,q){return C.match(this.pattern)||[]}}class Re extends _.Callable{constructor(C){super(),this.config=C}static fromConfig(C){if(C===null)return null;switch(C.type){case"TemplateProcessing":return new ct(C);case"ByteLevel":return new lt(C);case"RobertaProcessing":return new dt(C);case"BertProcessing":return new st(C);case"Sequence":return new ht(C);default:throw new Error(`Unknown PostProcessor type: ${C.type}`)}}post_process(C,...q){throw Error("post_process should be implemented in subclass.")}_call(C,...q){return this.post_process(C,...q)}}class st extends Re{constructor(C){super(C),this.cls=C.cls[0],this.sep=C.sep[0]}post_process(C,q=null,{add_special_tokens:ue=!0}={}){ue&&(C=(0,I.mergeArrays)([this.cls],C,[this.sep]));let be=new Array(C.length).fill(0);if(q!==null){const $e=ue&&this instanceof dt?[this.sep]:[],Qe=ue?[this.sep]:[];C=(0,I.mergeArrays)(C,$e,q,Qe),be=(0,I.mergeArrays)(be,new Array(q.length+$e.length+Qe.length).fill(1))}return{tokens:C,token_type_ids:be}}}class dt extends st{}class ct extends Re{constructor(C){super(C),this.single=C.single,this.pair=C.pair}post_process(C,q=null,{add_special_tokens:ue=!0}={}){const be=q===null?this.single:this.pair;let $e=[],Qe=[];for(const pt of be)"SpecialToken"in pt?ue&&($e.push(pt.SpecialToken.id),Qe.push(pt.SpecialToken.type_id)):"Sequence"in pt&&(pt.Sequence.id==="A"?($e=(0,I.mergeArrays)($e,C),Qe=(0,I.mergeArrays)(Qe,new Array(C.length).fill(pt.Sequence.type_id))):pt.Sequence.id==="B"&&($e=(0,I.mergeArrays)($e,q),Qe=(0,I.mergeArrays)(Qe,new Array(q.length).fill(pt.Sequence.type_id))));return{tokens:$e,token_type_ids:Qe}}}class lt extends Re{post_process(C,q=null){return q&&(C=(0,I.mergeArrays)(C,q)),{tokens:C}}}class ht extends Re{constructor(C){super(C),this.processors=C.processors.map(q=>Re.fromConfig(q))}post_process(C,q=null,ue={}){let be;for(const $e of this.processors)if($e instanceof lt)C=$e.post_process(C).tokens,q&&(q=$e.post_process(q).tokens);else{const Qe=$e.post_process(C,q,ue);C=Qe.tokens,be=Qe.token_type_ids}return{tokens:C,token_type_ids:be}}}class L extends _.Callable{constructor(C){super(),this.config=C,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=C.trim_offsets}static fromConfig(C){if(C===null)return null;switch(C.type){case"WordPiece":return new We(C);case"Metaspace":return new is(C);case"ByteLevel":return new Je(C);case"Replace":return new oe(C);case"ByteFallback":return new H(C);case"Fuse":return new me(C);case"Strip":return new Ae(C);case"Sequence":return new mt(C);case"CTC":return new ut(C);case"BPEDecoder":return new vt(C);default:throw new Error(`Unknown Decoder type: ${C.type}`)}}_call(C){return this.decode(C)}decode(C){return this.decode_chain(C).join("")}decode_chain(C){throw Error("`decode_chain` should be implemented in subclass.")}}class oe extends L{decode_chain(C){const q=O(this.config.pattern);return q===null?C:C.map(ue=>ue.replaceAll(q,this.config.content))}}class H extends L{constructor(C){super(C),this.text_decoder=new TextDecoder}decode_chain(C){const q=[];let ue=[];for(const be of C){let $e=null;if(be.length===6&&be.startsWith("<0x")&&be.endsWith(">")){const Qe=parseInt(be.slice(3,5),16);isNaN(Qe)||($e=Qe)}if($e!==null)ue.push($e);else{if(ue.length>0){const Qe=this.text_decoder.decode(Uint8Array.from(ue));q.push(Qe),ue=[]}q.push(be)}}if(ue.length>0){const be=this.text_decoder.decode(Uint8Array.from(ue));q.push(be),ue=[]}return q}}class me extends L{decode_chain(C){return[C.join("")]}}class Ae extends L{constructor(C){super(C),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(C){return C.map(q=>{let ue=0;for(let $e=0;$e(ue!==0&&(q.startsWith(this.config.prefix)?q=q.replace(this.config.prefix,""):q=" "+q),this.cleanup&&(q=ne(q)),q))}}class Je extends L{constructor(C){super(C),this.byte_decoder=ce,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(C){const q=C.join(""),ue=new Uint8Array([...q].map($e=>this.byte_decoder[$e]));return this.text_decoder.decode(ue)}decode_chain(C){const q=[];let ue=[];for(const be of C)this.added_tokens.find($e=>$e.content===be)!==void 0?(ue.length>0&&(q.push(this.convert_tokens_to_string(ue)),ue=[]),q.push(be)):ue.push(be);return ue.length>0&&q.push(this.convert_tokens_to_string(ue)),q}}class ut extends L{constructor(C){super(C),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(C){if(C.length===0)return"";const q=[C[0]];for(let $e=1;$e$e!==this.pad_token).join("");return this.cleanup&&(be=ne(be).replaceAll(this.word_delimiter_token," ").trim()),be}decode_chain(C){return[this.convert_tokens_to_string(C)]}}class mt extends L{constructor(C){super(C),this.decoders=C.decoders.map(q=>L.fromConfig(q))}decode_chain(C){return this.decoders.reduce((q,ue)=>ue.decode_chain(q),C)}}class vt extends L{constructor(C){super(C),this.suffix=this.config.suffix}decode_chain(C){return C.map((q,ue)=>q.replaceAll(this.suffix,ue===C.length-1?"":" "))}}class kt extends L{decode_chain(C){let q="";for(let ue=1;ueue.normalize("NFKC")).join("~"):C=C.normalize("NFKC"),C}}class ks extends je{constructor(C){super(),this.tokenizers=C.pretokenizers.map(q=>je.fromConfig(q))}pre_tokenize_text(C,q){return this.tokenizers.reduce((ue,be)=>be.pre_tokenize(ue,q),[C])}}class Ds extends je{constructor(C){super()}pre_tokenize_text(C,q){return C.match(/\w+|[^\w\s]+/g)||[]}}class sr extends je{constructor(C){super()}pre_tokenize_text(C,q){return S(C)}}class kr extends je{constructor(C){super(),this.config=C,this.pattern=O(this.config.pattern),this.content=this.config.content}pre_tokenize_text(C,q){return this.pattern===null?[C]:[C.replaceAll(this.pattern,this.config.content)]}}const Qr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Us(Pe,C,q,ue){for(const be of Object.keys(Pe)){const $e=C-Pe[be].length,Qe=q(be),pt=new Array($e).fill(Qe);Pe[be]=ue==="right"?(0,I.mergeArrays)(Pe[be],pt):(0,I.mergeArrays)(pt,Pe[be])}}function xr(Pe,C){for(const q of Object.keys(Pe))Pe[q].length=C}class Nt extends _.Callable{constructor(q,ue){super();fe(this,"return_token_type_ids",!1);fe(this,"padding_side","right");this._tokenizer_config=ue,this.normalizer=Ce.fromConfig(q.normalizer),this.pre_tokenizer=je.fromConfig(q.pre_tokenizer),this.model=ve.fromConfig(q.model,ue),this.post_processor=Re.fromConfig(q.post_processor),this.decoder=L.fromConfig(q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const be of q.added_tokens){const $e=new ie(be);this.added_tokens.push($e),this.model.tokens_to_ids.set($e.content,$e.id),this.model.vocab[$e.id]=$e.content,$e.special&&(this.special_tokens.push($e.content),this.all_special_ids.push($e.id))}if(this.additional_special_tokens=ue.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((be,$e)=>$e.content.length-be.content.length).map(be=>`${be.lstrip?"\\s*":""}(${(0,I.escapeRegExp)(be.content)})${be.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=ue.model_max_length,this.remove_space=ue.remove_space,this.clean_up_tokenization_spaces=ue.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ue.do_lowercase_and_remove_accent??!1,ue.padding_side&&(this.padding_side=ue.padding_side),this.legacy=!1,this.chat_template=ue.chat_template??null,Array.isArray(this.chat_template)){const be=Object.create(null);for(const{name:$e,template:Qe}of this.chat_template){if(typeof $e!="string"||typeof Qe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');be[$e]=Qe}this.chat_template=be}this._compiled_template_cache=new Map}getToken(...q){for(const ue of q){const be=this._tokenizer_config[ue];if(be)if(typeof be=="object"){if(be.__type==="AddedToken")return be.content;throw Error(`Unknown token: ${be}`)}else return be}return null}static async from_pretrained(q,{progress_callback:ue=null,config:be=null,cache_dir:$e=null,local_files_only:Qe=!1,revision:pt="main",legacy:gt=null}={}){const ft=await M(q,{progress_callback:ue,config:be,cache_dir:$e,local_files_only:Qe,revision:pt,legacy:gt});return new this(...ft)}_call(q,{text_pair:ue=null,add_special_tokens:be=!0,padding:$e=!1,truncation:Qe=null,max_length:pt=null,return_tensor:gt=!0,return_token_type_ids:ft=null}={}){const xt=Array.isArray(q);let Kt;if(xt){if(q.length===0)throw Error("text array must be non-empty");if(ue!==null){if(Array.isArray(ue)){if(q.length!==ue.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Kt=q.map((us,Fs)=>this._encode_plus(us,{text_pair:ue[Fs],add_special_tokens:be,return_token_type_ids:ft}))}else Kt=q.map(us=>this._encode_plus(us,{add_special_tokens:be,return_token_type_ids:ft}))}else{if(q==null)throw Error("text may not be null or undefined");if(Array.isArray(ue))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Kt=[this._encode_plus(q,{text_pair:ue,add_special_tokens:be,return_token_type_ids:ft})]}if(pt===null?$e==="max_length"?pt=this.model_max_length:pt=(0,Y.max)(Kt.map(us=>us.input_ids.length))[0]:Qe||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."),pt=Math.min(pt,this.model_max_length??1/0),$e||Qe)for(let us=0;uspt?Qe&&xr(Kt[us],pt):$e&&Us(Kt[us],pt,Fs=>Fs==="input_ids"?this.pad_token_id:0,this.padding_side));const hs={};if(gt){if(!($e&&Qe)&&Kt.some(Fs=>{var Bt;for(const rs of Object.keys(Fs))if(Fs[rs].length!==((Bt=Kt[0][rs])==null?void 0:Bt.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 us=[Kt.length,Kt[0].input_ids.length];for(const Fs of Object.keys(Kt[0]))hs[Fs]=new N.Tensor("int64",BigInt64Array.from(Kt.flatMap(Bt=>Bt[Fs]).map(BigInt)),us)}else{for(const us of Object.keys(Kt[0]))hs[us]=Kt.map(Fs=>Fs[us]);if(!xt)for(const us of Object.keys(hs))hs[us]=hs[us][0]}return hs}_encode_text(q){return q===null?null:(this.added_tokens_regex?q.split(this.added_tokens_regex).filter($e=>$e):[q]).map(($e,Qe)=>{if(this.added_tokens.find(gt=>gt.content===$e)!==void 0)return $e;{if(this.remove_space===!0&&($e=$e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&($e=U($e)),this.normalizer!==null&&($e=this.normalizer($e)),$e.length===0)return[];const gt=this.pre_tokenizer!==null?this.pre_tokenizer($e,{section_index:Qe}):[$e];return this.model(gt)}}).flat()}_encode_plus(q,{text_pair:ue=null,add_special_tokens:be=!0,return_token_type_ids:$e=null}={}){const{tokens:Qe,token_type_ids:pt}=this._tokenize_helper(q,{pair:ue,add_special_tokens:be}),gt=this.model.convert_tokens_to_ids(Qe),ft={input_ids:gt,attention_mask:new Array(gt.length).fill(1)};return($e??this.return_token_type_ids)&&pt&&(ft.token_type_ids=pt),ft}_tokenize_helper(q,{pair:ue=null,add_special_tokens:be=!1}={}){const $e=this._encode_text(q),Qe=this._encode_text(ue);return this.post_processor?this.post_processor($e,Qe,{add_special_tokens:be}):{tokens:(0,I.mergeArrays)($e??[],Qe??[])}}tokenize(q,{pair:ue=null,add_special_tokens:be=!1}={}){return this._tokenize_helper(q,{pair:ue,add_special_tokens:be}).tokens}encode(q,{text_pair:ue=null,add_special_tokens:be=!0,return_token_type_ids:$e=null}={}){return this._encode_plus(q,{text_pair:ue,add_special_tokens:be,return_token_type_ids:$e}).input_ids}batch_decode(q,ue={}){return q instanceof N.Tensor&&(q=q.tolist()),q.map(be=>this.decode(be,ue))}decode(q,ue={}){if(q instanceof N.Tensor&&(q=te(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,ue)}decode_single(q,{skip_special_tokens:ue=!1,clean_up_tokenization_spaces:be=null}){let $e=this.model.convert_ids_to_tokens(q);ue&&($e=$e.filter(pt=>!this.special_tokens.includes(pt)));let Qe=this.decoder?this.decoder($e):$e.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Qe=Qe.replaceAll(this.decoder.end_of_word_suffix," "),ue&&(Qe=Qe.trim())),(be??this.clean_up_tokenization_spaces)&&(Qe=ne(Qe)),Qe}get_chat_template({chat_template:q=null,tools:ue=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const be=this.chat_template;if(q!==null&&Object.hasOwn(be,q))q=be[q];else if(q===null)if(ue!==null&&"tool_use"in be)q=be.tool_use;else if("default"in be)q=be.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(be).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:ue=null,documents:be=null,chat_template:$e=null,add_generation_prompt:Qe=!1,tokenize:pt=!0,padding:gt=!1,truncation:ft=!1,max_length:xt=null,return_tensor:Kt=!0,return_dict:hs=!1,tokenizer_kwargs:us={},...Fs}={}){if($e=this.get_chat_template({chat_template:$e,tools:ue}),typeof $e!="string")throw Error(`chat_template must be a string, but got ${typeof $e}`);let Bt=this._compiled_template_cache.get($e);Bt===void 0&&(Bt=new b.Template($e),this._compiled_template_cache.set($e,Bt));const rs=Object.create(null);for(const Ws of Qr){const ze=this.getToken(Ws);ze&&(rs[Ws]=ze)}const rr=Bt.render({messages:q,add_generation_prompt:Qe,tools:ue,documents:be,...rs,...Fs});if(pt){const Ws=this._call(rr,{add_special_tokens:!1,padding:gt,truncation:ft,max_length:xt,return_tensor:Kt,...us});return hs?Ws:Ws.input_ids}return rr}}class Xr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Sr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class $r extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Yr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class cr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Jr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Ar extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Br extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Rr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class or extends Nt{}class it extends Nt{}class Tt extends Nt{constructor(q,ue){super(q,ue);fe(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 Dt extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Vs extends Nt{}class Nr extends Nt{}class Ir extends Nt{}class Ms extends Nt{constructor(C,q){super(C,q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)),this.lang_to_token=ue=>ue}_build_translation_inputs(C,q,ue){return fr(this,C,q,ue)}}class ar extends Ms{}class Is extends Nt{}class Tr extends Nt{}const ts="▁";class mn extends Nt{constructor(q,ue){super(q,ue);fe(this,"padding_side","left");this.legacy=ue.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new At({replacement:ts,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 ue=super._encode_text(ts+q.replaceAll(ts," "));return ue.length>1&&ue[0]===ts&&this.special_tokens.includes(ue[1])&&(ue=ue.slice(1)),ue}}class jr extends Nt{}class si extends Nt{}class An extends Nt{}class In extends Nt{}class On extends Nt{}class Ur extends Nt{}class Fn extends Nt{}class ri extends Nt{}class Vr extends Nt{}function fr(Pe,C,q,ue){if(!("language_codes"in Pe)||!Array.isArray(Pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Pe)||!(Pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Pe)||typeof Pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const be=ue.src_lang,$e=ue.tgt_lang;if(!Pe.language_codes.includes($e))throw new Error(`Target language code "${$e}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);if(be!==void 0){if(!Pe.language_codes.includes(be))throw new Error(`Source language code "${be}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);for(const Qe of Pe.post_processor.config.single)if("SpecialToken"in Qe&&Pe.languageRegex.test(Qe.SpecialToken.id)){Qe.SpecialToken.id=Pe.lang_to_token(be);break}}return ue.forced_bos_token_id=Pe.model.convert_tokens_to_ids([Pe.lang_to_token($e)])[0],Pe._call(C,q)}class lr extends Nt{constructor(C,q){super(C,q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)),this.lang_to_token=ue=>ue}_build_translation_inputs(C,q,ue){return fr(this,C,q,ue)}}class fn extends Nt{constructor(C,q){super(C,q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)).map(ue=>ue.slice(2,-2)),this.lang_to_token=ue=>`__${ue}__`}_build_translation_inputs(C,q,ue){return fr(this,C,q,ue)}}class Zr extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(C,{return_timestamps:q=!1,return_language:ue=!1,time_precision:be=null,force_full_sequences:$e=!0}={}){if(be===null)throw Error("Must specify time_precision");let Qe=null;const pt=q==="word";function gt(){return{language:Qe,timestamp:[null,null],text:""}}const ft=[];let xt=gt(),Kt=0;const hs=this.timestamp_begin,Fs=hs+1500;let Bt=[],rs=[],rr=!1,Ws=null;const ze=new Set(this.all_special_ids);for(const Ss of C){const qs=Ss.tokens,Ot=pt?Ss.token_timestamps:null;let nr=null,_r=hs;if("stride"in Ss){const[yt,qt,Ls]=Ss.stride;if(Kt-=qt,Ws=yt-Ls,qt&&(_r=qt/be+hs),Ls)for(let As=qs.length-1;As>=0;--As){const Gs=Number(qs[As]);if(Gs>=hs){if(nr!==null&&(Gs-hs)*be=hs&&qt<=Fs){const Ls=(qt-hs)*be+Kt,As=(0,Y.round)(Ls,2);if(nr!==null&&qt>=nr)rr=!0;else if(rr||Bt.length>0&&qt<_r)rr=!1;else if(xt.timestamp[0]===null)xt.timestamp[0]=As;else if(As!==xt.timestamp[0]){xt.timestamp[1]=As,Bt.push(ms),pt&&rs.push($s);const[Gs,$t]=this.findLongestCommonSequence(Bt,rs),en=this.decode(Gs);xt.text=en,pt&&(xt.words=this.collateWordTimestamps(Gs,$t,Qe)),ft.push(xt),Bt=[],ms=[],rs=[],$s=[],xt=gt()}}else if(ms.push(qt),pt){let Ls=(0,Y.round)(Ot[yt]+Kt,2),As;if(yt+10?(Bt.push(ms),pt&&rs.push($s)):Bt.every(yt=>yt.length===0)&&(xt=gt(),Bt=[],ms=[],rs=[],$s=[])}if(Bt.length>0){if($e&&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[Ss,qs]=this.findLongestCommonSequence(Bt,rs),Ot=this.decode(Ss);xt.text=Ot,pt&&(xt.words=this.collateWordTimestamps(Ss,qs,Qe)),ft.push(xt)}let Js=Object.create(null);const Or=ft.map(Ss=>Ss.text).join("");if(q||ue){for(let Ss=0;Ss0;let pt=Qe?[]:null,gt=Qe?q[0]:null;for(let ft=1;ftqt===_r[Ls]&>[Or+Ls]<=q[ft][Ot+Ls]).length:ms=qs.filter((qt,Ls)=>qt===_r[Ls]).length;const $s=Js/1e4,yt=ms/Js+$s;ms>1&&yt>Kt&&(Kt=yt,hs=[Or,Ss,Ot,nr])}const[Fs,Bt,rs,rr]=hs,Ws=Math.floor((Bt+Fs)/2),ze=Math.floor((rr+rs)/2);$e.push(...ue.slice(0,Ws)),ue=xt.slice(ze),be=ue.length,Qe&&(pt.push(...gt.slice(0,Ws)),gt=q[ft].slice(ze))}return $e.push(...ue),Qe?(pt.push(...gt),[$e,pt]):[$e,[]]}collateWordTimestamps(C,q,ue){const[be,$e,Qe]=this.combineTokensIntoWords(C,ue),pt=[];for(let gt=0;gt=be){const pt=((Qe-be)*ue).toFixed(2);$e.push(`<|${pt}|>`),$e.push([])}else $e[$e.length-1].push(Qe);return $e=$e.map(Qe=>typeof Qe=="string"?Qe:super.decode(Qe,q)),$e.join("")}splitTokensOnUnicode(C){const q=this.decode(C,{decode_with_timestamps:!0}),ue="�",be=[],$e=[],Qe=[];let pt=[],gt=[],ft=0;for(let xt=0;xt=this.model.tokens_to_ids.get("<|endoftext|>"),Fs=xt.startsWith(" "),Bt=xt.trim(),rs=gt.test(Bt);if(us||Fs||rs||$e.length===0)$e.push(xt),Qe.push(Kt),pt.push(hs);else{const rr=$e.length-1;$e[rr]+=xt,Qe[rr].push(...Kt),pt[rr].push(...hs)}}return[$e,Qe,pt]}mergePunctuations(C,q,ue,be,$e){const Qe=structuredClone(C),pt=structuredClone(q),gt=structuredClone(ue);let ft=Qe.length-2,xt=Qe.length-1;for(;ft>=0;)Qe[ft].startsWith(" ")&&be.includes(Qe[ft].trim())?(Qe[xt]=Qe[ft]+Qe[xt],pt[xt]=(0,I.mergeArrays)(pt[ft],pt[xt]),gt[xt]=(0,I.mergeArrays)(gt[ft],gt[xt]),Qe[ft]="",pt[ft]=[],gt[ft]=[]):xt=ft,--ft;for(ft=0,xt=1;xtKt),pt.filter(Kt=>Kt.length>0),gt.filter(Kt=>Kt.length>0)]}}class _n extends Nt{}class gn extends Nt{}class wn extends Nt{}class zt extends Nt{constructor(C,q){super(C,q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ue=>this.languageRegex.test(ue)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(C){if(C===null)return null;const[q,...ue]=C.trim().split(this.languageRegex);if(ue.length===0)return super._encode_text(q);if(ue.length===2){const[be,$e]=ue;return this.supported_language_codes.includes(be)||console.warn(`Unsupported language code "${be}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,I.mergeArrays)([be],super._encode_text($e))}}}class yn extends Nt{}class Dn extends Nt{}class Ln extends Nt{}class zn extends Nt{}class Wr extends Nt{}class Bn extends Nt{constructor(C,q){super(C,q),this.decoder=new kt({})}}class Mn extends Nt{}class Rn extends Nt{}class as{static async from_pretrained(C,{progress_callback:q=null,config:ue=null,cache_dir:be=null,local_files_only:$e=!1,revision:Qe="main",legacy:pt=null}={}){var hs;const[gt,ft]=await M(C,{progress_callback:q,config:ue,cache_dir:be,local_files_only:$e,revision:Qe,legacy:pt}),xt=((hs=ft.tokenizer_class)==null?void 0:hs.replace(/Fast$/,""))??"PreTrainedTokenizer";let Kt=this.TOKENIZER_CLASS_MAPPING[xt];return Kt||(console.warn(`Unknown tokenizer class "${xt}", attempting to construct from base class.`),Kt=Nt),new Kt(gt,ft)}}fe(as,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Vs,DistilBertTokenizer:or,CamembertTokenizer:it,DebertaTokenizer:cr,DebertaV2Tokenizer:Jr,BertTokenizer:Xr,HerbertTokenizer:Ar,ConvBertTokenizer:Br,RoFormerTokenizer:Rr,XLMTokenizer:Tt,ElectraTokenizer:Dt,MobileBertTokenizer:$r,SqueezeBertTokenizer:Yr,AlbertTokenizer:Sr,GPT2Tokenizer:Nr,BartTokenizer:Ir,MBartTokenizer:Ms,MBart50Tokenizer:ar,RobertaTokenizer:Is,WhisperTokenizer:Zr,CodeGenTokenizer:_n,CLIPTokenizer:gn,SiglipTokenizer:wn,MarianTokenizer:zt,BloomTokenizer:Tr,NllbTokenizer:lr,M2M100Tokenizer:fn,LlamaTokenizer:mn,CodeLlamaTokenizer:jr,XLMRobertaTokenizer:si,MPNetTokenizer:An,FalconTokenizer:In,GPTNeoXTokenizer:On,EsmTokenizer:Ur,Wav2Vec2CTCTokenizer:yn,BlenderbotTokenizer:Dn,BlenderbotSmallTokenizer:Ln,SpeechT5Tokenizer:zn,NougatTokenizer:Wr,VitsTokenizer:Bn,Qwen2Tokenizer:Fn,GemmaTokenizer:ri,Grok1Tokenizer:Vr,CohereTokenizer:Mn,MgpstrTokenizer:Rn,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(Ee,$,r)=>{r.r($),r.d($,{RawAudio:()=>we,hamming:()=>v,hanning:()=>M,mel_filter_bank:()=>X,read_audio:()=>b,spectrogram:()=>F,window_function:()=>ae});var _=r("./src/utils/hub.js"),I=r("./src/utils/maths.js"),R=r("./src/utils/core.js"),Y=r("./src/env.js"),N=r("?7a2c"),g=r("./src/utils/tensor.js");async function b(re,xe){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 ce=await(await(0,_.getFile)(re)).arrayBuffer(),Se=new AudioContext({sampleRate:xe});typeof xe>"u"&&console.warn(`No sampling rate provided, using default of ${Se.sampleRate}Hz.`);const Ie=await Se.decodeAudioData(ce);let Ce;if(Ie.numberOfChannels===2){const tt=Math.sqrt(2),Ge=Ie.getChannelData(0),ye=Ie.getChannelData(1);Ce=new Float32Array(Ge.length);for(let J=0;J2595*Math.log10(1+re/700),kaldi:re=>1127*Math.log(1+re/700),slaney:(re,xe=1e3,ce=15,Se=27/Math.log(6.4))=>re>=xe?ce+Math.log(re/xe)*Se:3*re/200};function K(re,xe="htk"){const ce=O[xe];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?ce(re):re.map(Se=>ce(Se))}const te={htk:re=>700*(10**(re/2595)-1),kaldi:re=>700*(Math.exp(re/1127)-1),slaney:(re,xe=1e3,ce=15,Se=Math.log(6.4)/27)=>re>=ce?xe*Math.exp(Se*(re-ce)):200*re/3};function ne(re,xe="htk"){const ce=te[xe];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?ce(re):re.map(Se=>ce(Se))}function W(re,xe){const ce=Float64Array.from({length:xe.length-1},(tt,Ge)=>xe[Ge+1]-xe[Ge]),Se=Array.from({length:re.length},()=>new Array(xe.length));for(let tt=0;ttnew Array(re.length));for(let tt=0;ttre+Se*Ce)}function X(re,xe,ce,Se,Ie,Ce=null,tt="htk",Ge=!1){if(Ce!==null&&Ce!=="slaney")throw new Error('norm must be one of null or "slaney"');const ye=K(ce,tt),J=K(Se,tt),de=U(ye,J,xe+2);let ke=ne(de,tt),Be;if(Ge){const se=Ie/(re*2);Be=K(Float64Array.from({length:re},(Ke,je)=>je*se),tt),ke=de}else Be=U(0,Math.floor(Ie/2),re);const Ze=W(Be,ke);if(Ce!==null&&Ce==="slaney")for(let se=0;seIe)throw Error(`frame_length (${ce}) may not be larger than fft_length (${Ie})`);if(Ne!==ce)throw new Error(`Length of the window (${Ne}) must equal frame_length (${ce})`);if(Se<=0)throw new Error("hop_length must be greater than zero");if(Ce===null&&de!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(tt){if(Ge!=="reflect")throw new Error(`pad_mode="${Ge}" not implemented yet.`);const We=Math.floor((Ie-1)/2)+1;re=A(re,We,We)}let Re=Math.floor(1+Math.floor((re.length-ce)/Se));le!==null&&ReRe?Ue&&(ct=Te):ct=dt=Te);const lt=new I.FFT(Ie),ht=new Float64Array(Ie),L=new Float64Array(lt.outputBufferSize),oe=new Float32Array(st*ct);for(let We=0;We=1;--mt)ht[mt]-=J*ht[mt-1];ht[0]*=1-J}for(let mt=0;mtMath.pow(Ge,.85));break;default:throw new Error(`Unknown window type ${xe}.`)}if(ce&&(tt=tt.subarray(0,re)),Se===null)return tt;if(re>Se)throw new Error(`Length of the window (${re}) may not be larger than frame_length (${Se})`);return tt}function ie(re,xe){let ce=44;const Se=new ArrayBuffer(ce+re.length*4),Ie=new DataView(Se);ve(Ie,0,"RIFF"),Ie.setUint32(4,36+re.length*4,!0),ve(Ie,8,"WAVE"),ve(Ie,12,"fmt "),Ie.setUint32(16,16,!0),Ie.setUint16(20,3,!0),Ie.setUint16(22,1,!0),Ie.setUint32(24,xe,!0),Ie.setUint32(28,xe*4,!0),Ie.setUint16(32,4,!0),Ie.setUint16(34,32,!0),ve(Ie,36,"data"),Ie.setUint32(40,re.length*4,!0);for(let Ce=0;Ce{let Ce=await Ie.arrayBuffer();N.writeFileSync(Se,Buffer.from(Ce))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await ce(xe,this.toBlob())}}},"./src/utils/constants.js":(Ee,$,r)=>{r.r($),r.d($,{CHAT_TEMPLATE_NAME:()=>g,CONFIG_NAME:()=>I,FEATURE_EXTRACTOR_NAME:()=>R,GENERATION_CONFIG_NAME:()=>b,GITHUB_ISSUE_URL:()=>_,IMAGE_PROCESSOR_NAME:()=>Y,PROCESSOR_NAME:()=>N});const _="https://github.com/huggingface/transformers.js/issues/new/choose",I="config.json",R="preprocessor_config.json",Y=R,N="processor_config.json",g="chat_template.json",b="generation_config.json"},"./src/utils/core.js":(Ee,$,r)=>{r.r($),r.d($,{calculateDimensions:()=>b,calculateReflectOffset:()=>O,count:()=>W,dispatchCallback:()=>_,escapeRegExp:()=>R,isIntegralNumber:()=>N,isNullishDimension:()=>g,isTypedArray:()=>Y,len:()=>ne,mergeArrays:()=>M,pick:()=>te,pop:()=>y,product:()=>v,reverseDictionary:()=>I,saveBlob:()=>K});function _(U,X){U&&U(X)}function I(U){return Object.fromEntries(Object.entries(U).map(([X,A])=>[A,X]))}function R(U){return U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(U){var X,A,S;return((S=(A=(X=U==null?void 0:U.prototype)==null?void 0:X.__proto__)==null?void 0:A.constructor)==null?void 0:S.name)==="TypedArray"}function N(U){return Number.isInteger(U)||typeof U=="bigint"}function g(U){return U==null||U===-1}function b(U){const X=[];let A=U;for(;Array.isArray(A);)X.push(A.length),A=A[0];return X}function y(U,X,A=void 0){const S=U[X];if(S!==void 0)return delete U[X],S;if(A===void 0)throw Error(`Key ${X} does not exist in object.`);return A}function M(...U){return Array.prototype.concat.apply([],U)}function v(...U){return U.reduce((X,A)=>X.flatMap(S=>A.map(w=>[S,w])))}function O(U,X){return Math.abs((U+X)%(2*X)-X)}function K(U,X){const A=URL.createObjectURL(X),S=document.createElement("a");S.href=A,S.download=U,S.click(),S.remove(),URL.revokeObjectURL(A)}function te(U,X){return Object.assign({},...X.map(A=>{if(U[A]!==void 0)return{[A]:U[A]}}))}function ne(U){let X=0;for(const A of U)++X;return X}function W(U,X){let A=0;for(const S of U)S===X&&++A;return A}},"./src/utils/data-structures.js":(Ee,$,r)=>{r.r($),r.d($,{CharTrie:()=>I,PriorityQueue:()=>_,TokenLattice:()=>Y});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 N(this.bosTokenId,0,0,0,0),O=new N(this.eosTokenId,1,this.len,0,0);this.nodes.push(v.clone()),this.nodes.push(O.clone()),this.beginNodes[this.len].push(O),this.endNodes[0].push(v)}insert(b,y,M,v){const O=this.nodes.length,K=new N(v,O,b,y,M);this.beginNodes[b].push(K),this.endNodes[b+y].push(K),this.nodes.push(K)}viterbi(){const b=this.len;let y=0;for(;y<=b;){if(this.beginNodes[y].length==0)return[];for(let te of this.beginNodes[y]){te.prev=null;let ne=0,W=null;for(let U of this.endNodes[y]){const X=U.backtraceScore+te.score;(W===null||X>ne)&&(W=U.clone(),ne=X)}if(W!==null)te.prev=W,te.backtraceScore=ne;else return[]}++y}const M=[],O=this.beginNodes[b][0].prev;if(O===null)return[];let K=O.clone();for(;K.prev!==null;)M.push(K.clone()),K=K.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 N{constructor(b,y,M,v,O){this.tokenId=b,this.nodeId=y,this.pos=M,this.length=v,this.score=O,this.prev=null,this.backtraceScore=0}clone(){const b=new N(this.tokenId,this.nodeId,this.pos,this.length,this.score);return b.prev=this.prev,b.backtraceScore=this.backtraceScore,b}}},"./src/utils/devices.js":(Ee,$,r)=>{r.r($),r.d($,{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":(Ee,$,r)=>{r.r($),r.d($,{DATA_TYPES:()=>Y,DEFAULT_DEVICE_DTYPE_MAPPING:()=>N,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>g,isWebGpuFp16Supported:()=>R});var _=r("./src/env.js"),I=r("./src/utils/devices.js");const R=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}}(),Y=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),N=Object.freeze({[I.DEVICE_TYPES.wasm]:Y.q8}),g=Object.freeze({[Y.fp32]:"",[Y.fp16]:"_fp16",[Y.int8]:"_int8",[Y.uint8]:"_uint8",[Y.q8]:"_quantized",[Y.q4]:"_q4",[Y.q4f16]:"_q4f16",[Y.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Ee,$,r)=>{r.r($),r.d($,{Callable:()=>_});const _=class{constructor(){let I=function(...R){return I._call(...R)};return Object.setPrototypeOf(I,new.target.prototype)}_call(...I){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Ee,$,r)=>{r.r($),r.d($,{getFile:()=>y,getModelFile:()=>te,getModelJSON:()=>ne});var _=r("?7a2c"),I=r("?a42a"),R=r("./src/env.js"),Y=r("./src/utils/core.js");const N={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(A){if(this.filePath=A,this.headers=new Headers,this.exists=_.existsSync(A),this.exists){this.status=200,this.statusText="OK";let S=_.statSync(A);this.headers.set("content-length",S.size.toString()),this.updateContentType();let w=this;this.body=new ReadableStream({start(x){w.arrayBuffer().then(F=>{x.enqueue(new Uint8Array(F)),x.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const A=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",N[A]??"application/octet-stream")}clone(){let A=new g(this.filePath);return A.exists=this.exists,A.status=this.status,A.statusText=this.statusText,A.headers=new Headers(this.headers),A}async arrayBuffer(){return(await _.promises.readFile(this.filePath)).buffer}async blob(){const A=await _.promises.readFile(this.filePath);return new Blob([A],{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(X,A=null,S=null){let w;try{w=new URL(X)}catch{return!1}return!(A&&!A.includes(w.protocol)||S&&!S.includes(w.hostname))}async function y(X){var A;if(R.env.useFS&&!b(X,["http:","https:","blob:"]))return new g(X);if(typeof process<"u"&&((A=process==null?void 0:process.release)==null?void 0:A.name)==="node"){const S=!!(kn!=null&&kn.TESTING_REMOTELY),w=R.env.version,x=new Headers;if(x.set("User-Agent",`transformers.js/${w}; is_ci/${S};`),b(X,["http:","https:"],["huggingface.co","hf.co"])){const ae=(kn==null?void 0:kn.HF_TOKEN)??(kn==null?void 0:kn.HF_ACCESS_TOKEN);ae&&x.set("Authorization",`Bearer ${ae}`)}return fetch(X,{headers:x})}else return fetch(X)}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(X,A,S){if(!S)return null;const w=M[X]??`Error (${X}) occurred while trying to load file`;throw Error(`${w}: "${A}".`)}class O{constructor(A){this.path=A}async match(A){let S=I.join(this.path,A),w=new g(S);if(w.exists)return w}async put(A,S){const w=Buffer.from(await S.arrayBuffer());let x=I.join(this.path,A);try{await _.promises.mkdir(I.dirname(x),{recursive:!0}),await _.promises.writeFile(x,w)}catch(F){console.warn("An error occurred while writing the file to cache:",F)}}}async function K(X,...A){for(let S of A)try{let w=await X.match(S);if(w)return w}catch{continue}}async function te(X,A,S=!0,w={}){if(!R.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(!R.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,Y.dispatchCallback)(w.progress_callback,{status:"initiate",name:X,file:A});let x;if(!x&&R.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{x=await caches.open("transformers-cache")}catch(tt){console.warn("An error occurred while opening the browser cache:",tt)}}if(!x&&R.env.useFSCache&&(x=new O(w.cache_dir??R.env.cacheDir)),!x&&R.env.useCustomCache){if(!R.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!R.env.customCache.match||!R.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");x=R.env.customCache}const F=w.revision??"main";let ae=U(X,A),ie=U(R.env.localModelPath,ae),ve=U(R.env.remoteHost,R.env.remotePathTemplate.replaceAll("{model}",X).replaceAll("{revision}",encodeURIComponent(F)),A),we=F==="main"?ae:U(X,F,A),re,xe=x instanceof O?we:ve,ce=!1,Se;x&&(Se=await K(x,ie,xe));const Ie=Se!==void 0;if(Se===void 0){if(R.env.allowLocalModels)if(b(ae,["http:","https:"])){if(w.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ae}.`);if(!R.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ae}.`)}else try{Se=await y(ie),re=ie}catch(Ge){console.warn(`Unable to load from local path "${ie}": "${Ge}"`)}if(Se===void 0||Se.status===404){if(w.local_files_only||!R.env.allowRemoteModels){if(S)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ie}".`);return null}if(Se=await y(ve),Se.status!==200)return v(Se.status,ve,S);re=xe}ce=x&&typeof Response<"u"&&Se instanceof Response&&Se.status===200}(0,Y.dispatchCallback)(w.progress_callback,{status:"download",name:X,file:A});let Ce;return w.progress_callback?Ie&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ce=new Uint8Array(await Se.arrayBuffer()),(0,Y.dispatchCallback)(w.progress_callback,{status:"progress",name:X,file:A,progress:100,loaded:Ce.length,total:Ce.length})):Ce=await W(Se,tt=>{(0,Y.dispatchCallback)(w.progress_callback,{status:"progress",name:X,file:A,...tt})}):Ce=new Uint8Array(await Se.arrayBuffer()),ce&&re&&await x.match(re)===void 0&&await x.put(re,new Response(Ce,{headers:Se.headers})).catch(tt=>{console.warn(`Unable to add response to browser cache: ${tt}.`)}),(0,Y.dispatchCallback)(w.progress_callback,{status:"done",name:X,file:A}),Ce}async function ne(X,A,S=!0,w={}){let x=await te(X,A,S,w);if(x===null)return{};let ae=new TextDecoder("utf-8").decode(x);return JSON.parse(ae)}async function W(X,A){const S=X.headers.get("Content-Length");S===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let w=parseInt(S??"0"),x=new Uint8Array(w),F=0;const ae=X.body.getReader();async function ie(){const{done:ve,value:we}=await ae.read();if(ve)return;let re=F+we.length;if(re>w){w=re;let ce=new Uint8Array(w);ce.set(x),x=ce}x.set(we,F),F=re;const xe=F/w*100;return A({progress:xe,loaded:F,total:w}),ie()}return await ie(),x}function U(...X){return X=X.map((A,S)=>(S&&(A=A.replace(new RegExp("^/"),"")),S!==X.length-1&&(A=A.replace(new RegExp("/$"),"")),A)),X.join("/")}},"./src/utils/image.js":(Ee,$,r)=>{r.r($),r.d($,{RawImage:()=>K,load_image:()=>te});var _=r("./src/utils/core.js"),I=r("./src/utils/hub.js"),R=r("./src/env.js"),Y=r("./src/utils/tensor.js"),N=r("?2b25");let g,b,y;const M=R.apis.IS_BROWSER_ENV||R.apis.IS_WEBWORKER_ENV;if(M)g=(ne,W)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ne,W)},y=self.createImageBitmap,b=self.ImageData;else if(N)y=async ne=>{const U=(await ne.metadata()).channels,{data:X,info:A}=await ne.rotate().raw().toBuffer({resolveWithObject:!0}),S=new K(new Uint8ClampedArray(X),A.width,A.height,A.channels);return U!==void 0&&U!==A.channels&&S.convert(U),S};else throw new Error("Unable to load image processing library.");const v={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},O=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class K{constructor(W,U,X,A){this.data=W,this.width=U,this.height=X,this.channels=A}get size(){return[this.width,this.height]}static async read(W){if(W instanceof K)return W;if(typeof W=="string"||W instanceof URL)return await this.fromURL(W);throw new Error(`Unsupported input type: ${typeof W}`)}static fromCanvas(W){if(!M)throw new Error("fromCanvas() is only supported in browser environments.");const X=W.getContext("2d").getImageData(0,0,W.width,W.height).data;return new K(X,W.width,W.height,4)}static async fromURL(W){const U=await(0,I.getFile)(W);if(U.status!==200)throw new Error(`Unable to read image from "${W}" (${U.status} ${U.statusText})`);const X=await U.blob();return this.fromBlob(X)}static async fromBlob(W){if(M){const U=await y(W),X=g(U.width,U.height).getContext("2d");return X.drawImage(U,0,0),new this(X.getImageData(0,0,U.width,U.height).data,U.width,U.height,4)}else{const U=N(await W.arrayBuffer());return await y(U)}}static fromTensor(W,U="CHW"){if(W.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${W.dims.length} dimensions.`);if(U==="CHW")W=W.transpose(1,2,0);else if(U!=="HWC")throw new Error(`Unsupported channel format: ${U}`);if(!(W.data instanceof Uint8ClampedArray||W.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${W.type}`);switch(W.dims[2]){case 1:case 2:case 3:case 4:return new K(W.data,W.dims[1],W.dims[0],W.dims[2]);default:throw new Error(`Unsupported number of channels: ${W.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const W=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let U=0,X=0;U=0?F=X:ie=-X,A>=0?ae=A:ve=-A,x.drawImage(w,F,ae,W,U,ie,ve,W,U),new K(x.getImageData(0,0,W,U).data,W,U,4).convert(S)}else{let S=this.toSharp();if(X>=0&&A>=0)S=S.extract({left:Math.floor(X),top:Math.floor(A),width:W,height:U});else if(X<=0&&A<=0){const w=Math.floor(-A),x=Math.floor(-X);S=S.extend({top:w,left:x,right:W-this.width-x,bottom:U-this.height-w})}else{let w=[0,0],x=0;A<0?(w[0]=Math.floor(-A),w[1]=U-this.height-w[0]):x=Math.floor(A);let F=[0,0],ae=0;X<0?(F[0]=Math.floor(-X),F[1]=W-this.width-F[0]):ae=Math.floor(X),S=S.extend({top:w[0],bottom:w[1],left:F[0],right:F[1]}).extract({left:ae,top:x,width:W,height:U})}return await y(S)}}async toBlob(W="image/png",U=1){if(!M)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:W,quality:U})}toTensor(W="CHW"){let U=new Y.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(W!=="HWC")if(W==="CHW")U=U.permute(2,0,1);else throw new Error(`Unsupported channel format: ${W}`);return U}toCanvas(){if(!M)throw new Error("toCanvas() is only supported in browser environments.");const W=this.clone().rgba(),U=g(W.width,W.height),X=new b(W.data,W.width,W.height);return U.getContext("2d").putImageData(X,0,0),U}split(){const{data:W,width:U,height:X,channels:A}=this,S=W.constructor,w=W.length/A,x=Array.from({length:A},()=>new S(w));for(let F=0;Fnew K(F,U,X,1))}_update(W,U,X,A=null){return this.data=W,this.width=U,this.height=X,A!==null&&(this.channels=A),this}clone(){return new K(this.data.slice(),this.width,this.height,this.channels)}convert(W){if(this.channels===W)return this;switch(W){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(W){if(M){if(R.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const U=W.split(".").pop().toLowerCase(),X=O.get(U)??"image/png",A=await this.toBlob(X);(0,_.saveBlob)(W,A)}else{if(R.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(W);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 N(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const te=K.read.bind(K)},"./src/utils/maths.js":(Ee,$,r)=>{r.r($),r.d($,{FFT:()=>te,bankers_round:()=>U,cos_sim:()=>g,dot:()=>N,dynamic_time_warping:()=>X,interpolate_data:()=>_,log_softmax:()=>Y,magnitude:()=>b,max:()=>M,medianFilter:()=>ne,min:()=>y,permute_data:()=>I,round:()=>W,softmax:()=>R});function _(A,[S,w,x],[F,ae],ie="bilinear",ve=!1){const we=ae/x,re=F/w,xe=new A.constructor(F*ae*S),ce=w*x,Se=F*ae;for(let Ie=0;Ie=0;--ve)F[ve]=we,x[ve]=S[w[ve]],we*=x[ve];const ae=w.map((ve,we)=>F[w.indexOf(we)]),ie=new A.constructor(A.length);for(let ve=0;ve=0;--re)we+=xe%S[re]*ae[re],xe=Math.floor(xe/S[re]);ie[we]=A[ve]}return[ie,x]}function R(A){const S=M(A)[0],w=A.map(ae=>Math.exp(ae-S)),x=w.reduce((ae,ie)=>ae+ie,0);return w.map(ae=>ae/x)}function Y(A){const S=M(A)[0];let w=0;for(let ae=0;aeae-S-x)}function N(A,S){let w=0;for(let x=0;xS+w*w,0))}function y(A){if(A.length===0)throw Error("Array must not be empty");let S=A[0],w=0;for(let x=1;xS&&(S=A[x],w=x);return[S,w]}function v(A){return A>0&&(A&A-1)===0}class O{constructor(S){if(this.size=S|0,this.size<=1||!v(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=S<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>F&3)<>>1);for(let F=0;F>>1]=S[F];return x}toComplexArray(S,w){const x=w||this.createComplexArray();for(let F=0;F>>1],x[F+1]=0;return x}transform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,1)}realTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._realTransform4(S,w,1)}inverseTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,-1);for(let x=0;x>=2;ie>=2;ie>>=2){ve=F/ie<<1;const Se=ve>>>2;for(we=0;we>>1,ie>>>1)}else for(we=0,re=0;we>>1,ie>>>1,x)}const ce=this.table;for(ie>>=2;ie>=2;ie>>=2){ve=F/ie<<1;const Ie=ve>>>1,Ce=Ie>>>1,tt=Ce>>>1;for(we=0;we>>1;for(let Ie=2;Ie>1;++xe){const ce=(xe+1-S)**2/2,Se=Math.sqrt(we**2+re**2)**ce,Ie=ce*Math.atan2(re,we),Ce=2*xe;ae[Ce]=Se*Math.cos(Ie),ae[Ce+1]=Se*Math.sin(Ie),ie[Ce]=ae[Ce],ie[Ce+1]=-ae[Ce+1]}this._slicedChirpBuffer=ae.subarray(w,x),this._f=new O(F>>1),this._f.transform(this._chirpBuffer,ie)}_transform(S,w,x){const F=this._buffer1,ae=this._buffer2,ie=this._outBuffer1,ve=this._outBuffer2,we=this._chirpBuffer,re=this._slicedChirpBuffer,xe=this._a;if(x)for(let ce=0;ce>1,Ce=w[Ie];F[ce]=Ce*re[ce],F[Se]=Ce*re[Se]}else for(let ce=0;ce=A.length&&(we=2*(A.length-1)-we),x[ie++]=A[we]}x.sort(),w[ae]=x[F]}return w}function W(A,S){const w=Math.pow(10,S);return Math.round(A*w)/w}function U(A){const S=Math.round(A);return Math.abs(A)%1===.5?S%2===0?S:S-1:S}function X(A){const S=A.length,w=A[0].length,x=[S+1,w+1],F=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));F[0][0]=0;const ae=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let xe=1;xe0||ve>0;)switch(we.push(ie-1),re.push(ve-1),ae[ie][ve]){case 0:--ie,--ve;break;case 1:--ie;break;case 2:--ve;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ie}, ${ve}]. Please file a bug report.`)}return we.reverse(),re.reverse(),[we,re]}},"./src/utils/tensor.js":(Ee,$,r)=>{r.r($),r.d($,{Tensor:()=>N,cat:()=>w,full:()=>re,full_like:()=>xe,interpolate:()=>y,interpolate_4d:()=>M,layer_norm:()=>U,matmul:()=>v,mean:()=>ie,mean_pooling:()=>W,ones:()=>ce,ones_like:()=>Se,permute:()=>b,quantize_embeddings:()=>Ge,rand:()=>tt,rfft:()=>O,slice:()=>ne,stack:()=>x,std_mean:()=>ae,topk:()=>K,zeros:()=>Ie,zeros_like:()=>Ce});var _=r("./src/utils/maths.js"),I=r("./src/backends/onnx.js"),R=r("./src/ops/registry.js");const Y=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 N{constructor(...J){fe(this,"ort_tensor");return(0,I.isONNXTensor)(J[0])?this.ort_tensor=J[0]:this.ort_tensor=new I.Tensor(J[0],J[1],J[2]),new Proxy(this,{get:(de,ke)=>{if(typeof ke=="string"){let Be=Number(ke);if(Number.isInteger(Be))return de._getitem(Be)}return de[ke]},set:(de,ke,Be)=>de[ke]=Be})}get dims(){return this.ort_tensor.dims}set dims(J){this.ort_tensor.dims=J}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[J,...de]=this.dims;if(de.length>0){const ke=de.reduce((Be,Ze)=>Be*Ze);for(let Be=0;Be0){const Be=ke.reduce((Ze,se)=>Ze*se);return this._subarray(J,Be,ke)}else return new N(this.type,[this.data[J]],ke)}indexOf(J){const de=this.data;for(let ke=0;keVe)throw new Error(`Invalid slice: ${Te}`);const Ne=[Math.max(Ue,0),Math.min(Ve,this.dims[le])];ke.push(Ne),de.push(Ne[1]-Ne[0])}else throw new Error(`Invalid slice: ${Te}`)}const Be=ke.map(([le,Te])=>Te-le),Ze=Be.reduce((le,Te)=>le*Te),se=this.data,Ke=new se.constructor(Ze),je=this.stride();for(let le=0;le=0;--Ue){const Ne=Be[Ue];Te+=(Ve%Ne+ke[Ue][0])*je[Ue],Ve=Math.floor(Ve/Ne)}Ke[le]=se[Te]}return new N(this.type,Ke,de)}permute(...J){return b(this,J)}transpose(...J){return this.permute(...J)}sum(J=null,de=!1){return this.norm(1,J,de)}norm(J="fro",de=null,ke=!1){if(J==="fro")J=2;else if(typeof J=="string")throw Error(`Unsupported norm: ${J}`);const Be=this.data,Ze=(le,Te)=>le+Te**J;if(de===null){const le=Be.reduce(Ze,0)**(1/J);return new N(this.type,[le],[])}const[se,Ke,je]=F(Ze,this,de,ke);if(J!==1)for(let le=0;le=0;--je){const Ue=this.dims[je];if(je!==de){const Ve=le%Ue;Ke+=Ve*Te,Te*=this.dims[je]}le=Math.floor(le/Ue)}Be[se]/=Ze[Ke]}return this}normalize(J=2,de=1){return this.clone().normalize_(J,de)}stride(){return ve(this.dims)}squeeze(J=null){return new N(this.type,this.data,X(this.dims,J))}squeeze_(J=null){return this.dims=X(this.dims,J),this}unsqueeze(J=null){return new N(this.type,this.data,A(this.dims,J))}unsqueeze_(J=null){return this.dims=A(this.dims,J),this}flatten_(J=0,de=-1){de=(de+this.dims.length)%this.dims.length;let ke=this.dims.slice(0,J),Be=this.dims.slice(J,de+1),Ze=this.dims.slice(de+1);return this.dims=[...ke,Be.reduce((se,Ke)=>se*Ke,1),...Ze],this}flatten(J=0,de=-1){return this.clone().flatten_(J,de)}view(...J){let de=-1;for(let Be=0;BeKe!==de?Ze*se:Ze,1);J[de]=ke.length/Be}return new N(this.type,ke,J)}neg_(){const J=this.data;for(let de=0;deJ?1:0;return new N("bool",de,this.dims)}lt(J){const de=new Uint8Array(this.data.length),ke=this.data;for(let Be=0;BeMath.min(se,Ke),this,J,de,1/0);return new N(ke,Be,Ze)}max(J=null,de=!1){if(J===null){const se=(0,_.max)(this.data)[0];return new N(this.type,[se],[])}const[ke,Be,Ze]=F((se,Ke)=>Math.max(se,Ke),this,J,de,-1/0);return new N(ke,Be,Ze)}argmin(J=null,de=!1){if(J!==null)throw new Error("`dim !== null` not yet implemented.");const ke=(0,_.min)(this.data)[1];return new N("int64",[BigInt(ke)],[])}argmax(J=null,de=!1){if(J!==null)throw new Error("`dim !== null` not yet implemented.");const ke=(0,_.max)(this.data)[1];return new N("int64",[BigInt(ke)],[])}to(J){if(this.type===J)return this;if(!Y.hasOwnProperty(J))throw new Error(`Unsupported type: ${J}`);let de;const ke=["int64","uint64"].includes(this.type),Be=["int64","uint64"].includes(J);return ke&&!Be?de=Number:!ke&&Be&&(de=BigInt),new N(J,Y[J].from(this.data,de),this.dims)}}function g(ye,J){const de=ye.length,ke=J.reduce((Ze,se)=>Ze*se);if(de!==ke)throw Error(`cannot reshape array of size ${de} into shape (${J})`);let Be=ye;for(let Ze=J.length-1;Ze>=0;Ze--)Be=Be.reduce((se,Ke)=>{let je=se[se.length-1];return je.lengthnew N("int64",ye,[ye.length]);async function ne(ye,J,de,ke,Be){return await(await R.TensorOpRegistry.slice)({x:ye,s:te(J),e:te(de),a:te(ke),t:te(Be??new Array(ke.length).fill(1))})}function W(ye,J){const de=ye.data,ke=J.data,Be=[ye.dims[0],ye.dims[2]],Ze=new de.constructor(Be[0]*Be[1]),[se,Ke,je]=ye.dims;let le=0;for(let Te=0;Tede!==1):typeof J=="number"?ye[J]===1&&ye.splice(J,1):Array.isArray(J)&&(ye=ye.filter((de,ke)=>de!==1||!J.includes(ke))),ye}function A(ye,J){return J=S(J,ye.length+1),ye=ye.slice(),ye.splice(J,0,1),ye}function S(ye,J,de=null,ke=!0){if(ke&&(ye<-J||ye>=J))throw new Error(`IndexError: index ${ye} is out of bounds for dimension${de===null?"":" "+de} with size ${J}`);return ye<0&&(ye=(ye%J+J)%J),ye}function w(ye,J=0){J=S(J,ye[0].dims.length);const de=ye[0].dims.slice();de[J]=ye.reduce((se,Ke)=>se+Ke.dims[J],0);const ke=de.reduce((se,Ke)=>se*Ke,1),Be=new ye[0].data.constructor(ke),Ze=ye[0].type;if(J===0){let se=0;for(const Ke of ye){const je=Ke.data;Be.set(je,se),se+=je.length}}else{let se=0;for(let Ke=0;Ke=0;--Ve){const st=le[Ve];let dt=Ne%st;Ve===J&&(dt+=se),Ue+=dt*Re,Re*=de[Ve],Ne=Math.floor(Ne/st)}Be[Ue]=je[Te]}se+=le[J]}}return new N(Ze,Be,de)}function x(ye,J=0){return w(ye.map(de=>de.unsqueeze(J)),J)}function F(ye,J,de=null,ke=!1,Be=null){const Ze=J.data,se=J.dims;de=S(de,se.length);const Ke=se.slice();Ke[de]=1;const je=new Ze.constructor(Ze.length/se[de]);Be!==null&&je.fill(Be);for(let le=0;le=0;--Ue){const Re=se[Ue];if(Ue!==de){const st=Ve%Re;Te+=st*Ne,Ne*=Ke[Ue]}Ve=Math.floor(Ve/Re)}je[Te]=ye(je[Te],Ze[le],le,Te)}return ke||Ke.splice(de,1),[J.type,je,Ke]}function ae(ye,J=null,de=1,ke=!1){const Be=ye.data,Ze=ye.dims;if(J===null){const Ne=Be.reduce((ct,lt)=>ct+lt,0)/Be.length,Re=Math.sqrt(Be.reduce((ct,lt)=>ct+(lt-Ne)**2,0)/(Be.length-de)),st=new N(ye.type,[Ne],[]);return[new N(ye.type,[Re],[]),st]}J=S(J,Ze.length);const se=ie(ye,J,ke),Ke=se.data,[je,le,Te]=F((Ve,Ne,Re,st)=>Ve+(Ne-Ke[st])**2,ye,J,ke);for(let Ve=0;Vele+Te,0);return new N(ye.type,[je/Be.length],[])}J=S(J,ke.length);const[Ze,se,Ke]=F((je,le)=>je+le,ye,J,de);if(ke[J]!==1)for(let je=0;je=0;--de)J[de]=ke,ke*=ye[de];return J}function we(ye,J,de,ke){const Be=ye.reduce((Ze,se)=>Ze*se,1);return new N(de,new ke(Be).fill(J),ye)}function re(ye,J){let de,ke;if(typeof J=="number")de="float32",ke=Float32Array;else if(typeof J=="bigint")de="int64",ke=BigInt64Array;else if(typeof J=="boolean")de="bool",ke=Uint8Array;else throw new Error(`Unsupported data type: ${typeof J}`);return we(ye,J,de,ke)}function xe(ye,J){return re(ye.dims,J)}function ce(ye){return we(ye,1n,"int64",BigInt64Array)}function Se(ye){return ce(ye.dims)}function Ie(ye){return we(ye,0n,"int64",BigInt64Array)}function Ce(ye){return Ie(ye.dims)}function tt(ye){const J=ye.reduce((de,ke)=>de*ke,1);return new N("float32",Float32Array.from({length:J},()=>Math.random()),ye)}function Ge(ye,J){if(ye.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ye.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(J))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=J==="binary",ke=de?"int8":"uint8",Be=de?Int8Array:Uint8Array,Ze=ye.data,se=new Be(Ze.length/8);for(let Ke=0;Ke0?1:0,le=Math.floor(Ke/8),Te=Ke%8;se[le]|=je<<7-Te,de&&Te===0&&(se[le]-=128)}return new N(ke,se,[ye.dims[0],ye.dims[1]/8])}}},hf={};function gs(Ee){var $=hf[Ee];if($!==void 0)return $.exports;var r=hf[Ee]={exports:{}};return _f[Ee](r,r.exports,gs),r.exports}gs.m=_f;(()=>{var Ee=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,$;gs.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);gs.r(I);var R={};$=$||[null,Ee({}),Ee([]),Ee(Ee)];for(var Y=_&2&&r;typeof Y=="object"&&!~$.indexOf(Y);Y=Ee(Y))Object.getOwnPropertyNames(Y).forEach(N=>R[N]=()=>r[N]);return R.default=()=>r,gs.d(I,R),I}})();gs.d=(Ee,$)=>{for(var r in $)gs.o($,r)&&!gs.o(Ee,r)&&Object.defineProperty(Ee,r,{enumerable:!0,get:$[r]})};gs.o=(Ee,$)=>Object.prototype.hasOwnProperty.call(Ee,$);gs.r=Ee=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Ee,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Ee,"__esModule",{value:!0})};(()=>{var Ee;if(typeof import.meta.url=="string"&&(Ee=import.meta.url),!Ee)throw new Error("Automatic publicPath is not supported in this browser");Ee=Ee.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),gs.p=Ee})();gs.b=new URL("./",import.meta.url);var c={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/gs.r(c),gs.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:()=>$.AudioClassificationPipeline,AutoConfig:()=>I.AutoConfig,AutoFeatureExtractor:()=>M.AutoFeatureExtractor,AutoImageProcessor:()=>K.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:()=>W.AutoProcessor,AutoTokenizer:()=>_.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>$.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>_.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>U.BaseStreamer,BeitFeatureExtractor:()=>O.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:()=>O.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:()=>O.CLIPFeatureExtractor,CLIPImageProcessor:()=>O.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:()=>O.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>y.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>A.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:()=>O.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>O.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>O.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>O.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:()=>O.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>O.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>$.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>O.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>O.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>r.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>r.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>r.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>_.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>$.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>O.DonutFeatureExtractor,DonutImageProcessor:()=>O.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>O.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:()=>X.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:()=>$.FeatureExtractionPipeline,FeatureExtractor:()=>b.FeatureExtractor,FillMaskPipeline:()=>$.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>ne.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>A.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>A.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>O.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,GroundingDinoForObjectDetection:()=>r.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>O.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>r.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>ne.GroundingDinoProcessor,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:()=>O.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>ne.Idefics3Processor,ImageClassificationPipeline:()=>$.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>$.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>y.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>v.ImageProcessor,ImageSegmentationPipeline:()=>$.ImageSegmentationPipeline,ImageToImagePipeline:()=>$.ImageToImagePipeline,ImageToTextPipeline:()=>$.ImageToTextPipeline,InterruptableStoppingCriteria:()=>X.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>O.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ne.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:()=>O.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>A.LogitsProcessor,LogitsProcessorList:()=>A.LogitsProcessorList,LogitsWarper:()=>A.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:()=>O.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>O.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>O.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>X.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>ne.MgpstrProcessor,MgpstrTokenizer:()=>_.MgpstrTokenizer,MinLengthLogitsProcessor:()=>A.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>A.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:()=>O.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>O.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>O.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>O.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>O.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>O.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>O.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>O.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,ModernBertForMaskedLM:()=>r.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>r.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>r.ModernBertForTokenClassification,ModernBertModel:()=>r.ModernBertModel,ModernBertPreTrainedModel:()=>r.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>y.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>ne.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:()=>A.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>A.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>O.NougatImageProcessor,NougatTokenizer:()=>_.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>$.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:()=>O.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>O.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>ne.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>O.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ne.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:()=>O.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>ne.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>$.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>_.PreTrainedTokenizer,PretrainedConfig:()=>I.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>te.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>O.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>y.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ne.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>$.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>_.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>O.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ne.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>O.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawAudio:()=>R.RawAudio,RawImage:()=>Y.RawImage,RepetitionPenaltyLogitsProcessor:()=>A.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:()=>O.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>ne.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>y.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>O.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>O.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>O.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:()=>ne.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:()=>X.StoppingCriteria,StoppingCriteriaList:()=>X.StoppingCriteriaList,StyleTextToSpeech2Model:()=>r.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>r.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>$.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>A.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>O.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:()=>A.TemperatureLogitsWarper,Tensor:()=>N.Tensor,Text2TextGenerationPipeline:()=>$.Text2TextGenerationPipeline,TextClassificationPipeline:()=>$.TextClassificationPipeline,TextGenerationPipeline:()=>$.TextGenerationPipeline,TextStreamer:()=>U.TextStreamer,TextToAudioPipeline:()=>$.TextToAudioPipeline,TokenClassificationPipeline:()=>$.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>_.TokenizerModel,TopKLogitsWarper:()=>A.TopKLogitsWarper,TopPLogitsWarper:()=>A.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>$.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:()=>ne.VLChatProcessor,VLMImageProcessor:()=>O.VLMImageProcessor,ViTFeatureExtractor:()=>O.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>O.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:()=>O.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>O.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:()=>ne.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:()=>ne.WhisperProcessor,WhisperTextStreamer:()=>U.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>A.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:()=>O.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>O.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>$.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>$.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>$.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>$.ZeroShotObjectDetectionPipeline,bankers_round:()=>g.bankers_round,cat:()=>N.cat,cos_sim:()=>g.cos_sim,dot:()=>g.dot,dynamic_time_warping:()=>g.dynamic_time_warping,env:()=>Ee.env,full:()=>N.full,full_like:()=>N.full_like,getKeyValueShapes:()=>I.getKeyValueShapes,hamming:()=>R.hamming,hanning:()=>R.hanning,interpolate:()=>N.interpolate,interpolate_4d:()=>N.interpolate_4d,interpolate_data:()=>g.interpolate_data,is_chinese_char:()=>_.is_chinese_char,layer_norm:()=>N.layer_norm,load_image:()=>Y.load_image,log_softmax:()=>g.log_softmax,magnitude:()=>g.magnitude,matmul:()=>N.matmul,max:()=>g.max,mean:()=>N.mean,mean_pooling:()=>N.mean_pooling,medianFilter:()=>g.medianFilter,mel_filter_bank:()=>R.mel_filter_bank,min:()=>g.min,ones:()=>N.ones,ones_like:()=>N.ones_like,permute:()=>N.permute,permute_data:()=>g.permute_data,pipeline:()=>$.pipeline,quantize_embeddings:()=>N.quantize_embeddings,rand:()=>N.rand,read_audio:()=>R.read_audio,rfft:()=>N.rfft,round:()=>g.round,slice:()=>N.slice,softmax:()=>g.softmax,spectrogram:()=>R.spectrogram,stack:()=>N.stack,std_mean:()=>N.std_mean,topk:()=>N.topk,window_function:()=>R.window_function,zeros:()=>N.zeros,zeros_like:()=>N.zeros_like});var Ee=gs("./src/env.js"),$=gs("./src/pipelines.js"),r=gs("./src/models.js"),_=gs("./src/tokenizers.js"),I=gs("./src/configs.js"),R=gs("./src/utils/audio.js"),Y=gs("./src/utils/image.js"),N=gs("./src/utils/tensor.js"),g=gs("./src/utils/maths.js"),b=gs("./src/base/feature_extraction_utils.js"),y=gs("./src/models/feature_extractors.js"),M=gs("./src/models/auto/feature_extraction_auto.js"),v=gs("./src/base/image_processors_utils.js"),O=gs("./src/models/image_processors.js"),K=gs("./src/models/auto/image_processing_auto.js"),te=gs("./src/base/processing_utils.js"),ne=gs("./src/models/processors.js"),W=gs("./src/models/auto/processing_auto.js"),U=gs("./src/generation/streamers.js"),X=gs("./src/generation/stopping_criteria.js"),A=gs("./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 W_=c.AutoModel;c.AutoModelForAudioClassification;c.AutoModelForAudioFrameClassification;c.AutoModelForCTC;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;c.AutoProcessor;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.Dinov2WithRegistersForImageClassification;c.Dinov2WithRegistersModel;c.Dinov2WithRegistersPreTrainedModel;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.GroundingDinoForObjectDetection;c.GroundingDinoImageProcessor;c.GroundingDinoPreTrainedModel;c.GroundingDinoProcessor;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;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.ModernBertForMaskedLM;c.ModernBertForSequenceClassification;c.ModernBertForTokenClassification;c.ModernBertModel;c.ModernBertPreTrainedModel;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.RawAudio;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.StyleTextToSpeech2Model;c.StyleTextToSpeech2PreTrainedModel;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 $h=c.Tensor;c.Text2TextGenerationPipeline;c.TextClassificationPipeline;c.TextGenerationPipeline;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;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;c.env;c.full;c.full_like;c.getKeyValueShapes;c.hamming;c.hanning;c.interpolate;c.interpolate_4d;c.interpolate_data;c.is_chinese_char;c.layer_norm;c.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;var G_=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 Fa=16e3,Ah=Fa/1e3,K_=.3,H_=.1,q_=400,Q_=q_*Ah,X_=80,kh=X_*Ah,Y_=250*Ah,J_=30,Z_=512,eg=Math.ceil(kh/Z_);async function tg(){try{return!("gpu"in navigator)||!navigator.gpu?!1:(await navigator.gpu.requestAdapter(),!0)}catch(Ee){return console.error(Ee),!1}}var $n=(Ee=>(Ee.Status="status",Ee.Output="output",Ee.Info="info",Ee.Request="request",Ee.Error="error",Ee.Load="load",Ee))($n||{}),Ih=(Ee=>(Ee.RecordingStart="recording_start",Ee.RecordingEnd="recording_end",Ee.Ready="ready",Ee))(Ih||{}),Wp=(Ee=>(Ee.UntilNext="until_next",Ee))(Wp||{});let Sh,Gp,Kp=Promise.resolve();const Oa=new Float32Array(J_*Fa);let Sn=0;const sg=new $h("int64",[Fa],[]);let mf=new $h("float32",new Float32Array(2*1*128),[2,1,128]),Nc=!1,jc=0;const rg={webgpu:{encoder_model:"fp32",decoder_model_merged:"q4"},wasm:{encoder_model:"fp32",decoder_model_merged:"q8"}};async function ng(){return await W_.from_pretrained("onnx-community/silero-vad",{config:{model_type:"custom"},dtype:"fp32"}).catch(Ee=>{throw self.postMessage({type:$n.Error,error:Ee}),Ee})}async function ig(Ee){return await G_("automatic-speech-recognition","onnx-community/moonshine-base-ONNX",{device:Ee,dtype:rg[Ee]}).catch($=>{throw self.postMessage({type:$n.Error,error:$}),$})}async function og(Ee){if(Sh===void 0)return console.warn("VAD model not loaded yet"),!1;const $=new $h("float32",Ee,[1,Ee.length]),{stateN:r,output:_}=await(Kp=Kp.then(R=>Sh({input:$,sr:sg,state:mf})));mf=r;const I=_.data[0];return I>K_||Nc&&I>=H_}async function ag(Ee,$){if(Gp===void 0){console.warn("Transcriber model not loaded yet");return}const{text:r}=await(Kp=Kp.then(_=>Gp(Ee)));self.postMessage({type:$n.Output,buffer:Ee,message:r,...$})}function yf(Ee=0){self.postMessage({type:$n.Status,status:Ih.RecordingEnd,message:"Transcribing...",duration:Wp.UntilNext}),Oa.fill(0,Ee),Sn=Ee,Nc=!1,jc=0}const Uc=[];function ff(Ee){const r=Date.now()-(jc+kh)/Fa*1e3,_=r-Sn/Fa*1e3,I=r-_,R=(Ee==null?void 0:Ee.length)??0,Y=Oa.slice(0,Sn+kh),N=Uc.reduce((y,M)=>y+M.length,0),g=new Float32Array(N+Y.length);let b=0;for(const y of Uc)g.set(y,b),b+=y.length;g.set(Y,b),ag(g,{start:_,end:r,duration:I}),Ee&&Oa.set(Ee,0),yf(R)}async function lg(){const Ee=await tg()?"webgpu":"wasm";self.postMessage({type:$n.Info,message:`Using device: "${Ee}"`}),self.postMessage({type:$n.Info,message:"Loading models...",duration:Wp.UntilNext}),Sh=await ng(),Gp=await ig(Ee),await Gp(new Float32Array(Fa)),self.postMessage({type:"status",status:"ready",message:"Ready!"}),self.onmessage=async $=>{const{buffer:r}=$.data,_=Nc,I=await og(r);if(!_&&!I){Uc.length>=eg&&Uc.shift(),Uc.push(r);return}const R=Oa.length-Sn;if(r.length>=R){Oa.set(r.subarray(0,R),Sn),Sn+=R;const Y=r.subarray(R);ff(Y);return}else Oa.set(r,Sn),Sn+=r.length;if(I){Nc||self.postMessage({type:$n.Status,status:Ih.RecordingStart,message:"Listening...",duration:Wp.UntilNext}),Nc=!0,jc=0;return}if(jc+=r.length,!(jc{const{type:$}=Ee.data;switch($){case $n.Load:lg();break}});